static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            byte[] data = e.Message;
            string dataString = System.Text.Encoding.Default.GetString(data);

            string[] dataSplit = dataString.Split(';');
            Console.WriteLine("Location: " + dataSplit[0]);
            Console.WriteLine("Temperatuur: " + dataSplit[1]);
            Console.WriteLine("Time: " + dataSplit[2]);

            SchrijfDataWeg(dataSplit);
        }
Exemple #2
1
        void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            MqttClient client = (MqttClient)sender;

            if (!mqttBridge.OnPublish(client, e)) return;

            // create PUBLISH message to publish
            // [v3.1.1] DUP flag from an incoming PUBLISH message is not propagated to subscribers
            //          It should be set in the outgoing PUBLISH message based on transmission for each subscriber
            MqttMsgPublish publish = new MqttMsgPublish(e.Topic, e.Message, false, e.QosLevel, e.Retain);

            // publish message through publisher manager
            this.publisherManager.Publish(publish);
        }
Exemple #3
0
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var fooValue       = Encoding.UTF8.GetString(e.Message);
            var fooMessageType = JsonConvert.DeserializeObject <MessageType>(fooValue);

            fooEventAggregator.GetEvent <ReceiveMessageEvent>().Publish(fooMessageType);
        }
 private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     //handle messge received
     this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
         (ThreadStart)delegate()
             {
                 if (sb.Length > 10000)
                 {
                     sb.Clear();
                 }
                 sb.Append("Topic:" + e.Topic.ToString() + " Len:" + e.Message.Length.ToString() + " Msg:");
                 if (hexCheckBox.IsChecked == true)
                 {
                     foreach (byte b in e.Message)
                     {
                         sb.Append(b.ToString("x2").ToUpper() + " ");
                     }
                 }
                 else
                 {
                     sb.Append(Encoding.Default.GetString(e.Message));
                 }
                 sb.AppendLine();
                 recvInfoTB.Text = sb.ToString();
             }
         );
 }
Exemple #5
0
 private static void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     if (e.Topic == "sensor/light")
     {
         Console.WriteLine("Sensor: {0}", System.Text.Encoding.Default.GetString(e.Message));
     }
 }
        //EventHandler
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            byte[] data = e.Message;

            //do stuff with data
            System.Console.WriteLine(data);
        }
Exemple #7
0
        static void client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string message = new string(Encoding.UTF8.GetChars(e.Message));

            Debug.Print("Message Received - Topic: " + e.Topic + ", Message: " + message + ", QosLevel: " + e.QosLevel + ", Retain: " + e.Retain + ", DupFlag: " + e.DupFlag);
            netduino.Set(message);
        }
Exemple #8
0
        private void HandleClientMqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var topic = e.Topic.Split('/');

            if (e.Topic.IndexOf("&present") >= 0)
            {
                this.onPresent(Encoding.UTF8.GetString(e.Message));
            }
            else if (e.Topic.IndexOf("&absent") >= 0)
            {
                this.onAbsent(Encoding.UTF8.GetString(e.Message));
            }
            else if (e.Topic.IndexOf("&id") >= 0)
            {
                //pass
            }
            else if (e.Topic.IndexOf("@info") >= 0)
            {
                this.onInfo(Encoding.UTF8.GetString(e.Message));
            }
            else if (e.Topic.IndexOf("&error") >= 0)
            {
                this.onError(Encoding.UTF8.GetString(e.Message));
            }
            else
            {
                this.onMessage(e.Topic, Encoding.UTF8.GetString(e.Message));
            }
        }
