Example #1
0
 private void Send()
 {
     if (Sending == false)
     {
         if (msg.Count() > 0)
         {
             Sending = true;
             Msg m = msg.Dequeue();
             if (m != null)
             {
                 byte[] buf = m.Serialize_Msg();
                 if (socket.CheckConnect())
                 {
                     socket.SendAsync(buf, (ok) =>
                     {
                         if (ok)
                         {
                             Sending = false;
                         }
                     });
                 }
                 else
                 {
                     msg.Enqueue(m);
                 }
             }
         }
     }
 }//end send
Example #2
0
        protected override void DoPost(CoapExchange exchange)
        {
            Task.Run(async() =>
            {
                try
                {
                    Int32 ct = MediaType.TextPlain;
                    Dictionary <string, object> keyValues = new Dictionary <string, object>();
                    if ((ct = MediaType.NegotiationContent(ct, _supported, exchange.Request.GetOptions(OptionType.Accept))) == MediaType.Undefined)
                    {
                        exchange.Respond(StatusCode.NotAcceptable, "supported list: ApplicationJson,TextPlain,TextXml,ApplicationOctetStream");
                        exchange.Reject();
                    }
                    else
                    {
                        if (!exchange.Request.UriQueries.Any())
                        {
                            exchange.Respond(StatusCode.BadRequest, "Forgot the parameters?");
                            exchange.Reject();
                        }
                        else
                        {
                            var querys   = exchange.Request.UriQueries.ToArray();
                            var acctoken = exchange.Request.UriQueries.FirstOrDefault();
                            switch (ct)
                            {
                            case MediaType.ApplicationJson:
                            case MediaType.TextPlain:
                                keyValues = JToken.Parse(exchange.Request.PayloadString)?.JsonToDictionary();
                                break;

                            case MediaType.TextXml:
                                if (querys.Length >= 2)
                                {
                                    var xml = new System.Xml.XmlDocument();
                                    try
                                    {
                                        xml.LoadXml(exchange.Request.PayloadString);
                                    }
                                    catch (Exception ex)
                                    {
                                        exchange.Respond(StatusCode.BadRequest, $"Can't load xml ,{ex.Message}");
                                    }
                                    keyValues.Add(querys[1], xml);
                                }
                                else
                                {
                                    exchange.Respond(StatusCode.BadRequest, "You did not specify  key name for xml.");
                                    exchange.Reject();
                                }
                                break;

                            case MediaType.ApplicationOctetStream:
                                if (querys.Length >= 2)
                                {
                                    keyValues.Add(querys[1], exchange.Request.Payload);
                                }
                                else
                                {
                                    exchange.Respond(StatusCode.BadRequest, "You did not specify  key name for binary.");
                                    exchange.Reject();
                                }
                                break;

                            default:
                                break;
                            }
                            var mcr = await _dbContext.DeviceIdentities.Include(d => d.Device).FirstOrDefaultAsync(di => di.IdentityType == IdentityType.AccessToken && di.IdentityId == acctoken);
                            var dev = mcr?.Device;
                            if (mcr != null && dev != null)
                            {
                                switch (_res)
                                {
                                case CoApRes.Attributes:
                                    _queue.Enqueue(new RawMsg()
                                    {
                                        MsgType = MsgType.CoAP, MsgBody = keyValues, DataCatalog = DataCatalog.AttributeData, DataSide = DataSide.ClientSide, DeviceId = dev.Id
                                    });
                                    exchange.Respond(StatusCode.Changed, $"OK");
                                    break;

                                case CoApRes.Telemetry:
                                    _queue.Enqueue(new RawMsg()
                                    {
                                        MsgType = MsgType.CoAP, MsgBody = keyValues, DataCatalog = DataCatalog.AttributeData, DataSide = DataSide.ClientSide, DeviceId = dev.Id
                                    });
                                    exchange.Respond(StatusCode.Created, $"OK");
                                    break;

                                default:
                                    break;
                                }
                                exchange.Accept();
                            }
                            else
                            {
                                exchange.Respond(StatusCode.NotFound, "Can't found  device.");
                                exchange.Reject();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    exchange.Respond(StatusCode.BadRequest, ex.Message);
                    exchange.Reject();
                }
            });
        }
Example #3
0
 internal void Server_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs 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")
                 {
                     _queue.Enqueue(new RawMsg()
                     {
                         DeviceId = device.Id, MsgBody = keyValues, DataSide = DataSide.ClientSide, DataCatalog = DataCatalog.TelemetryData
                     });
                 }
                 else if (tpary[2] == "attributes")
                 {
                     if (tpary.Length > 3 && tpary[3] == "request")
                     {
                         Task.Run(async() =>
                         {
                             await RequestAttributes(tpary, e.ApplicationMessage.ConvertPayloadToDictionary(), device);
                         });
                     }
                     else
                     {
                         _queue.Enqueue(new RawMsg()
                         {
                             DeviceId = device.Id, MsgBody = keyValues, DataSide = DataSide.ClientSide, DataCatalog = DataCatalog.AttributeData
                         });
                     }
                 }
             }
         }
     }
 }