public async static Task <bool> ServerSubIOT() { DbContextOptions <ContextString> options = new DbContextOptions <ContextString>(); ContextString dbContext = new ContextString(options); var serveriot = dbContext.ServerIOT.FirstOrDefault(); ServerMqttClient mqttClient = new ServerMqttClient(Method.BaiduIOT, 1883, serveriot.ServerMac, serveriot.Name, serveriot.Key); mqttClient.InitAsync(); mqttClient.Sub(); var isStop = false; if (serveriot != null) { Thread thread = new Thread(new ThreadStart(() => { while (!isStop) { Thread.Sleep(120000); try { var jsonstr = "{\"reported\": " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "}"; //await mqttClient.PublishAsync(serveriot.ServerMac, jsonstr); mqttClient.PublishAsync(serveriot.ServerMac, jsonstr); } catch (Exception ex) { QMLog qMLog = new QMLog(); qMLog.WriteLogToFile("", ex.ToString()); } finally { Thread.Sleep(10000); } } })); thread.IsBackground = true; thread.Start(); } return(true); }
public async static Task <bool> ServerPublishIOT(ServerMqttClient mqttClient, ServerIOT serveriot) { var _r = true; try { var jsonstr = "{\"reported\": " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "}"; await mqttClient.PublishAsync(serveriot.ServerMac, jsonstr); } catch (Exception ex) { QMLog qMLog = new QMLog(); qMLog.WriteLogToFile("", "发送心跳包失败" + ex.ToString()); _r = false; } return(_r); }