Exemple #9
0
        public void ReceivedMessage(string message, MqttMsgPublishEventArgs mqttMsgPublishEventArgs)
        {
            object val = message;
            try
            {
                if (_measurement != null)
                {
                    if (JsonConverter != null)
                    {
                        val = JsonConverter.Convert(message);
                    }

                    foreach (var textConverterRule in _ruleConfiguration.TextConverterRules)
                    {
                        if (Equals(textConverterRule.SourceValue, val))
                        {
                            val = textConverterRule.ConvertedValue;
                            break;
                        }
                    }

                    _measurement.ReceivedValue(val, mqttMsgPublishEventArgs);

                }

            }
            catch (Exception ex)
            {
                Logger.Warn(
                    $"Excpetion in topic {Topic}, content: {message}, reason: {ex.Message}");
            }
        }
Exemple #10
0
        private void mqttClient_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var command = e.Topic.ToUpper().Split('/').Last();
            var data    = Encoding.ASCII.GetString(e.Message);

            otgwClient.SendCommand(command, data);
        }
Exemple #11
0
        private void EventPublished(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            Image image;

            try
            {
                String msg = System.Text.UTF8Encoding.UTF8.GetString(e.Message);
                if (msg.StartsWith("["))
                {
                    SetText(msg);
                }
                else
                {
                    Console.WriteLine(msg);
                    byte[] imageBytes = Convert.FromBase64String(msg);
                    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                    {
                        image = Image.FromStream(ms, true);
                    }
                    SetImage(image);
                }
            }
            catch (InvalidCastException ex)
            {
            }
        }
Exemple #12
0
        // received the data from NB-IoT Gateway
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            if (e.Topic.EndsWith("status")) // /maxlong/broker/imei/{0}/status
            {
                string json = System.Text.Encoding.Default.GetString(e.Message);
                Dictionary <string, string> status = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                string type      = status["type"];
                string timestamp = status["timestamp"];

                if ("heartbeat".Equals(type)) // { "imei":"866425030027611","type":"heartbeat","timestamp":"2019-09-08T06:58:26.436Z","from":"211.77.241.100:12191","step":1,"rssi":-79,"locationAreaCode":10222,"cellId":14723,"accessTechnology":"Cat NB1"}
                {
                    string from = status["from"];
                    string step = status["step"];
                    string rssi = status["rssi"];

                    Println(String.Format("Heartbeat[#{0}] from {1}. RSSI is {2} dBm.", step, from, rssi));
                    SetStatus("on-line", (Color)ColorConverter.ConvertFromString("Green"));
                }
                else if ("disconnect".Equals(type)) // {"imei":"866425030027611","type":"disconnect","timestamp":"2019-09-08T07:15:48.767Z","from":"211.77.241.100:44791"}
                {
                    Println("Disconnected!");
                    SetStatus("off-line", (Color)ColorConverter.ConvertFromString("Red"));
                }
            }
            else if (e.Topic.EndsWith("rx")) // /maxlong/broker/imei/{0}/rx
            {
                Println("RECV - " + ByteArrayToString(e.Message));

                // write data to serial port
                if (bridge != null)
                {
                    bridge.Write(e.Message);
                }
            }
        }
Exemple #13
0
 private void onMqttReceive(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     if (!this.requestHandlers.ContainsKey(e.Topic))
     {
         return;
     }
     this.requestHandlers[e.Topic](e.Message);
 }
Exemple #14
0
 static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     Console.WriteLine("Received");
     //  Console.WriteLine(e.Message.);
     string msg = Encoding.UTF8.GetString(e.Message);
     Console.WriteLine(msg);
     Mapper.buildDictionary();
 }
