Exemple #1
0
        public string Subscribe(string uid, string topicFilter, Action <MqttApplicationMessageReceivedEventArgs> callback)
        {
            if (topicFilter == null)
            {
                throw new ArgumentNullException(nameof(topicFilter));
            }
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            if (string.IsNullOrEmpty(uid))
            {
                uid = Guid.NewGuid().ToString("D");
            }

            lock (Subscribers)
            {
                Subscribers[uid] = new MqttSubscriber(uid, topicFilter, callback);
            }

            // Enqueue all retained messages to match the expected MQTT behavior.
            // Here we have no client per subscription. So we need to adopt some
            // features here manually.
            foreach (var retainedMessage in _serverEx.GetRetainedApplicationMessagesAsync().GetAwaiter().GetResult())
            {
                IncomingMessages.Add(new MqttApplicationMessageReceivedEventArgs(null, retainedMessage));
            }

            return(uid);
        }
Exemple #2
0
            public void ProcessMessageString(string message, long senderId, bool isglobal)
            {
                RawMessage rawMessage = new RawMessage();

                rawMessage.isGlobal       = isglobal;
                rawMessage.SenderReceiver = senderId;

                rawMessage.Type = (MessageType)BitConverter.ToInt32(Convert.FromBase64String(message.Substring(0, 8)), 0);
                rawMessage.Args = Convert.FromBase64String(message.Substring(8));
                IncomingMessages.Add(rawMessage);
            }
Exemple #3
0
        private void ProcessBuffer(byte[] buffer)
        {
            if (_currentIncomingMessage == null)
            {
                _currentIncomingMessage = new mBlockIncomingMessage();
            }

            foreach (var value in buffer)
            {
                /* Received message format
                 *  0xFF - Header Byte 1
                 *  0x55 - Header Byte 2
                 *  0xXX - Message index corresponding to request
                 *  0x0X - Payload Type - 1 byte 2 float 3 short 4 len+string 5 double
                 *  [0xXX....0xXX] Payload matcing size
                 *  0x0D
                 *  0x0A
                 */

                _currentIncomingMessage.AddByte(value);
                if (_currentIncomingMessage.EndsWithCRLF())
                {
                    IncomingMessages.Add(_currentIncomingMessage);

                    if (_currentIncomingMessage.BufferSize > 4)
                    {
                        _currentIncomingMessage.MessageSerialNumber = _currentIncomingMessage.Buffer[2];
                        _logger.NotifyUserInfo("mBlock", $"<<< {_currentIncomingMessage.MessageSerialNumber:X2}. " + _currentIncomingMessage.MessageHexString);

                        ProcessMessage(_currentIncomingMessage);
                    }
                    else
                    {
                        _logger.NotifyUserInfo("mBlock", $"<<< XXXXX. " + _currentIncomingMessage.MessageHexString);
                    }

                    _currentIncomingMessage = new mBlockIncomingMessage();
                }
            }
        }
Exemple #4
0
        private void ProcessBuffer(byte[] buffer)
        {
            if (_currentIncomingMessage == null)
            {
                _currentIncomingMessage = new mBlockIncomingMessage();
            }

            foreach (var value in buffer)
            {
                /* Received message format
                 *  0xFF - Header Byte 1
                 *  0x55 - Header Byte 2
                 *  0xXX - Message index corresponding to request
                 *  0x0X - Payload Type - 1 byte 2 float 3 short 4 len+string 5 double
                 *  [0xXX....0xXX] Payload matcing size
                 *  0x0D
                 *  0x0A
                 */

                _currentIncomingMessage.AddByte(value);
                if (_currentIncomingMessage.EndsWithCRLF())
                {
                    IncomingMessages.Add(_currentIncomingMessage);
                    //     Debug.WriteLine(String.Format("{0:000000} <<<", (DateTime.Now - _start).TotalMilliseconds) + _currentIncomingMessage.MessageHexString);
                    _logger.NotifyUserInfo("mBlock", "<<< " + _currentIncomingMessage.MessageHexString);

                    if (_currentIncomingMessage.BufferSize > 4)
                    {
                        _currentIncomingMessage.MessageSerialNumber = _currentIncomingMessage.Buffer[2];
                        ProcessMessage(_currentIncomingMessage);
                    }

                    _currentIncomingMessage = new mBlockIncomingMessage();
                }
            }
        }
