protected override void WriteLog(MQTTMessage message) { if (this.MQTTMessageStore.AddMessage(message)) { MessageReceived?.Invoke(); } }
/// <summary> /// Catches the incomming MQTTMessage and writes it to the MQTTMessageStore /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void MqttClient_MessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { MQTTMessage message = new MQTTMessage(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload), DateTime.Now); this.WriteLog(message); }
/// <summary> /// Validates whether the MQTTMessage is valid. /// A MQTTMessage is valid when it is unique and when said message is not null. /// </summary> /// <param name="message"></param> /// <returns>Boolean based on whether the message is valid or not.</returns> private bool IsValidMessage(MQTTMessage message) { if (this.IsDuplicate(message) || message == null) { return(false); } return(true); }
public void Publish(string topic, string message) { if (topic == "WateringSystem") { topic = "WateringSystem/Status"; } if (topic == "cmnd/coffee/POWER") { topic = "Coffee/Status"; } MQTTMessage newMessage = new MQTTMessage(topic, message, DateTime.Now); this.WriteLog(newMessage); }
/// <summary> /// Validated whether a MQTTMessage is a duplicate or not. /// Validation is based on topic, payload and DateTime. /// </summary> /// <param name="message"></param> /// <returns>Boolean based on whether the message is a duplicate or not.</returns> private bool IsDuplicate(MQTTMessage message) { lock (this.Messages) { foreach (MQTTMessage storedMessage in this.Messages) { if (storedMessage != null) { if (storedMessage.GetFullMessageAsString().Equals(message.GetFullMessageAsString())) { return(true); } } } } return(false); }
/// <summary> /// Adds a MQTTMessage to the Messages list. /// Locks the Messages list while perfomerming operations to the list. /// </summary> /// <param name="message"></param> /// <returns>Boolean depending on if message was added sucessfully or not.</returns> public bool AddMessage(MQTTMessage message) { if (!IsValidMessage(message)) { return(false); } /* It is important to lock the Messages list because the asyncronous nature of our application. * We do not want to add a message to the list while we are performing another operation with said list. * Doing so would also crash the application as provide unwanted behaviour */ lock (this.Messages) { this.Messages.Add(message); this.Truncate(50); } return(true); }