Exemple #15
0
        private static async void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string[] topicParts = e.Topic.Split('/');

            if (topicParts.Length < 3)
            {
                return;
            }

            string device = topicParts[1];
            string sensor = topicParts[2];
            string value  = System.Text.Encoding.Default.GetString(e.Message);

            string data = "";
            int    i1   = device.IndexOf(':');

            if (i1 < 0)
            {
                return;
            }

            int deviceIndex = int.Parse(device.Substring(i1 + 1));

            DeviceClient dc = _devices[deviceIndex];

            if (topicParts.Length == 5 &&
                device.StartsWith("fridge-monitoring") &&
                sensor.Equals("thermometer"))
            {
                string sensorInfo  = topicParts[3];
                string measurement = topicParts[4];

                if (measurement.Equals("temperature") &&
                    sensorInfo.Equals("0:0"))
                {
                    _lastTemperature = double.Parse(value);
                    data             = $"{{\"temperature\":{_lastTemperature}}}";
                }
            }
            else if (topicParts.Length == 3 &&
                     (sensor.Equals("high") || sensor.Equals("low")))
            {
                _lastTemperature = double.Parse(value);
                data             = $"{{\"{sensor}\":{_lastTemperature}}}";
            }

            if (data.Length > 0)
            {
                Message payload = new Message(System.Text.Encoding.UTF8.GetBytes(data));
                await dc.SendEventAsync(payload);

                Console.Write(DateTime.Now.ToString());
                Console.Write(";");
                Console.Write(device);
                Console.Write(";");
                Console.WriteLine(data);
            }
        }
    private void CLIENT_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
    {
        var topic = e.Topic;
        var msg   = System.Text.Encoding.UTF8.GetString(e.Message);

        Debug.Log(">Receive : topic=" + topic + ", message=" + msg);

        LIST_MQTT_MSG_QUEUE.Enqueue(new MyMqttMsg(topic, msg));
    }
Exemple #17
0
        private void M_client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var msg = TTNMessage.DeserialiseMessage(e);

            if (m_msgReceived != null)
            {
                m_msgReceived(msg);
            }
        }
Exemple #18
0
        // Callback when message is received in topic subscription
        private void _client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            NotifyUser($"Msg rec'd on topic {e.Topic.ToString()}: {System.Text.UTF8Encoding.UTF8.GetString(e.Message)}");

            Telemetry data = JsonConvert.DeserializeObject <Telemetry>(System.Text.UTF8Encoding.UTF8.GetString(e.Message));

            // Update radial guage on UI thread with MQTT response value
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateRadial(data.temperature));
        }
 private void MqttClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     string msg = Encoding.UTF8.GetString(e.Message);
     System.Diagnostics.Debug.WriteLine(msg);
     if (OnMessage != null)
     {
         OnMessage(this, new MessageEventArgs(e.Message));
     }
 }
 private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     var rawMessage = Encoding.UTF8.GetString(e.Message);
     var thingsMessage = ThingsMessage.FromJsonSingle(rawMessage);
     WindReadEvent?.Invoke(this,
         new WindReadEventArgs
         {
             WindMeasurement = WindMeasurement.FromJson(thingsMessage.DataPlain, thingsMessage.NodeEui),
         });
 }
Exemple #21
0
        private void MqttClientReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var apiResponse   = Encoding.UTF8.GetString(e.Message);
            var now           = DateTime.Now;
            var sensorStatus  = JsonConvert.DeserializeObject <Infrastructure.ViewModel.MQTT.IOTSensorResponse>(apiResponse);
            var responseTime  = Convert.ToDateTime(sensorStatus.Time).ToString("yyyy-MM-ddTHH:mm:ss");
            var responseValue = sensorStatus.Value.Length > 0 ? sensorStatus.Value[0] : "0";

            Clients.All.mqttresponse(responseTime, sensorStatus.Id, responseValue);
        }
        private void OnMessageReceived(object sender, MqttMsgPublishEventArgs e)
        {
            var topic = e.Topic.Split('/').LastOrDefault();
            if (string.IsNullOrEmpty(topic))
                return;

            if (!Feed.Actions.ContainsKey(topic.ToLower()))
                return;

            Feed.Actions[topic.ToLower()](Encoding.UTF8.GetString(e.Message));
        }
Exemple #23
0
        private static void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            watch.Stop();
            var msg = Encoding.UTF8.GetString(e.Message);

            Console.Clear();
            Console.WriteLine($"recebido:{msg}");
            Console.WriteLine($"Tempo:{watch.Elapsed}");
            Console.WriteLine("------------------------");
            Console.WriteLine("Digite sua messagem:");
        }
