App.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. using App.Shared.DeviceRPC;
  2. using Applications.FDC;
  3. using Edge.Core.Processor;
  4. using Edge.Core.IndustryStandardInterface.Pump;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Wayne.FDCPOSLibrary;
  15. using Edge.Core.IndustryStandardInterface.NetworkController;
  16. using Microsoft.Extensions.Logging.Abstractions;
  17. using System.Text.Json;
  18. namespace DeviceInfoToAliIotHubViaGateway
  19. {
  20. /// <summary>
  21. /// https://help.aliyun.com/document_detail/73734.html
  22. /// 使用子设备动态注册的认证方式,在控制台打开动态注册开关,预注册子设备的DeviceName。
  23. /// 由网关代替子设备进行注册,云端校验子设备DeviceName,校验通过后,动态下发DeviceSecret。
  24. /// 然后子设备通过设备证书(ProductKey、DeviceName和DeviceSecret)接入物联网平台。
  25. /// By using this App which acting as a gateway to delegate multiple products and deivces in a single Mqtt connection.
  26. /// </summary>
  27. public class App : IAppProcessor
  28. {
  29. public string MetaConfigName { get; set; }
  30. /// <summary>
  31. /// 表示客户端ID,建议使用设备的MAC地址或SN码,64字符内,无特殊要求以及关联。
  32. /// </summary>
  33. //public static string AliIotHub_LocalClientId = "liteFccCore873645";
  34. //public static string AliIotHub_GatewayProductKey = "a19OTbmuC7g";
  35. //public static string AliIotHub_GatewayDeviceName = "xxEdgeGatewayDevice0";
  36. //public static string AliIotHub_GatewayDeviceSecret = "DbauniPezDmAbNg3hNWP2qe0SM9rIlkr";
  37. //public static string AliIotHub_PumpProductKey = "a19yWoc0Glx";
  38. #region 网关与子设备,子设备的动态注册 https://help.aliyun.com/document_detail/73734.html
  39. /*
  40. * 设备身份注册 https://help.aliyun.com/document_detail/89298.html
  41. *
  42. */
  43. /// <summary>
  44. /// 设备上线之前您需要对设备进行身份注册,标识您的设备
  45. /// 子设备的动态注册, 上行,请求Topic
  46. /// </summary>
  47. private string dynamicDeviceReg_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/sub/register";
  48. /// <summary>
  49. /// 子设备的动态注册, 上行,响应Topic
  50. /// </summary>
  51. private string dynamicDeviceReg_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/sub/register_reply";
  52. /// <summary>
  53. ///添加设备拓扑关系, 上行,请求Topic
  54. /// </summary>
  55. private string dynamicDeviceTopoAdd_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add";
  56. /// <summary>
  57. /// 添加设备拓扑关系, 上行,响应Topic
  58. /// </summary>
  59. private string dynamicDeviceTopoAdd_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add_reply";
  60. /// <summary>
  61. /// 删除设备的拓扑关系, 上行,请求Topic
  62. /// </summary>
  63. private string dynamicDeviceTopoDelete_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/delete";
  64. /// <summary>
  65. /// 删除设备的拓扑关系, 上行,响应Topic
  66. /// </summary>
  67. private string dynamicDeviceTopoDelete_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/delete_reply";
  68. /// <summary>
  69. /// 获取设备的拓扑关系, 上行,请求Topic
  70. /// </summary>
  71. private string dynamicDeviceTopoGet_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/get";
  72. /// <summary>
  73. /// 获取设备的拓扑关系, 上行,响应Topic
  74. /// </summary>
  75. private string dynamicDeviceTopoGet_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/get_reply";
  76. /// <summary>
  77. /// 发现设备列表上报, 上行,请求Topic
  78. /// </summary>
  79. private string dynamicDeviceListFound_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/list/found";
  80. /// <summary>
  81. /// 发现设备列表上报, 上行,响应Topic
  82. /// </summary>
  83. private string dynamicDeviceListFound_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/list/found_reply";
  84. /// <summary>
  85. /// 通知网关添加设备拓扑关系, 上行,请求Topic
  86. /// 通知网关设备对子设备发起添加拓扑关系,可以配合发现设备列表上报功能使用。可以通过数据流转获取设备返回的结果
  87. /// </summary>
  88. private string dynamicDeviceTopoAddNotify_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add/notify";
  89. /// <summary>
  90. /// 通知网关添加设备拓扑关系, 上行,响应Topic
  91. /// 通知网关设备对子设备发起添加拓扑关系,可以配合发现设备列表上报功能使用。可以通过数据流转获取设备返回的结果
  92. /// </summary>
  93. private string dynamicDeviceTopoAddNotify_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add/notify_reply";
  94. /// <summary>
  95. /// 子设备上线, 上行,请求Topic
  96. /// 子设备上下线消息,只支持QoS=0,不支持QoS=1。
  97. /// 子设备上线之前,需在物联网平台为子设备注册身份,建立子设备与网关的拓扑关系。
  98. /// 子设备上线时,物联网平台会根据拓扑关系进行子设备身份校验,以确定子设备是否具备使用网关通道的能力。
  99. ///
  100. /// 因为子设备通过网关通道与物联网平台通信,以上Topic为网关设备的Topic。
  101. /// Topic中变量 ${productKey}和 ${deviceName}需替换为网关设备的对应信息。
  102. /// 消息体中,参数 productKey和 deviceName的值是子设备的对应信息。
  103. /// </summary>
  104. private string dynamicDeviceOnline_Request_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/login";
  105. /// <summary>
  106. /// 子设备上线, 上行,请求Topic
  107. /// 子设备上下线消息,只支持QoS=0,不支持QoS=1。
  108. ///
  109. /// 因为子设备通过网关通道与物联网平台通信,以上Topic为网关设备的Topic。
  110. /// Topic中变量 ${productKey}和 ${deviceName}需替换为网关设备的对应信息。
  111. /// 消息体中,参数 productKey和 deviceName的值是子设备的对应信息。
  112. /// </summary>
  113. private string dynamicDeviceOnline_Response_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/login_reply";
  114. /// <summary>
  115. /// 子设备下线, 上行,请求Topic
  116. /// 子设备上下线消息,只支持QoS=0,不支持QoS=1。
  117. /// 子设备上线之前,需在物联网平台为子设备注册身份,建立子设备与网关的拓扑关系。
  118. /// 子设备上线时,物联网平台会根据拓扑关系进行子设备身份校验,以确定子设备是否具备使用网关通道的能力。
  119. ///
  120. /// 因为子设备通过网关通道与物联网平台通信,以上Topic为网关设备的Topic。
  121. /// Topic中变量 ${productKey}和 ${deviceName}需替换为网关设备的对应信息。
  122. /// 消息体中,参数 productKey和 deviceName的值是子设备的对应信息。
  123. /// </summary>
  124. private string dynamicDeviceOffline_Request_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/logout";
  125. /// <summary>
  126. /// 子设备下线, 上行,请求Topic
  127. /// 子设备上下线消息,只支持QoS=0,不支持QoS=1。
  128. ///
  129. /// 因为子设备通过网关通道与物联网平台通信,以上Topic为网关设备的Topic。
  130. /// Topic中变量 ${productKey}和 ${deviceName}需替换为网关设备的对应信息。
  131. /// 消息体中,参数 productKey和 deviceName的值是子设备的对应信息。
  132. /// </summary>
  133. private string dynamicDeviceOffline_Response_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/logout_reply";
  134. #endregion
  135. /// <summary>
  136. /// productKey:deviceName:deviceSecret
  137. /// </summary>
  138. //internal static List<Device3Tuple> AliIotHub_Pump_DeviceInfos
  139. // = new List<Device3Tuple>()
  140. // {
  141. // new Device3Tuple(AliIotHub_PumpProductKey,"Pump1","dK3iVP4kFS8NGNVpawlEEJnKahDt2YBw"),
  142. // new Device3Tuple(AliIotHub_PumpProductKey,"Pump2","mfCtJkAlD4iEoSq4Qg6C7ZXjHTkoGyID"),
  143. // };
  144. //public static string AliIotHub_PumpDeviceSecret = "DbauniPezDmAbNg3hNWP2qe0SM9rIlkr";
  145. #region device specific topic, for Alink JSON
  146. /// <summary>
  147. /// 设备上报属性 上行(Alink JSON)
  148. /// Local device property change at local should publish the msg on this topic.
  149. /// must fill the concrete: deviceName
  150. /// </summary>
  151. private string TopicPropertySetInLocalFormatStr = "/sys/{productKey}/{deviceName}/thing/event/property/post";
  152. /// <summary>
  153. /// 设备上报属性 上行(Alink JSON)云端的回复
  154. /// </summary>
  155. private string TopicPropertySetInLocalReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/event/property/post_reply";
  156. /// <summary>
  157. /// 设置设备属性 下行(Alink JSON)
  158. /// Local device property change at remote should sub the msg on this topic.
  159. /// must fill the concrete: deviceName
  160. /// </summary>
  161. private string TopicPropertySetInRemoteFormatStr = "/sys/{productKey}/{deviceName}/thing/service/property/set";
  162. /// <summary>
  163. /// 设置设备属性 下行(Alink JSON)回复给云端
  164. /// </summary>
  165. private string TopicPropertySetInRemoteReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/service/property/set_reply";
  166. /// <summary>
  167. /// 设备事件上报 上行(Alink JSON)
  168. /// Local device event fire should publish the msg on this topic.
  169. /// must fill the concrete: deviceName
  170. /// </summary>
  171. private string TopicEventFormatStr = "/sys/{productKey}/{deviceName}/thing/event/{tsl.event.identifier}/post";
  172. /// <summary>
  173. /// 设备事件上报 上行(Alink JSON)云端的回复
  174. /// </summary>
  175. private string TopicEventReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/event/{tsl.event.identifier}/post_reply";
  176. /// <summary>
  177. /// 设备服务调用 下行(Alink JSON)
  178. /// Local device service invoked at remote should sub the msg on this topic.
  179. /// must fill the concrete: deviceName
  180. /// </summary>
  181. private string TopicServiceInvokedInRemoteFormatStr = "/sys/{productKey}/{deviceName}/thing/service/{tsl.service.identifier}";
  182. /// <summary>
  183. /// 设备服务调用 下行(Alink JSON)回复给云端
  184. /// </summary>
  185. private string TopicServiceInvokedInRemoteReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/service/{tsl.service.identifier}_reply";
  186. #endregion
  187. /// <summary>
  188. /// successfully online in AliIotHub device info will be kept here.
  189. /// </summary>
  190. private List<DynamicDevice2TupleParam> onlineDevices = new List<DynamicDevice2TupleParam>();
  191. /// <summary>
  192. /// 填写mqttClientId,用于MQTT的底层协议报文。
  193. ///
  194. /// ${clientId}为设备的ID信息。可取任意值,长度在64字符以内。建议使用设备的MAC地址或SN码。
  195. /// securemode为安全模式,TCP直连模式设置为securemode=3,TLS直连为securemode=2。
  196. /// signmethod为算法类型,支持hmacmd5和hmacsha1。
  197. /// </summary>
  198. //public static string AliIotHub_MqttComplexClientId = AliIotHub_LocalClientId + "|securemode=3,signmethod=hmacsha1|";
  199. private FdcServerHostApp fdcServerHostApp = null;
  200. private bool isStopped = false;
  201. private bool mqttClientInitialized = false;
  202. private ILogger logger = NullLogger.Instance;
  203. private AppConfigV1 appConfig;
  204. public class AppConfigV1
  205. {
  206. /// <summary>
  207. /// 是否开启 网关-子设备 模式, 如果开启,将先注册网关设备,其再代理注册各子设备,再上传拓扑结构。
  208. /// 在这种模式下,请确保子设备已经预注册了, 因为在此模式下,不支持 动态注册-免预注册 子设备
  209. ///
  210. /// 否则,各设备都将采用直连方法,可以进行 动态注册-免预注册 流程进行.
  211. /// </summary>
  212. public bool EnableGatewayMode { get; set; }
  213. public AliIotGatewayProductInfo GatewayProductInfo { get; set; }
  214. public AliIotLogicalNozzleProductInfo LogicalNozzleProductInfo { get; set; }
  215. }
  216. public class AliIotGatewayProductInfo
  217. {
  218. public string DynamicGatewayDeviceName { get; set; }
  219. public string ProductKey { get; set; }
  220. public string ProductSecret { get; set; }
  221. }
  222. public class AliIotLogicalNozzleProductInfo
  223. {
  224. public string ProductKey { get; set; }
  225. public string ProductSecret { get; set; }
  226. public string DynamicDeviceNamePrefix { get; set; }
  227. }
  228. //public enum AliIotProductLocalTypeEnum
  229. //{
  230. // FCC_Gateway,
  231. // Pump,
  232. // ATG
  233. //}
  234. public App(IServiceProvider serviceProvider, AppConfigV1 appConfig)
  235. {
  236. var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
  237. this.logger = loggerFactory.CreateLogger("DynamicPrivate_DeviceInfoToAliIotHubViaGateway");
  238. this.appConfig = appConfig;
  239. }
  240. Queue<Tuple<string, byte[]>> publishQueue = new Queue<Tuple<string, byte[]>>();
  241. public void Init(IEnumerable<IProcessor> processors)
  242. {
  243. //var iotNetWorkProcessor = processors.OfType<GenericDeviceProcessor<byte[], Quectel_BC35_G_NBIOT.MessageEntity.MessageBase>>().FirstOrDefault();
  244. //if (iotNetWorkProcessor == null) throw new ArgumentException("Could not find IotNetWorkProcessor(Mqtt) from processors");
  245. //this.mqttClient = iotNetWorkProcessor.Context.Handler as IMqttClientNetworkController;
  246. //var fastMqttClient = new FastMqttClient(this.logger);
  247. //this.mqttClient = fastMqttClient;
  248. //AliIotHubMqttClientInitializer.Default.MqttClient = this.mqttClient;
  249. //this.mqttClient.OnNetworkControllerStateChange += async (a, b) =>
  250. //{
  251. // this.logger.LogInformation("mqttClient.OnNetworkControllerStateChange to " + b.NewState);
  252. //};
  253. //this.mqttClient.OnMessageReceived += (a, b) =>
  254. //{
  255. // // sample of IOT hub cloud side call a service provided by local device.
  256. // //{"method":"thing.service.property.set","id":"12345","version":"1.0","params":{"prop_float":123.452, "prop_int16":333, "prop_bool":1}}
  257. // this.logger.LogTrace("mqttClient OnMessageReceived on topic: " + b.Message.Topic
  258. // + ", msgId: " + b.Message.MessageId
  259. // + ", msg string: " + Encoding.UTF8.GetString(b.Message.Message));
  260. //};
  261. this.fdcServerHostApp = processors.OfType<FdcServerHostApp>().FirstOrDefault();
  262. if (this.fdcServerHostApp == null)
  263. throw new ArgumentNullException("Can't find the FdcServerHostApp from processors");
  264. int propertyChangeRequestIdCounter = 1;
  265. this.fdcServerHostApp.OnStateChange += async (s, a) =>
  266. {
  267. if (!this.mqttClientInitialized) return;
  268. if (this.isStopped) return;
  269. var pump = s as IFdcPumpController;
  270. foreach (var nozzle in pump.Nozzles)
  271. {
  272. var nozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == pump.PumpId && n.NozzleLogicalId == nozzle.LogicalId);
  273. if (nozzleExtraInfo?.SiteLevelNozzleId == null) continue;
  274. var localDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + nozzleExtraInfo.SiteLevelNozzleId;
  275. AliIotHubMqttClientInitializer initor;
  276. if (!this.dynamicRegisteredDeviceInfos.TryGetValue(localDeviceName, out initor))
  277. {
  278. continue;
  279. }
  280. if (initor.MqttClient.QueryStatusAsync().Result != NetworkState.NetworkConnected)
  281. continue;
  282. //var registedRemoteDevice = this.onlineDevices.FirstOrDefault(d => d.deviceName == localDeviceName);
  283. //if (registedRemoteDevice == null)
  284. //{
  285. // this.logger.LogInformation(" fdcServerHostApp.OnStateChange, could not map local device: " + localDeviceName + " to remote Ali device, will skip report local property change");
  286. // return;
  287. //}
  288. //var request = "CurState".WrapToPropertyChangedInLocalJson(a.NewState.ToString(), propertyChangeRequestIdCounter++);
  289. //this.logger.LogDebug("Pump: " + pump.PumpId + " state changed to: " + a.NewPumpState + ", publishing event...");
  290. var request_设备上报属性 = new Alink_PropertyChanging_FromLocal()
  291. {
  292. id = propertyChangeRequestIdCounter++.ToString(),
  293. Params = new Dictionary<string, object>()
  294. {
  295. { "LogicalId", nozzle.LogicalId },
  296. {"SiteLevelNozzleId", nozzleExtraInfo.SiteLevelNozzleId},
  297. {"ProductName", nozzleExtraInfo.ProductName },
  298. {"Price", (nozzle.ExpectingPriceOnFcSide / Math.Pow(10, pump.PriceDecimalDigits))??-1 },
  299. {"PumpId", pump.PumpId },
  300. {"CurState", (int)(a.NewPumpState) }
  301. }
  302. };
  303. //var waitPropertyChangeResponseTask = this.mqttClient.SubscribeAndWaitFor<string>(
  304. // this.TopicPropertySetInLocalReplyFormatStr.TopicMaker(aliDevice.productKey, aliDevice.deviceName), 8000, Mqtt_QosLevel.AtMostOnce);
  305. var pubPropertyResult = await initor.MqttClient.PublishAsync(0,
  306. this.TopicPropertySetInLocalFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName),
  307. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request_设备上报属性)),
  308. Mqtt_QosLevel.AtMostOnce,
  309. false);
  310. if (!pubPropertyResult)
  311. {
  312. this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish property to remote for local device: " + localDeviceName + " failed, will skip report local property change");
  313. }
  314. //var remoteReply = await waitPropertyChangeResponseTask;
  315. //if (remoteReply.Contains("\"code\": 200"))
  316. //{
  317. // this.logger.LogInformation(" remote reply with 200");
  318. //}
  319. var pubEventResult = await initor.MqttClient.PublishAsync(0,
  320. this.TopicEventFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName, "OnNozzleStateChanged"),
  321. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(
  322. new Alink_EventFiring_FromLocal("OnNozzleStateChanged")
  323. {
  324. id = propertyChangeRequestIdCounter++.ToString(),
  325. Params = new
  326. {
  327. value = new Dictionary<string, object>()
  328. {
  329. {"CurState", (int)(a.NewPumpState) }
  330. }
  331. }
  332. })),
  333. Mqtt_QosLevel.AtMostOnce,
  334. false);
  335. if (!pubEventResult)
  336. {
  337. this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish event to remote for local device: " + localDeviceName + " failed, will skip report local event firing");
  338. }
  339. }
  340. };
  341. this.fdcServerHostApp.OnCurrentFuellingStatusChange += async (s, a) =>
  342. {
  343. if (!this.mqttClientInitialized) return;
  344. if (this.isStopped) return;
  345. var pump = s as IFdcPumpController;
  346. foreach (var nozzle in pump.Nozzles)
  347. {
  348. var nozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == pump.PumpId && n.NozzleLogicalId == nozzle.LogicalId);
  349. if (nozzleExtraInfo?.SiteLevelNozzleId == null) continue;
  350. var localDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + nozzleExtraInfo.SiteLevelNozzleId;
  351. AliIotHubMqttClientInitializer initor;
  352. if (!this.dynamicRegisteredDeviceInfos.TryGetValue(localDeviceName, out initor))
  353. {
  354. continue;
  355. }
  356. if (initor.MqttClient.QueryStatusAsync().Result != NetworkState.NetworkConnected)
  357. continue;
  358. //var request = "CurState".WrapToPropertyChangedInLocalJson(a.NewState.ToString(), propertyChangeRequestIdCounter++);
  359. //this.logger.LogDebug("Pump: " + pump.PumpId + " OnCurrentFuellingStatusChange, publishing event...");
  360. var overallStateInfo = new Dictionary<string, object>();
  361. overallStateInfo.Add("PumpId", pump.PumpId);
  362. overallStateInfo.Add("LogicalId", nozzle.LogicalId);
  363. overallStateInfo.Add("SiteLevelNozzleId", nozzleExtraInfo.SiteLevelNozzleId);
  364. overallStateInfo.Add("ProductName", nozzleExtraInfo.ProductName);
  365. overallStateInfo.Add("Price", (nozzle.ExpectingPriceOnFcSide / Math.Pow(10, pump.PriceDecimalDigits)) ?? -1);
  366. if (!a.Transaction.Finished)
  367. {
  368. overallStateInfo.Add("CurSaleVol", a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits));
  369. overallStateInfo.Add("CurSaleAmt", a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits));
  370. overallStateInfo.Add("CurState", (int)LogicalDeviceState.FDC_FUELLING);
  371. }
  372. else
  373. {
  374. overallStateInfo.Add("LastSaleVol", a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits));
  375. overallStateInfo.Add("LastSaleAmt", a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits));
  376. overallStateInfo.Add("TotalizerVol", (a.Transaction.VolumeTotalizer / Math.Pow(10, pump.VolumeTotalizerDecimalDigits)) ?? -1);
  377. overallStateInfo.Add("LastSaleTime", (a.FuelingEndTime ?? DateTime.Now).ToString());
  378. overallStateInfo.Add("CurSaleVol", 0);
  379. overallStateInfo.Add("CurSaleAmt", 0);
  380. overallStateInfo.Add("CurState", (int)LogicalDeviceState.FDC_READY);
  381. }
  382. var request = new Alink_PropertyChanging_FromLocal()
  383. {
  384. id = propertyChangeRequestIdCounter++.ToString(),
  385. Params = overallStateInfo
  386. };
  387. //var waitPropertyChangeResponseTask = this.mqttClient.SubscribeAndWaitFor<string>(
  388. // this.TopicPropertySetInLocalReplyFormatStr.TopicMaker(aliDevice.productKey, aliDevice.deviceName), 8000, Mqtt_QosLevel.AtMostOnce);
  389. var pubResult = await initor.MqttClient.PublishAsync(0,
  390. this.TopicPropertySetInLocalFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName),
  391. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
  392. Mqtt_QosLevel.AtMostOnce,
  393. false);
  394. if (!pubResult)
  395. {
  396. this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish to remote for local device: " + localDeviceName + " failed, will skip report local property change");
  397. }
  398. }
  399. };
  400. }
  401. private int isInPublishStackLoop = 0;
  402. private int maxQueueDepth = 20;
  403. //private async Task KickPublishQueue()
  404. //{
  405. // if (0 == Interlocked.CompareExchange(ref this.isInPublishStackLoop, 1, 0))
  406. // {
  407. // Tuple<string, byte[]> poped;
  408. // while (true)
  409. // {
  410. // while (this.publishQueue.TryDequeue(out poped))
  411. // {
  412. // var succeed = await this.mqttClient.PublishAsync(1,
  413. // poped.Item1,
  414. // poped.Item2, Mqtt_QosLevel.AtLeastOnce, false);
  415. // if (!succeed)
  416. // {
  417. // this.logger.LogInformation(" Publishing to topic: " + poped.Item1 + " failed, will set mqttClientInitialized to false");
  418. // this.mqttClientInitialized = false;
  419. // this.publishQueue.Clear();
  420. // }
  421. // // max stack 5 msg, and remove the old messages.
  422. // if (this.publishQueue.Count > maxQueueDepth) for (int i = 0; i < this.publishQueue.Count - maxQueueDepth; i++) this.publishQueue.Dequeue();
  423. // }
  424. // Thread.Sleep(1000);
  425. // }
  426. // this.isInPublishStackLoop = 0;
  427. // }
  428. //}
  429. //public class AliIotHubJsonFormatResolver : DefaultContractResolver
  430. //{
  431. // protected override string ResolvePropertyName(string propertyName)
  432. // {
  433. // if (propertyName == "Params")
  434. // return propertyName.ToLower();
  435. // return propertyName;
  436. // }
  437. //}
  438. /// <summary>
  439. ///
  440. /// </summary>
  441. /// <param name="gatewayDeviceProductKey"></param>
  442. /// <param name="gatewayDeviceName"></param>
  443. /// <param name="subDevices"></param>
  444. /// <returns></returns>
  445. private async Task<DynamicDeviceRegResponse> DynamicDeviceRegAsync(string gatewayDeviceProductKey, string gatewayDeviceName,
  446. IEnumerable<Device3Tuple> subDevices, AliIotHubMqttClientInitializer initor)
  447. {
  448. var waitDeviceRegResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceRegResponse>(
  449. this.dynamicDeviceReg_Response_FormatStr.TopicMaker(gatewayDeviceProductKey, gatewayDeviceName), 10000, Mqtt_QosLevel.AtMostOnce);
  450. var request = new DynamicDeviceRegRequest()
  451. {
  452. id = "223",
  453. Params = subDevices.Select(p =>
  454. new DynamicDevice2TupleParam() { productKey = p.ProductKey, deviceName = p.DeviceName }).ToList()
  455. };
  456. var pubResult = await initor.MqttClient.PublishAsync(0,
  457. this.dynamicDeviceReg_Request_FormatStr.TopicMaker(gatewayDeviceProductKey, gatewayDeviceName),
  458. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
  459. Mqtt_QosLevel.AtMostOnce, false);
  460. if (!pubResult) return null;
  461. return await waitDeviceRegResponseTask;
  462. }
  463. private async Task<DynamicDeviceTopoAddResponse> DynamicDeviceTopoAddAsync(string gatewayProductKey, string gatewayDeviceName,
  464. IEnumerable<Device3Tuple> subDevices, AliIotHubMqttClientInitializer initor)// string subDeviceProductKey, string subDeviceName, string subDeviceSecret)
  465. {
  466. var waitDeviceTopoAddResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceTopoAddResponse>(
  467. this.dynamicDeviceTopoAdd_Response_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
  468. var request = new DynamicDeviceTopoAddRequest()
  469. {
  470. id = "123",
  471. Params = new List<DynamicDeviceTopoAddRequestParam>(),
  472. };
  473. foreach (var subDevice in subDevices)
  474. {
  475. var subDeviceClientId = subDevice.ProductKey + "&" + subDevice.DeviceName;
  476. var timestamp = DateTime.Now.Ticks.ToString();
  477. var toBeHashing = string.Format("clientId{0}deviceName{1}productKey{2}timestamp{3}",
  478. subDeviceClientId,
  479. subDevice.DeviceName,
  480. subDevice.ProductKey,
  481. timestamp);
  482. request.Params.Add(
  483. new DynamicDeviceTopoAddRequestParam()
  484. {
  485. productKey = subDevice.ProductKey,
  486. deviceName = subDevice.DeviceName,
  487. sign = Encoding.UTF8.GetBytes(toBeHashing).SignWithHMacSHA1(Encoding.UTF8.GetBytes(subDevice.DeviceSecret)),
  488. timestamp = timestamp,
  489. clientId = subDeviceClientId
  490. });
  491. }
  492. var pubResult = await initor.MqttClient.PublishAsync(0,
  493. this.dynamicDeviceTopoAdd_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
  494. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
  495. Mqtt_QosLevel.AtMostOnce, false);
  496. if (!pubResult) return null;
  497. return await waitDeviceTopoAddResponseTask;
  498. }
  499. /// <summary>
  500. /// 单个批次上下线的子设备数量不超过5个
  501. /// </summary>
  502. /// <param name="gatewayProductKey"></param>
  503. /// <param name="gatewayDeviceName"></param>
  504. /// <param name="subDevice"></param>
  505. /// <returns></returns>
  506. private async Task<DynamicDeviceOnlineResponse> DynamicDeviceOnlineAsync(string gatewayProductKey, string gatewayDeviceName,
  507. DynamicDeviceRegResponseParam subDevice, AliIotHubMqttClientInitializer initor)// string subDeviceProductKey, string subDeviceName, string subDeviceSecret)
  508. {
  509. var waitDeviceOnlineResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceOnlineResponse>(
  510. this.dynamicDeviceOnline_Response_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
  511. var subDeviceClientId = subDevice.productKey + "&" + subDevice.deviceName;
  512. var timestamp = DateTime.Now.Ticks.ToString();
  513. var toBeHashing = string.Format("clientId{0}deviceName{1}productKey{2}timestamp{3}",
  514. subDeviceClientId,
  515. subDevice.deviceName,
  516. subDevice.productKey,
  517. timestamp);
  518. var request = new DynamicDeviceOnlineRequest()
  519. {
  520. id = "123",
  521. Params = new DynamicDeviceOnlineRequestParam()
  522. {
  523. productKey = subDevice.productKey,
  524. deviceName = subDevice.deviceName,
  525. clientId = subDeviceClientId,
  526. timestamp = timestamp,
  527. sign = Encoding.UTF8.GetBytes(toBeHashing).SignWithHMacSHA1(Encoding.UTF8.GetBytes(subDevice.deviceSecret)),
  528. }
  529. };
  530. var pubResult = await initor.MqttClient.PublishAsync(0,
  531. this.dynamicDeviceOnline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
  532. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
  533. Mqtt_QosLevel.AtMostOnce, false);
  534. if (!pubResult) return null;
  535. return await waitDeviceOnlineResponseTask;
  536. }
  537. private async Task<DynamicDeviceOfflineResponse> DynamicDeviceOfflineAsync(string gatewayProductKey, string gatewayDeviceName,
  538. Device3Tuple subDevice, AliIotHubMqttClientInitializer initor)// string subDeviceProductKey, string subDeviceName, string subDeviceSecret)
  539. {
  540. var waitDeviceOfflineResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceOfflineResponse>(
  541. this.dynamicDeviceOffline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
  542. var request = new DynamicDeviceOfflineRequest()
  543. {
  544. id = "123",
  545. Params = new DynamicDevice2TupleParam()
  546. {
  547. productKey = subDevice.ProductKey,
  548. deviceName = subDevice.DeviceName,
  549. }
  550. };
  551. var pubResult = await initor.MqttClient.PublishAsync(0,
  552. this.dynamicDeviceOffline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
  553. Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
  554. Mqtt_QosLevel.AtMostOnce, false);
  555. if (!pubResult) return null;
  556. return await waitDeviceOfflineResponseTask;
  557. }
  558. internal class DynamicDeviceInfo
  559. {
  560. public string clientId { get; set; }
  561. public string productKey { get; set; }
  562. public string deviceName { get; set; }
  563. public string deviceToken { get; set; }
  564. }
  565. public Task<bool> Start()
  566. {
  567. Task.Run(async () =>
  568. {
  569. Thread.Sleep(1000);
  570. while (true)
  571. {
  572. if (!this.mqttClientInitialized)
  573. {
  574. this.logger.LogInformation("Initializing Mqtt client...");
  575. try
  576. {
  577. if (this.appConfig.EnableGatewayMode)
  578. {
  579. // regist the gateway device first
  580. var targetDynamicGatewayDeviceName = this.appConfig.GatewayProductInfo.DynamicGatewayDeviceName + "_on_shawn_laptop";
  581. string aliMqttServerUrl = this.appConfig.GatewayProductInfo.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
  582. var iotInitor = new AliIotHubMqttClientInitializer(new FastMqttClient(this.logger));
  583. var dynamicRegistedGatewayDeviceInfo = await iotInitor.DynamicRegDeviceWithoutPreRegAsync(
  584. aliMqttServerUrl, 1883,
  585. "23423423shawnLaptopMAC",
  586. this.appConfig.GatewayProductInfo.ProductKey, this.appConfig.GatewayProductInfo.ProductSecret,
  587. targetDynamicGatewayDeviceName);
  588. if (dynamicRegistedGatewayDeviceInfo == null)
  589. {
  590. this.logger.LogInformation("DynamicDeviceInitConn failed, will retry later");
  591. await Task.Delay(5000);
  592. continue;
  593. }
  594. // the close is required, should use real token to conn again.
  595. var closeResult = await iotInitor.MqttClient.CloseAsync();
  596. var directConnResult = await iotInitor.DynamicDeviceConnAsync(aliMqttServerUrl, 1883, dynamicRegistedGatewayDeviceInfo);
  597. this.mqttClientInitialized = true;
  598. this.onlineDevices = new List<DynamicDevice2TupleParam>();
  599. #region 子设备的动态注册,即网关FCC来帮助非智能的子设备进行云端逻辑注册
  600. var pendingForRegistDevices = this.fdcServerHostApp.FdcPumpControllers.SelectMany(
  601. (p, index) => p.Nozzles,
  602. (p, nz) => new
  603. {
  604. Pump = p,
  605. Nozzle = nz,
  606. NozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == p.PumpId && n.NozzleLogicalId == nz.LogicalId)
  607. }).Where(d => d.NozzleExtraInfo.SiteLevelNozzleId.HasValue).ToList();
  608. DynamicDeviceRegResponse regResponse = null;
  609. try
  610. {
  611. this.logger.LogInformation($"========>子设备的动态注册,请确保子设备已经预注册了,网关-子设备 不支持 动态注册-免预注册 子设备. total device count: {pendingForRegistDevices.Count()}");
  612. regResponse = await DynamicDeviceRegAsync(this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName,
  613. pendingForRegistDevices.Select(d =>
  614. {
  615. //var nozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == d.Pump.PumpId && n.NozzleLogicalId == d.Nozzle.LogicalId);
  616. //if (nozzleExtraInfo?.SiteLevelNozzleId == null)
  617. //{
  618. // this.logger.LogInformation($"Nozzle with Logical Nozzle Id: {d.Nozzle.LogicalId} on Pump with PumpId: {d.Pump.PumpId} does not have site level id defined, will not regist it on cloud.");
  619. // continue;
  620. //}
  621. var remoteDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + d.NozzleExtraInfo.SiteLevelNozzleId;
  622. return new Device3Tuple(this.appConfig.LogicalNozzleProductInfo.ProductKey, remoteDeviceName, "");
  623. }), iotInitor);// AliIotHub_Pump_DeviceInfos) ;
  624. if (regResponse == null)
  625. {
  626. this.logger.LogInformation(" 子设备的动态注册 failed due to timedout or no data from remote");
  627. return;
  628. }
  629. else if (regResponse.code != 200)
  630. {
  631. this.logger.LogInformation(" 子设备的动态注册 failed due to return code: " + regResponse.code
  632. + ", message: " + (regResponse.message ?? ""));
  633. return;
  634. }
  635. else if (regResponse.data == null || regResponse.data.Count == 0)
  636. {
  637. this.logger.LogInformation(" 子设备的动态注册 failed, 请确保子设备已经 预注册 了,因为 网关-子设备 结构下 不支持对子设备进行 动态注册-免预注册");
  638. break;
  639. }
  640. this.logger.LogInformation(" 子设备的动态注册 succeed");
  641. // + this.fdcServerHostApp.FdcPumpControllers.Select(i => i.PumpId.ToString()).Aggregate((acc, n) => acc + ", " + n));
  642. }
  643. catch (Exception exx)
  644. {
  645. this.logger.LogInformation(" 子设备的动态注册 exceptioned: " + exx);
  646. return;
  647. }
  648. #endregion
  649. #region 添加设备拓扑关系
  650. try
  651. {
  652. this.logger.LogInformation("========>添加设备拓扑关系");
  653. var topoAddResponse = await DynamicDeviceTopoAddAsync(
  654. this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName,
  655. regResponse.data.Select(s => new Device3Tuple(s.productKey, s.deviceName, s.deviceSecret)), iotInitor);
  656. if (topoAddResponse == null)
  657. {
  658. this.logger.LogInformation(" 添加设备拓扑关系 failed due to timedout or no data from remote");
  659. return;
  660. }
  661. else if (topoAddResponse.code != 200)
  662. {
  663. this.logger.LogInformation(" 添加设备拓扑关系 failed due to return code: " + topoAddResponse.code);
  664. return;
  665. }
  666. this.logger.LogInformation(" 添加设备拓扑关系 succeed for PumpDevices: "
  667. + regResponse.data.Select(i => i.deviceName).Aggregate((acc, n) => acc + ", " + n));
  668. }
  669. catch (Exception exxx)
  670. {
  671. this.logger.LogInformation(" 添加设备拓扑关系 exceptioned: " + exxx);
  672. return;
  673. }
  674. #endregion
  675. #region 子设备上线
  676. try
  677. {
  678. this.logger.LogInformation("========>子设备上线");
  679. foreach (var regDevice in regResponse.data)
  680. {
  681. //var localDeviceName = "Pump" + pump.PumpId;
  682. //var aliDevice = regResponse.data.FirstOrDefault(d => d.deviceName == localDeviceName);
  683. //if (aliDevice == null)
  684. //{
  685. // this.logger.LogInformation(" 子设备上线, could not map local device: " + localDeviceName + " to remote Ali device, will skip online this device");
  686. // continue;
  687. //}
  688. var onlineResponse
  689. = await DynamicDeviceOnlineAsync(
  690. this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName, regDevice, iotInitor);
  691. //new Device3Tuple(aliDevice.productKey, aliDevice.deviceName, aliDevice.deviceSecret));
  692. if (onlineResponse == null)
  693. {
  694. //this.logger.LogInformation(" 子设备上线 failed for local device: " + localDeviceName
  695. // + " due to timedout or no data from remote");
  696. continue;
  697. }
  698. else if (onlineResponse.code != 200)
  699. {
  700. //this.logger.LogInformation(" 子设备上线 failed for local device: " + localDeviceName
  701. // + " due to return code: " + onlineResponse.code
  702. // + ", message: " + (onlineResponse.message ?? ""));
  703. continue;
  704. }
  705. this.onlineDevices.Add(onlineResponse.data);
  706. this.logger.LogInformation(" 子设备上线 succeed for local device: " + regDevice.deviceName);
  707. }
  708. }
  709. catch (Exception exxx)
  710. {
  711. this.logger.LogInformation(" 子设备上线 exceptioned: " + exxx);
  712. return;
  713. }
  714. #endregion
  715. }
  716. else
  717. {
  718. var pendingForRegistDevices = this.fdcServerHostApp.FdcPumpControllers.SelectMany(
  719. (p, index) => p.Nozzles,
  720. (p, nz) => new
  721. {
  722. Pump = p,
  723. Nozzle = nz,
  724. NozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == p.PumpId && n.NozzleLogicalId == nz.LogicalId)
  725. }).Where(d => d.NozzleExtraInfo.SiteLevelNozzleId.HasValue).ToList();
  726. foreach (var device in pendingForRegistDevices)
  727. {
  728. var targetDynamicDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + device.NozzleExtraInfo.SiteLevelNozzleId;
  729. string aliMqttServerUrl = this.appConfig.LogicalNozzleProductInfo.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
  730. var iotInitor = new AliIotHubMqttClientInitializer(new FastMqttClient(this.logger));
  731. var dynamicRegistedDeviceInfo = await iotInitor.DynamicRegDeviceWithoutPreRegAsync(
  732. aliMqttServerUrl, 1883, "23423423shawnLaptopMAC",
  733. this.appConfig.LogicalNozzleProductInfo.ProductKey,
  734. this.appConfig.LogicalNozzleProductInfo.ProductSecret,
  735. targetDynamicDeviceName);
  736. if (dynamicRegistedDeviceInfo == null)
  737. {
  738. this.logger.LogInformation($"DynamicRegDeviceWithoutPreRegAsync failed for nozzle with sitelevelId: {device.NozzleExtraInfo.SiteLevelNozzleId}");
  739. //await Task.Delay(5000);
  740. continue;
  741. }
  742. this.dynamicRegisteredDeviceInfos.Add(targetDynamicDeviceName, iotInitor);
  743. // the close is required, should use real token to conn again.
  744. var closeResult = await iotInitor.MqttClient.CloseAsync();
  745. var directConnResult = await iotInitor.DynamicDeviceConnAsync(aliMqttServerUrl, 1883, dynamicRegistedDeviceInfo);
  746. }
  747. this.mqttClientInitialized = true;
  748. }
  749. }
  750. catch (Exception exxx)
  751. {
  752. logger.LogError("Initializing Mqtt client exceptioned: " + exxx);
  753. }
  754. }
  755. await Task.Delay(1000);
  756. }
  757. });
  758. return Task.FromResult(true);
  759. }
  760. private Dictionary<string, AliIotHubMqttClientInitializer> dynamicRegisteredDeviceInfos = new Dictionary<string, AliIotHubMqttClientInitializer>();
  761. public async Task<bool> Stop()
  762. {
  763. return true;
  764. //bool overallResult = true;
  765. //foreach (var pump in this.fdcServerHostApp.FdcPumpControllers)
  766. //{
  767. // var offlineResponse = await DynamicDeviceOfflineAsync(
  768. // this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName,
  769. // new Device3Tuple(AliIotHub_PumpProductKey, "Pump" + pump.PumpId, ""));// AliIotHub_Pump_DeviceInfos) ;
  770. // if (offlineResponse == null)
  771. // {
  772. // this.logger.LogInformation(" 子设备下线 failed due to timedout or no data from remote");
  773. // overallResult = false;
  774. // }
  775. //}
  776. //return overallResult;
  777. }
  778. }
  779. }