Exemple #1
0
        public void OnTimeSyncResponse(long device_send_time, long server_recv_time, long server_send_time)
        {
            long device_recv_time = Convert.ToInt64(IotUtil.GetTimeStamp());
            long now = (server_recv_time + server_send_time + device_recv_time - device_send_time) / 2;

            Console.WriteLine("now is " + StampToDatetime(now));
        }
        public void FunDeviceShadowSample(string serverUri, int port, string deviceId)
        {
            // 创建设备
            string deviceCertPath = IotUtil.GetRootDirectory() + @"\certificate\deviceCert.pfx";

            if (!File.Exists(deviceCertPath))
            {
                Log.Error("请将设备证书放到根目录!");

                return;
            }

            X509Certificate2 deviceCert = new X509Certificate2(deviceCertPath, "123456");

            // 使用证书创建设备,X509证书接入
            device = new IoTDevice(serverUri, port, deviceId, deviceCert);

            if (device.Init() != 0)
            {
                return;
            }

            device.GetClient().deviceShadowListener = this;

            string guid = Guid.NewGuid().ToString();

            Console.WriteLine(guid);

            string topic = CommonTopic.TOPIC_SYS_SHADOW_GET + "=" + guid;

            device.GetClient().Report(new PubMessage(topic, string.Empty));
        }
Exemple #3
0
        public override void OnSubdevPropertiesSet(string requestId, PropsSet propsSet)
        {
            if (propsSet.deviceId == null)
            {
                return;
            }

            string nodeId = IotUtil.GetNodeIdFromDeviceId(propsSet.deviceId);

            if (nodeId == null)
            {
                return;
            }

            Session session = nodeIdToSesseionDic[nodeId];

            if (session == null)
            {
                Log.Error("session is null ,nodeId:" + nodeId);

                return;
            }

            // 这里我们直接把对象转成string发给子设备,实际场景中可能需要进行一定的编解码转换
            session.channel.WriteAndFlushAsync(JsonUtil.ConvertObjectToJsonString(propsSet));

            // 为了简化处理,我们在这里直接回响应。更合理做法是在子设备处理完后再回响应
            GetClient().RespondPropsSet(requestId, IotResult.SUCCESS);

            Log.Info("WriteAndFlushAsync " + propsSet);
        }
Exemple #4
0
        public override void OnSubdevMessage(DeviceMessage message)
        {
            if (message.deviceId == null)
            {
                return;
            }

            string nodeId = IotUtil.GetNodeIdFromDeviceId(message.deviceId);

            if (nodeId == null)
            {
                return;
            }

            Session session = nodeIdToSesseionDic[nodeId];

            if (session == null)
            {
                Log.Error("session is null ,nodeId:" + nodeId);
                return;
            }

            session.channel.WriteAndFlushAsync(message.content);
            Log.Info("WriteAndFlushAsync " + message.content);
        }
Exemple #5
0
        public override void OnSubdevCommand(string requestId, Command command)
        {
            if (command.deviceId == null)
            {
                return;
            }

            string nodeId = IotUtil.GetNodeIdFromDeviceId(command.deviceId);

            if (nodeId == null)
            {
                return;
            }

            Session session = nodeIdToSesseionDic[nodeId];

            if (session == null)
            {
                Log.Error("session is null ,nodeId is " + nodeId);

                return;
            }

            // 这里我们直接把command对象转成string发给子设备,实际场景中可能需要进行一定的编解码转换
            session.channel.WriteAndFlushAsync(JsonUtil.ConvertObjectToJsonString(command));

            // 为了简化处理,我们在这里直接回命令响应。更合理做法是在子设备处理完后再回响应
            GetClient().RespondCommand(requestId, new CommandRsp(0));
            Log.Info("WriteAndFlushAsync " + command);
        }
Exemple #6
0
        /// <summary>
        /// OTA sample,用来演示如何实现设备升级。
        /// 使用方法:用户在平台上创建升级任务后,修改main函数里设备参数后启动本例,即可看到设备收到升级通知,并下   载升级包进行升级,
        /// 并上报升级结果。在平台上可以看到升级结果
        /// 前提条件:\download\ 其中根目录必须包含download文件夹(可根据情况自定义)
        /// </summary>
        /// <param name="serverUri"></param>
        /// <param name="port"></param>
        /// <param name="deviceId"></param>
        /// <param name="deviceSecret"></param>
        public void FunOTASample(string serverUri, int port, string deviceId, string deviceSecret)
        {
            // 创建设备
            IoTDevice device = new IoTDevice(serverUri, port, deviceId, deviceSecret);

            // package路径必须包含软固件包名称及后缀
            string     packageSavePath = IotUtil.GetRootDirectory() + @"\download\test.bin";
            OTAUpgrade otaSample       = new OTAUpgrade(device, packageSavePath);

            otaSample.Init();
        }
