Пример #1
0
        private void OnMqttMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"{DateTime.Now} Received MQTT message. Topic: {e.ApplicationMessage.Topic} Payload: {e.ApplicationMessage.ConvertPayloadToString()}");
            try
            {
                string   parm    = null;
                string[] tokens  = e.ApplicationMessage.Topic.Split('/');
                string   payload = e.ApplicationMessage.ConvertPayloadToString();

                if (tokens.Length != 4)
                {
                    throw new InvalidMqttTopicException();
                }

                GenericDevice device = _hub.GetDeviceByLabel <GenericDevice>(tokens[2]) as GenericDevice;
                if (!string.IsNullOrEmpty(payload))
                {
                    parm = payload;
                }

                device.DoAction(tokens[3], parm);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now} {ex}");
            }
        }
Пример #2
0
        /// <summary>
        /// 客户端收到消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void _client_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            PurVar.PurStatic.WriteToStatus("收到来自客户端" + e.ClientId + ",主题为" + e.ApplicationMessage.Topic + "的消息:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            string strSql  = string.Format("update param_temp set needset=1,setvalue={1} where paramid={0}", e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            string message = _dbHelperMySQL.Updata(strSql);

            PublishRepeater("service/" + PurVar.Repeater.repeaterId.ToString() + "/writeMessage", message);
        }
Пример #3
0
        private void Mqtt_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            _logger.LogInformation($"Received  : {e.ApplicationMessage.Topic}");
            if (e.ApplicationMessage.Topic.ToLower().StartsWith("/devices/telemetry"))
            {
                if (Devices.ContainsKey(e.ClientId))
                {
                    var device = Devices[e.ClientId];

                    Task.Run(async() =>
                    {
                        try
                        {
                            var telemetrys = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, object> >(e.ApplicationMessage.ConvertPayloadToString());
                            var result     = await _dbContext.SaveAsync <TelemetryLatest, TelemetryData>(telemetrys, device, DataSide.ClientSide);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"Can't upload telemetry to device {device.Name}({device.Id}).the payload is {e.ApplicationMessage.ConvertPayloadToString()}");
                        }
                    });
                }
            }
            else if (e.ApplicationMessage.Topic.ToLower().StartsWith("/devices/attributes"))
            {
                if (Devices.ContainsKey(e.ClientId))
                {
                    var device = Devices[e.ClientId];
                    Task.Run(async() =>
                    {
                        try
                        {
                            var attributes = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, object> >(e.ApplicationMessage.ConvertPayloadToString());
                            var result     = await _dbContext.SaveAsync <AttributeLatest, AttributeData>(attributes, device, DataSide.ClientSide);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"Can't upload attributes to device {device.Name}({device.Id}).the payload is \"{e.ApplicationMessage.ConvertPayloadToString()}\"");
                        }
                    });
                }
            }
        }
Пример #4
0
        private async void OnMqttMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"{DateTime.Now} Received MQTT message. Topic: {e.ApplicationMessage.Topic} Payload: {e.ApplicationMessage.ConvertPayloadToString()}");
            using (var operation =
                       _telemetryClient.StartOperation <RequestTelemetry>($"{this.ToString()}: Message Received"))
            {
                _telemetryClient.TrackEvent("MQTT Message Received",
                                            new Dictionary <string, string>()
                {
                    { "Topic", e.ApplicationMessage.Topic },
                    { "Payload", e.ApplicationMessage.ConvertPayloadToString() },
                });
                try
                {
                    string   parm    = null;
                    string[] tokens  = e.ApplicationMessage.Topic.Split('/');
                    string   payload = e.ApplicationMessage.ConvertPayloadToString();

                    if (tokens.Length != 4)
                    {
                        throw new InvalidMqttTopicException();
                    }

                    GenericDevice device = await _hub.GetDeviceByLabel <GenericDevice>(tokens[2]);

                    if (!string.IsNullOrEmpty(payload))
                    {
                        parm = payload;
                    }

                    await device.DoAction(tokens[3], parm);
                }
                catch (Exception ex)
                {
                    operation.Telemetry.Success = false;
                    _telemetryClient.TrackException(ex);
                    Console.WriteLine($"{DateTime.Now} {ex}");
                }
            }
        }