Exemple #24
0
        /// <summary>
        /// MQTT訊息接收與發佈要處理的委派事件
        /// 當 MQTT 訊息有發布或接收的時候,會執行這個委派方法這個方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            // 將接收到的 MQTT 訊息進行解碼
            var fooValue       = Encoding.UTF8.GetString(e.Message);
            var fooMessageType = JsonConvert.DeserializeObject <MessageType>(fooValue);

            // 原生專案 -> 核心 PCL 專案
            // 使用 Prism 事件聚合器,將 ReceiveMessageEvent 型別的非同步訊息送出
            // 在核心 PCL 專案內的訂閱事件委派方法收到之後,會更新其檢視模型
            fooEventAggregator.GetEvent <ReceiveMessageEvent>().Publish(fooMessageType);
        }
        private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            if (e.Topic== DeviceDiscoverCallbackTopic || e.Topic==DeviceSigninTopic)//device register(discover)
            {
                if (DeviceSignIn!=null)
                {
                    DeviceSignIn(this, MQTTDevice.Create(e.Message));
                }

            }
        }
        public void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // handle message received
            string result = System.Text.Encoding.UTF8.GetString(e.Message);

            string topic = e.Topic;
            string[] tokens = topic.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            log.Info("tokens from Device Client : " + tokens);

            this.commandCallback(tokens[2], tokens[4], result);
        }
        private void M_mqtt_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            var msg = JsonConvert.DeserializeObject <TKMessage>(Encoding.UTF8.GetString(e.Message));
            Dictionary <string, string> msgProp = new Dictionary <string, string>();

            msgProp.Add("source", "tktelemetry");
            msgProp.Add("macAddress", msg.macAddress);

            Message messageToPublish = new Message(e.Message, msgProp);

            this.m_broker.Publish(messageToPublish);
        }
Exemple #28
0
 //------------------------------------------------------------------------------------------------------------------------
 private void _mqttClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     var mqttMsg = Encoding.UTF8.GetString(e.Message);
     DebugEx.TraceLog(System.DateTime.Now
                      + ": MqttClient: Received msg: " + mqttMsg
                      + " on topic: " + e.Topic
                      + ", retained: " + e.Retain
                      + ", QoS level: " + e.QosLevel
                      );
     if (OnRxMessagecb != null)
         OnRxMessagecb(System.Text.Encoding.Default.GetString(e.Message), e.Topic);
 }
Exemple #29
0
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string msg = System.Text.Encoding.GetEncoding("Big5").GetString(e.Message);

            messageRichTextBox.Invoke(
                new EventHandler(
                    delegate
            {
                messageRichTextBox.AppendText(msg + "\n");
            }
                    )
                );
        }
Exemple #30
0
        private static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            if (e.Topic == "/RXAUTH")
            {
                string newSerial = Encoding.UTF8.GetString(e.Message);
                var robot = new RobotManager(newSerial);
                if (Robots == null)
                    Robots = new List<RobotManager>();
                Robots.Add(robot);
            }

            Console.WriteLine(e.Topic + " : " + Encoding.UTF8.GetString(e.Message));
        }
Exemple #31
0
        private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
            using (var db = new RawMQTTDataModel())
            {
                var message = new MQTTMessage{
                    Topic=e.Topic, Message = Encoding.UTF8.GetString(e.Message), ReceivedDateTime = DateTime.Now
                };

                db.Messages.Add(message);
                db.SaveChanges();
            }
        }
 private void EventPublished(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     try
     {
         SetText("*** Received Message");
         SetText("*** Topic: " + e.Topic);
         SetText("*** Message: " + System.Text.UTF8Encoding.UTF8.GetString(e.Message));
         SetText("");
     }
     catch (InvalidCastException ex)
     {
     }
 }
