public static List <MQTTMessage> GetUnreadMessagesByGmail(string gmail) { MessengerDataContext dc = new MessengerDataContext(); List <MQTTMessage> mqttMessageList = new List <MQTTMessage>(); IQueryable <Message> messageList = from messages in dc.Messages join users in dc.Users on messages.ToID equals users.ID where users.gmail == gmail && messages.SendingPending select messages; foreach (Message message in messageList) { MQTTMessage mqttMessage = new MQTTMessage(); mqttMessage.gmail = GetGmailByID(message.FromID); mqttMessage.message = message.Text; mqttMessage.time = message.Time.ToString(); mqttMessageList.Add(mqttMessage); } return(mqttMessageList); }
private MQTTMessage GetPeerMessage(string toInstanceId = "ALL", string type = "INSTANCE_CONNECTED") { var myPeerData = new MQTTPeerMessageContent() { PeerId = Program.InstanceConfig.ServerInstanceID, DiscoveryUrls = string.Format("http://{0}/eureka/apps", Program.InstanceConfig.Urls), InstanceIP = Program.INSTANCE_IP, InstancePort = Program.INSTANCE_PORT }; var jsonPeer = JsonConvert.SerializeObject(myPeerData).Replace("\"", "'"); var destInstances = new List <string>(); destInstances.Add(toInstanceId); var newPeerMessage = new MQTTMessage() { FromInstanceId = Program.InstanceConfig.ServerInstanceID, ToInstancesIds = destInstances, Type = type, Message = jsonPeer }; return(newPeerMessage); }
public void PublishDeletedInstance(string tenantId, string appName, string instanceId) { var toIds = GetPeerIds(); if (toIds.Count == 0) { return; } var deleteMessage = new MQTTInstanceDeleteMessageContent() { AppName = appName, TenantId = tenantId, InstanceId = instanceId }; var jsonMessage = JsonConvert.SerializeObject(deleteMessage); jsonMessage = jsonMessage.Replace("\"", "'"); var mqttMessage = new MQTTMessage() { FromInstanceId = Program.InstanceConfig.ServerInstanceID, ToInstancesIds = toIds, Type = "DELETE_INSTANCE", Message = jsonMessage }; _mqttService.SendMQTTMessageToMultipleInstances(tenantId, toIds, mqttMessage); }
public void SendMQTTMessageToInstance(string tenantId, string toInstanceId, MQTTMessage message) { Task task = Task.Factory.StartNew(async() => { MqttClientPublishResult res = null; var myMqttClient = _mqttClients.SingleOrDefault(c => (c.TenantId + "-" + c.TenantType).CompareTo(tenantId) == 0); message.ToInstancesIds = new List <string>(); message.ToInstancesIds.Add(toInstanceId); string jsonMessage = JsonConvert.SerializeObject(message); if (myMqttClient != null && myMqttClient.mqttClient.IsConnected) { res = await myMqttClient.mqttClient.PublishAsync(myMqttClient.mqttTopic, jsonMessage, MyMQTTClient.MQTTQualityOfService); InstanceHealthService.Health.MQTTMessagesSent += 1; } else { if (MQTTSendQueue.CheckIfMQTTIsConfigured()) { MQTTSendQueue.MessagesToSend.Add(new MQTTQueueMessage() { Topic = myMqttClient.mqttTopic, QueuedMessage = jsonMessage, QoS = MyMQTTClient.MQTTQualityOfService }); } } return(res); }); }
public void Notify(MQTTMessage msg) { //Set up an intent so that tapping the notification returns to this app Intent intent = new Intent(ctx, typeof(MainActivity)); //Create a PendingIntent; const int pendingIntentId = 0; PendingIntent pendingIntent = PendingIntent.GetActivity(ctx, pendingIntentId, intent, PendingIntentFlags.OneShot); //Instantiate the builder and set notification elements, including Pending Intent Notification.Builder builder = new Notification.Builder(ctx) .SetContentIntent(pendingIntent) .SetContentTitle(msg.Topic) .SetContentText(msg.Payload) .SetSmallIcon(Resource.Drawable.ic_stat_button_click); //Build the notification Notification notification = builder.Build(); //Get the notification manager NotificationManager notificationManager = ctx.GetSystemService(Context.NotificationService) as NotificationManager; //Publish the notification const int notificationId = 0; notificationManager.Notify(notificationId, notification); }
private MQTTMessage CreateMQTTMessage(MessageDispatch dispatch) { MQTTMessage message = dispatch.Message.Clone() as MQTTMessage; if (this.ConsumerTransformer != null) { IMessage newMessage = ConsumerTransformer(this.session, this, message); if (newMessage != null) { message = this.messageTransformation.TransformMessage <MQTTMessage>(newMessage); } } message.Connection = this.session.Connection; if (IsClientAcknowledge) { message.Acknowledger += new AcknowledgeHandler(DoClientAcknowledge); } else if (IsIndividualAcknowledge) { message.Acknowledger += new AcknowledgeHandler(DoIndividualAcknowledge); } else { message.Acknowledger += new AcknowledgeHandler(DoNothingAcknowledge); } return(message); }
protected void DoIndividualAcknowledge(MQTTMessage message) { MessageDispatch dispatch = null; lock (this.dispatchedMessages) { foreach (MessageDispatch originalDispatch in this.dispatchedMessages) { if (originalDispatch.Message.MessageId.Equals(message.MessageId)) { dispatch = originalDispatch; this.dispatchedMessages.Remove(originalDispatch); break; } } } if (dispatch == null) { Tracer.DebugFormat("Attempt to Ack MessageId[{0}] failed because the original dispatch is not in the Dispatch List", message.MessageId); return; } // MessageAck ack = new MessageAck(dispatch, (byte) AckType.IndividualAck, 1); // Tracer.Debug("Sending Individual Ack for MessageId: " + ack.LastMessageId.ToString()); // this.session.SendAck(ack); }
public void WaterSwitchClick(string WaterSystemOnOffFeedback) { MQTTMessage wateringStatus = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("WateringSystem/Status"); if (LastTimeWatered != null) { if ((DateTime.Now - LastTimeWatered).TotalSeconds <= 5) { this.SetErrorMessageAndShowLabel("Watering the plant has a 5 second cooldown to prevent accidents!"); return; } } if (wateringStatus == null) { this.SetErrorMessageAndShowLabel("Cannot use button when no information about the current state is available"); return; } if (wateringStatus.Message == "ON") { App.Client.Publish("WateringSystem", "OFF"); } else { App.Client.Publish("WateringSystem", "ON"); } LastTimeWatered = DateTime.Now; }
public async void InitCycle(bool FirstCall = false) { //await App.MoistMeterDatabase.EmptyDatabase(); MQTTMessage latestMessage = App.Client.MQTTMessageStore.GetLatestMessageFromTopic(this.Topic); if (latestMessage != null) { await SaveEntryToDatabase(latestMessage); } CreateXamlView(); if (FirstCall) { Device.StartTimer(TimeSpan.FromSeconds(5), () => { Device.BeginInvokeOnMainThread(() => { InitCycle(); }); //return true to keep loop going, false to stop timer return(true); }); } }
public void PublishClientConfigurationActivity(string tenantId, string clientHostname) { var toIds = GetPeerIds(); if (toIds.Count == 0) { return; } var activityMessage = new MQTTConfigurationClientActivityMessageContent() { TenantId = tenantId, ClientHostname = clientHostname, LastUpdateTimestamp = DateTime.UtcNow }; var jsonMessage = JsonConvert.SerializeObject(activityMessage); jsonMessage = jsonMessage.Replace("\"", "'"); var mqttMessage = new MQTTMessage() { FromInstanceId = Program.InstanceConfig.ServerInstanceID, ToInstancesIds = toIds, Type = "CLIENT_CONFIGURATION_ACTIVITY", Message = jsonMessage }; _mqttService.SendMQTTMessageToMultipleInstances(tenantId, toIds, mqttMessage); }
public void PublishInstanceStatusChange(string tenantId, string appName, string instanceId, string status, long dirtyTimestamp) { var toIds = GetPeerIds(); if (toIds.Count == 0) { return; } var changeMessage = new MQTTInstanceChangeStatusMessageContent() { AppName = appName, TenantId = tenantId, InstanceId = instanceId, Status = status, LastDirtyTimestamp = dirtyTimestamp }; var jsonMessage = JsonConvert.SerializeObject(changeMessage); jsonMessage = jsonMessage.Replace("\"", "'"); var mqttMessage = new MQTTMessage() { FromInstanceId = Program.InstanceConfig.ServerInstanceID, ToInstancesIds = toIds, Type = "CHANGE_INSTANCE_STATUS", Message = jsonMessage }; _mqttService.SendMQTTMessageToMultipleInstances(tenantId, toIds, mqttMessage); }
public void GetLatestTempStatus() { MQTTMessage latestTemperature = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Plant/Temperature"); if (latestTemperature != null) { CurrentTempStatus = $"Temperature: {latestTemperature.Message}°C"; } }
public void GetLatestCoffeeStatus() { MQTTMessage latestCoffeeStatus = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Coffee/Status"); if (latestCoffeeStatus != null) { CurrentCoffeeStatus = latestCoffeeStatus.Message; } }
public void Test() { MQTTMessage mqttMessage = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Coffee"); if (mqttMessage != null) { TestLabel = mqttMessage.Message; } }
public void GetLatestHumidityStatus() { MQTTMessage latesHumidity = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Plant/Humidity"); if (latesHumidity != null) { CurrentHumidityStatus = $"Humidity: {latesHumidity.Message}%"; } }
public void GetLatestWaterStatus() { MQTTMessage latestWaterStatus = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("WateringSystem/Status"); if (latestWaterStatus != null) { CurrentWaterStatus = latestWaterStatus.Message; } }
public void GetLatestMoistureStatus() { MQTTMessage latestMoisture = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Plant/Moisture"); if (latestMoisture != null) { CurrentGroundMoisture = $"Soil moisture: {latestMoisture.Message}%"; } }
public void AddMessage() { List <MQTTMessage> expected = new List <MQTTMessage>(); MQTTMessageStore messageStore = new MQTTMessageStore(); MQTTMessage msg = new MQTTMessage("test", "test", DateTime.Now); messageStore.AddMessage(msg); expected.Add(msg); Assert.AreEqual(expected.Count, messageStore.Messages.Count); }
public void GetLastAddedItemByTopicName() { MQTTMessageStore messageStore = new MQTTMessageStore(); MQTTMessage msg = new MQTTMessage("test", "test", DateTime.Now); messageStore.AddMessage(msg); MQTTMessage result = messageStore.GetLatestMessageFromTopic("test"); Assert.AreEqual(result, msg); }
public async Task PreventDuplicateMessage() { MQTTMockClient client = new MQTTMockClient(); _ = await client.Connect(this.IP, this.PORT, this.PASSWORD); MQTTMessage duplicateMessage = new MQTTMessage(this.TESTCHANNEL, "hello world", DateTime.Now); client.MQTTMessageStore.AddMessage(duplicateMessage); Assert.IsFalse(client.MQTTMessageStore.AddMessage(duplicateMessage)); }
public async Task SubscribeAndSendMessageMockup() { MQTTMockClient client = new MQTTMockClient(); _ = await client.Connect(this.IP, this.PORT, this.PASSWORD); client.Subscribe(this.TESTCHANNEL); client.Publish(this.TESTCHANNEL, "hello world"); MQTTMessage message = client.MQTTMessageStore.GetLatestMessageFromTopic(this.TESTCHANNEL); Assert.AreEqual("hello world", message.Message); }
public void ProcessClientConfigurationActivity(MQTTMessage mqttMessage, string topic) { InstanceHealthService.Health.MQTTMessagesReceived += 1; var receivedMessage = mqttMessage.Message.ToString().Replace("'", "\""); var messageContent = JsonConvert.DeserializeObject <MQTTConfigurationClientActivityMessageContent>(receivedMessage); if (messageContent != null && mqttMessage.FromInstanceId.CompareTo(Program.InstanceConfig.ServerInstanceID) != 0) { this._clientConfigurationRepo.Add(new DiscoveryClient(messageContent.ClientHostname, messageContent.LastUpdateTimestamp)); } }
public void ProcessInstanceDelete(MQTTMessage mqttMessage, string topic) { InstanceHealthService.Health.MQTTMessagesReceived += 1; var receivedMessage = mqttMessage.Message.ToString().Replace("'", "\""); var messageContent = JsonConvert.DeserializeObject <MQTTInstanceDeleteMessageContent>(receivedMessage); if (messageContent != null && mqttMessage.FromInstanceId.CompareTo(Program.InstanceConfig.ServerInstanceID) != 0) { var memoryRepo = new MemoryServicesRepository(messageContent.TenantId, Program.InstanceConfig.EvictionInSecs); memoryRepo.Delete(messageContent.AppName, messageContent.InstanceId); } }
public void ProcessInstanceUpdated(MQTTMessage mqttMessage, string topic) { InstanceHealthService.Health.MQTTMessagesReceived += 1; var receivedMessage = mqttMessage.Message.ToString().Replace("'", "\""); var instance = JsonConvert.DeserializeObject <Instance>(receivedMessage); instance.TenantId = GetTenantFromTopicName(topic); if (instance != null && mqttMessage.FromInstanceId.CompareTo(Program.InstanceConfig.ServerInstanceID) != 0) { var memoryRepo = new MemoryServicesRepository(instance.TenantId, Program.InstanceConfig.EvictionInSecs); memoryRepo.Add(instance); } }
public async Task <int> SaveEntryToDatabase(MQTTMessage latestMessage) { if (latestMessage == null) { return(0); } MoistMeter compressedMoistMeter = new MoistMeter { Topic = Topic, Data = Convert.ToDouble(latestMessage.Message), DateTime = DateTime.Now }; return(await App.MoistMeterDatabase.SaveItemAsync(compressedMoistMeter)); }
public void CoffeeSwitchClick(string CoffeeOnOffFeedback) { MQTTMessage coffeeStatus = App.Client.MQTTMessageStore.GetLatestMessageFromTopic("Coffee/Status"); if (coffeeStatus == null) { this.SetErrorMessageAndShowLabel("Cannot use button when no information about the current state is available"); return; } if (coffeeStatus.Message == "ON") { App.Client.Publish("cmnd/coffee/POWER", "OFF"); } else { App.Client.Publish("cmnd/coffee/POWER", "ON"); } }
/* PROCESS RECEIVING MESSAGES */ private void ProcessInstanceConnected(string topic, MQTTMessage mqttMessage) { InstanceHealthService.Health.MQTTMessagesReceived += 1; var receivedMessage = mqttMessage.Message.ToString().Replace("'", "\""); var peerMessageContent = JsonConvert.DeserializeObject <MQTTPeerMessageContent>(receivedMessage); if (peerMessageContent != null && mqttMessage.FromInstanceId.CompareTo(Program.InstanceConfig.ServerInstanceID) != 0) { // respond back with my peer data var myMqttClient = _mqttClients.SingleOrDefault(c => c.mqttTopic.CompareTo(topic) == 0); if (myMqttClient != null && myMqttClient.mqttClient.IsConnected) { var myPeerMessage = GetPeerMessage(peerMessageContent.PeerId, "INSTANCE_HEARTBEAT"); myMqttClient.mqttClient.PublishAsync(myMqttClient.mqttTopic, JsonConvert.SerializeObject(myPeerMessage)); } // add new peer to my peers DiscoveryPeer existingPeer = null; lock (Memory.Peers) { existingPeer = Memory.Peers.FirstOrDefault(p => p.ServerInstanceID.CompareTo(peerMessageContent.PeerId) == 0); } if (existingPeer == null) { var newPeer = new DiscoveryPeer() { LastUpdateTimestamp = DateTime.UtcNow, ServerInstanceID = peerMessageContent.PeerId, DiscoveryUrls = peerMessageContent.DiscoveryUrls, InstanceIP = peerMessageContent.InstanceIP, InstancePort = peerMessageContent.InstancePort }; Memory.Peers.Add(newPeer); } } }
public void ProcessInstanceHeartbeat(string topic, MQTTMessage mqttMessage) { InstanceHealthService.Health.MQTTMessagesReceived += 1; var receivedMessage = mqttMessage.Message.ToString().Replace("'", "\""); var peerMessageContent = JsonConvert.DeserializeObject <MQTTPeerMessageContent>(receivedMessage); if (peerMessageContent != null && mqttMessage.FromInstanceId.CompareTo(Program.InstanceConfig.ServerInstanceID) != 0) { DiscoveryPeer existingPeer = null; // add new peer to my peers lock (Memory.Peers) { existingPeer = Memory.Peers.FirstOrDefault(p => p.ServerInstanceID.CompareTo(peerMessageContent.PeerId) == 0); } if (existingPeer == null) { var newPeer = new DiscoveryPeer() { LastUpdateTimestamp = DateTime.UtcNow, ServerInstanceID = peerMessageContent.PeerId, DiscoveryUrls = peerMessageContent.DiscoveryUrls, InstanceIP = peerMessageContent.InstanceIP, InstancePort = peerMessageContent.InstancePort }; _memoryDiscoveryPeerRepository.Add(newPeer); } else { existingPeer.LastUpdateTimestamp = DateTime.UtcNow; existingPeer.DiscoveryUrls = peerMessageContent.DiscoveryUrls; existingPeer.InstanceIP = peerMessageContent.InstanceIP; existingPeer.InstancePort = peerMessageContent.InstancePort; } } }
public void PublishAddedOrUpdatedInstance(Instance instance, string type = "ADD_INSTANCE") { var toIds = GetPeerIds(); if (toIds.Count == 0) { return; } var jsonMessage = JsonConvert.SerializeObject(instance); jsonMessage = jsonMessage.Replace("\"", "'"); var mqttMessage = new MQTTMessage() { FromInstanceId = Program.InstanceConfig.ServerInstanceID, ToInstancesIds = toIds, Type = type, Message = jsonMessage }; _mqttService.SendMQTTMessageToMultipleInstances(instance.TenantId, toIds, mqttMessage); }
static async Task Start() { var mqttService = new MQTTService(); var mqttClientOptions = new Options { Uri = new Uri("mqtt://test.mosquitto.org:1883"), //UseTls = true, //IgnoreCertificateChainErrors = true, //IgnoreCertificateRevocationErrors = true, //AllowUntrustedCertificates = true, //Uri = new Uri("ws://broker.mqttdashboard.com:8000/mqtt"), //Server = "broker.mqttdashboard.com", ////Port = 1883, //Port = 8000, //Url = "broker.mqttdashboard.com", //Path = "mqtt", ConnectionType = ConnectionType.Tcp, //ConnectionType = ConnectionType.WebSocket }; var topic1 = new TopicFilter { QualityOfServiceLevel = QoSLevel.ExactlyOnce, //Topic = "PP/#" Topic = "/#" }; var topic2 = new TopicFilter { QualityOfServiceLevel = QoSLevel.AtLeastOnce, //Topic = "EFM/#" Topic = "MQTTClientRx/Test" }; ITopicFilter[] topicFilters = { topic1, //topic2 }; var MQTTService = mqttService.CreateObservableMQTTService(mqttClientOptions, topicFilters); _disp1 = MQTTService.observableMessage.Subscribe( msg => { if (msg.Topic.Contains("EFM")) { Console.ForegroundColor = ConsoleColor.Yellow; } else { Console.ForegroundColor = ConsoleColor.Blue; } Console.WriteLine($"{Encoding.UTF8.GetString(msg.Payload)}, " + $"{msg.QualityOfServiceLevel.ToString()}, " + $"Retain: {msg.Retain}, " + $"Topic: {msg.Topic}"); }, ex => { Console.WriteLine($"{ex.Message} : inner {ex.InnerException.Message}"); }, () => { Console.WriteLine("Completed..."); }); await Task.Delay(TimeSpan.FromSeconds(5)); var newMessage = new MQTTMessage { Payload = Encoding.UTF8.GetBytes("Hello MQTT EO"), QualityOfServiceLevel = QoSLevel.ExactlyOnce, Retain = false, Topic = "MQTTClientRx/Test" }; await MQTTService.client.PublishAsync(newMessage); _disp2 = MQTTService.observableMessage.Subscribe( msg => { if (msg.Topic.Contains("EFM")) { Console.ForegroundColor = ConsoleColor.Cyan; } else { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine($"{Encoding.UTF8.GetString(msg.Payload)}, " + $"{msg.QualityOfServiceLevel.ToString()}, " + $"Retain: {msg.Retain}, " + $"Topic: {msg.Topic}"); }, ex => { Console.WriteLine($"{ex.Message} : inner {ex.InnerException.Message}"); }, () => { Console.WriteLine("Completed..."); }); await Task.Delay(TimeSpan.FromSeconds(2)); await MQTTService.client.UnsubscribeAsync(new[] { topic2 }); await Task.Delay(TimeSpan.FromSeconds(5)); //await MQTTService.client.UnsubscribeAsync(new [] {topic1}); //await Task.Delay(TimeSpan.FromSeconds(2)); //await MQTTService.client.SubscribeAsync(new[] { topic2 }); await Task.Delay(TimeSpan.FromSeconds(2)); _disp2.Dispose(); await Task.Delay(TimeSpan.FromSeconds(2)); _disp1.Dispose(); await Task.Delay(TimeSpan.FromSeconds(30)); //var topic2a = new TopicFilter //{ // QualityOfServiceLevel = QoSLevel.ExactlyOnce, // Topic = "EFM/#" //}; //Console.ForegroundColor = ConsoleColor.DarkBlue; //await MQTTService.client.UnsubscribeAsync(new[] { topic2 }); //await MQTTService.client.SubscribeAsync(new[] { topic2a }); }