Azure / azure-iot-arduino

Azure IoT library for the Arduino
Other
168 stars 95 forks source link

Is it possible to receive message from IOT Hub endpoint? #66

Closed mopplayer closed 6 years ago

mopplayer commented 7 years ago

By default, send message could work properly. Is it possible to receive message from IOT Hub endpoint? Is there a implement without running Linux??

JetstreamRoySprowl commented 6 years ago

Certainly. Here is direction on building the (great many) samples for Windows. Search for "--run-e2e-tests" on that page.

This doc shows how to send cloud-to-device messages in C#.

mopplayer commented 6 years ago

@JetstreamRoySprowl hi, I used Function to trigger ML data cloud to device if (response.IsSuccessStatusCode) { log.Info($"OK....1"); string result = await response.Content.ReadAsStringAsync(); AMLMessage AMLresult = JsonConvert.DeserializeObject(result); // if (AMLresult.Results.output1[0].scoredProbabilities < AMLaccuracy) { // we have less than AMLaccuracy% accuracy, sending a message string IoTHubConnectionString = iotHubString; IoTMessageSend messageSend = new IoTMessageSend(); messageSend.scoredProbabilities = AMLresult.Results.output1[0].ProbabilityofPrecipitation; messageSend.action = "runcode"; messageSend.id = iotMessage.id; log.Info($"OK....2"); //messageSend.macaddress = iotMessage.macaddress; ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(IoTHubConnectionString); log.Info($"OK....3"); Message sendMessage = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(messageSend))); log.Info($"OK....4"); log.Info($"Sent message {JsonConvert.SerializeObject(messageSend)}"); await serviceClient.SendAsync("myFirstNodeDevice", sendMessage); // } } else { log.Info($"Error: {response.StatusCode}"); } but still got stuck: `2017-09-15T18:05:22.096 OK....1

2017-09-15T18:05:22.096 OK....2

2017-09-15T18:05:22.128 Exception while executing function: Functions.EventHubTriggerCSharp1. Microsoft.Azure.WebJobs.Script: One or more errors occurred. Microsoft.Azure.Devices: Could not load file or assembly 'Microsoft.Azure.Devices.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

2017-09-15T18:05:22.174 Function completed (Failure, Id=0c6e7565-d93a-44dd-b2a8-848445a7f911, Duration=179ms) `

mopplayer commented 6 years ago

@JetstreamRoySprowl settings: { "frameworks": { "net46": { "dependencies": { "Microsoft.Azure.Devices": "1.3.2", "Microsoft.Azure.Devices.Shared": "1.1.0", "Microsoft.AspNet.WebApi.Client": "5.2.3" } } } }

JetstreamRoySprowl commented 6 years ago

@mopplayer : I'm afraid I'm unclear what the context is here. Can you tell me exactly what sample you're trying to run and provide a web link to the instructions that you followed to build the sample?

mopplayer commented 6 years ago

@JetstreamRoySprowl Hi, thanks. it is Azure cloud functions. example from: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-store-data-in-azure-table-storage

I use C# to send message wrapped Azure Machine Learning result from Cloud to device.

example code: **// This code requires the Nuget package Microsoft.AspNet.WebApi.Client to be installed. // Instructions for doing this in Visual Studio: // Tools -> Nuget Package Manager -> Package Manager Console // Install-Package Microsoft.AspNet.WebApi.Client

using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks;

namespace CallRequestResponseService { class Program { static void Main(string[] args) { InvokeRequestResponseService().Wait(); }

    static async Task InvokeRequestResponseService()
    {
        using (var client = new HttpClient())
        {
            var scoreRequest = new
            {
                Inputs = new Dictionary<string, List<Dictionary<string, string>>> () {
                    {
                        "input1",
                        new List<Dictionary<string, string>>(){new Dictionary<string, string>(){
                                        {
                                            "temperature", "1"
                                        },
                                        {
                                            "humidity", "1"
                                        },
                            }
                        }
                    },
                },
                GlobalParameters = new Dictionary<string, string>() {
                }
            };

            const string apiKey = "abc123"; // Replace this with the API key for the web service
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);
            client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/20afa97b5c5a4fb8aa2685a3452cea43/services/2629ee1328e04e8ba7566105ebca569d/execute?api-version=2.0&format=swagger");

            // WARNING: The 'await' statement below can result in a deadlock
            // if you are calling this code from the UI thread of an ASP.Net application.
            // One way to address this would be to call ConfigureAwait(false)
            // so that the execution does not attempt to resume on the original context.
            // For instance, replace code such as:
            //      result = await DoSomeTask()
            // with the following:
            //      result = await DoSomeTask().ConfigureAwait(false)

            HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Result: {0}", result);
            }
            else
            {
                Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                // Print the headers - they include the requert ID and the timestamp,
                // which are useful for debugging the failure
                Console.WriteLine(response.Headers.ToString());

                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
            }
        }
    }
}

}// This code requires the Nuget package Microsoft.AspNet.WebApi.Client to be installed. // Instructions for doing this in Visual Studio: // Tools -> Nuget Package Manager -> Package Manager Console // Install-Package Microsoft.AspNet.WebApi.Client

using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks;

namespace CallRequestResponseService { class Program { static void Main(string[] args) { InvokeRequestResponseService().Wait(); }

    static async Task InvokeRequestResponseService()
    {
        using (var client = new HttpClient())
        {
            var scoreRequest = new
            {
                Inputs = new Dictionary<string, List<Dictionary<string, string>>> () {
                    {
                        "input1",
                        new List<Dictionary<string, string>>(){new Dictionary<string, string>(){
                                        {
                                            "temperature", "1"
                                        },
                                        {
                                            "humidity", "1"
                                        },
                            }
                        }
                    },
                },
                GlobalParameters = new Dictionary<string, string>() {
                }
            };

            const string apiKey = "abc123"; // Replace this with the API key for the web service
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);
            client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/20afa97b5c5a4fb8aa2685a3452cea43/services/2629ee1328e04e8ba7566105ebca569d/execute?api-version=2.0&format=swagger");

            // WARNING: The 'await' statement below can result in a deadlock
            // if you are calling this code from the UI thread of an ASP.Net application.
            // One way to address this would be to call ConfigureAwait(false)
            // so that the execution does not attempt to resume on the original context.
            // For instance, replace code such as:
            //      result = await DoSomeTask()
            // with the following:
            //      result = await DoSomeTask().ConfigureAwait(false)

            HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Result: {0}", result);
            }
            else
            {
                Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                // Print the headers - they include the requert ID and the timestamp,
                // which are useful for debugging the failure
                Console.WriteLine(response.Headers.ToString());

                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
            }
        }
    }
}

}**

Reference project: https://github.com/ksaye/IoTDemonstrations/blob/master/sendTakePicture/run.csx

Thanks.

tameraw commented 6 years ago

@mopplayer - If issue pertains to the C# SDK, please file in the repo for C# here, if still encountering problems. Thanks.