Exemple #7
0
        /// <summary>
        /// 设备侧删除子设备
        /// </summary>
        /// <param name="devicesId">待删除的子设备(设备id)列表,单次删除最大不超过50个设备</param>
        public void ReportDeleteSubDevice(List <string> devicesId)
        {
            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.serviceId = "$sub_device_manager";
            deviceEvent.eventTime = IotUtil.GetTimeStamp();
            deviceEvent.eventType = "delete_sub_device_request";

            Dictionary <string, object> para = new Dictionary <string, object>();

            para.Add("devices", devicesId);
            deviceEvent.paras = para;
            GetClient().ReportEvent(deviceEvent);
        }
Exemple #8
0
        /// <summary>
        /// 批量上报子设备状态
        /// </summary>
        /// <param name="statuses">子设备状态列表</param>
        public void ReportSubDeviceStatus(List <DeviceStatus> statuses)
        {
            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.serviceId = "$sub_device_manager";
            deviceEvent.eventTime = IotUtil.GetTimeStamp();
            deviceEvent.eventType = "sub_device_update_status";

            Dictionary <string, object> para = new Dictionary <string, object>();

            para.Add("device_statuses", statuses);
            deviceEvent.paras = para;
            GetClient().ReportEvent(deviceEvent);
        }
        public void RequestTimeSync()
        {
            Dictionary <string, object> node = new Dictionary <string, object>();

            node.Add("device_send_time", IotUtil.GetTimeStamp());

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "time_sync_request";
            deviceEvent.paras     = node;
            deviceEvent.serviceId = "$time_sync";
            deviceEvent.eventTime = IotUtil.GetEventTime();

            iotDevice.GetClient().messagePublishListener = this;
            iotDevice.GetClient().ReportEvent(deviceEvent);
        }
Exemple #10
0
        /// <summary>
        /// 向平台请求同步子设备信息
        /// </summary>
        protected void SyncSubDevices()
        {
            Log.Info("start to syncSubDevices, local version is " + subDevicesPersistence.GetVersion());

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "sub_device_sync_request";
            deviceEvent.serviceId = "sub_device_manager";
            deviceEvent.eventTime = IotUtil.GetTimeStamp();

            Dictionary <string, object> para = new Dictionary <string, object>();

            para.Add("version", subDevicesPersistence.GetVersion());
            deviceEvent.paras = para;
            GetClient().ReportEvent(deviceEvent);
        }
        /// <summary>
        /// 上报固件版本信息
        /// </summary>
        /// <param name="version">固件版本</param>
        public void ReportVersion(string version)
        {
            Dictionary <string, object> node = new Dictionary <string, object>();

            node.Add("fw_version", version);
            node.Add("sw_version", version);

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "version_report";
            deviceEvent.paras     = node;
            deviceEvent.serviceId = "$ota";
            deviceEvent.eventTime = IotUtil.GetEventTime();

            iotDevice.GetClient().ReportEvent(deviceEvent);
        }
        private void OnPropertiesGet(RawMessage message)
        {
            string requestId = IotUtil.GetRequestId(message.Topic);

            PropsGet propsGet = JsonUtil.ConvertJsonStringToObject <PropsGet>(message.ToString());

            if (propsGet == null)
            {
                return;
            }

            if (propertyListener != null && (propsGet.deviceId == null || propsGet.deviceId == this.deviceId))
            {
                propertyListener.OnPropertiesGet(requestId, propsGet.serviceId);

                return;
            }

            device.OnPropertiesGet(requestId, propsGet);
        }
