forked from nanoframework/Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
174 lines (145 loc) · 7.57 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Device.Gpio;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using nanoFramework.Json;
using nanoFramework.Networking;
#if HAS_WIFI
using System.Device.Wifi;
#endif
namespace HttpSamples.HttpAzureGET
{
public class Program
{
#if HAS_WIFI
private static string MySsid = "ssid";
private static string MyPassword = "password";
#endif
private static AutoResetEvent sendMessage = new AutoResetEvent(false);
private static GpioPin _userButton;
private static SetPoint _setPoint = new SetPoint();
private static HttpClient _httpClient;
public static void Main()
{
Debug.WriteLine("Waiting for network up, IP address and valid date & time...");
bool success;
CancellationTokenSource cs = new(60000);
#if HAS_WIFI
// if the device doesn't have the Wifi credentials stored
success = WifiNetworkHelper.ConnectDhcp(MySsid, MyPassword, requiresDateTime: true, token: cs.Token);
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
// if the device has the Wifi credentials already stored, this call it's faster //
// success = WifiNetworkHelper.Reconnect(requiresDateTime: true, token: cs.Token); //
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
#else
success = NetworkHelper.SetupAndConnectNetwork(cs.Token, true);
#endif
if (!success)
{
Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.Status}.");
if (NetworkHelper.HelperException != null)
{
Debug.WriteLine($"Exception: {NetworkHelper.HelperException}");
}
return;
}
// setup user button
_userButton = new GpioController().OpenPin(0, PinMode.Input);
_userButton.ValueChanged += UserButton_ValueChanged;
// crate HTTP Client
_httpClient = new HttpClient();
_httpClient.SslProtocols = System.Net.Security.SslProtocols.Tls12;
/////////////////////////////////////////////////////////////////////////////////////
////add certificate in PEM format(as a string in the app). This was taken from Azure's sample at https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
/// chis cert should be used when connecting to Azure IoT on the Azure Cloud available globally. Additional certs can be found in the link above
_httpClient.HttpsAuthentCert = new X509Certificate(azurePEMCertBaltimore);
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
/// enter your Shared Access Signature. You can create this using the Azure IOT Explorer under "Device Identity" format is
/// "SharedAccessSignature sr=<iotHubName>.azure-devices.net%2Fdevices%2F<deviceName>&sig=<signature>"
/// See "Readme" for more details
string sas = "<Enter SAS Token Here See Read Me for example>";
///////////////////////////////////////////////////////////////////////////////////
// add an Authorization header of our SAS
_httpClient.DefaultRequestHeaders.Add("Authorization", sas);
//strip the device iotHubName from the SAS token
var from = sas.IndexOf('=') + 1;
var to = sas.IndexOf(".");
string iotHubName = sas.Substring(from, to - from);
// strip the deviceName from the SAS
to = sas.IndexOf("&");
from = sas.IndexOf("%2Fdevices%2F") + 13;
string deviceName = sas.Substring(from, to - from);
//Create the url for the azure iot hub
_httpClient.BaseAddress = new Uri($"https://{iotHubName}.azure-devices.net/devices/{deviceName}/messages/devicebound?api-version=2020-03-13");
Debug.WriteLine($"Your IOT Hub Name: {iotHubName} and your Device Name: {deviceName}");
Debug.WriteLine($"Getting data from: {_httpClient.BaseAddress.AbsoluteUri}");
WorkerThread();
// A custom class that we will convert to Json and pass as the body of the post
Thread.Sleep(Timeout.Infinite);
}
private static void WorkerThread()
{
while (true)
{
//wait for button press to do this just ground the pin set above (Pin 0 in this sample)
sendMessage.WaitOne();
Debug.WriteLine("Button Clicked");
/////////////////////////////////////////////////////////////////////////////////
/// Send data to the IOT device using Azure IOT Explorer cloud-device message ///
/////////////////////////////////////////////////////////////////////////////////
// perform the request via HTTP Client
var response = _httpClient.GetString("");
if (string.IsNullOrEmpty(response))
{
Debug.WriteLine("No Data was returned");
}
else
{
_setPoint = (SetPoint)JsonConvert.DeserializeObject(response, typeof(SetPoint));
Debug.WriteLine($"Device ID: {_setPoint.DeviceID} Value: {_setPoint.Value}");
}
}
}
private static void UserButton_ValueChanged(object sender, PinValueChangedEventArgs e)
{
if (e.ChangeType == PinEventTypes.Falling)
{
// signal event
sendMessage.Set();
}
}
// X509 RSA key PEM format
private const string azurePEMCertBaltimore =
@"-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ
RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD
VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX
DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y
ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy
VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr
mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr
IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK
mpYcqWe4PwzV9/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