56 |
57 |
Current Temperature
The last recorded reading on device {{ latest_reading.deviceid }} was:
58 |
59 |
60 |
61 | Temperature |
62 | Time |
63 |
64 |
65 |
66 |
67 | {{ latest_reading.temperature | number }}°C | {{ latest_reading.eventtime | date : 'medium' }} |
68 |
69 |
70 |
71 |
72 |
73 |
Alerts
74 |
75 |
{{ alert | json }}
76 |
77 |
78 |
79 |
80 |
Temperature History
81 |
82 |
Most recent {{ temperatures.length }} readings
83 |
84 |
85 |
86 | Temperature |
87 | Time |
88 |
89 |
90 |
91 |
92 | {{ t.temperature | number }}°C | {{ t.eventtime | date : 'medium' }} |
93 |
94 |
95 |
96 |
97 | No temperature history found
98 |
99 |
100 |
101 |
102 |
142 |
143 |
144 |
--------------------------------------------------------------------------------
/command_center_node/server.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var express = require('express');
4 | var bodyParser = require('body-parser');
5 |
6 | var ServiceClient = require('azure-iothub').Client;
7 | var Message = require('azure-iot-common').Message;
8 | var EventHubClient = require('azure-event-hubs').Client;
9 | var DeviceConnectionString = require('azure-iot-device').ConnectionString;
10 | var azure = require('azure-storage');
11 | var nconf = require('nconf');
12 |
13 | nconf.argv().env().file('./config.json');
14 | var eventHubName = nconf.get('eventHubName');
15 | var ehConnString = nconf.get('ehConnString');
16 | var deviceConnString = nconf.get('deviceConnString');
17 | var storageAcountName = nconf.get('storageAcountName');
18 | var storageAccountKey = nconf.get('storageAccountKey');
19 | var storageTable = nconf.get('storageTable');
20 | var iotHubConnString = nconf.get('iotHubConnString');
21 |
22 | var deviceId = DeviceConnectionString.parse(deviceConnString).DeviceId;
23 | var iotHubClient = ServiceClient.fromConnectionString(iotHubConnString);
24 |
25 | // event hub alerts
26 | var alerts = [];
27 | var ehclient = EventHubClient.fromConnectionString(ehConnString, eventHubName)
28 | ehclient.createReceiver('$Default', '0', { startAfterTime: Date.now() })
29 | .then(function(rx) {
30 | rx.on('errorReceived', function(err) { console.log(err); });
31 | rx.on('message', function(message) {
32 | alerts.push(message.body);
33 | alerts = alerts.slice(-5); // keep last 5
34 | });
35 | });
36 |
37 | // table storage
38 | var tableSvc = azure.createTableService(storageAcountName, storageAccountKey);
39 | tableSvc.createTableIfNotExists(storageTable, function(err, result, response) {
40 | if (err) {
41 | console.log('error looking up table');
42 | console.log(err)
43 | }
44 | });
45 |
46 | // website setup
47 | var app = express();
48 | var port = nconf.get('port');
49 | app.use(express.static('public'));
50 | app.use(express.static('bower_components'));
51 | app.use(bodyParser.json());
52 |
53 | // app api
54 | app.get('/api/alerts', function(req, res) {
55 | res.json(alerts);
56 | });
57 |
58 | app.get('/api/temperatures', function(req, res) {
59 | var query = new azure.TableQuery()
60 | .select(['eventtime', 'temperaturereading', 'deviceid'])
61 | .where('PartitionKey eq ?', deviceId);
62 | var nextContinuationToken = null;
63 | var fullresult = { entries: [] };
64 | queryTable(storageTable, query, nextContinuationToken, fullresult, function (err, result, response) {
65 | res.json(result.entries.slice(-10));
66 | })
67 | })
68 |
69 | function queryTable(table, query, token, fullresult, callback) {
70 | var nextContinuationToken = token;
71 | tableSvc.queryEntities(table, query, nextContinuationToken, function (err, result, response) {
72 | fullresult.entries.push.apply(fullresult.entries, result.entries);
73 | if (result.continuationToken) {
74 | nextContinuationToken = result.continuationToken;
75 | queryTable(table, query, nextContinuationToken, fullresult, callback);
76 | } else {
77 | callback(err, fullresult, response);
78 | }
79 | })
80 | };
81 |
82 | var completedCallback = function(err, res) {
83 | if (err) { console.log(err); }
84 | else { console.log(res); }
85 | };
86 |
87 | app.post('/api/command', function(req, res) {
88 | console.log('command received: ' + req.body.command);
89 |
90 | var command = "TurnFanOff";
91 | if (req.body.command === 1) {
92 | command = "TurnFanOn";
93 | }
94 |
95 | iotHubClient.open(function(err) {
96 | if (err) {
97 | console.error('Could not connect: ' + err.message);
98 | } else { // {"Name":"TurnFanOn","Parameters":""}
99 | var data = JSON.stringify({ "Name":command,"Parameters":null });
100 | var message = new Message (data);
101 | console.log('Sending message: ' + data);
102 | iotHubClient.send(deviceId, message, printResultFor('send'));
103 | }
104 | });
105 |
106 | // Helper function to print results in the console
107 | function printResultFor(op) {
108 | return function printResult(err, res) {
109 | if (err) {
110 | console.log(op + ' error: ' + err.toString());
111 | } else {
112 | console.log(op + ' status: ' + res.constructor.name);
113 | }
114 | };
115 | }
116 |
117 | res.end();
118 | });
119 |
120 | app.listen(port, function() {
121 | console.log('app running on http://localhost:' + port);
122 | });
123 |
--------------------------------------------------------------------------------
/device_twin/device_twin.ino:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | // Please use an Arduino IDE 1.6.8 or greater
5 |
6 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
7 | // iot_configs.h
8 | #include "iot_configs.h"
9 |
10 | #include
11 | #if defined(IOT_CONFIG_MQTT)
12 | #include
13 | #elif defined(IOT_CONFIG_HTTP)
14 | #include
15 | #endif
16 |
17 | #include "sample.h"
18 | #include "esp8266/sample_init.h"
19 |
20 | static char ssid[] = IOT_CONFIG_WIFI_SSID;
21 | static char pass[] = IOT_CONFIG_WIFI_PASSWORD;
22 |
23 | void setup() {
24 | sample_init(ssid, pass);
25 | }
26 |
27 | // Azure IoT samples contain their own loops, so only run them once
28 | static bool done = false;
29 | void loop() {
30 | if (!done)
31 | {
32 | // Run the sample
33 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
34 | // iot_configs.h
35 | sample_run();
36 | done = true;
37 | }
38 | else
39 | {
40 | delay(500);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/device_twin/iot_configs.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef IOT_CONFIGS_H
5 | #define IOT_CONFIGS_H
6 |
7 | /**
8 | * WiFi setup
9 | */
10 | #define IOT_CONFIG_WIFI_SSID ""
11 | #define IOT_CONFIG_WIFI_PASSWORD ""
12 |
13 | /**
14 | * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys
15 | * String containing Hostname, Device Id & Device Key in the format:
16 | * "HostName=;DeviceId=;SharedAccessKey="
17 | */
18 | #define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey="
19 |
20 | /**
21 | * Choose the transport protocol
22 | */
23 | #define IOT_CONFIG_MQTT // uncomment this line for MQTT
24 | // #define IOT_CONFIG_HTTP // uncomment this line for HTTP
25 |
26 | #endif /* IOT_CONFIGS_H */
27 |
--------------------------------------------------------------------------------
/device_twin/iothub_client_sample_device_twin.c:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #include
5 | #include
6 | #include "iot_configs.h"
7 | #include "sample.h"
8 |
9 | #include
10 | #include
11 |
12 | /*String containing Hostname, Device Id & Device Key in one of the formats: */
13 | /* "HostName=;DeviceId=;SharedAccessKey=" */
14 | /* "HostName=;DeviceId=;SharedAccessSignature=" */
15 | static const char* connectionString = IOT_CONFIG_CONNECTION_STRING;
16 |
17 | static char msgText[1024];
18 | static char propText[1024];
19 | static bool g_continueRunning;
20 | #define DOWORK_LOOP_NUM 100
21 |
22 | static void deviceTwinCallback(DEVICE_TWIN_UPDATE_STATE update_state, const unsigned char* payLoad, size_t size, void* userContextCallback)
23 | {
24 | (void)userContextCallback;
25 |
26 | printf("Device Twin update received (state=%s, size=%u): \r\n",
27 | ENUM_TO_STRING(DEVICE_TWIN_UPDATE_STATE, update_state), size);
28 | for (size_t n = 0; n < size; n++)
29 | {
30 | printf("%c", payLoad[n]);
31 | }
32 | printf("\r\n");
33 | }
34 |
35 | static void reportedStateCallback(int status_code, void* userContextCallback)
36 | {
37 | (void)userContextCallback;
38 | printf("Device Twin reported properties update completed with result: %d\r\n", status_code);
39 |
40 | g_continueRunning = false;
41 | }
42 |
43 |
44 | void iothub_client_sample_device_twin_run(void)
45 | {
46 | // Result checks are omitted to simplify the sample.
47 | // Please verify all returns on your production code.
48 | IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
49 | g_continueRunning = true;
50 |
51 | IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = MQTT_Protocol;
52 |
53 | if (platform_init() != 0)
54 | {
55 | (void)printf("Failed to initialize the platform.\r\n");
56 | }
57 | else
58 | {
59 | if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, protocol)) == NULL)
60 | {
61 | (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
62 | }
63 | else
64 | {
65 | bool traceOn = true;
66 | // This json-format reportedState is created as a string for simplicity. In a real application
67 | // this would likely be done with parson (which the Azure IoT SDK uses) or a similar tool.
68 | const char* reportedState = "{ 'device_property': 'new_value'}";
69 | size_t reportedStateSize = strlen(reportedState);
70 |
71 | (void)IoTHubClient_LL_SetOption(iotHubClientHandle, OPTION_LOG_TRACE, &traceOn);
72 |
73 | // Check the return of all API calls when developing your solution. Return checks ommited for sample simplification.
74 |
75 | (void)IoTHubClient_LL_SetDeviceTwinCallback(iotHubClientHandle, deviceTwinCallback, iotHubClientHandle);
76 | (void)IoTHubClient_LL_SendReportedState(iotHubClientHandle, (const unsigned char*)reportedState, reportedStateSize, reportedStateCallback, iotHubClientHandle);
77 |
78 | do
79 | {
80 | IoTHubClient_LL_DoWork(iotHubClientHandle);
81 | ThreadAPI_Sleep(100);
82 | } while (g_continueRunning);
83 |
84 | for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
85 | {
86 | IoTHubClient_LL_DoWork(iotHubClientHandle);
87 | ThreadAPI_Sleep(100);
88 | }
89 | LogInfo("IoTHubClient_LL_Destroy starting");
90 |
91 | IoTHubClient_LL_Destroy(iotHubClientHandle);
92 | LogInfo("IoTHubClient_LL_Destroy okay");
93 | }
94 | platform_deinit();
95 | }
96 | }
97 |
98 | void sample_run(void)
99 | {
100 | iothub_client_sample_device_twin_run();
101 | }
102 |
--------------------------------------------------------------------------------
/device_twin/sample.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SAMPLE_H
5 | #define SAMPLE_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void sample_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SAMPLE_H */
18 |
--------------------------------------------------------------------------------
/img/thingdev_command_center.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/f85cdb42f13bae74be2f7279a55bdfa5fd19aac4/img/thingdev_command_center.png
--------------------------------------------------------------------------------
/img/thingdev_remote_monitoring.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/f85cdb42f13bae74be2f7279a55bdfa5fd19aac4/img/thingdev_remote_monitoring.png
--------------------------------------------------------------------------------
/remote_monitoring/iot_configs.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef IOT_CONFIGS_H
5 | #define IOT_CONFIGS_H
6 |
7 | /**
8 | * WiFi setup
9 | */
10 | #define IOT_CONFIG_WIFI_SSID ""
11 | #define IOT_CONFIG_WIFI_PASSWORD ""
12 |
13 | /**
14 | * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys
15 | * String containing Hostname, Device Id & Device Key in the format:
16 | * "HostName=;DeviceId=;SharedAccessKey="
17 | */
18 | #define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey="
19 |
20 | /**
21 | * Choose the transport protocol
22 | */
23 | #define IOT_CONFIG_MQTT // uncomment this line for MQTT
24 | // #define IOT_CONFIG_HTTP // uncomment this line for HTTP
25 |
26 | #endif /* IOT_CONFIGS_H */
27 |
--------------------------------------------------------------------------------
/remote_monitoring/remote_monitoring.c:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #include "iot_configs.h"
5 | #include "sample.h"
6 |
7 | #include "AzureIoTHub.h"
8 | #include "sdk/schemaserializer.h"
9 | #include "sensor.h"
10 |
11 | /* CODEFIRST_OK is the new name for IOT_AGENT_OK. The follow #ifndef helps during the name migration. Remove it when the migration ends. */
12 | #ifndef IOT_AGENT_OK
13 | #define IOT_AGENT_OK CODEFIRST_OK
14 | #endif // ! IOT_AGENT_OK
15 |
16 | #define MAX_DEVICE_ID_SIZE 20
17 |
18 | // Define the Model
19 | BEGIN_NAMESPACE(Contoso);
20 |
21 | DECLARE_STRUCT(SystemProperties,
22 | ascii_char_ptr, DeviceID,
23 | _Bool, Enabled
24 | );
25 |
26 | DECLARE_STRUCT(DeviceProperties,
27 | ascii_char_ptr, DeviceID,
28 | _Bool, HubEnabledState
29 | );
30 |
31 | DECLARE_MODEL(Thermostat,
32 |
33 | /* Event data (temperature, external temperature and humidity) */
34 | WITH_DATA(int, Temperature),
35 | WITH_DATA(int, ExternalTemperature),
36 | WITH_DATA(int, Humidity),
37 | WITH_DATA(ascii_char_ptr, DeviceId),
38 |
39 | /* Device Info - This is command metadata + some extra fields */
40 | WITH_DATA(ascii_char_ptr, ObjectType),
41 | WITH_DATA(_Bool, IsSimulatedDevice),
42 | WITH_DATA(ascii_char_ptr, Version),
43 | WITH_DATA(DeviceProperties, DeviceProperties),
44 | WITH_DATA(ascii_char_ptr_no_quotes, Commands),
45 |
46 | /* Commands implemented by the device */
47 | WITH_ACTION(SetTemperature, int, temperature),
48 | WITH_ACTION(SetHumidity, int, humidity)
49 | );
50 |
51 | END_NAMESPACE(Contoso);
52 |
53 | EXECUTE_COMMAND_RESULT SetTemperature(Thermostat* thermostat, int temperature)
54 | {
55 | LogInfo("Received temperature %d\r\n", temperature);
56 | thermostat->Temperature = temperature;
57 | return EXECUTE_COMMAND_SUCCESS;
58 | }
59 |
60 | EXECUTE_COMMAND_RESULT SetHumidity(Thermostat* thermostat, int humidity)
61 | {
62 | LogInfo("Received humidity %d\r\n", humidity);
63 | thermostat->Humidity = humidity;
64 | return EXECUTE_COMMAND_SUCCESS;
65 | }
66 |
67 | static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size)
68 | {
69 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
70 | if (messageHandle == NULL)
71 | {
72 | LogInfo("unable to create a new IoTHubMessage\r\n");
73 | }
74 | else
75 | {
76 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
77 | {
78 | LogInfo("failed to hand over the message to IoTHubClient");
79 | }
80 | else
81 | {
82 | LogInfo("IoTHubClient accepted the message for delivery\r\n");
83 | }
84 |
85 | IoTHubMessage_Destroy(messageHandle);
86 | }
87 | free((void*)buffer);
88 | }
89 |
90 | static size_t GetDeviceId(const char* connectionString, char* deviceID, size_t size)
91 | {
92 | size_t result;
93 | const char* runStr = connectionString;
94 | char ustate = 0;
95 | char* start = NULL;
96 |
97 | if (runStr == NULL)
98 | {
99 | result = 0;
100 | }
101 | else
102 | {
103 | while (*runStr != '\0')
104 | {
105 | if (ustate == 0)
106 | {
107 | if (strncmp(runStr, "DeviceId=", 9) == 0)
108 | {
109 | runStr += 9;
110 | start = runStr;
111 | }
112 | ustate = 1;
113 | }
114 | else
115 | {
116 | if (*runStr == ';')
117 | {
118 | if (start == NULL)
119 | {
120 | ustate = 0;
121 | }
122 | else
123 | {
124 | break;
125 | }
126 | }
127 | runStr++;
128 | }
129 | }
130 |
131 | if (start == NULL)
132 | {
133 | result = 0;
134 | }
135 | else
136 | {
137 | result = runStr - start;
138 | if (deviceID != NULL)
139 | {
140 | for (size_t i = 0; ((i < size - 1) && (start < runStr)); i++)
141 | {
142 | *deviceID++ = *start++;
143 | }
144 | *deviceID = '\0';
145 | }
146 | }
147 | }
148 |
149 | return result;
150 | }
151 |
152 | /*this function "links" IoTHub to the serialization library*/
153 | static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
154 | {
155 | IOTHUBMESSAGE_DISPOSITION_RESULT result;
156 | const unsigned char* buffer;
157 | size_t size;
158 | if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
159 | {
160 | LogInfo("unable to IoTHubMessage_GetByteArray\r\n");
161 | result = EXECUTE_COMMAND_ERROR;
162 | }
163 | else
164 | {
165 | /*buffer is not zero terminated*/
166 | char* temp = malloc(size + 1);
167 | if (temp == NULL)
168 | {
169 | LogInfo("failed to malloc\r\n");
170 | result = EXECUTE_COMMAND_ERROR;
171 | }
172 | else
173 | {
174 | EXECUTE_COMMAND_RESULT executeCommandResult;
175 |
176 | memcpy(temp, buffer, size);
177 | temp[size] = '\0';
178 | executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp);
179 | result =
180 | (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED :
181 | (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED :
182 | IOTHUBMESSAGE_REJECTED;
183 | free(temp);
184 | }
185 | }
186 | return result;
187 | }
188 |
189 | void remote_monitoring_run(void)
190 | {
191 | initSensor();
192 |
193 | srand((unsigned int)time(NULL));
194 | if (serializer_init(NULL) != SERIALIZER_OK)
195 | {
196 | LogInfo("Failed on serializer_init\r\n");
197 | }
198 | else
199 | {
200 | IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
201 |
202 | #if defined(IOT_CONFIG_MQTT)
203 | iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(IOT_CONFIG_CONNECTION_STRING, MQTT_Protocol);
204 | #elif defined(IOT_CONFIG_HTTP)
205 | iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(IOT_CONFIG_CONNECTION_STRING, HTTP_Protocol);
206 | #else
207 | iotHubClientHandle = NULL;
208 | #endif
209 |
210 | if (iotHubClientHandle == NULL)
211 | {
212 | LogInfo("Failed on IoTHubClient_CreateFromConnectionString\r\n");
213 | }
214 | else
215 | {
216 | #ifdef MBED_BUILD_TIMESTAMP
217 | // For mbed add the certificate information
218 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
219 | {
220 | LogInfo("failure to set option \"TrustedCerts\"\r\n");
221 | }
222 | #endif // MBED_BUILD_TIMESTAMP
223 |
224 | Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat);
225 | if (thermostat == NULL)
226 | {
227 | LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n");
228 | }
229 | else
230 | {
231 | STRING_HANDLE commandsMetadata;
232 |
233 | if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
234 | {
235 | LogInfo("unable to IoTHubClient_SetMessageCallback\r\n");
236 | }
237 | else
238 | {
239 |
240 | char deviceId[MAX_DEVICE_ID_SIZE];
241 | if (GetDeviceId(IOT_CONFIG_CONNECTION_STRING, deviceId, MAX_DEVICE_ID_SIZE) > 0)
242 | {
243 | LogInfo("deviceId=%s", deviceId);
244 | }
245 |
246 | /* send the device info upon startup so that the cloud app knows
247 | what commands are available and the fact that the device is up */
248 | thermostat->ObjectType = "DeviceInfo";
249 | thermostat->IsSimulatedDevice = false;
250 | thermostat->Version = "1.0";
251 | thermostat->DeviceProperties.HubEnabledState = true;
252 | thermostat->DeviceProperties.DeviceID = (char*)deviceId;
253 |
254 | commandsMetadata = STRING_new();
255 | if (commandsMetadata == NULL)
256 | {
257 | LogInfo("Failed on creating string for commands metadata\r\n");
258 | }
259 | else
260 | {
261 | /* Serialize the commands metadata as a JSON string before sending */
262 | if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK)
263 | {
264 | LogInfo("Failed serializing commands metadata\r\n");
265 | }
266 | else
267 | {
268 | unsigned char* buffer;
269 | size_t bufferSize;
270 | thermostat->Commands = (char*)STRING_c_str(commandsMetadata);
271 |
272 | /* Here is the actual send of the Device Info */
273 | if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK)
274 | {
275 | LogInfo("Failed serializing\r\n");
276 | }
277 | else
278 | {
279 | sendMessage(iotHubClientHandle, buffer, bufferSize);
280 | }
281 |
282 | }
283 |
284 | STRING_delete(commandsMetadata);
285 | }
286 |
287 | thermostat->DeviceId = (char*)deviceId;
288 | int sendCycle = 10;
289 | int currentCycle = 0;
290 | while (1)
291 | {
292 | if(currentCycle >= sendCycle) {
293 | float Temp;
294 | float Humi;
295 | getNextSample(&Temp, &Humi);
296 | //thermostat->Temperature = 50 + (rand() % 10 + 2);
297 | thermostat->Temperature = (Temp>600)?600:(int)round(Temp);
298 | thermostat->ExternalTemperature = 55 + (rand() % 5 + 2);
299 | //thermostat->Humidity = 50 + (rand() % 8 + 2);
300 | thermostat->Humidity = (Humi>100)?100:(int)round(Humi);
301 | currentCycle = 0;
302 | unsigned char*buffer;
303 | size_t bufferSize;
304 |
305 | LogInfo("Sending sensor value Temperature = %d, Humidity = %d\r\n", thermostat->Temperature, thermostat->Humidity);
306 |
307 | if (SERIALIZE(&buffer, &bufferSize, thermostat->DeviceId, thermostat->Temperature, thermostat->Humidity, thermostat->ExternalTemperature) != IOT_AGENT_OK)
308 | {
309 | LogInfo("Failed sending sensor value\r\n");
310 | }
311 | else
312 | {
313 | sendMessage(iotHubClientHandle, buffer, bufferSize);
314 | }
315 | }
316 |
317 | IoTHubClient_LL_DoWork(iotHubClientHandle);
318 | ThreadAPI_Sleep(1000);
319 | currentCycle++;
320 | }
321 | }
322 |
323 | DESTROY_MODEL_INSTANCE(thermostat);
324 | }
325 | IoTHubClient_LL_Destroy(iotHubClientHandle);
326 | }
327 | serializer_deinit();
328 |
329 | }
330 | }
331 |
332 |
333 | void sample_run(void)
334 | {
335 | remote_monitoring_run();
336 | }
337 |
338 |
--------------------------------------------------------------------------------
/remote_monitoring/remote_monitoring.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef REMOTE_MONITORING_H
5 | #define REMOTE_MONITORING_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void remote_monitoring_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* REMOTE_MONITORING_H */
18 |
--------------------------------------------------------------------------------
/remote_monitoring/remote_monitoring.ino:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | // Please use an Arduino IDE 1.6.8 or greater
5 |
6 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
7 | // iot_configs.h
8 | #include "iot_configs.h"
9 |
10 | #include
11 | #if defined(IOT_CONFIG_MQTT)
12 | #include
13 | #elif defined(IOT_CONFIG_HTTP)
14 | #include
15 | #endif
16 |
17 | #include "sample.h"
18 | #include "esp8266/sample_init.h"
19 |
20 | static char ssid[] = IOT_CONFIG_WIFI_SSID;
21 | static char pass[] = IOT_CONFIG_WIFI_PASSWORD;
22 |
23 | void setup() {
24 | sample_init(ssid, pass);
25 | }
26 |
27 | // Azure IoT samples contain their own loops, so only run them once
28 | static bool done = false;
29 | void loop() {
30 | if (!done)
31 | {
32 | // Run the sample
33 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
34 | // iot_configs.h
35 | sample_run();
36 | done = true;
37 | }
38 | else
39 | {
40 | delay(500);
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/remote_monitoring/sample.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SAMPLE_H
5 | #define SAMPLE_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void sample_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SAMPLE_H */
18 |
--------------------------------------------------------------------------------
/remote_monitoring/sensor.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef __SENSOR_H
5 | #define __SENSOR_H
6 |
7 |
8 | #ifdef __cplusplus
9 | extern "C" {
10 | #endif
11 |
12 | void initSensor(void);
13 | void getNextSample(float* Temperature, float* Humidity);
14 |
15 | #ifdef __cplusplus
16 | }
17 | #endif
18 |
19 |
20 | #endif//__SENSOR_H
21 |
22 |
--------------------------------------------------------------------------------
/remote_monitoring/sensor_dht22.cpp:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "sensor.h"
9 |
10 |
11 | #define DHTPIN 2 // Pin which is connected to the DHT sensor.
12 | #define DHTTYPE DHT22 // DHT 22 (AM2302)
13 | // See guide for details on sensor wiring and usage:
14 | // https://learn.adafruit.com/dht/overview
15 | DHT_Unified dht(DHTPIN, DHTTYPE);
16 | uint32_t delayMS;
17 | uint32_t nextSampleAllowedMS = 0;
18 |
19 | void initSensor(void) {
20 | // Initialize device.
21 | dht.begin();
22 | Serial.println("DHTxx Unified Sensor Example");
23 | // Print temperature sensor details.
24 | sensor_t sensor;
25 | dht.temperature().getSensor(&sensor);
26 | Serial.println("------------------------------------");
27 | Serial.println("Temperature");
28 | Serial.print ("Sensor: "); Serial.println(sensor.name);
29 | Serial.print ("Driver Ver: "); Serial.println(sensor.version);
30 | Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
31 | Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C");
32 | Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C");
33 | Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C");
34 | Serial.println("------------------------------------");
35 | // Print humidity sensor details.
36 | dht.humidity().getSensor(&sensor);
37 | Serial.println("------------------------------------");
38 | Serial.println("Humidity");
39 | Serial.print ("Sensor: "); Serial.println(sensor.name);
40 | Serial.print ("Driver Ver: "); Serial.println(sensor.version);
41 | Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
42 | Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%");
43 | Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%");
44 | Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%");
45 | Serial.println("------------------------------------");
46 | // Set delay between sensor readings based on sensor details.
47 | delayMS = sensor.min_delay / 1000;
48 | }
49 |
50 | void getNextSample(float* Temperature, float* Humidity)
51 | {
52 | // Enforce a delay between measurements.
53 | uint32_t currTimeMS = millis();
54 | if (currTimeMS < nextSampleAllowedMS) return;
55 | nextSampleAllowedMS = currTimeMS + delayMS;
56 |
57 | // Get temperature event and print its value.
58 | sensors_event_t event;
59 | dht.temperature().getEvent(&event);
60 | if (isnan(event.temperature)) {
61 | Serial.println("Error reading temperature!");
62 | }
63 | else {
64 | Serial.print("Temperature: ");
65 | Serial.print(event.temperature);
66 | Serial.println(" *C");
67 | *Temperature = event.temperature;
68 | }
69 | // Get humidity event and print its value.
70 | dht.humidity().getEvent(&event);
71 | if (isnan(event.relative_humidity)) {
72 | Serial.println("Error reading humidity!");
73 | }
74 | else {
75 | Serial.print("Humidity: ");
76 | Serial.print(event.relative_humidity);
77 | Serial.println("%");
78 | *Humidity = event.relative_humidity;
79 | }
80 | }
81 |
82 |
83 |
--------------------------------------------------------------------------------
/simplesample_http/README.md:
--------------------------------------------------------------------------------
1 | ### simplesample_http
2 |
3 | Instructions for this sample are
4 | [here in the Azure IoT HTTP protocol library for Arduino.](https://github.com/Azure/azure-iot-arduino-protocol-http)
--------------------------------------------------------------------------------
/simplesample_http/iot_configs.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef IOT_CONFIGS_H
5 | #define IOT_CONFIGS_H
6 |
7 | /**
8 | * WiFi setup
9 | */
10 | #define IOT_CONFIG_WIFI_SSID ""
11 | #define IOT_CONFIG_WIFI_PASSWORD ""
12 |
13 | /**
14 | * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys
15 | * String containing Hostname, Device Id & Device Key in the format:
16 | * "HostName=;DeviceId=;SharedAccessKey="
17 | */
18 | #define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey="
19 |
20 | /**
21 | * Choose the transport protocol
22 | */
23 | // #define IOT_CONFIG_MQTT // uncomment this line for MQTT
24 | #define IOT_CONFIG_HTTP // uncomment this line for HTTP
25 |
26 | #endif /* IOT_CONFIGS_H */
27 |
--------------------------------------------------------------------------------
/simplesample_http/sample.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SAMPLE_H
5 | #define SAMPLE_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void sample_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SAMPLE_H */
18 |
--------------------------------------------------------------------------------
/simplesample_http/simplesample_http.c:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #include
5 |
6 | #include
7 | #include
8 | #include "iot_configs.h"
9 |
10 | /* This sample uses the _LL APIs of iothub_client for example purposes.
11 | That does not mean that HTTP only works with the _LL APIs.
12 | Simply changing the using the convenience layer (functions not having _LL)
13 | and removing calls to _DoWork will yield the same results. */
14 |
15 | #include "AzureIoTHub.h"
16 |
17 |
18 | /*String containing Hostname, Device Id & Device Key in the format: */
19 | /* "HostName=;DeviceId=;SharedAccessKey=" */
20 | static const char* connectionString = IOT_CONFIG_CONNECTION_STRING;
21 |
22 | // Define the Model
23 | BEGIN_NAMESPACE(WeatherStation);
24 |
25 | DECLARE_MODEL(ContosoAnemometer,
26 | WITH_DATA(ascii_char_ptr, DeviceId),
27 | WITH_DATA(int, WindSpeed),
28 | WITH_DATA(float, Temperature),
29 | WITH_DATA(float, Humidity),
30 | WITH_ACTION(TurnFanOn),
31 | WITH_ACTION(TurnFanOff),
32 | WITH_ACTION(SetAirResistance, int, Position)
33 | );
34 |
35 | END_NAMESPACE(WeatherStation);
36 |
37 | static char propText[1024];
38 |
39 | EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device)
40 | {
41 | (void)device;
42 | (void)printf("Turning fan on.\r\n");
43 | return EXECUTE_COMMAND_SUCCESS;
44 | }
45 |
46 | EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device)
47 | {
48 | (void)device;
49 | (void)printf("Turning fan off.\r\n");
50 | return EXECUTE_COMMAND_SUCCESS;
51 | }
52 |
53 | EXECUTE_COMMAND_RESULT SetAirResistance(ContosoAnemometer* device, int Position)
54 | {
55 | (void)device;
56 | (void)printf("Setting Air Resistance Position to %d.\r\n", Position);
57 | return EXECUTE_COMMAND_SUCCESS;
58 | }
59 |
60 | void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
61 | {
62 | unsigned int messageTrackingId = (unsigned int)(uintptr_t)userContextCallback;
63 |
64 | (void)printf("Message Id: %u Received.\r\n", messageTrackingId);
65 |
66 | (void)printf("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
67 | }
68 |
69 | static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size)
70 | {
71 | static unsigned int messageTrackingId;
72 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
73 | if (messageHandle == NULL)
74 | {
75 | printf("unable to create a new IoTHubMessage\r\n");
76 | }
77 | else
78 | {
79 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
80 | {
81 | printf("failed to hand over the message to IoTHubClient");
82 | }
83 | else
84 | {
85 | printf("IoTHubClient accepted the message for delivery\r\n");
86 | }
87 | IoTHubMessage_Destroy(messageHandle);
88 | }
89 | free((void*)buffer);
90 | messageTrackingId++;
91 | }
92 |
93 | /*this function "links" IoTHub to the serialization library*/
94 | static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
95 | {
96 | IOTHUBMESSAGE_DISPOSITION_RESULT result;
97 | const unsigned char* buffer;
98 | size_t size;
99 | if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
100 | {
101 | printf("unable to IoTHubMessage_GetByteArray\r\n");
102 | result = IOTHUBMESSAGE_ABANDONED;
103 | }
104 | else
105 | {
106 | /*buffer is not zero terminated*/
107 | char* temp = malloc(size + 1);
108 | if (temp == NULL)
109 | {
110 | printf("failed to malloc\r\n");
111 | result = IOTHUBMESSAGE_ABANDONED;
112 | }
113 | else
114 | {
115 | EXECUTE_COMMAND_RESULT executeCommandResult;
116 |
117 | (void)memcpy(temp, buffer, size);
118 | temp[size] = '\0';
119 | executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp);
120 | result =
121 | (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED :
122 | (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED :
123 | IOTHUBMESSAGE_REJECTED;
124 | free(temp);
125 | }
126 | }
127 | return result;
128 | }
129 |
130 | void simplesample_http_run(void)
131 | {
132 | if (platform_init() != 0)
133 | {
134 | printf("Failed to initialize the platform.\r\n");
135 | }
136 | else
137 | {
138 | if (serializer_init(NULL) != SERIALIZER_OK)
139 | {
140 | (void)printf("Failed on serializer_init\r\n");
141 | }
142 | else
143 | {
144 | IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
145 | int avgWindSpeed = 10;
146 | float minTemperature = 20.0;
147 | float minHumidity = 60.0;
148 |
149 | srand((unsigned int)time(NULL));
150 |
151 | if (iotHubClientHandle == NULL)
152 | {
153 | (void)printf("Failed on IoTHubClient_LL_Create\r\n");
154 | }
155 | else
156 | {
157 | // Because it can poll "after 9 seconds" polls will happen
158 | // effectively at ~10 seconds.
159 | // Note that for scalabilty, the default value of minimumPollingTime
160 | // is 25 minutes. For more information, see:
161 | // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
162 | unsigned int minimumPollingTime = 9;
163 | ContosoAnemometer* myWeather;
164 |
165 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
166 | {
167 | printf("failure to set option \"MinimumPollingTime\"\r\n");
168 | }
169 |
170 | #ifdef SET_TRUSTED_CERT_IN_SAMPLES
171 | // For mbed add the certificate information
172 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
173 | {
174 | (void)printf("failure to set option \"TrustedCerts\"\r\n");
175 | }
176 | #endif // SET_TRUSTED_CERT_IN_SAMPLES
177 |
178 | myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
179 | if (myWeather == NULL)
180 | {
181 | (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
182 | }
183 | else
184 | {
185 | if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
186 | {
187 | printf("unable to IoTHubClient_SetMessageCallback\r\n");
188 | }
189 | else
190 | {
191 | myWeather->DeviceId = "myFirstDevice";
192 | myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
193 | myWeather->Temperature = minTemperature + (rand() % 10);
194 | myWeather->Humidity = minHumidity + (rand() % 20);
195 | {
196 | unsigned char* destination;
197 | size_t destinationSize;
198 | if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed, myWeather->Temperature, myWeather->Humidity) != CODEFIRST_OK)
199 | {
200 | (void)printf("Failed to serialize\r\n");
201 | }
202 | else
203 | {
204 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
205 | if (messageHandle == NULL)
206 | {
207 | printf("unable to create a new IoTHubMessage\r\n");
208 | }
209 | else
210 | {
211 | MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);
212 | (void)sprintf_s(propText, sizeof(propText), myWeather->Temperature > 28 ? "true" : "false");
213 | if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
214 | {
215 | printf("ERROR: Map_AddOrUpdate Failed!\r\n");
216 | }
217 |
218 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
219 | {
220 | printf("failed to hand over the message to IoTHubClient");
221 | }
222 | else
223 | {
224 | printf("IoTHubClient accepted the message for delivery\r\n");
225 | }
226 |
227 | IoTHubMessage_Destroy(messageHandle);
228 | }
229 | free(destination);
230 | }
231 | }
232 |
233 | /* wait for commands */
234 | while (1)
235 | {
236 | IoTHubClient_LL_DoWork(iotHubClientHandle);
237 | ThreadAPI_Sleep(100);
238 | }
239 | }
240 |
241 | DESTROY_MODEL_INSTANCE(myWeather);
242 | }
243 | IoTHubClient_LL_Destroy(iotHubClientHandle);
244 | }
245 | serializer_deinit();
246 | }
247 | platform_deinit();
248 | }
249 | }
250 |
251 | void sample_run(void)
252 | {
253 | simplesample_http_run();
254 | }
255 |
256 |
--------------------------------------------------------------------------------
/simplesample_http/simplesample_http.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SIMPLESAMPLEHTTP_H
5 | #define SIMPLESAMPLEHTTP_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void simplesample_http_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SIMPLESAMPLEHTTP_H */
18 |
--------------------------------------------------------------------------------
/simplesample_http/simplesample_http.ino:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | // Please use an Arduino IDE 1.6.8 or greater
5 |
6 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
7 | // iot_configs.h
8 | #include "iot_configs.h"
9 |
10 | #include
11 | #if defined(IOT_CONFIG_MQTT)
12 | #include
13 | #elif defined(IOT_CONFIG_HTTP)
14 | #include
15 | #endif
16 |
17 | #include "sample.h"
18 | #include "esp8266/sample_init.h"
19 |
20 | static char ssid[] = IOT_CONFIG_WIFI_SSID;
21 | static char pass[] = IOT_CONFIG_WIFI_PASSWORD;
22 |
23 | void setup() {
24 | sample_init(ssid, pass);
25 | }
26 |
27 | // Azure IoT samples contain their own loops, so only run them once
28 | static bool done = false;
29 | void loop() {
30 | if (!done)
31 | {
32 | // Run the sample
33 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
34 | // iot_configs.h
35 | sample_run();
36 | done = true;
37 | }
38 | else
39 | {
40 | delay(500);
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/simplesample_mqtt/README.md:
--------------------------------------------------------------------------------
1 | ### simplesample_mqtt
2 |
3 | Instructions for this sample are
4 | [here in the Azure IoT MQTT protocol library for Arduino.](https://github.com/Azure/azure-iot-arduino-protocol-mqtt)
--------------------------------------------------------------------------------
/simplesample_mqtt/iot_configs.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef IOT_CONFIGS_H
5 | #define IOT_CONFIGS_H
6 |
7 | /**
8 | * WiFi setup
9 | */
10 | #define IOT_CONFIG_WIFI_SSID ""
11 | #define IOT_CONFIG_WIFI_PASSWORD ""
12 |
13 | /**
14 | * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys
15 | * String containing Hostname, Device Id & Device Key in the format:
16 | * "HostName=;DeviceId=;SharedAccessKey="
17 | */
18 | #define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey="
19 |
20 | /**
21 | * Choose the transport protocol
22 | */
23 | #define IOT_CONFIG_MQTT // uncomment this line for MQTT
24 | // #define IOT_CONFIG_HTTP // uncomment this line for HTTP
25 |
26 | #endif /* IOT_CONFIGS_H */
27 |
--------------------------------------------------------------------------------
/simplesample_mqtt/sample.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SAMPLE_H
5 | #define SAMPLE_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void sample_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SAMPLE_H */
18 |
--------------------------------------------------------------------------------
/simplesample_mqtt/simplesample_mqtt.c:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #include
5 |
6 | #include
7 | #include
8 |
9 | /* This sample uses the _LL APIs of iothub_client for example purposes.
10 | That does not mean that MQTT only works with the _LL APIs.
11 | Simply changing the using the convenience layer (functions not having _LL)
12 | and removing calls to _DoWork will yield the same results. */
13 |
14 | #include "AzureIoTHub.h"
15 | #include "iot_configs.h"
16 |
17 |
18 | /*String containing Hostname, Device Id & Device Key in the format: */
19 | /* "HostName=;DeviceId=;SharedAccessKey=" */
20 | static const char* connectionString = IOT_CONFIG_CONNECTION_STRING;
21 |
22 | // Define the Model
23 | BEGIN_NAMESPACE(WeatherStation);
24 |
25 | DECLARE_MODEL(ContosoAnemometer,
26 | WITH_DATA(ascii_char_ptr, DeviceId),
27 | WITH_DATA(int, WindSpeed),
28 | WITH_DATA(float, Temperature),
29 | WITH_DATA(float, Humidity),
30 | WITH_ACTION(TurnFanOn),
31 | WITH_ACTION(TurnFanOff),
32 | WITH_ACTION(SetAirResistance, int, Position)
33 | );
34 |
35 | END_NAMESPACE(WeatherStation);
36 |
37 | static char propText[1024];
38 |
39 | EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device)
40 | {
41 | (void)device;
42 | (void)printf("Turning fan on.\r\n");
43 | return EXECUTE_COMMAND_SUCCESS;
44 | }
45 |
46 | EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device)
47 | {
48 | (void)device;
49 | (void)printf("Turning fan off.\r\n");
50 | return EXECUTE_COMMAND_SUCCESS;
51 | }
52 |
53 | EXECUTE_COMMAND_RESULT SetAirResistance(ContosoAnemometer* device, int Position)
54 | {
55 | (void)device;
56 | (void)printf("Setting Air Resistance Position to %d.\r\n", Position);
57 | return EXECUTE_COMMAND_SUCCESS;
58 | }
59 |
60 | void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
61 | {
62 | unsigned int messageTrackingId = (unsigned int)(uintptr_t)userContextCallback;
63 |
64 | (void)printf("Message Id: %u Received.\r\n", messageTrackingId);
65 |
66 | (void)printf("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
67 | }
68 |
69 | static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size, ContosoAnemometer *myWeather)
70 | {
71 | static unsigned int messageTrackingId;
72 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
73 | if (messageHandle == NULL)
74 | {
75 | printf("unable to create a new IoTHubMessage\r\n");
76 | }
77 | else
78 | {
79 | MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);
80 | (void)sprintf_s(propText, sizeof(propText), myWeather->Temperature > 28 ? "true" : "false");
81 | if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
82 | {
83 | (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
84 | }
85 |
86 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
87 | {
88 | printf("failed to hand over the message to IoTHubClient");
89 | }
90 | else
91 | {
92 | printf("IoTHubClient accepted the message for delivery\r\n");
93 | }
94 | IoTHubMessage_Destroy(messageHandle);
95 | }
96 | messageTrackingId++;
97 | }
98 |
99 | /*this function "links" IoTHub to the serialization library*/
100 | static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
101 | {
102 | IOTHUBMESSAGE_DISPOSITION_RESULT result;
103 | const unsigned char* buffer;
104 | size_t size;
105 | if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
106 | {
107 | printf("unable to IoTHubMessage_GetByteArray\r\n");
108 | result = IOTHUBMESSAGE_ABANDONED;
109 | }
110 | else
111 | {
112 | /*buffer is not zero terminated*/
113 | char* temp = malloc(size + 1);
114 | if (temp == NULL)
115 | {
116 | printf("failed to malloc\r\n");
117 | result = IOTHUBMESSAGE_ABANDONED;
118 | }
119 | else
120 | {
121 | (void)memcpy(temp, buffer, size);
122 | temp[size] = '\0';
123 | EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp);
124 | result =
125 | (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED :
126 | (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED :
127 | IOTHUBMESSAGE_REJECTED;
128 | free(temp);
129 | }
130 | }
131 | return result;
132 | }
133 |
134 | void simplesample_mqtt_run(void)
135 | {
136 | if (platform_init() != 0)
137 | {
138 | (void)printf("Failed to initialize platform.\r\n");
139 | }
140 | else
141 | {
142 | if (serializer_init(NULL) != SERIALIZER_OK)
143 | {
144 | (void)printf("Failed on serializer_init\r\n");
145 | }
146 | else
147 | {
148 | IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
149 | srand((unsigned int)time(NULL));
150 | int avgWindSpeed = 10;
151 | float minTemperature = 20.0;
152 | float minHumidity = 60.0;
153 |
154 | if (iotHubClientHandle == NULL)
155 | {
156 | (void)printf("Failed on IoTHubClient_LL_Create\r\n");
157 | }
158 | else
159 | {
160 | #ifdef SET_TRUSTED_CERT_IN_SAMPLES
161 | // For mbed add the certificate information
162 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
163 | {
164 | (void)printf("failure to set option \"TrustedCerts\"\r\n");
165 | }
166 | #endif // SET_TRUSTED_CERT_IN_SAMPLES
167 |
168 |
169 | ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
170 | if (myWeather == NULL)
171 | {
172 | (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
173 | }
174 | else
175 | {
176 | if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
177 | {
178 | printf("unable to IoTHubClient_SetMessageCallback\r\n");
179 | }
180 | else
181 | {
182 | myWeather->DeviceId = "myFirstDevice";
183 | myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
184 | myWeather->Temperature = minTemperature + (rand() % 10);
185 | myWeather->Humidity = minHumidity + (rand() % 20);
186 | {
187 | unsigned char* destination;
188 | size_t destinationSize;
189 | if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed, myWeather->Temperature, myWeather->Humidity) != CODEFIRST_OK)
190 | {
191 | (void)printf("Failed to serialize\r\n");
192 | }
193 | else
194 | {
195 | sendMessage(iotHubClientHandle, destination, destinationSize, myWeather);
196 | free(destination);
197 | }
198 | }
199 |
200 | /* wait for commands */
201 | while (1)
202 | {
203 | IoTHubClient_LL_DoWork(iotHubClientHandle);
204 | ThreadAPI_Sleep(100);
205 | }
206 | }
207 |
208 | DESTROY_MODEL_INSTANCE(myWeather);
209 | }
210 | IoTHubClient_LL_Destroy(iotHubClientHandle);
211 | }
212 | serializer_deinit();
213 | }
214 | platform_deinit();
215 | }
216 | }
217 |
218 | void sample_run(void)
219 | {
220 | simplesample_mqtt_run();
221 | }
222 |
223 |
--------------------------------------------------------------------------------
/simplesample_mqtt/simplesample_mqtt.h:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #ifndef SIMPLESAMPLEMQTT_H
5 | #define SIMPLESAMPLEMQTT_H
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | void simplesample_mqtt_run(void);
12 |
13 | #ifdef __cplusplus
14 | }
15 | #endif
16 |
17 | #endif /* SIMPLESAMPLEMQTT_H */
18 |
--------------------------------------------------------------------------------
/simplesample_mqtt/simplesample_mqtt.ino:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | // Please use an Arduino IDE 1.6.8 or greater
5 |
6 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
7 | // iot_configs.h
8 | #include "iot_configs.h"
9 |
10 | #include
11 | #if defined(IOT_CONFIG_MQTT)
12 | #include
13 | #elif defined(IOT_CONFIG_HTTP)
14 | #include
15 | #endif
16 |
17 | #include "sample.h"
18 | #include "esp8266/sample_init.h"
19 |
20 | static char ssid[] = IOT_CONFIG_WIFI_SSID;
21 | static char pass[] = IOT_CONFIG_WIFI_PASSWORD;
22 |
23 | void setup() {
24 | sample_init(ssid, pass);
25 | }
26 |
27 | // Azure IoT samples contain their own loops, so only run them once
28 | static bool done = false;
29 | void loop() {
30 | if (!done)
31 | {
32 | // Run the sample
33 | // You must set the device id, device key, IoT Hub name and IotHub suffix in
34 | // iot_configs.h
35 | sample_run();
36 | done = true;
37 | }
38 | else
39 | {
40 | delay(500);
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------