Ejemplo n.º 1
0
        // Invoke the direct method on the device, passing the payload
        private static async Task InvokeMethodAsync()
        {
            var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30),
            };

            methodInvocation.SetPayloadJson("10");

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync("MyDotnetDevice", methodInvocation);

            Console.WriteLine($"\nResponse status: {response.Status}, payload:\n\t{response.GetPayloadAsJson()}");
        }
Ejemplo n.º 2
0
        private static async Task InvokeMethod()
        {
            var methodInvocation = new CloudToDeviceMethod("writeLine")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson("'a line to be written'");

            var response = await serviceClient.InvokeDeviceMethodAsync("dmTest", methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 3
0
 public async Task InvokeModuleDirectMethodAsync(string edgeDeviceId, string moduleId, string methodName, object body)
 {
     try
     {
         var c2d = new CloudToDeviceMethod(methodName, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
         c2d.SetPayloadJson(JsonConvert.SerializeObject(body));
         await this.GetServiceClient().InvokeDeviceMethodAsync(edgeDeviceId, moduleId, c2d);
     }
     catch (Exception ex)
     {
         TestLogger.Log($"[ERROR] Failed to call direct method, deviceId: {edgeDeviceId}, moduleId: {moduleId}, method: {methodName}: {ex.Message}");
         throw;
     }
 }
Ejemplo n.º 4
0
        public async Task StartMethodJob(string jobId)
        {
            CloudToDeviceMethod directMethod =
                new CloudToDeviceMethod("LockDoor", TimeSpan.FromSeconds(5),
                                        TimeSpan.FromSeconds(5));

            JobResponse result = await jobClient.ScheduleDeviceMethodAsync(jobId,
                                                                           $"DeviceId IN ['{deviceId}']",
                                                                           directMethod,
                                                                           DateTime.UtcNow,
                                                                           (long)TimeSpan.FromMinutes(2).TotalSeconds);

            System.Diagnostics.Debug.WriteLine("Started Method Job");
        }
Ejemplo n.º 5
0
        static async Task InvokeMethod(string deviceId, string methodName, string payload)
        {
            var methodInvocation = new CloudToDeviceMethod(methodName)
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(payload);

            var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);

            Console.WriteLine($"Response Status: {response.Status}");
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 6
0
        private static async Task InvokeMethod(string interval)
        {
            var methodInvocation = new CloudToDeviceMethod("SendMessage")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(interval);

            var response = await serviceClient.InvokeDeviceMethodAsync(deviceName, methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 7
0
        private void InvokeMethodSendTimeInterval(int time)
        {
            var methodInvocation = new CloudToDeviceMethod("SetSensorInterval")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.ConnectionTimeout = TimeSpan.FromSeconds(30);
            methodInvocation.SetPayloadJson(time.ToString());


            // var response = await _serviceClient.InvokeDeviceMethodAsync("MyNodeDevice", methodInvocation);
            _serviceClient.InvokeDeviceMethodAsync("MyNodeDevice", methodInvocation);
        }
        /// <summary>
        /// Message explicitly addressed to Lantern
        /// </summary>
        /// <param name="lanternId"></param>
        /// <param name="commands"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public async Task SendCloudToLanternMethodAsync(string lanternId, List <Command> commands, int?table = null)
        {
            // Nothing to do if no lanternId or no commands
            if (commands == null)
            {
                return;
            }
            if (commands.Count == 0)
            {
                return;
            }
            if (string.IsNullOrEmpty(lanternId))
            {
                return;
            }

            try
            {
                foreach (var cmd in commands)
                {
                    cmd.LanternID = lanternId;
                }

                // Convert commands to json to send to IOT hub

                DefaultContractResolver contractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };

                var body = JsonConvert.SerializeObject(commands, new JsonSerializerSettings
                {
                    ContractResolver = contractResolver,
                    Formatting       = Formatting.None
                });

#if DEBUG
                Debug.WriteLine(body);
#else
                var c2l = new CloudToDeviceMethod("C2L");
                c2l.SetPayloadJson(body);
                await _serviceClient.InvokeDeviceMethodAsync(DEVICE_ID, c2l).ConfigureAwait(false);
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        public async Task <(int Status, string ResponsePayload)> InvokeMethod(string methodName, string reqPayload = "{}")
        {
            var methodInvocation =
                new CloudToDeviceMethod(methodName)
            {
                ResponseTimeout   = TimeSpan.FromSeconds(10),
                ConnectionTimeout = TimeSpan.FromSeconds(10)
            };

            methodInvocation.SetPayloadJson(reqPayload);

            var response = await _serviceClient.InvokeDeviceMethodAsync(DeviceId, methodInvocation);

            return(response.Status, response.GetPayloadAsJson());
        }
 public async Task InvokeDeviceMethodAsync(DeviceEntity deviceId, string method, Payload payload)
 {
     try
     {
         var methodInvocation = new CloudToDeviceMethod(method)
         {
             ResponseTimeout = TimeSpan.FromSeconds(30)
         };
         methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(payload));
         var response = await serviceClient.InvokeDeviceMethodAsync(deviceId.Id, methodInvocation);
     } catch (Exception e)
     {
         throw e;
     }
 }
Ejemplo n.º 11
0
        public async Task <bool> RegisterDevice(string deviceId)
        {
            var methodInvocation = new CloudToDeviceMethod("RegisterDevice")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };
            var msg = "{\"deviceId\": \"" + deviceId + "\"}";

            methodInvocation.SetPayloadJson(msg);
            var response = await serviceClient.InvokeDeviceMethodAsync(lockId, methodInvocation);

            var isRegistered = bool.Parse(JObject.Parse(response.GetPayloadAsJson())["result"].ToString());

            return(isRegistered);
        }
Ejemplo n.º 12
0
        public async Task <CloudToDeviceMethodResult> InvokeMethod(string deviceId, string methodName, string payload)
        {
            var methodinvokation = new CloudToDeviceMethod(methodName);

            methodinvokation.SetPayloadJson(payload);

            var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodinvokation);


            Console.WriteLine($"Response status : {response.Status}");

            Console.WriteLine(response.GetPayloadAsJson());

            return(response);
        }
Ejemplo n.º 13
0
        // Invoke the direct method on the device
        private static async Task InvokeMethod()
        {
            var methodInvocation = new CloudToDeviceMethod("spinmotor")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson("10"); //num of seconds

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync("feeder", methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 14
0
        // Invoke the direct method on the device, passing the payload
        private static async Task InvokeMethod()
        {
            var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson("10");

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync("myEdgeDevice", "IotEdgeModule1", methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 15
0
        public static async Task StartFirmwareUpdate()
        {
            client = ServiceClient.CreateFromConnectionString(connString);
            CloudToDeviceMethod method = new CloudToDeviceMethod("firmwareUpdate");

            method.ResponseTimeout = TimeSpan.FromSeconds(30);
            method.SetPayloadJson(
                @"{
             fwPackageUri : 'https://someurl'
         }");

            CloudToDeviceMethodResult result = await client.InvokeDeviceMethodAsync(deviceId, method);

            Console.WriteLine("Invoked firmware update on device.");
        }
Ejemplo n.º 16
0
        private static async Task InvokeRemoteFunc(string remoteFunc, string vin, string contractId)
        {
            var methodInvocation = new CloudToDeviceMethod(remoteFunc)
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(contractId);

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync(vin, methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 17
0
        private async Task <string> InvokeMethod()
        {
            //Web call device method
            var methodInvocation = new CloudToDeviceMethod("GetWeight")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson("10");

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync("Device ID", methodInvocation);

            return(response.GetPayloadAsJson());
        }
Ejemplo n.º 18
0
        public async Task <LockState> GetLockStatusAsync()
        {
            var methodInvocation = new CloudToDeviceMethod("SendLockState")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };
            var msg = "{\"deviceId\": \"" + SettingsService.DeviceId + "\"}";

            methodInvocation.SetPayloadJson(msg);
            var response = await serviceClient.InvokeDeviceMethodAsync(SettingsService.LockId, methodInvocation);

            var status = JObject.Parse(response.GetPayloadAsJson())["result"].ToString();

            return((LockState)Enum.Parse(typeof(LockState), status));
        }
Ejemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetDevice"></param>
        /// <returns></returns>
        public async void StartFirmwareUpdate(string targetDevice)
        {
            // assign the URL of Blob from where the latest firmware can be downloaded
            String bloburl = "";

            _client = ServiceClient.CreateFromConnectionString(AzureIoTHub.GetConnectionString());
            CloudToDeviceMethod method = new CloudToDeviceMethod("firmwareUpdate");

            method.ResponseTimeout = TimeSpan.FromSeconds(30);
            method.SetPayloadJson(@"{fwPackageUri : '" + bloburl + "'}");

            await _client.InvokeDeviceMethodAsync(targetDevice, method);

            Console.WriteLine("firmware update on device is Successful.");
        }
Ejemplo n.º 20
0
        public async Task StartFirmwareUpdate(string deviceId)
        {
            CloudToDeviceMethod method = new CloudToDeviceMethod("firmwareUpdate");

            method.ResponseTimeout   = TimeSpan.FromSeconds(90);
            method.ConnectionTimeout = TimeSpan.FromSeconds(60);
            method.SetPayloadJson(
                @"{
                         firmwareUrl : 'https://example.com'
                }");

            CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

            Console.WriteLine("Invoked firmware update on device.");
        }
Ejemplo n.º 21
0
        private static async Task InvokeMethod()
        {
            var methodInvocation = new CloudToDeviceMethod(methodName)
            {
                ResponseTimeout = TimeSpan.FromSeconds(10), ConnectionTimeout = TimeSpan.FromSeconds(10)
            };

            methodInvocation.SetPayloadJson($"10");

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await s_serviceClient.InvokeDeviceMethodAsync(DEVICE_ID, methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 22
0
        public async Task factoryReset(string deviceId)
        {
            CloudToDeviceMethod method = new CloudToDeviceMethod("factoryReset");

            method.ResponseTimeout   = TimeSpan.FromSeconds(90);
            method.ConnectionTimeout = TimeSpan.FromSeconds(60);
            method.SetPayloadJson(
                @"{
                         reset :  'true'
                }");

            CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

            Console.WriteLine("Invoked factoryReset on device.");
        }
Ejemplo n.º 23
0
        private static async Task InvokeService(string command)
        {
            var methodInvocation = new CloudToDeviceMethod("OperateDoor")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson("{'Value':'" + command + "'}");

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response = await serviceClient.InvokeDeviceMethodAsync("DoorOpener", methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 24
0
        private static async Task InvokeMethod(DriveCommandData data)
        {
            string payload          = JsonConvert.SerializeObject(data);
            var    methodInvocation = new CloudToDeviceMethod("Drive")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(payload);

            var response = await s_serviceClient.InvokeDeviceMethodAsync("PI3", methodInvocation);

            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
        private async Task <IActionResult> SendMessageViaDirectMethodAsync(
            string preferredGatewayID,
            DevEui devEUI,
            LoRaCloudToDeviceMessage c2dMessage)
        {
            try
            {
                var method = new CloudToDeviceMethod(LoraKeysManagerFacadeConstants.CloudToDeviceMessageMethodName, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
                _ = method.SetPayloadJson(JsonConvert.SerializeObject(c2dMessage));

                var res = await this.serviceClient.InvokeDeviceMethodAsync(preferredGatewayID, LoraKeysManagerFacadeConstants.NetworkServerModuleId, method);

                if (IsSuccessStatusCode(res.Status))
                {
                    this.log.LogInformation("Direct method call to {gatewayID} and {devEUI} succeeded with {statusCode}", preferredGatewayID, devEUI, res.Status);

                    return(new OkObjectResult(new SendCloudToDeviceMessageResult()
                    {
                        DevEui = devEUI,
                        MessageID = c2dMessage.MessageId,
                        ClassType = "C",
                    }));
                }

                this.log.LogError("Direct method call to {gatewayID} failed with {statusCode}. Response: {response}", preferredGatewayID, res.Status, res.GetPayloadAsJson());

                return(new ObjectResult(res.GetPayloadAsJson())
                {
                    StatusCode = res.Status,
                });
            }
            catch (JsonSerializationException ex)
            {
                this.log.LogError(ex, "Failed to serialize C2D message {c2dmessage} to {devEUI}", JsonConvert.SerializeObject(c2dMessage), devEUI);
                return(new ObjectResult("Failed serialize C2D Message")
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError
                });
            }
            catch (IotHubException ex)
            {
                this.log.LogError(ex, "Failed to send message for {devEUI} to the IoT Hub", devEUI);
                return(new ObjectResult("Failed to send message for device to the iot Hub")
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError
                });
            }
        }
Ejemplo n.º 26
0
Archivo: Caller.cs Proyecto: moadh/iot
        private static async Task InvokeMethod(MetricsPayload dataToSend)
        {
            string output           = JsonConvert.SerializeObject(dataToSend);
            var    methodInvocation = new CloudToDeviceMethod("count")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };

            methodInvocation.SetPayloadJson(output);

            var response = await serviceClient.InvokeDeviceMethodAsync(dataToSend.deviceName, methodInvocation);

            payload = JsonConvert.DeserializeObject <MetricsPayload>(response.GetPayloadAsJson());
            Console.WriteLine("Response status: {0}, payload:", response.Status);
            Console.WriteLine(response.GetPayloadAsJson());
        }
Ejemplo n.º 27
0
        private static async Task ShutDown()
        {
            var methodInvocation = new CloudToDeviceMethod("shutdown")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };
            var parameters = new
            {
                Force = true,
                User  = "******"
            };

            methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(parameters));

            var response = await serviceClient.InvokeDeviceMethodAsync(Config.DeviceId, methodInvocation);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static async Task <CloudToDeviceMethodResult> InvokeDirectMethodOnDevice()
        {
            var serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

            var methodInvocation = new CloudToDeviceMethod("TriggerAction")
            {
                ResponseTimeout = TimeSpan.FromSeconds(300)
            };

            methodInvocation.SetPayloadJson("'Switch ON Light'");

            //Interactively invokes a method on device
            var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);

            return(response);
        }
Ejemplo n.º 29
0
        //Direct method does not work for offline devices.
        private static async Task <CloudToDeviceMethodResult> CallDirectMethod(string message, string deviceId)
        {
            var serviceClient = ServiceClient.CreateFromConnectionString(Environment.GetEnvironmentVariable("ServiceConnectionString"));
            //The name of the method to send should match with the method while recieving.
            //If the method name is not found it will trigger the default method handler in the device.
            var method = new CloudToDeviceMethod("CloudToDeviceMessageHandler");

            //This has to be a valid json expression.
            method.SetPayloadJson($"'{message}'");

            var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

            Console.WriteLine($"Response status: {response.Status}, payload: {response.GetPayloadAsJson()}");

            return(response);
        }
Ejemplo n.º 30
0
        public static async Task StopGameMethod()
        {
            try
            {
                ServiceClient client = GetServiceClient();

                // Send method 'stopgame'
                CloudToDeviceMethod method = new CloudToDeviceMethod("stopgame");

                await client.InvokeDeviceMethodAsync(_DEVICEID, method);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }