123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880 |
- using App.Shared.DeviceRPC;
- using Applications.FDC;
- using Edge.Core.Processor;
- using Edge.Core.IndustryStandardInterface.Pump;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Wayne.FDCPOSLibrary;
- using Edge.Core.IndustryStandardInterface.NetworkController;
- using Microsoft.Extensions.Logging.Abstractions;
- using System.Text.Json;
- namespace DeviceInfoToAliIotHubViaGateway
- {
-
-
-
-
-
-
-
- public class App : IAppProcessor
- {
- public string MetaConfigName { get; set; }
-
-
-
-
-
-
-
-
- #region 网关与子设备,子设备的动态注册 https://help.aliyun.com/document_detail/73734.html
-
-
-
-
-
- private string dynamicDeviceReg_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/sub/register";
-
-
-
- private string dynamicDeviceReg_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/sub/register_reply";
-
-
-
- private string dynamicDeviceTopoAdd_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add";
-
-
-
- private string dynamicDeviceTopoAdd_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add_reply";
-
-
-
- private string dynamicDeviceTopoDelete_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/delete";
-
-
-
- private string dynamicDeviceTopoDelete_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/delete_reply";
-
-
-
- private string dynamicDeviceTopoGet_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/get";
-
-
-
- private string dynamicDeviceTopoGet_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/get_reply";
-
-
-
- private string dynamicDeviceListFound_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/list/found";
-
-
-
- private string dynamicDeviceListFound_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/list/found_reply";
-
-
-
-
- private string dynamicDeviceTopoAddNotify_Request_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add/notify";
-
-
-
-
- private string dynamicDeviceTopoAddNotify_Response_FormatStr = "/sys/{productKey}/{deviceName}/thing/topo/add/notify_reply";
-
-
-
-
-
-
-
-
-
-
- private string dynamicDeviceOnline_Request_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/login";
-
-
-
-
-
-
-
-
- private string dynamicDeviceOnline_Response_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/login_reply";
-
-
-
-
-
-
-
-
-
-
- private string dynamicDeviceOffline_Request_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/logout";
-
-
-
-
-
-
-
-
- private string dynamicDeviceOffline_Response_FormatStr = "/ext/session/{productKey}/{deviceName}/combine/logout_reply";
- #endregion
-
-
-
-
-
-
-
-
-
-
- #region device specific topic, for Alink JSON
-
-
-
-
-
- private string TopicPropertySetInLocalFormatStr = "/sys/{productKey}/{deviceName}/thing/event/property/post";
-
-
-
- private string TopicPropertySetInLocalReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/event/property/post_reply";
-
-
-
-
-
- private string TopicPropertySetInRemoteFormatStr = "/sys/{productKey}/{deviceName}/thing/service/property/set";
-
-
-
- private string TopicPropertySetInRemoteReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/service/property/set_reply";
-
-
-
-
-
- private string TopicEventFormatStr = "/sys/{productKey}/{deviceName}/thing/event/{tsl.event.identifier}/post";
-
-
-
- private string TopicEventReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/event/{tsl.event.identifier}/post_reply";
-
-
-
-
-
- private string TopicServiceInvokedInRemoteFormatStr = "/sys/{productKey}/{deviceName}/thing/service/{tsl.service.identifier}";
-
-
-
- private string TopicServiceInvokedInRemoteReplyFormatStr = "/sys/{productKey}/{deviceName}/thing/service/{tsl.service.identifier}_reply";
- #endregion
-
-
-
- private List<DynamicDevice2TupleParam> onlineDevices = new List<DynamicDevice2TupleParam>();
-
-
-
-
-
-
-
-
- private FdcServerHostApp fdcServerHostApp = null;
- private bool isStopped = false;
- private bool mqttClientInitialized = false;
- private ILogger logger = NullLogger.Instance;
- private AppConfigV1 appConfig;
- public class AppConfigV1
- {
-
-
-
-
-
-
- public bool EnableGatewayMode { get; set; }
- public AliIotGatewayProductInfo GatewayProductInfo { get; set; }
- public AliIotLogicalNozzleProductInfo LogicalNozzleProductInfo { get; set; }
- }
- public class AliIotGatewayProductInfo
- {
- public string DynamicGatewayDeviceName { get; set; }
- public string ProductKey { get; set; }
- public string ProductSecret { get; set; }
- }
- public class AliIotLogicalNozzleProductInfo
- {
- public string ProductKey { get; set; }
- public string ProductSecret { get; set; }
- public string DynamicDeviceNamePrefix { get; set; }
- }
-
-
-
-
-
-
- public App(IServiceProvider serviceProvider, AppConfigV1 appConfig)
- {
- var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
- this.logger = loggerFactory.CreateLogger("DynamicPrivate_DeviceInfoToAliIotHubViaGateway");
- this.appConfig = appConfig;
- }
- Queue<Tuple<string, byte[]>> publishQueue = new Queue<Tuple<string, byte[]>>();
- public void Init(IEnumerable<IProcessor> processors)
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- this.fdcServerHostApp = processors.OfType<FdcServerHostApp>().FirstOrDefault();
- if (this.fdcServerHostApp == null)
- throw new ArgumentNullException("Can't find the FdcServerHostApp from processors");
- int propertyChangeRequestIdCounter = 1;
- this.fdcServerHostApp.OnStateChange += async (s, a) =>
- {
- if (!this.mqttClientInitialized) return;
- if (this.isStopped) return;
- var pump = s as IFdcPumpController;
- foreach (var nozzle in pump.Nozzles)
- {
- var nozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == pump.PumpId && n.NozzleLogicalId == nozzle.LogicalId);
- if (nozzleExtraInfo?.SiteLevelNozzleId == null) continue;
- var localDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + nozzleExtraInfo.SiteLevelNozzleId;
- AliIotHubMqttClientInitializer initor;
- if (!this.dynamicRegisteredDeviceInfos.TryGetValue(localDeviceName, out initor))
- {
- continue;
- }
- if (initor.MqttClient.QueryStatusAsync().Result != NetworkState.NetworkConnected)
- continue;
-
-
-
-
-
-
-
-
- var request_设备上报属性 = new Alink_PropertyChanging_FromLocal()
- {
- id = propertyChangeRequestIdCounter++.ToString(),
- Params = new Dictionary<string, object>()
- {
- { "LogicalId", nozzle.LogicalId },
- {"SiteLevelNozzleId", nozzleExtraInfo.SiteLevelNozzleId},
- {"ProductName", nozzleExtraInfo.ProductName },
- {"Price", (nozzle.ExpectingPriceOnFcSide / Math.Pow(10, pump.PriceDecimalDigits))??-1 },
- {"PumpId", pump.PumpId },
- {"CurState", (int)(a.NewPumpState) }
- }
- };
-
-
- var pubPropertyResult = await initor.MqttClient.PublishAsync(0,
- this.TopicPropertySetInLocalFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request_设备上报属性)),
- Mqtt_QosLevel.AtMostOnce,
- false);
- if (!pubPropertyResult)
- {
- this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish property to remote for local device: " + localDeviceName + " failed, will skip report local property change");
- }
-
-
-
-
-
- var pubEventResult = await initor.MqttClient.PublishAsync(0,
- this.TopicEventFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName, "OnNozzleStateChanged"),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(
- new Alink_EventFiring_FromLocal("OnNozzleStateChanged")
- {
- id = propertyChangeRequestIdCounter++.ToString(),
- Params = new
- {
- value = new Dictionary<string, object>()
- {
- {"CurState", (int)(a.NewPumpState) }
- }
- }
- })),
- Mqtt_QosLevel.AtMostOnce,
- false);
- if (!pubEventResult)
- {
- this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish event to remote for local device: " + localDeviceName + " failed, will skip report local event firing");
- }
- }
- };
- this.fdcServerHostApp.OnCurrentFuellingStatusChange += async (s, a) =>
- {
- if (!this.mqttClientInitialized) return;
- if (this.isStopped) return;
- var pump = s as IFdcPumpController;
- foreach (var nozzle in pump.Nozzles)
- {
- var nozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == pump.PumpId && n.NozzleLogicalId == nozzle.LogicalId);
- if (nozzleExtraInfo?.SiteLevelNozzleId == null) continue;
- var localDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + nozzleExtraInfo.SiteLevelNozzleId;
- AliIotHubMqttClientInitializer initor;
- if (!this.dynamicRegisteredDeviceInfos.TryGetValue(localDeviceName, out initor))
- {
- continue;
- }
- if (initor.MqttClient.QueryStatusAsync().Result != NetworkState.NetworkConnected)
- continue;
-
-
- var overallStateInfo = new Dictionary<string, object>();
- overallStateInfo.Add("PumpId", pump.PumpId);
- overallStateInfo.Add("LogicalId", nozzle.LogicalId);
- overallStateInfo.Add("SiteLevelNozzleId", nozzleExtraInfo.SiteLevelNozzleId);
- overallStateInfo.Add("ProductName", nozzleExtraInfo.ProductName);
- overallStateInfo.Add("Price", (nozzle.ExpectingPriceOnFcSide / Math.Pow(10, pump.PriceDecimalDigits)) ?? -1);
- if (!a.Transaction.Finished)
- {
- overallStateInfo.Add("CurSaleVol", a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits));
- overallStateInfo.Add("CurSaleAmt", a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits));
- overallStateInfo.Add("CurState", (int)LogicalDeviceState.FDC_FUELLING);
- }
- else
- {
- overallStateInfo.Add("LastSaleVol", a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits));
- overallStateInfo.Add("LastSaleAmt", a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits));
- overallStateInfo.Add("TotalizerVol", (a.Transaction.VolumeTotalizer / Math.Pow(10, pump.VolumeTotalizerDecimalDigits)) ?? -1);
- overallStateInfo.Add("LastSaleTime", (a.FuelingEndTime ?? DateTime.Now).ToString());
- overallStateInfo.Add("CurSaleVol", 0);
- overallStateInfo.Add("CurSaleAmt", 0);
- overallStateInfo.Add("CurState", (int)LogicalDeviceState.FDC_READY);
- }
- var request = new Alink_PropertyChanging_FromLocal()
- {
- id = propertyChangeRequestIdCounter++.ToString(),
- Params = overallStateInfo
- };
-
-
- var pubResult = await initor.MqttClient.PublishAsync(0,
- this.TopicPropertySetInLocalFormatStr.TopicMaker(this.appConfig.LogicalNozzleProductInfo.ProductKey, localDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
- Mqtt_QosLevel.AtMostOnce,
- false);
- if (!pubResult)
- {
- this.logger.LogInformation(" fdcServerHostApp.OnStateChange, publish to remote for local device: " + localDeviceName + " failed, will skip report local property change");
- }
- }
- };
- }
- private int isInPublishStackLoop = 0;
- private int maxQueueDepth = 20;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- private async Task<DynamicDeviceRegResponse> DynamicDeviceRegAsync(string gatewayDeviceProductKey, string gatewayDeviceName,
- IEnumerable<Device3Tuple> subDevices, AliIotHubMqttClientInitializer initor)
- {
- var waitDeviceRegResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceRegResponse>(
- this.dynamicDeviceReg_Response_FormatStr.TopicMaker(gatewayDeviceProductKey, gatewayDeviceName), 10000, Mqtt_QosLevel.AtMostOnce);
- var request = new DynamicDeviceRegRequest()
- {
- id = "223",
- Params = subDevices.Select(p =>
- new DynamicDevice2TupleParam() { productKey = p.ProductKey, deviceName = p.DeviceName }).ToList()
- };
- var pubResult = await initor.MqttClient.PublishAsync(0,
- this.dynamicDeviceReg_Request_FormatStr.TopicMaker(gatewayDeviceProductKey, gatewayDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
- Mqtt_QosLevel.AtMostOnce, false);
- if (!pubResult) return null;
- return await waitDeviceRegResponseTask;
- }
- private async Task<DynamicDeviceTopoAddResponse> DynamicDeviceTopoAddAsync(string gatewayProductKey, string gatewayDeviceName,
- IEnumerable<Device3Tuple> subDevices, AliIotHubMqttClientInitializer initor)
- {
- var waitDeviceTopoAddResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceTopoAddResponse>(
- this.dynamicDeviceTopoAdd_Response_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
- var request = new DynamicDeviceTopoAddRequest()
- {
- id = "123",
- Params = new List<DynamicDeviceTopoAddRequestParam>(),
- };
- foreach (var subDevice in subDevices)
- {
- var subDeviceClientId = subDevice.ProductKey + "&" + subDevice.DeviceName;
- var timestamp = DateTime.Now.Ticks.ToString();
- var toBeHashing = string.Format("clientId{0}deviceName{1}productKey{2}timestamp{3}",
- subDeviceClientId,
- subDevice.DeviceName,
- subDevice.ProductKey,
- timestamp);
- request.Params.Add(
- new DynamicDeviceTopoAddRequestParam()
- {
- productKey = subDevice.ProductKey,
- deviceName = subDevice.DeviceName,
- sign = Encoding.UTF8.GetBytes(toBeHashing).SignWithHMacSHA1(Encoding.UTF8.GetBytes(subDevice.DeviceSecret)),
- timestamp = timestamp,
- clientId = subDeviceClientId
- });
- }
- var pubResult = await initor.MqttClient.PublishAsync(0,
- this.dynamicDeviceTopoAdd_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
- Mqtt_QosLevel.AtMostOnce, false);
- if (!pubResult) return null;
- return await waitDeviceTopoAddResponseTask;
- }
-
-
-
-
-
-
-
- private async Task<DynamicDeviceOnlineResponse> DynamicDeviceOnlineAsync(string gatewayProductKey, string gatewayDeviceName,
- DynamicDeviceRegResponseParam subDevice, AliIotHubMqttClientInitializer initor)
- {
- var waitDeviceOnlineResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceOnlineResponse>(
- this.dynamicDeviceOnline_Response_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
- var subDeviceClientId = subDevice.productKey + "&" + subDevice.deviceName;
- var timestamp = DateTime.Now.Ticks.ToString();
- var toBeHashing = string.Format("clientId{0}deviceName{1}productKey{2}timestamp{3}",
- subDeviceClientId,
- subDevice.deviceName,
- subDevice.productKey,
- timestamp);
- var request = new DynamicDeviceOnlineRequest()
- {
- id = "123",
- Params = new DynamicDeviceOnlineRequestParam()
- {
- productKey = subDevice.productKey,
- deviceName = subDevice.deviceName,
- clientId = subDeviceClientId,
- timestamp = timestamp,
- sign = Encoding.UTF8.GetBytes(toBeHashing).SignWithHMacSHA1(Encoding.UTF8.GetBytes(subDevice.deviceSecret)),
- }
- };
- var pubResult = await initor.MqttClient.PublishAsync(0,
- this.dynamicDeviceOnline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
- Mqtt_QosLevel.AtMostOnce, false);
- if (!pubResult) return null;
- return await waitDeviceOnlineResponseTask;
- }
- private async Task<DynamicDeviceOfflineResponse> DynamicDeviceOfflineAsync(string gatewayProductKey, string gatewayDeviceName,
- Device3Tuple subDevice, AliIotHubMqttClientInitializer initor)
- {
- var waitDeviceOfflineResponseTask = initor.MqttClient.SubscribeAndWaitForThenUnsubscribe<DynamicDeviceOfflineResponse>(
- this.dynamicDeviceOffline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName), 8000, Mqtt_QosLevel.AtMostOnce);
- var request = new DynamicDeviceOfflineRequest()
- {
- id = "123",
- Params = new DynamicDevice2TupleParam()
- {
- productKey = subDevice.ProductKey,
- deviceName = subDevice.DeviceName,
- }
- };
- var pubResult = await initor.MqttClient.PublishAsync(0,
- this.dynamicDeviceOffline_Request_FormatStr.TopicMaker(gatewayProductKey, gatewayDeviceName),
- Encoding.UTF8.GetBytes(JsonSerializer.Serialize(request)),
- Mqtt_QosLevel.AtMostOnce, false);
- if (!pubResult) return null;
- return await waitDeviceOfflineResponseTask;
- }
- internal class DynamicDeviceInfo
- {
- public string clientId { get; set; }
- public string productKey { get; set; }
- public string deviceName { get; set; }
- public string deviceToken { get; set; }
- }
- public Task<bool> Start()
- {
- Task.Run(async () =>
- {
- Thread.Sleep(1000);
- while (true)
- {
- if (!this.mqttClientInitialized)
- {
- this.logger.LogInformation("Initializing Mqtt client...");
- try
- {
- if (this.appConfig.EnableGatewayMode)
- {
-
- var targetDynamicGatewayDeviceName = this.appConfig.GatewayProductInfo.DynamicGatewayDeviceName + "_on_shawn_laptop";
- string aliMqttServerUrl = this.appConfig.GatewayProductInfo.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
- var iotInitor = new AliIotHubMqttClientInitializer(new FastMqttClient(this.logger));
- var dynamicRegistedGatewayDeviceInfo = await iotInitor.DynamicRegDeviceWithoutPreRegAsync(
- aliMqttServerUrl, 1883,
- "23423423shawnLaptopMAC",
- this.appConfig.GatewayProductInfo.ProductKey, this.appConfig.GatewayProductInfo.ProductSecret,
- targetDynamicGatewayDeviceName);
- if (dynamicRegistedGatewayDeviceInfo == null)
- {
- this.logger.LogInformation("DynamicDeviceInitConn failed, will retry later");
- await Task.Delay(5000);
- continue;
- }
-
- var closeResult = await iotInitor.MqttClient.CloseAsync();
- var directConnResult = await iotInitor.DynamicDeviceConnAsync(aliMqttServerUrl, 1883, dynamicRegistedGatewayDeviceInfo);
- this.mqttClientInitialized = true;
- this.onlineDevices = new List<DynamicDevice2TupleParam>();
- #region 子设备的动态注册,即网关FCC来帮助非智能的子设备进行云端逻辑注册
- var pendingForRegistDevices = this.fdcServerHostApp.FdcPumpControllers.SelectMany(
- (p, index) => p.Nozzles,
- (p, nz) => new
- {
- Pump = p,
- Nozzle = nz,
- NozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == p.PumpId && n.NozzleLogicalId == nz.LogicalId)
- }).Where(d => d.NozzleExtraInfo.SiteLevelNozzleId.HasValue).ToList();
- DynamicDeviceRegResponse regResponse = null;
- try
- {
- this.logger.LogInformation($"========>子设备的动态注册,请确保子设备已经预注册了,网关-子设备 不支持 动态注册-免预注册 子设备. total device count: {pendingForRegistDevices.Count()}");
- regResponse = await DynamicDeviceRegAsync(this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName,
- pendingForRegistDevices.Select(d =>
- {
-
-
-
-
-
-
- var remoteDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + d.NozzleExtraInfo.SiteLevelNozzleId;
- return new Device3Tuple(this.appConfig.LogicalNozzleProductInfo.ProductKey, remoteDeviceName, "");
- }), iotInitor);
- if (regResponse == null)
- {
- this.logger.LogInformation(" 子设备的动态注册 failed due to timedout or no data from remote");
- return;
- }
- else if (regResponse.code != 200)
- {
- this.logger.LogInformation(" 子设备的动态注册 failed due to return code: " + regResponse.code
- + ", message: " + (regResponse.message ?? ""));
- return;
- }
- else if (regResponse.data == null || regResponse.data.Count == 0)
- {
- this.logger.LogInformation(" 子设备的动态注册 failed, 请确保子设备已经 预注册 了,因为 网关-子设备 结构下 不支持对子设备进行 动态注册-免预注册");
- break;
- }
- this.logger.LogInformation(" 子设备的动态注册 succeed");
-
- }
- catch (Exception exx)
- {
- this.logger.LogInformation(" 子设备的动态注册 exceptioned: " + exx);
- return;
- }
- #endregion
- #region 添加设备拓扑关系
- try
- {
- this.logger.LogInformation("========>添加设备拓扑关系");
- var topoAddResponse = await DynamicDeviceTopoAddAsync(
- this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName,
- regResponse.data.Select(s => new Device3Tuple(s.productKey, s.deviceName, s.deviceSecret)), iotInitor);
- if (topoAddResponse == null)
- {
- this.logger.LogInformation(" 添加设备拓扑关系 failed due to timedout or no data from remote");
- return;
- }
- else if (topoAddResponse.code != 200)
- {
- this.logger.LogInformation(" 添加设备拓扑关系 failed due to return code: " + topoAddResponse.code);
- return;
- }
- this.logger.LogInformation(" 添加设备拓扑关系 succeed for PumpDevices: "
- + regResponse.data.Select(i => i.deviceName).Aggregate((acc, n) => acc + ", " + n));
- }
- catch (Exception exxx)
- {
- this.logger.LogInformation(" 添加设备拓扑关系 exceptioned: " + exxx);
- return;
- }
- #endregion
- #region 子设备上线
- try
- {
- this.logger.LogInformation("========>子设备上线");
- foreach (var regDevice in regResponse.data)
- {
-
-
-
-
-
-
-
- var onlineResponse
- = await DynamicDeviceOnlineAsync(
- this.appConfig.GatewayProductInfo.ProductKey, targetDynamicGatewayDeviceName, regDevice, iotInitor);
-
- if (onlineResponse == null)
- {
-
-
- continue;
- }
- else if (onlineResponse.code != 200)
- {
-
-
-
- continue;
- }
- this.onlineDevices.Add(onlineResponse.data);
- this.logger.LogInformation(" 子设备上线 succeed for local device: " + regDevice.deviceName);
- }
- }
- catch (Exception exxx)
- {
- this.logger.LogInformation(" 子设备上线 exceptioned: " + exxx);
- return;
- }
- #endregion
- }
- else
- {
- var pendingForRegistDevices = this.fdcServerHostApp.FdcPumpControllers.SelectMany(
- (p, index) => p.Nozzles,
- (p, nz) => new
- {
- Pump = p,
- Nozzle = nz,
- NozzleExtraInfo = this.fdcServerHostApp.GetNozzleExtraInfos().FirstOrDefault(n => n.PumpId == p.PumpId && n.NozzleLogicalId == nz.LogicalId)
- }).Where(d => d.NozzleExtraInfo.SiteLevelNozzleId.HasValue).ToList();
- foreach (var device in pendingForRegistDevices)
- {
- var targetDynamicDeviceName = this.appConfig.LogicalNozzleProductInfo.DynamicDeviceNamePrefix + device.NozzleExtraInfo.SiteLevelNozzleId;
- string aliMqttServerUrl = this.appConfig.LogicalNozzleProductInfo.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
- var iotInitor = new AliIotHubMqttClientInitializer(new FastMqttClient(this.logger));
- var dynamicRegistedDeviceInfo = await iotInitor.DynamicRegDeviceWithoutPreRegAsync(
- aliMqttServerUrl, 1883, "23423423shawnLaptopMAC",
- this.appConfig.LogicalNozzleProductInfo.ProductKey,
- this.appConfig.LogicalNozzleProductInfo.ProductSecret,
- targetDynamicDeviceName);
- if (dynamicRegistedDeviceInfo == null)
- {
- this.logger.LogInformation($"DynamicRegDeviceWithoutPreRegAsync failed for nozzle with sitelevelId: {device.NozzleExtraInfo.SiteLevelNozzleId}");
-
- continue;
- }
- this.dynamicRegisteredDeviceInfos.Add(targetDynamicDeviceName, iotInitor);
-
- var closeResult = await iotInitor.MqttClient.CloseAsync();
- var directConnResult = await iotInitor.DynamicDeviceConnAsync(aliMqttServerUrl, 1883, dynamicRegistedDeviceInfo);
- }
- this.mqttClientInitialized = true;
- }
- }
- catch (Exception exxx)
- {
- logger.LogError("Initializing Mqtt client exceptioned: " + exxx);
- }
- }
- await Task.Delay(1000);
- }
- });
- return Task.FromResult(true);
- }
- private Dictionary<string, AliIotHubMqttClientInitializer> dynamicRegisteredDeviceInfos = new Dictionary<string, AliIotHubMqttClientInitializer>();
- public async Task<bool> Stop()
- {
- return true;
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- }
|