Exemple #33
0
 private void EventPublished(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     try
     {
         //SetText("*** Speak: " + ((uPLibrary.Networking.M2Mqtt.MqttClient)sender).ClientId); //uPLibrary.Networking.M2Mqtt.MqttClient.ClientId //TODO!
         SetText("*** Topic: " + e.Topic);
         SetText("*** Message: " + System.Text.UTF8Encoding.UTF8.GetString(e.Message));
         SetText("");
     }
     catch (InvalidCastException ex)
     {
         textBoxInfo.Text += System.Environment.NewLine + ("* Invalid Cast Exception");
     }
 }
Exemple #34
0
 void client_EventPublished(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     try
     {
         log.Info("*** Message Received.");
         log.Info("*** Topic: " + e.Topic);
         log.Info("*** Message: " + System.Text.UTF8Encoding.UTF8.GetString(e.Message));
         log.Info("");
     }
     catch (Exception ex)
     {
         log.Error("Execption has occer in client_EventPublished", ex);
     }
 }
Exemple #35
0
 void client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     try
     {
         if (Subscribes.ContainsKey(e.Topic))
         {
             Received?.Invoke(this, new MQReceiveArgs(Subscribes[e.Topic], e.Message));
         }
         else
         {
             Received?.Invoke(this, new MQReceiveArgs(e.Topic, e.Message));
         }
     }
     catch (Exception ex) { }
 }
Exemple #36
0
        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            switch (e.Topic)
            {
            case secrets.topic_desktop:
                string msg = Encoding.Default.GetString(e.Message);
                handleDesktopMessage(msg);
                break;

            case secrets.topic_test:
            default:
                _log.logReceivedMessage(e);
                break;
            }
        }
        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            string Pesan = Encoding.UTF8.GetString(e.Message);
            switch (e.Topic)
            {
                case "/raspberry/control":
                    WriteMessage(Pesan);
                    break;
                case "/raspberry/status":
                    WriteMessage(Pesan);
                    UpdateState(Pesan);
                    break;
            }

        }
Exemple #38
0
 static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     string Pesan = Encoding.UTF8.GetString(e.Message);
     switch (e.Topic)
     {
         case "/robot/status":
             Console.WriteLine(Pesan);
             break;
         case "/robot/control":
             Console.WriteLine(Pesan);
             break;
         case "/robot/state":
             Console.WriteLine(Pesan);
             break;
     }
 }
Exemple #39
0
        private static void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string[] topicParts = e.Topic.Split('/');

            if (topicParts.Length != 5)
            {
                return;
            }

            string key   = topicParts[4];
            string value = System.Text.Encoding.Default.GetString(e.Message);

            string data = "{'" + key + "':" + value + "}";

            Console.WriteLine(data);
        }
        private static void ClientOnMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            if (!e.DupFlag)
            {
                SensorData data =
                    JsonConvert.DeserializeObject<SensorData>(Encoding.UTF8.GetString(e.Message));

                Console.WriteLine("Received message on topic {0} with device id {1}", e.Topic, data.DeviceId);

                if (e.Topic == Topics.Humidity)
                    _bus.Publish(new HumiditySensorDataReceived(data));

                if (e.Topic == Topics.Temperature)
                    _bus.Publish(new TemperatureSensorDataReceived(data));
            }
        }
Exemple #41
0
        private void M_client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            try
            {
                var msg = TTNMessage.DeserialiseMessage(e);

                if (m_msgReceived != null)
                {
                    m_msgReceived(msg);
                }
            }
            catch
            {
                // Swallow any exceptions during message receive
            }
        }
Exemple #42
0
        void mqtt_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            DateTime now = DateTime.Now;

            if (now < lastSystemRequestTime.AddSeconds(2) || e.Message.Length > 4096 || e.Topic.Length > 256)
            {
                return;
            }

            lastSystemRequestTime = now;

            string[] result = IotList.Action(DecodeAction(e.Topic, Utilities.BytesToString(e.Message)));
            if (result != null)
            {
                Publish(ConfigurationManager.MqttDeviceAnnounce + ConfigurationManager.DeviceName, SystemConfig(result));
            }
        }