Пример #5
0
 /// <summary>
 /// 客户端收到消息
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void _client_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
 {
     WriteToStatus("收到来自客户端" + e.ClientId + ",主题为" + e.ApplicationMessage.Topic + "的消息:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
 }
Пример #6
0
        /// <summary>
        /// 客户端收到消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void _client_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            //dfsajflasdjf

            PurVar.PurStatic.WriteToStatus("收到来自客户端" + e.ClientId + ",主题为" + e.ApplicationMessage.Topic + "的消息:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            string gettopic = e.ApplicationMessage.Topic;
            string getstr   = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);//得到json字符串

            // string hh = "[{\"mid\": \"123456\",\"nid\": \"321\",\"name\": \"222\" }\r\n]";
            // [{"setValue":0,"StartTemp":32.5}]

            //根据topic选择不同的数据库,有timer?  GPIO?之分,判断选择不同的数据表格,条件为选择的
            if (gettopic.Contains("GPIO"))//[{"setValue":0,"StartTemp":32.5}]
            {
                JArray  getArray = JArray.Parse(getstr);
                JObject job1     = (JObject)getArray[0];


                string setControlStyle;//定时模式、自动模式、手动模式等后面完善
                string setStartHum;
                string setStopHum;
                string setStartTemp;
                string setStopTemp;
                string setDelayTime;
                string setEnable;
                string setSetValue;
                string setGPIOName;
                string sqlstr = "update param_GPIO set GPIOName='" + gettopic + "'";

                if (getstr.Contains("ControlStyle"))
                {
                    setControlStyle = job1["ControlStyle"].ToString(); sqlstr = sqlstr + ", ControlStyle=" + setControlStyle;
                }
                if (getstr.Contains("StartHum"))
                {
                    setStartHum = job1["StartHum"].ToString(); sqlstr = sqlstr + ",StartHum=" + setStartHum;
                }
                if (getstr.Contains("StopHum"))
                {
                    setStopHum = job1["StopHum"].ToString(); sqlstr = sqlstr + ",StopHum=" + setStopHum;
                }
                if (getstr.Contains("Enable"))
                {
                    setEnable = job1["Enable"].ToString(); sqlstr = sqlstr + " ,Enable=" + setEnable;
                }
                if (getstr.Contains("StartTemp"))
                {
                    setStartTemp = job1["StartTemp"].ToString(); sqlstr = sqlstr + ",StartTemp=" + setStartTemp;
                }
                if (getstr.Contains("StopTemp"))
                {
                    setStopTemp = job1["StopTemp"].ToString(); sqlstr = sqlstr + ",StopTemp=" + setStopTemp;
                }
                if (getstr.Contains("DelayTime"))
                {
                    setStartTemp = job1["DelayTime"].ToString(); sqlstr = sqlstr + ",DelayTime=" + setStartTemp;
                }
                if (getstr.Contains("StartTemp"))
                {
                    setDelayTime = job1["StartTemp"].ToString(); sqlstr = sqlstr + ",StartTemp=" + setDelayTime;
                }
                if (getstr.Contains("SetValue"))
                {
                    setSetValue = job1["SetValue"].ToString(); sqlstr = sqlstr + ",SetValue=" + setSetValue;
                }
                if (getstr.Contains("GPIOName"))
                {
                    setGPIOName = job1["GPIOName"].ToString(); sqlstr = sqlstr + ",GPIOName=" + setGPIOName;
                }
                string TstrSql  = string.Format(sqlstr + " where GPIOName='{0}", e.ApplicationMessage.Topic + "'");
                string Tmessage = _dbHelperMySQL.Updata(TstrSql);
                PublishRepeater("service/" + PurVar.Repeater.repeaterId.ToString() + "/writeMessage", Tmessage);
            }
            //订阅 修改定时器Timerx
            if (gettopic.Contains("Timer"))// [{"StartTime":7050,"StopTime":8002}]
            {
                JArray  getArray = JArray.Parse(getstr);
                JObject job1     = (JObject)getArray[0];
                string  setTimerName;
                string  setStartTime;
                string  setStopTime;
                string  setEnable;
                string  setGPIONum;
                string  sqlstr = "update param_timer set TimerNum='" + gettopic + "'";

                if (getstr.Contains("TimerName"))
                {
                    setTimerName = job1["TimerName"].ToString(); sqlstr = sqlstr + ", TimerName=" + setTimerName;
                }
                if (getstr.Contains("StartTime"))
                {
                    setStartTime = job1["StartTime"].ToString(); sqlstr = sqlstr + ",StartTime=" + setStartTime;
                }
                if (getstr.Contains("StopTime"))
                {
                    setStopTime = job1["StopTime"].ToString(); sqlstr = sqlstr + ",StopTime=" + setStopTime;
                }
                if (getstr.Contains("Enable"))
                {
                    setEnable = job1["Enable"].ToString(); sqlstr = sqlstr + " ,Enable=" + setEnable;
                }
                if (getstr.Contains("GPIONum"))
                {
                    setGPIONum = job1["GPIONum"].ToString(); sqlstr = sqlstr + ",GPIONum=" + setGPIONum;
                }
                string TstrSql  = string.Format(sqlstr + " where TimerNum='{0}", e.ApplicationMessage.Topic + "'");
                string Tmessage = _dbHelperMySQL.Updata(TstrSql);
                PublishRepeater("service/" + PurVar.Repeater.repeaterId.ToString() + "/writeMessage", Tmessage);
            }
            //订阅增加定时器为了方便区别上面,timer小写
            if (gettopic.Contains("ADDtimer"))//
            {
            }
            //订阅增加端口为了方便区别上面,gpio小写
            if (gettopic.Contains("ADDgpio"))//
            {
                ////addgpio
            }

            string strSql  = string.Format("update param_temp set needset=1,setvalue={1} where paramid={0}", e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            string message = _dbHelperMySQL.Updata(strSql);

            PublishRepeater("service/" + PurVar.Repeater.repeaterId.ToString() + "/writeMessage", message);
        }