Exemple #5
0
 internal void Server_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     InboundCounter.Increment();
     IncomingMessages.Add(e);
     if (string.IsNullOrEmpty(e.ClientId))
     {
         _logger.LogInformation($"Message: Topic=[{e.ApplicationMessage.Topic }]");
     }
     else
     {
         _logger.LogInformation($"Server received {e.ClientId}'s message: Topic=[{e.ApplicationMessage.Topic }],Retain=[{e.ApplicationMessage.Retain}],QualityOfServiceLevel=[{e.ApplicationMessage.QualityOfServiceLevel}]");
         if (!lstTopics.ContainsKey(e.ApplicationMessage.Topic))
         {
             lstTopics.Add(e.ApplicationMessage.Topic, 1);
             Task.Run(() => _serverEx.PublishAsync("$SYS/broker/subscriptions/count", lstTopics.Count.ToString()));
         }
         else
         {
             lstTopics[e.ApplicationMessage.Topic]++;
         }
         if (e.ApplicationMessage.Payload != null)
         {
             received += e.ApplicationMessage.Payload.Length;
         }
         string topic = e.ApplicationMessage.Topic;
         var    tpary = topic.Split('/', StringSplitOptions.RemoveEmptyEntries);
         if (tpary.Length >= 3 && tpary[0] == "devices" && Devices.ContainsKey(e.ClientId))
         {
             Device device = JudgeOrCreateNewDevice(tpary, Devices[e.ClientId]);
             if (device != null)
             {
                 Dictionary <string, object> keyValues = new Dictionary <string, object>();
                 if (tpary.Length >= 4)
                 {
                     string keyname = tpary.Length >= 5 ? tpary[4] : tpary[3];
                     if (tpary[3].ToLower() == "xml")
                     {
                         try
                         {
                             var xml = new System.Xml.XmlDocument();
                             xml.LoadXml(e.ApplicationMessage.ConvertPayloadToString());
                             keyValues.Add(keyname, xml);
                         }
                         catch (Exception ex)
                         {
                             _logger.LogWarning(ex, $"xml data error {topic},{ex.Message}");
                         }
                     }
                     else if (tpary[3].ToLower() == "binary")
                     {
                         keyValues.Add(keyname, e.ApplicationMessage.Payload);
                     }
                 }
                 else
                 {
                     try
                     {
                         keyValues = e.ApplicationMessage.ConvertPayloadToDictionary();
                     }
                     catch (Exception ex)
                     {
                         _logger.LogWarning(ex, $"ConvertPayloadToDictionary   Error {topic},{ex.Message}");
                     }
                 }
                 if (tpary[2] == "telemetry")
                 {
                     Task.Run(async() =>
                     {
                         try
                         {
                             var result = await _dbContext.SaveAsync <TelemetryLatest, TelemetryData>(keyValues, 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 (tpary[2] == "attributes")
                 {
                     if (tpary.Length > 3 && tpary[3] == "request")
                     {
                         Task.Run(async() =>
                         {
                             await RequestAttributes(tpary, e.ApplicationMessage.ConvertPayloadToDictionary(), device);
                         });
                     }
                     else
                     {
                         Task.Run(async() =>
                         {
                             try
                             {
                                 var result = await _dbContext.SaveAsync <AttributeLatest, AttributeData>(keyValues, 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()}\"");
                             }
                         });
                     }
                 }
             }
         }
     }
 }
Exemple #6
0
 public void Add(ClientMessage msg)
 {
     incomingMessages.Add(msg);
 }