Exemple #43
0
 static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     string msg = Encoding.UTF8.GetString(e.Message);
     string top = e.Topic;
     if (top == "doebi/watergun/button" && msg == "DOWN") {
         Debug.Log("trigger down");
     }
     if (top == "doebi/watergun/button" && msg == "UP") {
         Debug.Log("trigger up");
     }
     if (top == "doebi/bullshit/button" && msg == "DOWN") {
         Debug.Log("button down");
     }
     if (top == "doebi/bullshit/button" && msg == "UP") {
         Debug.Log("button up");
     }
 }
 static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     string Pesan = Encoding.UTF8.GetString(e.Message);
     switch (e.Topic)
     {
         case "/home/status":
             var MyRoom = JsonConvert.DeserializeObject<Room>(Pesan);
             StringBuilder sb = new StringBuilder();
             sb.Append("DHT sensor Read() ok, RH = " + MyRoom.Humidity.ToString("F1") + "%, Temp = " + MyRoom.Temperature.ToString("F1") + "°C " + (MyRoom.Temperature * 1.8 + 32).ToString("F1") + "°F <br/>");
             sb.Append("Suara : " + MyRoom.Sound +"<br/>");
             sb.Append("Gas Lpg : " + MyRoom.Gas + "<br/>");
             sb.Append((MyRoom.Movement ? "Ada Gerakan" : "Ruangan Kosong") + "<br/>");
             sb.Append("Cahaya :" + MyRoom.Light + "<br/>");
             //you can put some logic to test threshold here...
             WriteMessage(sb.ToString());
             break;
     }
 }
Exemple #45
0
        private void MqttMsgReceived(MqttMsgPublishEventArgs e)
        {
            var message = new MqttMessage { Message = Encoding.UTF8.GetString(e.Message), Topic = e.Topic };

            List<Action<MqttMessage>> actions = new List<Action<MqttMessage>>();

            lock (_handlers)
            {
                foreach (var handler in _handlers)
                {
                    if (_topicMatcher.TopicsMatch(message, handler.Topic, e.Topic))
                        actions.Add(handler.Action);
                }
            }

            foreach (var action in actions)
                action(message);
        }
Exemple #46
0
        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            var message = UTF8Encoding.UTF8.GetChars(e.Message);

            string command = new string(message);

            Debug.Print("Command is: " + command);

            if (command == "On")
            {
                led.Write(true);

            }
            else
            {
                led.Write(false);

            }
        }
Exemple #47
0
 private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
 {
     try
     {
         DataRecived        = (Encoding.UTF8.GetString(e.Message)).ToString();
         data.WaterData     = DataRecived.Split('/')[1];
         data.WaterLevel    = DataRecived.Split('/')[1].Split(',')[1];
         data.WaterPressure = DataRecived.Split('/')[1].Split(',')[2];
         data.WaterFlow     = DataRecived.Split('/')[1].Split(',')[3];
         data.MotorStatus   = DataRecived.Split('/')[2].Split(',')[1];
         data.Voltage       = DataRecived.Split('/')[2].Split(',')[2];
         data.MotorLoad     = DataRecived.Split('/')[2].Split(',')[3];
         data.Current       = DataRecived.Split('/')[2].Split(',')[4];
         data.CircuitData   = DataRecived.Split('/')[3];
     }
     catch (Exception ex)
     {
     }
 }
Exemple #48
0
        private static async void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string[] topicParts = e.Topic.Split('/');
            Console.WriteLine(e.Topic);
            Console.WriteLine(topicParts[1]);
            string value = System.Text.Encoding.Default.GetString(e.Message);

            Console.WriteLine(value);

            DeviceMessage _dm = new DeviceMessage(value);


            DeviceClient dc = null;

            if (_deviceConnectionStrings.TryGetValue(topicParts[_ac.MQTTDeviceNameIndex], out dc))
            {
                Message eventMessage = new Message(System.Text.Encoding.UTF8.GetBytes(_dm.GetServerMessageJSON()));
                // send message
                await dc.SendEventAsync(eventMessage);
            }
        }