Exemple #13
0
        public void FunCertificateSample(string serverUri, int port, string deviceId)
        {
            string deviceCertPath = IotUtil.GetRootDirectory() + @"\certificate\deviceCert.pfx";

            if (!File.Exists(deviceCertPath))
            {
                Log.Error("请将设备证书放到根目录!");

                return;
            }

            X509Certificate2 deviceCert = new X509Certificate2(deviceCertPath, "123456");

            // 使用证书创建设备
            IoTDevice device = new IoTDevice(serverUri, port, deviceId, deviceCert);

            if (device.Init() != 0)
            {
                return;
            }

            Dictionary <string, object> json = new Dictionary <string, object>();

            // 按照物模型设置属性
            json["alarm"]              = 1;
            json["temperature"]        = 23.45811;
            json["humidity"]           = 56.89012;
            json["smokeConcentration"] = 89.56723;

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.properties = json;
            serviceProperty.serviceId  = "smokeDetector"; // serviceId要和物模型一致

            List <ServiceProperty> properties = new List <ServiceProperty>();

            properties.Add(serviceProperty);

            device.GetClient().Report(new PubMessage(properties));
        }
        public void OnCommand(RawMessage message)
        {
            string requestId = IotUtil.GetRequestId(message.Topic);

            Command command = JsonUtil.ConvertJsonStringToObject <Command>(message.ToString());

            if (command == null)
            {
                Log.Error("invalid command");

                return;
            }

            if (commandListener != null && (command.deviceId == null || command.deviceId == deviceId))
            {
                commandListener.OnCommand(requestId, command.serviceId, command.commandName, command.paras);

                return;
            }

            device.OnCommand(requestId, command);
        }
        /// <summary>
        /// 上报升级状态
        /// </summary>
        /// <param name="result">升级结果</param>
        /// <param name="progress">升级进度0-100</param>
        /// <param name="version">当前版本</param>
        /// <param name="description">具体失败的原因,可选参数</param>
        public void ReportOtaStatus(int result, int progress, string version, string description)
        {
            Dictionary <string, object> node = new Dictionary <string, object>();

            node.Add("result_code", result);
            node.Add("progress", progress);
            if (description != null)
            {
                node.Add("description", description);
            }

            node.Add("version", version);

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "upgrade_progress_report";
            deviceEvent.paras     = node;
            deviceEvent.serviceId = "$ota";
            deviceEvent.eventTime = IotUtil.GetEventTime();

            iotDevice.GetClient().ReportEvent(deviceEvent);
        }
        /// <summary>
        /// 触发属性变化,SDK会上报变化的属性
        /// </summary>
        /// <param name="serviceId">服务id</param>
        /// <param name="properties">属性列表</param>
        internal void FirePropertiesChanged(string serviceId, string[] properties)
        {
            AbstractService deviceService = GetService(serviceId);

            if (deviceService == null)
            {
                return;
            }

            Dictionary <string, object> props = deviceService.OnRead(properties);

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.serviceId  = deviceService.ServiceId;
            serviceProperty.properties = props;
            serviceProperty.eventTime  = IotUtil.GetEventTime();

            List <ServiceProperty> listProperties = new List <ServiceProperty>();

            listProperties.Add(serviceProperty);

            client.ReportProperties(listProperties);
        }
        private void OnShadowCommand(RawMessage message)
        {
            string requestId = IotUtil.GetRequestId(message.Topic);

            deviceShadowListener.OnShadowCommand(requestId, message.Payload);
        }
