Ejemplo n.º 1
0
        public static async Task SubscribeMQTT(List <string> topicList)
        {
            foreach (string topic in topicList)
            {
                if (topic != "")
                {
                    var topicFilter = new MqttTopicFilterBuilder()
                                      .WithAtLeastOnceQoS()
                                      .WithTopic(topic)
                                      .Build();
                    await mqttClient.SubscribeAsync(topicFilter);
                }
            }
            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                MqttMessageEventArgs messageReceivedEventArgs = new()
                {
                    Topic   = e.ApplicationMessage.Topic,
                    Message = System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload),
                };
                MqttMessageReceived?.Invoke(null, messageReceivedEventArgs);
                Debug.WriteLine("Received Message int topic: " + e.ApplicationMessage.Topic + " : " + System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload));
            });

            return;
        }
Ejemplo n.º 2
0
        private void Client_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            var match = regex.Match(e.ApplicationMessage.Topic);

            if (!match.Success)
            {
                return;
            }

            MqttMessageReceived?.Invoke(match.Groups.Cast <Group>().Skip(1).Select(o => o.Value).ToList(), e);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Index(string key, double jd = 123.373345, double wd = 41.874623)
        {
            if (key == "liuzhe")
            {
                // 设备编码 测试: 1125132097 线上有数据: 1124347989
                var received = new MqttMessageReceived
                {
                    Topic   = "cnc_sbm/gps_card",
                    Payload = "{\"pkid\":\"4475EEDC2BB74F7C8FA6A59CEDB64720\",\"dev_id\":\"1124347989\",\"sxc_zt\":\"1\",\"jd\":\"123.354068\",\"wd\":\"41.857727\",\"gd\":\"0\",\"card_num\":\"1\",\"card_list\":[\"3603631297\"]}",
                    QoS     = new MQTTnet.Protocol.MqttQualityOfServiceLevel(),
                    Retain  = false
                };
                await _schoolBusBusines.MqttMessageReceivedAsync(received);
            }
            await _chatHub.Clients.Group("3603631297").SendAsync("ReceiveMessage", jd, wd);

            return(View());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// TODO Mqtt回调消息处理
        /// </summary>
        /// <param name="received"></param>
        /// <returns></returns>
        public async Task MqttMessageReceivedAsync(MqttMessageReceived received)
        {
            if (!string.IsNullOrEmpty(received.Payload) && received.Payload != "close" && !string.IsNullOrEmpty(received.Topic) && received.Topic == "cnc_sbm/gps_card")
            {
                try
                {
                    var mqttMessage = JsonConvert.DeserializeObject <MqttMessage>(received.Payload);
                    if (int.TryParse(mqttMessage.card_num, out var cardnum) && cardnum > 0)
                    {
                        decimal.TryParse(mqttMessage.jd, out var jd);
                        decimal.TryParse(mqttMessage.wd, out var wd);
                        int.TryParse(mqttMessage.sxc_zt, out var sxcZt);
                        var cardList = mqttMessage.card_list;
                        if (cardList != null && cardList.Count > 0)
                        {
                            #region 记录打卡位置和实时位置
                            var map         = new Dictionary <string, string>();
                            var cardLogList = new List <tcardlog>();
                            foreach (var cardid in cardList)
                            {
                                //await _chatHub.Clients.Group(cardid).SendAsync("ReceiveMessage", jd, wd);
                                await _chatHub.Clients.Group("3603631297").SendAsync("ReceiveMessage", jd, wd);

                                var tcardlog = new tcardlog
                                {
                                    pkid        = Guid.NewGuid().ToString("N"),
                                    fcreatetime = DateTime.Now,
                                    fcode       = mqttMessage.dev_id,
                                    fid         = cardid,
                                    flng        = jd,
                                    flat        = wd,
                                    ftype       = sxcZt
                                };
                                cardLogList.Add(tcardlog);
                                map.TryAdd(cardid, tcardlog.pkid);
                            }

                            if (cardLogList.Count == 1)
                            {
                                await _schoolBusRepository.InsertCardLogAsync(cardLogList.First());
                            }
                            else
                            {
                                await _schoolBusRepository.InsertCardLogListAsync(cardLogList);
                            }
                            await _schoolBusRepository.InsertLocatelogAsync(new tlocatelog { fcreatetime = DateTime.Now, fcode = mqttMessage.dev_id, flng = jd, flat = wd });

                            #endregion

                            #region 推送模板消息和日志
                            var sb = new StringBuilder("SELECT tcard.fname as fname,twxuser.fwxid as fwxid,tdevice.fplatenumber as fplatenumber,tdevice.fdriver,tdevice.fdriverphone,tcard.fid,");
                            sb.Append("case when(tcard.ftrialdate >= now() or (SELECT count(1) FROM tterm INNER JOIN ttermpay ON ttermpay.fk_term_id = tterm.pkid ");
                            // 是否服务判断,未在试用期和付费用户只推送一条上车消息
                            sb.Append("where ttermpay.fcode = tcard.fcode and tterm.fstartdate <= now() and tterm.fenddate >= now()) > 0)");
                            sb.Append("then 1 else 0 end as paystate,");
                            // 判断当天是否推送过消息判断
                            sb.Append("(select count(1) from twxpushlog where twxpushlog.fwxid = twxuser.fwxid and ");
                            sb.Append("to_char(twxpushlog.fcreatetime, 'yyyy-mm-dd') = to_char(now(), 'yyyy-mm-dd')) as wxmsgcount ");
                            sb.Append("FROM tcard LEFT JOIN twxuser ON twxuser.fk_card_id = tcard.pkid LEFT JOIN tdevice ON tdevice.fcode = '" + mqttMessage.dev_id + "' and tdevice.fstate = 0 ");
                            // 2019年3月7日 填加试用和付款筛选 去掉筛选
                            sb.Append("WHERE tcard.fstatus in (0,1) and tcard.fid IN ( '" + cardList[0] + "'");
                            for (var i = 1; i < cardList.Count; i++)
                            {
                                sb.Append(",'" + cardList[i] + "'");
                            }
                            sb.Append(")");

                            var twxpushlogs = new List <twxpushlog>();
                            // 查询系统微信绑定卡记录
                            var userList = await _schoolBusRepository.GetUserBindCardAsync(sb.ToString());

                            foreach (var user in userList)
                            {
                                // paystate:1 付款用户,非付款用户 每天第一次上车 推送一条消息
                                if (user.paystate != 1 && (!int.TryParse(mqttMessage.sxc_zt, out var sxc) || sxc != 1 || user.wxmsgcount != 0))
                                {
                                    continue;
                                }

                                twxpushlogs.Add(new twxpushlog
                                {
                                    fk_id       = map.GetValueOrDefault(user.fid),
                                    fcreatetime = DateTime.Now,
                                    fwxid       = user.fwxid,
                                    fstate      = 1,
                                    fmsg        = "微信id:" + _option.WxOption.WXConfigName + ",模板id:" + _option.WxOption.TemplateId
                                });

                                #region 发送模板消息

#if !DEBUG
                                const string remk       = "\r\n鲸卫士全面上线,关注学生安全,鲸卫士让您实时了解孩子行程!";
                                string       url        = _option.WxOption.Domainnames + "SchoolBus/GoAddress?showType=0&cardLogId=" + map.GetValueOrDefault(user.fid);
                                const string openid     = "ovzSu1Ux_R10fGTWCEawfdVADSy8"; //user.fwxid
                                var          schoolData = new
                                {
                                    first    = new TemplateDataItem("点击查看刷卡位置", "#000000"),
                                    keyword1 = new TemplateDataItem(user.fname, "#000000"),
                                    keyword2 = new TemplateDataItem(DateTime.Now.ToString("HH:mm"), "#000000"),
                                    keyword3 = new TemplateDataItem(user.fplatenumber, "#000000"),
                                    remark   = new TemplateDataItem(remk, "#ff0000")
                                };
                                await Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessageAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, openid, _option.WxOption.TemplateId, url, schoolData, null);
#endif
                                #endregion
                            }
                            await _schoolBusRepository.InsertWXpushlogListAsync(twxpushlogs);

                            #endregion
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task ConnectMqttServerAsync()
        {
            // var logger = _loggerFactory.CreateLogger("MqttHelper");
            IMqttClientOptions MqttOptions()
            {
                var options = new MqttClientOptionsBuilder()
                              .WithClientId(_option.ClientID)
                              .WithTcpServer(_option.HostIp, _option.HostPort)
                              .WithCredentials(_option.UserName, _option.Password)
                              //.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常
                              .WithCleanSession()
                              .Build();

                return(options);
            }

            // Create a new Mqtt client.
            try
            {
                if (MqttClient == null)
                {
                    MqttClient = new MqttFactory().CreateMqttClient();

                    // 接收到消息回调
                    MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
                    {
                        var received = new MqttMessageReceived
                        {
                            Topic   = e.ApplicationMessage.Topic,
                            Payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload),
                            QoS     = e.ApplicationMessage.QualityOfServiceLevel,
                            Retain  = e.ApplicationMessage.Retain
                        };
#if DEBUG
                        //const string path = "E:\\MQTTPayload.txt";
                        //await Tools.WriteTxt(path, received.Payload);
#endif

                        var messageQueue = new SenparcMessageQueue();
                        var key          = SenparcMessageQueue.GenerateKey("MessageHandlerSendMessageAsync", MqttClient.GetType(), Guid.NewGuid().ToString(), "MqttClient.ApplicationMessageReceivedHandler");
                        messageQueue.Add(key, async() =>
                        {
                            _logger.LogWarning("MqttReceivedMsg:\r\n" + received.Payload);
                            await _schoolBusBusines.MqttMessageReceivedAsync(received);
                        });

                        //Console.WriteLine($">> ### 接受消息 ###{Environment.NewLine}");
                        //Console.WriteLine($">> Topic = {received.Topic}{Environment.NewLine}");
                        //Console.WriteLine($">> Payload = {received.Payload}{Environment.NewLine}");
                        //Console.WriteLine($">> QoS = {received.QoS}{Environment.NewLine}");
                        //Console.WriteLine($">> Retain = {received.Retain}{Environment.NewLine}");
                    });

                    // 连接成功回调
                    MqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e =>
                    {
                        Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine);
                        await Subscribe(MqttClient, _option.MqttTopic);
                    });

                    // 断开连接回调
                    MqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
                    {
                        var curTime = DateTime.UtcNow;
                        Console.WriteLine($">> [{curTime.ToLongTimeString()}]");
                        Console.WriteLine("已断开MQTT连接!" + Environment.NewLine);
                        //Reconnecting 重连
                        if (IsReconnect && !e.ClientWasConnected)
                        {
                            Console.WriteLine("正在尝试重新连接" + Environment.NewLine);
                            await Task.Delay(TimeSpan.FromSeconds(5));
                            try
                            {
                                await MqttClient.ConnectAsync(MqttOptions());
                            }
                            catch
                            {
                                Console.WriteLine("### 重新连接 失败 ###" + Environment.NewLine);
                            }
                        }
                        else
                        {
                            Console.WriteLine("已下线!" + Environment.NewLine);
                        }
                    });

                    try
                    {
                        await MqttClient.ConnectAsync(MqttOptions());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("连接到MQTT服务器未知异常!" + Environment.NewLine + e.Message + Environment.NewLine);
            }
        }
        public async Task ConnectToBrokerAsync(string nelloTopicId)
        {
            try
            {
                _nelloTopicId = nelloTopicId;

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(SERVER_ADDRESS, SERVER_PORT)
                              .Build();

                _client.UseDisconnectedHandler(async e =>
                {
                    try
                    {
                        await _client.ReconnectAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseConnectedHandler(async e =>
                {
                    try
                    {
                        foreach (var topic in _mqttListeningTopics)
                        {
                            await SubscribeToTopicAsync(string.Format("{0}{1}/{2}", TOPIC_PREFIX, _nelloTopicId, topic));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                _client.UseApplicationMessageReceivedHandler(e =>
                {
                    try
                    {
                        if (e.ApplicationMessage.Topic.StartsWith("/nello_one"))
                        {
                            var args      = new MqttMessageEventArgs();
                            args.ClientId = e.ClientId;
                            args.Message  = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            args.Topic    = e.ApplicationMessage.Topic;
                            MqttMessageReceived?.Invoke(this, args);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString());
                    }
                });

                await _client.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                _logger.LogError("ConnectToBrokerAsync error:\n" + ex.ToString());
            }
        }
Ejemplo n.º 7
0
        public async Task InitializeAsync()
        {
            Logger        = new TestableLogger();
            LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(c => c.ConfigureTestableLogger(Logger));

            LogoHardwareMock = new LogoHardwareMock();

            var brokerIpAddress = IPAddress.Loopback;
            var brokerPort      = 1889;

            var mqttFactory = new MqttFactory();

            mqttServer = mqttFactory.CreateMqttServer();
            MqttClient = mqttFactory.CreateMqttClient();
            MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => MqttMessageReceived?.Invoke(this, args));

            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithClientId(nameof(IntegrationTestEnvironment) + "Broker")
                                    .WithDefaultEndpointBoundIPAddress(brokerIpAddress)
                                    .WithDefaultEndpointPort(brokerPort)
                                    .Build();

            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(nameof(IntegrationTestEnvironment) + "Client")
                                    .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                    .Build();

            await mqttServer
            .StartAsync(mqttServerOptions)
            .ConfigureAwait(false);

            await MqttClient
            .ConnectAsync(mqttClientOptions)
            .ConfigureAwait(false);

            var config = IntegrationTests.GetConfig(brokerIpAddress.ToString(), brokerPort);

            config.Validate();
            appContext = Logic
                         .Initialize(LoggerFactory, config);
            await appContext
            .Connect()
            .ConfigureAwait(false);
        }