Exemple #49
0
        private static async void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            string[] topicParts = e.Topic.Split('/');

            if (topicParts.Length != 5)
            {
                return;
            }

            string device = topicParts[1];
            string key    = topicParts[4];
            string value  = System.Text.Encoding.Default.GetString(e.Message);

            string data = $"{{\"device\":\"{device}\",\"key\":\"{key}\",\"value\":{value}}}";

            Console.WriteLine(data);
            Message payload = new Message(System.Text.Encoding.UTF8.GetBytes(data));
            await _deviceClient.SendEventAsync(payload);

            Console.WriteLine("Send");
        }
        //MQTT 收到消息转发到本地
        private void MqttPostProperty_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            LOG("reply topic  :" + e.Topic);
            LOG("reply payload:" + Encoding.UTF8.GetString(e.Message));
            iot_message_set message = JsonConvert.DeserializeObject <iot_message_set>(Encoding.UTF8.GetString(e.Message).Replace("1:", ""));
            socket_set      ss      = new socket_set();

            ss.DeviceID = deviceName;
            ss.CMD      = message.@params;
            Socket_LOG(JsonConvert.SerializeObject(ss));

            try
            {
                mysession.Send(JsonConvert.SerializeObject(ss));
                //sc.SendData(JsonConvert.SerializeObject(ss));
            }
            catch {
                Socket_LOG("Socket发送数据失败");
            }
            //Encoding.UTF8.GetString()
        }
Exemple #51
0
        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            string[] topicAry = e.Topic.Split('/');

            try
            {
                if (topicAry.Length <= 3)
                {
                    throw new Exception("Topic must have at least <appid>/d/<deviceid>/<sensorid>");
                }

                switch(topicAry[1].ToUpper())
                {
                    case "D":
                        string message = DecodeMessage(e.Message);

                        Models.Application app = GetApplication(topicAry[0]);
                        if (app == null)
                        {
                            throw new Exception("Application for " + topicAry[0] + " Could not be found!");
                        }

                        string returnJSON = ctLib.Helpers.JsonHelper.ExecuteRESTForString(app.apiuri, "{\"deviceid\":" + topicAry[2] + ",\"sensorid\":\"" + topicAry[3] + "\",\"value\":\"" + message + "\"}", JSONHeaders, HttpMethod.Post);

                        Console.WriteLine("topic: " + e.Topic + "\nmessage: " + message);

                        break;

                    default:
                        return;
                }

            }
            catch(Exception ex)
            {
                Console.WriteLine("ERROR:  " + ex.Message);
            }
        }
 void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     Console.WriteLine(@"Received = " + Encoding.UTF8.GetString(e.Message) + @" on topic " + e.Topic);
     OnDataLayerPublishReceived(e);
 }