Exemple #18
0
        private void DownloadPackage()
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                // 声明HTTP请求
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(otaPackage.url));

                // SSL安全通道认证证书
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => { return(true); });

                myRequest.ClientCertificates.Add(IotUtil.GetCert(@"\certificate\DigiCertGlobalRootCA.crt.pem"));

                WebHeaderCollection wc = new WebHeaderCollection();
                wc.Add("Authorization", "Bearer " + otaPackage.token);
                myRequest.Headers = wc;

                int nfileSize = 0;
                using (WebResponse webResponse = myRequest.GetResponse())
                {
                    using (Stream myStream = webResponse.GetResponseStream())
                    {
                        using (FileStream fs = new FileStream(packageSavePath, FileMode.Create))
                        {
                            using (BinaryWriter bw = new BinaryWriter(fs))
                            {
                                using (BinaryReader br = new BinaryReader(myStream))
                                {
                                    // 向服务器请求,获得服务器的回应数据流
                                    byte[] nbytes    = new byte[1024 * 10];
                                    int    nReadSize = 0;
                                    nReadSize = br.Read(nbytes, 0, 1024 * 10);
                                    nfileSize = nReadSize;
                                    while (nReadSize > 0)
                                    {
                                        bw.Write(nbytes, 0, nReadSize);
                                        nReadSize = br.Read(nbytes, 0, 1024 * 10);
                                    }
                                }
                            }
                        }
                    }
                }

                if (nfileSize == otaPackage.fileSize)
                {
                    string strSHA256 = IotUtil.GetSHA256HashFromFile(packageSavePath);
                    Log.Info("SHA256 = " + strSHA256);

                    otaService.ReportOtaStatus(OTAService.OTA_CODE_SUCCESS, 100, version, null);
                    OnUpgradeSuccess(strSHA256);
                }
            }
            catch (WebException exp)
            {
                otaService.ReportOtaStatus(OTAService.OTA_CODE_DOWNLOAD_TIMEOUT, 0, version, exp.Message);
                OnUpgradeFailure();
            }
            catch (Exception ex)
            {
                otaService.ReportOtaStatus(OTAService.OTA_CODE_INNER_ERROR, 0, version, ex.Message);
                OnUpgradeFailure();
            }
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns></returns>
        public int Connect()
        {
            string caCertPath = @"\certificate\DigiCertGlobalRootCA.crt.pem";

            try
            {
                string timestamp = DateTime.Now.ToString("yyyyMMddHH");
                string clientID  = clientConf.DeviceId + "_0_0_" + timestamp;

                // 对密码进行HmacSHA256加密
                string secret = string.Empty;
                if (!string.IsNullOrEmpty(clientConf.Secret))
                {
                    secret = EncryptUtil.HmacSHA256(clientConf.Secret, timestamp);
                }

                client = new MqttFactory().CreateManagedMqttClient();

                // 判断是否为安全连接
                if (clientConf.Port == 1883)
                {
                    options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithTcpServer(clientConf.ServerUri, clientConf.Port)
                                                 .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT))
                                                 .WithCredentials(clientConf.DeviceId, secret)
                                                 .WithClientId(clientID)
                                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE))
                                                 .WithCleanSession(false)
                                                 .WithProtocolVersion(MqttProtocolVersion.V311)
                                                 .Build())
                              .Build();
                }
                else if (clientConf.Port == 8883 && clientConf.DeviceCert == null)
                {
                    options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithTcpServer(clientConf.ServerUri, clientConf.Port)
                                                 .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT))
                                                 .WithCredentials(clientConf.DeviceId, secret)
                                                 .WithClientId(clientID)
                                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE))
                                                 .WithCleanSession(false)
                                                 .WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        AllowUntrustedCertificates = true,
                        UseTls       = true,
                        Certificates = new List <X509Certificate> {
                            IotUtil.GetCert(caCertPath)
                        },
                        CertificateValidationHandler      = delegate { return(true); },
                        IgnoreCertificateChainErrors      = false,
                        IgnoreCertificateRevocationErrors = false
                    })
                                                 .WithProtocolVersion(MqttProtocolVersion.V311)
                                                 .Build())
                              .Build();
                }
                else
                {
                    // 证书接入平台
                    options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithTcpServer(clientConf.ServerUri, clientConf.Port)
                                                 .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT))
                                                 .WithCredentials(clientConf.DeviceId, string.Empty)
                                                 .WithClientId(clientID)
                                                 .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE))
                                                 .WithCleanSession(false)
                                                 .WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        AllowUntrustedCertificates = true,
                        UseTls       = true,
                        Certificates = new List <X509Certificate> {
                            IotUtil.GetCert(caCertPath), clientConf.DeviceCert
                        },
                        CertificateValidationHandler      = delegate { return(true); },
                        IgnoreCertificateChainErrors      = false,
                        IgnoreCertificateRevocationErrors = false
                    })
                                                 .WithProtocolVersion(MqttProtocolVersion.V311)
                                                 .Build())
                              .Build();
                }

                // 注册事件
                client.ApplicationMessageProcessedHandler = new ApplicationMessageProcessedHandlerDelegate(new Action <ApplicationMessageProcessedEventArgs>(ApplicationMessageProcessedHandlerMethod)); // 消息发布回调

                client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action <MqttApplicationMessageReceivedEventArgs>(MqttApplicationMessageReceived));      // 命令下发回调

                client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(new Action <MqttClientConnectedEventArgs>(OnMqttClientConnected));

                client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(new Action <MqttClientDisconnectedEventArgs>(OnMqttClientDisconnected)); // 连接断开回调

                client.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(new Action <ManagedProcessFailedEventArgs>(OnMqttClientConnectingFailed));

                Log.Info("try to connect to server " + clientConf.ServerUri);

                // 连接平台设备
                client.StartAsync(options);

                mre.WaitOne();

                return(client.IsConnected ? 0 : -1);
            }
            catch (Exception ex)
            {
                Log.Error("SDK.Error: Connect to mqtt server fail, the deviceid is " + clientConf.DeviceId);

                return(-1);
            }
        }