/// <summary> /// 根据物接入ID获取一个新的client serivce /// </summary> /// <param name="id"></param> /// <returns></returns> private MqttClientService GetNewMqttServiceByConnectID(long id) { DeviceMonitoringApi deviceApi = new DeviceMonitoringApi(); IoTHubConfigurationModel model = new IoTHubConfigurationModel(); model.ID = id; var conf = deviceApi.GetIoTHubConnection(model); if (conf.Code == -1) { throw new Exception("获取IoTHub连接信息失败" + conf.Msg); } RetIoTHubConfiguration connectInfo = (RetIoTHubConfiguration)conf.Data; string[] ipPort = connectInfo.Url.Replace("http://", "").Replace("HTTP://", "").Split(':'); string ip = ipPort[0]; int port; try { port = ipPort.Count() > 1 ? Int32.Parse(ipPort[1].Replace("/", "")) : 1883; //1883是MQTT Server默认端口 } catch (Exception) { log.Error("[MQTT]获取mqtt server端口号失败: " + connectInfo.Url); throw new Exception("[MQTT]获取mqtt server端口号失败"); } MqttClientService mqttService = new MqttClientService(ip, port, connectInfo.UserName, connectInfo.Password); mqttService.OnMqttConnectNotify += MqttService_OnMqttConnectNotify; if (connectInfo.Type == "1")//直连 { mqttService.OnMqttMessageNotify += MqttService_OnMqttMessageNotify; } else if (connectInfo.Type == "3") { // 研华网关的接入方式 mqttService.OnMqttMessageNotify += MqttService_OnYanhuaMessageNotify; } mqttService.Connect(); container.Add(id, mqttService); return(mqttService); }