终端一体化运控平台
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

Program.cs 12 KiB

1 anno fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using BPA.PahoMQ;
  2. using Newtonsoft.Json;
  3. using System.Collections.Specialized;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using uPLibrary.Networking.M2Mqtt.Messages;
  8. namespace 阿里云IOT平台测试
  9. {
  10. /// <summary>
  11. /// 以输送线设备作为测试对象
  12. /// </summary>
  13. internal class Program
  14. {
  15. public static bool PropertyReport = false; //属性上报主题订阅标志
  16. //public static bool PropertySet = false; //属性设置主题订阅标志
  17. public static bool EventReport = false; //事件上报主题订阅标志
  18. //public static bool ServiceCall = false; //服务调用主题订阅标志
  19. public static string productKey = "j090GlJPJNv";
  20. //public static string deviceName = "Conveyer";
  21. //public static string deviceSecret = "b3df8aaa82de59f478dffb172acf78cd";
  22. public static string deviceName = "Stock1";
  23. public static string deviceSecret = "b0928d8f6e36aabd94f0fce3f9b02536";
  24. private static MessageHandler _messageHandler;
  25. static void Main(string[] args)
  26. {
  27. //string s= JsonConvert.SerializeObject(new Test());
  28. //string s2 = JsonConvert.SerializeXmlNode();
  29. //string s1 = JsonConvert.SerializeXNode(new Test());
  30. if (_messageHandler == null)
  31. _messageHandler = new MessageHandler(new PahoMQOption()
  32. {
  33. Broker = "iot-06z00carjduqaue.mqtt.iothub.aliyuncs.com",
  34. ProductKey = productKey,
  35. DeviceName = deviceName,
  36. DeviceSecret = deviceSecret,
  37. Port = 1883
  38. });
  39. //云端属性设置主题订阅及回调
  40. _messageHandler.Subscribe((op) =>
  41. {
  42. op.TopicReply = $"/sys/{productKey}/{deviceName}/thing/service/property/set";
  43. op.ThresholdCallback += Op_ThresholdCallback;
  44. });
  45. //服务订阅
  46. var serviceIdentifier = "RecipeSendService";
  47. var serviceTopicReply = $"/sys/{productKey}/{deviceName}/thing/service/{serviceIdentifier}";
  48. _messageHandler.Subscribe((op) =>
  49. {
  50. op.TopicReply = serviceTopicReply;
  51. op.ThresholdCallback += Op_ThresholdCallback1; ; // MqttPostProperty_MqttMsgPublishReceived;
  52. });
  53. Console.WriteLine("云端属性设置主题订阅成功");
  54. Console.WriteLine("云端服务调用主题订阅成功");
  55. ep: string result = Console.ReadLine();
  56. if (result.Equals("属性上报"))
  57. {
  58. //属性上报与订阅
  59. var mqdeviceTestProperty = new PostPropertyParams<StockModel>();
  60. mqdeviceTestProperty.sys = new Sys { ack = 1 };
  61. mqdeviceTestProperty.method = "thing.event.property.post";
  62. mqdeviceTestProperty.version = "1.0";
  63. //默认模板
  64. // mqdeviceTestProperty.Model = new StockModel();
  65. //自定义模板
  66. mqdeviceTestProperty.ModelName = "StockModel";
  67. mqdeviceTestProperty.Model = new StockModel();
  68. mqdeviceTestProperty.Init();
  69. var message = JsonConvert.SerializeObject(mqdeviceTestProperty);
  70. var topic = $"/sys/{productKey}/{deviceName}/thing/event/property/post";//发布主题
  71. var topicReply = $"/sys/{productKey}/{deviceName}/thing/event/property/post_reply";//订阅主题
  72. _messageHandler.Publish((op) =>
  73. {
  74. op.Message = message;
  75. op.Topic = topic;
  76. op.TopicReply = topicReply;
  77. if (!PropertyReport)
  78. {
  79. op.ThresholdCallback += MqttPostProperty_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
  80. PropertyReport = true;
  81. }
  82. });
  83. }
  84. if (result.Equals("事件上报"))
  85. {
  86. string eventIdentifier = "StockModel:StockJerk1StatusEvent";
  87. var mqdeviceTestEvent = new PostEventParams<EventModel>();
  88. mqdeviceTestEvent.id = Guid.NewGuid().ToString();
  89. mqdeviceTestEvent.sys = new Sys { ack = 1 };
  90. mqdeviceTestEvent.method = $"thing.event.{eventIdentifier}.post";
  91. mqdeviceTestEvent.version = "1.0";
  92. mqdeviceTestEvent.@params = new EventParam<EventModel> { value = new EventModel (), time = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds() };
  93. var eventMessage = JsonConvert.SerializeObject(mqdeviceTestEvent);
  94. //事件上报
  95. var eventTopic = $"/sys/{productKey}/{deviceName}/thing/event/{eventIdentifier}/post";
  96. //事件订阅主题
  97. var eventTopicReply = $"/sys/{productKey}/{deviceName}/thing/event/{eventIdentifier}/post_reply";
  98. _messageHandler.Publish((op) =>
  99. {
  100. op.Message = eventMessage;
  101. op.Topic = eventTopic;
  102. op.TopicReply = eventTopicReply;
  103. if (!EventReport)
  104. {
  105. op.ThresholdCallback += MqttPostEvent_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
  106. EventReport= true;
  107. }
  108. });
  109. }
  110. //if (result.Equals("事件上报2"))
  111. //{
  112. // string eventIdentifier = "StockServoFaultEvent";
  113. // var mqdeviceTestEvent = new PostEventParams<EventModel>();
  114. // mqdeviceTestEvent.id = Guid.NewGuid().ToString();
  115. // mqdeviceTestEvent.sys = new Sys { ack = 1 };
  116. // mqdeviceTestEvent.method = $"thing.event.{eventIdentifier}.post";
  117. // mqdeviceTestEvent.version = "1.0";
  118. // mqdeviceTestEvent.@params = new EventParam<EventModel> { value = new EventModel { StockNum = 1 }, time = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds() };
  119. // var eventMessage = JsonConvert.SerializeObject(mqdeviceTestEvent);
  120. // //事件上报
  121. // var eventTopic = $"/sys/{productKey}/{deviceName}/thing/event/{eventIdentifier}/post";
  122. // //事件订阅主题
  123. // var eventTopicReply = $"/sys/{productKey}/{deviceName}/thing/event/{eventIdentifier}/post_reply";
  124. // _messageHandler.Publish((op) =>
  125. // {
  126. // op.Message = eventMessage;
  127. // op.Topic = eventTopic;
  128. // op.TopicReply = eventTopicReply;
  129. // if (!EventReport)
  130. // {
  131. // op.ThresholdCallback += MqttPostEvent_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
  132. // EventReport = true;
  133. // }
  134. // });
  135. // }
  136. goto ep;
  137. }
  138. /// <summary>
  139. /// 云端服务调用回调
  140. /// </summary>
  141. /// <param name="sender"></param>
  142. /// <param name="e"></param>
  143. private static void Op_ThresholdCallback1(object sender, MqttMsgPublishEventArgs e)
  144. {
  145. if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*thing/service/[0-9a-zA-Z:]*$"))
  146. {
  147. Console.WriteLine("---------------------------云端设备服务调用Start---------------------");
  148. Console.WriteLine("reply topic :" + e.Topic);
  149. var rtn = JsonConvert.DeserializeObject<ServiceBaseResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  150. PropertyInfo property = rtn.@params.GetType().GetProperty("Root");
  151. string result = property.GetValue(rtn.@params).ToString();
  152. var array = result.Replace("\r\n", "").Replace(" ", "").Replace("{", "").Replace("}", "").Replace("\"", "").Split(',');
  153. Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  154. Console.WriteLine("---------------------------云端设备服务调用End---------------------");
  155. }
  156. }
  157. /// <summary>
  158. /// 事件上报
  159. /// </summary>
  160. /// <param name="sender"></param>
  161. /// <param name="e"></param>
  162. /// <exception cref="NotImplementedException"></exception>
  163. private static void MqttPostEvent_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
  164. {
  165. if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*thing/event/(?!property).*/(post_reply)$"))
  166. {
  167. Console.WriteLine("---------------------------设备事件上报Start---------------------");
  168. Console.WriteLine("reply topic :" + e.Topic);
  169. var rtn = JsonConvert.DeserializeObject<BaseMqResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  170. Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  171. Console.WriteLine("---------------------------设备事件上报End---------------------");
  172. }
  173. }
  174. /// <summary>
  175. /// 云端属性设置回调
  176. /// </summary>
  177. /// <param name="sender"></param>
  178. /// <param name="e"></param>
  179. /// <exception cref="NotImplementedException"></exception>
  180. private static void Op_ThresholdCallback(object sender, MqttMsgPublishEventArgs e)
  181. {
  182. if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*(thing/service/property/set)$"))
  183. {
  184. Console.WriteLine("---------------------------云端设置属性Start---------------------");
  185. Console.WriteLine("reply topic :" + e.Topic);
  186. var rtn = JsonConvert.DeserializeObject<ServiceBaseResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  187. PropertyInfo property= rtn.@params.GetType().GetProperty("Root");
  188. string result=property.GetValue(rtn.@params).ToString();
  189. var array= result.Replace("\r\n", "").Replace(" ","").Replace("{","").Replace("}","").Replace("\"", "").Split(',');
  190. foreach (var item in array)
  191. {
  192. var str=item.Split(":"); //数据格式:
  193. switch (str[1])
  194. {
  195. }
  196. }
  197. Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  198. Console.WriteLine("---------------------------云端设置属性End---------------------");
  199. }
  200. }
  201. private static void MqttPostProperty_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
  202. {
  203. //考虑使用正则表达判断是属性,事件,服务其中那个回调
  204. if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*thing/event/property/post_reply"))
  205. {
  206. Console.WriteLine("---------------------------设备端属性上报回调Start---------------------");
  207. var rtn = JsonConvert.DeserializeObject<BaseMqResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  208. Console.WriteLine($"code:{rtn.code}");
  209. Console.WriteLine("reply topic :" + e.Topic);
  210. Console.WriteLine("messageID :" + rtn.id);
  211. Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
  212. Console.WriteLine("---------------------------设备端属性上报回调End---------------------");
  213. }
  214. }
  215. }
  216. /// <summary>
  217. /// 属性测试类
  218. /// </summary>
  219. public class StockModel
  220. {
  221. //public string Test { get; set; } = "测试2";
  222. public int StockRealWeight { get; set; } = 250000;
  223. public float BucketRealWeight { get; set; } = 16000;
  224. public string StockBatchStatus { get; set; } = "配料完成";
  225. public int StockWorkModel { get; set; } = 1;
  226. }
  227. /// <summary>
  228. /// 事件测试类
  229. /// </summary>
  230. public class EventModel
  231. {
  232. // public string Result { get; set; }
  233. }
  234. }