Exemple #53
0
 public virtual bool OnPublish(MqttClient client, MqttMsgPublishEventArgs message)
 {
     Composable.GetExport<IXLogger>().Verbose("Mqtt Publish {@m}", message);
     return true;
 }
        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {

            string Message = new string(Encoding.UTF8.GetChars(e.Message));
            if (Message.IndexOf(":") < 1) return;
            // handle message received 
            Debug.Print("Message Received : " + Message);
            string[] splittedMessage = Message.Split(':');
            if (splittedMessage[0] == "ALARM" && splittedMessage[1]=="ON")
            {
                Buzzer.Write(true);
            }
            else
            {
                Buzzer.Write(false);
            }
        }
 protected virtual void OnDataLayerPublishReceived(MqttMsgPublishEventArgs e)
 {
     DataLayerPublishReceived?.Invoke(this, e);
 }
 //Event - when messages is recieved
 private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     IoTSensor sensor = SharedVariables.sensorHandler.getSensorByTopic(e.Topic);
     if (sensor != null)
     {
         sensor.updateValue(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
     }
 }
 void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     Debug.Log("Received: " + System.Text.Encoding.UTF8.GetString(e.Message)  );
 }
 void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
     onMqttMsgPublishReceived(new MqttMsgPublishReceivedEventArgs(e.Message, e.QosLevel, e.Topic));
 }
 /// <summary>
 /// ON receipt of a message from a MQTT broker, process it.
 /// </summary>
 /// <param name="sender">
 /// The MQTT session that raised the event.
 /// </param>
 /// <param name="mqttMsgPublishEventArgs">
 /// The message details that were received.
 /// </param>
 private void OnMessage(object sender, MqttMsgPublishEventArgs mqttMsgPublishEventArgs)
 {
     throw new NotImplementedException();
     //m_MessageHandler.HandleMessage(ref mqttMsgPublishEventArgs.Message);
 }
        private async void mqtt_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            try
            {
                var msg = System.Text.Encoding.UTF8.GetString(e.Message);
                if (msg == "list_nodes")
                {
                    using (var context = new ZvsContext(EntityContextConnection))
                    {
                        foreach (var d in context.Devices)
                        {
                            var cmd = new
                            {
                                Name = d.Name,
                                NodeNumber = d.NodeNumber,
                                Location = d.Location,

                            };
                            Publish(ControlTopicFormat, Newtonsoft.Json.JsonConvert.SerializeObject(cmd));
                     
                        }
                    }
                }
                else
                {
                    var control =
                        Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceCommand>(msg);
                    if (control != null)
                    {
                        using (var context = new ZvsContext(EntityContextConnection))
                        {
                            var device1 =
                                (from d1 in context.Devices where d1.NodeNumber == control.NodeId select d1).FirstOrDefault();
                            if (device1 != null)
                            {
                                if (control.Argument1.ToLower() == "list_commands")
                                {
                                    var topic = this.TopicFormat;
                                    topic = topic.Replace("{NodeNumber}", device1.NodeNumber.ToString());
                                    string cmdList = "";
                                    foreach (var cmd in device1.Commands)
                                    {
                                        var outCmd = new
                                        {
                                            NodeNumber = cmd.Device.NodeNumber,
                                            DeviceId = cmd.DeviceId,
                                            DeviceName = cmd.Device.Name,
                                            Id = cmd.Id,
                                            Name = cmd.Name,
                                            Value = cmd.Value,

                                        };

                                        Publish(topic, Newtonsoft.Json.JsonConvert.SerializeObject(outCmd));
                                    }
                                }
                                else if (control.Argument1.ToLower() == "list_values")
                                {
                                    var topic = this.TopicFormat;
                                    topic = topic.Replace("{NodeNumber}", device1.NodeNumber.ToString());
                                    string cmdList = "";
                                    foreach (var v in device1.Values)
                                    {
                                        var outPro = new
                                        {
                                            NodeNumber = v.Device.NodeNumber,
                                            DeviceId = v.DeviceId,
                                            Genre = v.Genre,
                                            Name = v.Name,
                                            Value = v.Value,
                                            ValueType = v.ValueType                                            
                                        };

                                        Publish(topic, Newtonsoft.Json.JsonConvert.SerializeObject(outPro));
                                    }
                                }
                                else
                                {
                                    var cmd =
                                        (from c in device1.Commands where c.Id == control.CommandId select c)
                                            .FirstOrDefault
                                            ();
                                    if (cmd != null)
                                    {
                                        await
                                            this.RunCommandAsync(cmd.Id, control.Argument1, control.Argument2,
                                                CancellationToken);
                                    }
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception exc)
            {
                Publish(FloodTopic, "Could not process incoming control message:" + exc.ToString());
            }

        }