├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── command_center ├── command_center.c ├── command_center.h ├── command_center.ino ├── sensor.h └── sensor_dht22.cpp ├── command_center_node ├── .gitignore ├── bower.json ├── config.json ├── package.json ├── public │ └── index.html └── server.js ├── device_twin ├── device_twin.ino ├── iot_configs.h ├── iothub_client_sample_device_twin.c └── sample.h ├── img ├── thingdev_command_center.png └── thingdev_remote_monitoring.png ├── remote_monitoring ├── iot_configs.h ├── remote_monitoring.c ├── remote_monitoring.h ├── remote_monitoring.ino ├── sample.h ├── sensor.h └── sensor_dht22.cpp ├── simplesample_http ├── README.md ├── iot_configs.h ├── sample.h ├── simplesample_http.c ├── simplesample_http.h └── simplesample_http.ino └── simplesample_mqtt ├── README.md ├── iot_configs.h ├── sample.h ├── simplesample_mqtt.c ├── simplesample_mqtt.h └── simplesample_mqtt.ino /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure samples 2 | 3 | Thank you for your interest in contributing to Azure samples! 4 | 5 | ## Ways to contribute 6 | 7 | You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways: 8 | 9 | - Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/iot-hub-c-thingdev-getstartedkit/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/issues) on GitHub. We are actively monitoring the issues and improving our samples. 11 | - If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Get Started with Microsoft Azure IoT Starter Kit - SparkFun ESP8266 Thing Dev Kit (Arduino-compatible) 4 | 5 | **Note: this article has been archived and it is not longer updated. Instructions may not be totally up to date.** 6 | 7 | *** 8 | **Looking for something simple?** This tutorial is very complete and contains a lot of detail. If you want 9 | something quick and simple, try one of these: 10 | * [Azure IoT HTTP protocol sample](https://github.com/Azure/azure-iot-arduino-protocol-http) 11 | * [Azure IoT MQTT protocol sample](https://github.com/Azure/azure-iot-arduino-protocol-mqtt) 12 | *** 13 | This page contains technical information to help you get familiar with Azure IoT using the Azure IoT Starter Kit - SparkFun ESP8266 Thing Dev Kit (Arduino-compatible). You will find two tutorials that will walk you through different scenarios. The first tutorial will show you how to connect your Azure IoT Starter kit to our Remote Monitoring preconfigured solution from Azure IoT Suite. In the second tutorial, you will leverage Azure IoT services to create your own IoT solution. 14 | 15 | You can choose to start with whichever tutorial you want to. If you've never worked with Azure IoT services before, we encourage you to start with the Remote Monitoring solution tutorial, because all of the Azure services will be provisioned for you in a built-in preconfigured solution. Then you can explore how each of the services work by going through the second tutorial. 16 | 17 | We hope you enjoy the tutorials! Please provide feedback if there's anything that we can improve. 18 | 19 | *** 20 | **Don't have a kit yet?:** Click [here](http://azure.com/iotstarterkits) 21 | *** 22 | 23 | - [Running a Simple Remote Monitoring Solution with the SparkFun ESP8266 Thing Dev Kit](#run-on-device) 24 | - [Using Microsoft Azure IoT to Process and Use Sensor Data to Indicate Abnormal Temperatures](#using-microsoft-azure-iot) 25 | 26 | 27 | 28 | # Running a Simple Remote Monitoring Solution with the SparkFun ESP8266 Thing Dev Kit (Arduino-compatible) 29 | 30 | This tutorial describes the process of taking your SparkFun ESP8266 Thing Dev Kit kit, and using it to develop a temperature, humidity and pressure reader that can communicate with the cloud using the  Microsoft Azure IoT SDK.  31 | 32 | ## Table of Contents 33 | 34 | - [1.1 Tutorial Overview](#section1.1) 35 | - [1.2 Before Starting](#section1.2) 36 | - [1.2.1 Required Software](#section1.2.1) 37 | - [1.2.2 Required Hardware](#section1.2.2) 38 | - [1.3 Create a New Azure IoT Suite Remote Monitoring solution and Add Device](#section1.3) 39 | - [1.4 Connect the DHT22 Sensor Module to your Device](#section1.4) 40 | - [1.5 Add the SparkFun ESP8266 Thing Dev Kit to the Arduino IDE](#section1.5) 41 | - [1.6 Install Library Dependencies](#section1.6) 42 | - [1.7 Modify the Remote Monitoring Sample](#section1.7) 43 | - [1.8 Build Your Remote Monitoring Sample](#section1.8) 44 | - [1.9 View the Sensor Data from the Remote Monitoring Portal](#section1.9) 45 | - [1.10 Next steps](#section1.10) 46 | 47 | 48 | 49 | ## 1.1 Tutorial Overview 50 | 51 | In this tutorial, you'll be doing the following: 52 | - Setting up your environment on Azure using the Microsoft Azure IoT Suite Remote Monitoring preconfigured solution, getting a large portion of the set-up that would be required done in one step. 53 | - Setting your device and sensors up so that it can communicate with both your computer, and Azure IoT. 54 | - Updating the device code sample to include our connection data and send it to Azure to be viewed remotely. 55 | 56 | 57 | 58 | ## 1.2 Before Starting 59 | 60 | 61 | 62 | ### 1.2.1 Required Software 63 | 64 | - Arduino IDE, version 1.6.8. from www.arduino.cc (Earlier versions will not work with the AzureIoT library) 65 | - Sensor interface library from Adafruit 66 | 67 | 68 | 69 | ### 1.2.2 Required Hardware 70 | 71 | - SparkFun ESP8266 Thing Dev Kit kit 72 | - A microB USB cable 73 | - A desktop or laptop computer which can run **Arduino IDE 1.6.8** 74 | 75 | 76 | 77 | ## 1.3 Create a New Azure IoT Suite Remote Monitoring solution and Add Device 78 | 79 | - Log in to [Azure IoT Suite](https://www.azureiotsuite.com/) with your Microsoft account and click **Create a New Preconfigured Solution** 80 | 81 | *** 82 | **Note:** For first time users, click here to get your [Azure free trial](https://azure.microsoft.com/en-us/pricing/free-trial/) which gives you 200USD of credit to get started. 83 | *** 84 | 85 | - Click select in the **Remote Monitoring** option 86 | - Type in a solution name. For this tutorial we’ll be using _“SparkFunSuite”_ (You will have to name it something else. Make it unique. I.E. "ContosoSample") 87 | 88 | *** 89 | **Note:** Make sure to copy down the names and connection strings mentioned into a text document for reference later. 90 | *** 91 | 92 | - Choose your subscription and desired region to deploy, then click **Create Solution** 93 | - Wait for Azure to finish provisioning your IoT suite (this process may take up to 10 minutes), and then click **Launch** 94 | 95 | *** 96 | **Note:** You may be asked to log back in. This is to ensure your solution has proper permissions associated with your account. 97 | *** 98 | 99 | - Open the link to your IoT Suite’s “Solution Dashboard.” You may have been redirected there already. 100 | - This opens your personal remote monitoring site at the URL _<Your Azure IoT Hub suite name>.azurewebsites.net_ (e.g. _SparkFunSuite.azurewebsites.net_) 101 | - Click **Add a Device** at the lower left hand corner of your screen 102 | - Add a new **custom device** 103 | - Enter your desired `device ID`. In this case we’ll use _“SparkFun_w_DHT22”_, and then click Check ID 104 | - If Device ID is available, go ahead and click **Create** 105 | - Make note of your `device ID`, `Device Key`, and `IoT Hub Hostname` to enter into the code you’ll run on your device later  106 | 107 | *** 108 | **Warning:** The Remote Monitoring solution provisions a set of Azure IoT Services in your Azure account. It is meant to reflect a real enterprise architecture and thus its Azure consumption is quite heavy. To avoid unnecessary Azure consumption, we recommend you delete the preconfigured solution in azureiotsuite.com once you are done with your work (since it is easy to recreate). Alternatively, if you want to keep it up and running you can do two things to reduce consumption: 109 | 110 | 1) Visit this [guide](https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md) to run the solution in demo mode and reduce the Azure consumption. 111 | 112 | 2) Disable the simulated devices created with the solution (Go to Devices>>Select the device>> on the device details menu on the right, clich on Disable Device. Repeat with all the simulated devices). 113 | 114 | 3) **Stop** your remote monitoring solution while you are working on the next steps. (See: [Troubleshooting](#troubleshooting)) 115 | *** 116 | 117 | - For additional reference, refer to the following: 118 | - https://azure.microsoft.com/en-us/documentation/articles/iot-suite-remote-monitoring-sample-walkthrough/ 119 | - https://azure.microsoft.com/en-us/documentation/articles/iot-suite-connecting-devices/ 120 | 121 | 122 | 123 | ## 1.4 Connect the DHT22 Sensor Module to your Device 124 | 125 | - Using [this image](https://github.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/blob/master/img/thingdev_remote_monitoring.png?raw=true) as a reference, connect your DHT22 and SparkFun ESP8266 Thing Dev Kit to the breadboard 126 | 127 | *** 128 | **Note:** Column on the left corresponds to sensor and on the Right to board. On the image, the board is place between 10 and 30 and sensor between 1 and 9. 129 | *** 130 | - For sensor pins, we will use the following wiring: 131 | 132 | | Start | End | Cable Color | 133 | | ----------------------- | ---------------------- | ------------: | 134 | | VDD (Pin 1G) | Pin 24J | Red cable | 135 | | DATA (Pin 2G) | Pin 23J | White cable | 136 | | GND (Pin 4G) | Pin 25A | Black cable | 137 | 138 | | Start | End | Connector | 139 | | ----------------------- | ---------------------- | ------------: | 140 | | DHT22 (Pin 1I) | DHT22 (Pin 4I) | DHT22 | 141 | | NULL (Pin 2H) | Pin 1F | 10k Ohm Resistor | 142 | 143 | - For more information, see: [Adafruit DHT22 sensor setup](https://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor). 144 | 145 | **At the end of your work, your SparkFun ESP8266 Thing Dev Kit should be connected with a working sensor. We'll test it in the next sections.** 146 | 147 | 148 | 149 | ## 1.5 Add the SparkFun ESP8266 Thing Dev Kit to the Arduino IDE 150 | 151 | You will need to install the SparkFun ESP8266 Thing Dev Kit board extension for the Arduino IDE: 152 | 153 | - Follow the instructions up to the end of "Setting Up Arduino" [here](https://learn.sparkfun.com/tutorials/esp8266-thing-development-board-hookup-guide). There you will see how to add a URL pointing to SparkFun's repository of board extensions, how to make the SparkFun ESP8266 Thing Dev Kit board selectable under the **Tools** menu, and how to get the Blink sketch to run. 154 | 155 | *** 156 | **Note**: Make sure that you select "SparkFun ESP8266 Thing Dev" and NOT "SparkFun ESP8266 Thing" in the Arduino IDE (under **Tools -> Board)** 157 | *** 158 | 159 | - After going through this, you should have a working sample with a blinking light on your board. 160 | - If you can’t upload the sample, reconnect the device, then the power switch to OFF. Press the upload button, and flip the switch back to ON. 161 | 162 | 163 | 164 | ## 1.6 Install Library Dependencies 165 | 166 | For this project, we'll also need the following libraries: 167 | 168 | - DHT Sensor Library 169 | - Adafruit DHT Unified 170 | - AzureIoTHub 171 | - AzureIoTUtility 172 | - AzureIoTProtocol_MQTT 173 | 174 | To install them, click on the `Sketch -> Include Library -> Manage Libraries`. Search for each library using the box in the upper-right to filter your search, click on the found library, and click the "Install" button. 175 | 176 | The Adafruit Sensor library is also needed. This can be downloaded [here](https://github.com/adafruit/Adafruit_Sensor). Instructions for manually installing a library can be found [here](https://www.arduino.cc/en/Guide/Libraries). 177 | 178 | *** 179 | **Note**: Starting on version 1.0.17, `AzureIoTHub` required the `AzureIoTUtility` and one of the available protocols. These samples use the `AzureIoTProtocol_MQTT`, but it is prepared to work with `AzureIoTProtocol_HTTP` too. 180 | *** 181 | 182 | 183 | 184 | ## 1.7 Modify the Remote Monitoring sample 185 | 186 | - Unzip the [example code](https://github.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/archive/master.zip), and double-click the file `remote_monitoring.ino` to open the project in the Arduino IDE. 187 | - You will be prompted to creat a folder. Do this, and move the other files in the folder into the newly created child folder 188 | - In the project, edit the `iot_configs.h`, look for the following lines of code: 189 | 190 | ``` 191 | #define IOT_CONFIG_WIFI_SSID "" 192 | #define IOT_CONFIG_WIFI_PASSWORD "" 193 | ``` 194 | 195 | - Replace the placeholders with your WiFi name (SSID), WiFi password, and the device connection string you created at the beginning of this tutorial.  196 | - Look for the following line of code and replace the placeholders connection information (this is the Device information that you obtained in the Remote Monitoring console): 197 | 198 | ``` 199 | #define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey=" 200 | ``` 201 | 202 | - Save with `Control-s` 203 | 204 | 205 | 206 | ## 1.8 Build Your Remote Monitoring Sample 207 | 208 | - On windows, the COM port will disconnect, and a new one will appear. Use **Tools -> Port -> COM** to re-select it. 209 | - Build and upload the code using **Sketch ->  Upload**. 210 | 211 | *** 212 | **Note**: As of 1.6.8, the Arduino IDE doesn't properly show "Upload Completed", even when it succeeds. 213 | *** 214 | 215 | - There should now be a green LED on your SparkFun ESP8266 Thing Dev Kit. Re-select the COM port if necessary, and then open the Serial Monitor. After 15 seconds you should see a measurements update. 216 | 217 | *** 218 | **Note**: When first starting you will likely see a “Fetching NTP epoch time failed” error – This is normal, and it trying to sync with Azure. This can take even up to 30 seconds to find a NTP server to sync with. One it is synced, it should start transmitting from there. 219 | *** 220 | 221 | 222 | 223 | ## 1.9 View the Sensor Data from the Remote Monitoring Portal 224 | 225 | - Once you have the sample running, visit your dashboard by visiting azureiotsuite.com and clicking “Launch” on your solution 226 | - Make sure the “Device to View” in the upper right is set to your device 227 | - If the demo is running, you should see the graph change as your data updates in real time! 228 | 229 | *** 230 | **Note:** Make sure you delete or **stop** your remote monitoring solution once you have completed this to avoid unnecessary Azure consumption! (See: [Troubleshooting](#troubleshooting)) 231 | *** 232 | 233 | 234 | 235 | ## 1.10 Next steps 236 | 237 | Please visit our [Azure IoT Dev Center](https://azure.microsoft.com/en-us/develop/iot/) for more samples and documentation on Azure IoT. 238 | 239 | 240 | 241 | # Using Microsoft Azure IoT Services to Identify Temperature Anomalies 242 | 243 | This tutorial describes the process of taking your Microsoft Azure IoT Starter Kit for the SparkFun ESP8266 Thing Dev Kit, and using it to develop a temperature and humidity reader that can communicate with the cloud using the Microsoft Azure IoT SDK. 244 | 245 | ## Table of Contents 246 | 247 | - [2.1 Tutorial Overview](#section2.1) 248 | - [2.2 Before Starting](#section2.2) 249 | - [2.2.1 Required Software](#section2.2.1) 250 | - [2.2.2 Required Hardware](#section2.2.2) 251 | - [2.3 Connect the Sensor Module to your Device](#section2.3) 252 | - [2.4 Create a New Microsoft Azure IoT Hub and Add Device](#section2.4) 253 | - [2.5 Create an Event Hub](#section2.5) 254 | - [2.6 Create a Storage Account for Table Storage](#section2.6) 255 | - [2.7 Create a Stream Analytics job to Save IoT Data in Table Storage and Raise Alerts](#section2.7) 256 | - [2.8 Node Application Setup](#section2.8) 257 | - [2.9 Add the SparkFun ESP8266 Thing Dev Kit to the Arduino IDE](#section2.9) 258 | - [2.10 Install Library Dependencies](#section2.10) 259 | - [2.11 Modify the Command Center Sample](#section2.11) 260 | - [2.12 Build Your Command Center Sample](#section2.12) 261 | - [2.13 Next steps](#section2.13) 262 | 263 | 264 | 265 | ## 2.1 Tutorial Overview 266 | 267 | This tutorial has the following steps: 268 | - Provision an IoT Hub instance on Microsoft Azure and adding your device. 269 | - Prepare the device, get connected to the device, and set it up so that it can read sensor data. 270 | - Configure your Microsoft Azure IoT services by adding Event Hub, Storage Account, and Stream Analytics resources. 271 | - Prepare your local web solution for monitoring and sending commands to your device. 272 | - Update the sample code to respond to commands and include the data from our sensors, sending it to Microsoft Azure to be viewed remotely. 273 | 274 | Here is a breakdown of the data flow: 275 | - The application running on the Adafruit Huzzah ESP8266 will get temperature data from the temperature sensor and it will send them to the IoT Hub 276 | - A Stream Analytics job will read the data from IoT Hub and write them to an Azure Storage Table. Also, if an anomaly is detected, then this job will write data to an Event Hub 277 | - The Node.js application that is running on your computers will read the data from the Azure Storage Table and the Event Hub and will present them to the user 278 | 279 | The end result will be a functional command center where you can view the history of your device's sensor data, a history of alerts, and send commands back to the device. 280 | 281 | 282 | 283 | ## 2.2 Before Starting 284 | 285 | 286 | 287 | ### 2.2.1 Required Software 288 | 289 | - [Git](https://git-scm.com/downloads) - For cloning the required repositories 290 | - Node.js - For the Node application, we will go over this later. 291 | - Arduino IDE, version 1.6.8. (Earlier versions will not work with the Azure IoT library) 292 | - Sensor interface from Adafruit 293 | 294 | 295 | 296 | ### 2.2.2 Required Hardware 297 | - SparkFun ESP8266 Thing Dev Kit IoT kit 298 | - A microB USB cable 299 | - A desktop or laptop computer which can run **Arduino IDE 1.6.8** 300 | 301 | 302 | 303 | ## 2.3 Connect the Sensor Module to your Device 304 | 305 | - Using [this image](https://github.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit/blob/master/img/thingdev_command_center.png?raw=true) as a reference, connect your DHT22 and SparkFun ESP8266 Thing Dev Kit to the breadboard 306 | 307 | *** 308 | **Note:** Column on the left corresponds to sensor and on the Right to board. On the image, the board is place between 10 and 30 and sensor between 1 and 9. Additionally, when counting the - pins, start from the right and count in, as these do not align with the numbers indicated on the board. 309 | 310 | **Note:** The resistors can change a little from one kit to another, e.g. it can be 330 Ohm (orange, orange, brown) or 560 Ohm (green, blue, brown). Both will work with success. 311 | *** 312 | 313 | | Start | End | Cable Color | 314 | | ----------------------- | ---------------------- | ------------: | 315 | | VDD (Pin 1G) | Pin 24J | Red cable | 316 | | Pin 19A | Pin 6A | Red cable | 317 | | DATA (Pin 2G) | Pin 23J | White cable | 318 | | GND (Pin 4G) | Pin 1- | Black cable | 319 | | GND (Pin 25A) | Pin 21- | Black cable | 320 | | Pin 20A | Pin 3A | Green cable | 321 | 322 | | Start | End | Connector | 323 | | ----------------------- | ---------------------- | ------------: | 324 | | DHT22 (Pin 1I) | DHT22 (Pin 4I) | DHT22 | 325 | | NULL (Pin 2H) | Pin 1F | 10k Ohm Resistor | 326 | | GRN LED (Pin 2C) | Pin 3C | Green LED | 327 | | RED LED (Pin 5C) | Pin 6C | Red LED | 328 | 329 | - For more information, see: [Adafruit DHT22 sensor setup](https://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor). 330 | 331 | **At the end of your work, your SparkFun ESP8266 Thing Dev Kit should be connected with a working sensor. We'll test it in the next sections.** 332 | 333 | 334 | 335 | ### 2.4 Create a New Microsoft Azure IoT Hub and Add Device 336 | 337 | - To create your Microsoft Azure IoT Hub and add a device, follow the instructions outlined in the [Setup IoT Hub Microsoft Azure Iot SDK page](https://github.com/Azure/azure-iot-sdks/blob/master/doc/setup_iothub.md). 338 | - After creating your device, make note of your connection string to enter into the code you’ll run on your device later 339 | 340 | *** 341 | **Note:** Make sure to copy down the names and connection strings mentioned into a text document for reference later. 342 | *** 343 | 344 | 345 | 346 | ## 2.5 Create an Event Hub 347 | Event Hub is an Azure IoT publish-subscribe service that can ingest millions of events per second and stream them into multiple applications, services or devices. 348 | 349 | - Log on to the [Microsoft Azure Portal](https://portal.azure.com/) 350 | - Click on **New** -> **Internet of Things**-> **Event Hub** 351 | - Enter the following settings for the Event Hub Namespace (use a name of your choice for the event hub and the namespace): 352 | - Name: `Your choice` (we chose `SparkFun2Suite`) 353 | - Pricing Tier: `Basic` 354 | - Subscription: `Your choice` 355 | - Resource Group: `Your choice` 356 | - Location: `Your choice` 357 | - Click on **Create** 358 | - Wait until the Event Hub Namespace is created, and then create an Event Hub using the following steps: 359 | - Click on your `SparkFun2Suite` Event Hub Namespace (or pick any other name that you used) 360 | - Click the **Add Event Hub** 361 | - Name: `thingdevEventHub` 362 | - Click on **Create** 363 | - Wait until the new Event Bus is created 364 | - Click on the **Event Hubs** arrow in the **Overview** tab (might require a few clicks, until the UI is updated) 365 | - Select the `thingdevEventHub` eventhub and go in the **Configure** tab in the **Shared Access Policies** section, add a new policy: 366 | - Name = `readwrite` 367 | - Permissions = `Send, Listen` 368 | - Click **Save** at the bottom of the page, then click the **Dashboard** tab near the top and click on **Connection Information** at the bottom 369 | - _Copy down the connection string for the `readwrite` policy you created._ 370 | - From the your IoT Hub Settings (The Resource that has connected dots) on the [Microsoft Azure Portal](https://portal.azure.com/), click the **Messaging blade** (found in your settings), write down the _Event Hub-compatible name_ 371 | - Look at the _Event-hub-compatible Endpoint_, and write down this part: sb://**thispart**.servicebus.windows.net/ we will call this one the _IoTHub EventHub-compatible namespace_ 372 | 373 | 374 | 375 | ## 2.6 Create a Storage Account for Table Storage 376 | Now we will create a service to store our data in the cloud. 377 | - Log on to the [Microsoft Azure Portal](https://portal.azure.com/) 378 | - In the menu, click **New** and select **Data + Storage** then **Storage Account** 379 | - Name: `Your choice` (we chose `thingdevstorage`) 380 | - Deployment model: `Classic` 381 | - Performance: `Standard` 382 | - Replication: `Read-access geo-redundant storage (RA-GRS)` 383 | - Subscription: `Your choice` 384 | - Resource Group: `Your choice` 385 | - Location: `Your choice` 386 | - Once the account is created, find it in the **resources blade** or click on the **pinned tile**, go to **Settings**, **Keys**, and write down the _primary connection string_. 387 | 388 | 389 | 390 | ## 2.7 Create a Stream Analytics job to Save IoT Data in Table Storage and Raise Alerts 391 | Stream Analytics is an Azure IoT service that streams and analyzes data in the cloud. We'll use it to process data coming from your device. 392 | 393 | - Log on to the [Microsoft Azure Portal](https://portal.azure.com/) 394 | - In the menu, click **New**, then click **Internet of Things**, and then click **Stream Analytics Job** 395 | - Enter a name for the job (We chose “SparkFunStorageJob”), a preferred region, then choose your subscription. At this stage you are also offered to create a new or to use an existing resource group. Choose the resource group you created earlier. 396 | - Once the job is created, open your **Job’s blade** or click on the **pinned tile**, and find the section titled _“Job Topology”_ and click the **Inputs** tile. In the Inputs blade, click on **Add** 397 | - Enter the following settings: 398 | - Input Alias = _`TempSensors`_ 399 | - Source Type = _`Data Stream`_ 400 | - Source = _`IoT Hub`_ 401 | - IoT Hub = _`SparkFun2Suite`_ (use the name for the IoT Hub you create before) 402 | - Shared Access Policy Name = _`iothubowner`_ 403 | - Shared Access Policy Key = _The `iothubowner` primary key can be found in your IoT Hub Settings -> Shared access policies_ 404 | - IoT Hub Consumer Group = "" (leave it to the default empty value) 405 | - Event serialization format = _`JSON`_ 406 | - Encoding = _`UTF-8`_ 407 | 408 | - Back to the **Stream Analytics Job blade**, click on the **Query tile** (next to the Inputs tile). In the Query settings blade, type in the below query and click **Save**: 409 | 410 | ``` 411 | SELECT 412 |     DeviceId, 413 |     EventTime, 414 |     MTemperature as TemperatureReading 415 | INTO 416 |     TemperatureTableStorage 417 | from TempSensors 418 | WHERE 419 |    DeviceId is not null 420 |    and EventTime is not null 421 | 422 | SELECT 423 |     DeviceId, 424 |     EventTime, 425 |     MTemperature as TemperatureReading 426 | INTO    427 |     TemperatureAlertToEventHub 428 | FROM 429 |     TempSensors 430 | WHERE MTemperature>25 431 | ``` 432 | 433 | *** 434 | **Note:** You can change the `25` to `0` when you're ready to generate alerts to look at. This number represents the temperature in degrees celsius to check for when creating alerts. 25 degrees celsius is 77 degrees fahrenheit. 435 | *** 436 | 437 | - Back to the **Stream Analytics Job blade**, click on the **Outputs** tile and in the **Outputs blade**, click on **Add** 438 | - Enter the following settings then click on **Create**: 439 | - Output Alias = _`TemperatureTableStorage`_ 440 | - Sink = _`Table Storage`_ 441 | - Subscription = _`Provide table settings storage manually`_ 442 | - Storage account = _`thingdevstorage`_ (The storage account you created earlier) 443 | - Storage account key = _(The primary key for the storage account made earlier, can be found in Settings -> Keys -> Primary Access Key)_ 444 | - Table Name = _`TemperatureRecords`_ (Your choice - If the table doesn’t already exist, Local Storage will create it) 445 | - Partition Key = _`DeviceId`_ 446 | - Row Key = _`EventTime`_ 447 | - Batch size = _`1`_ 448 | - Back to the **Stream Analytics Job blade**, click on the **Outputs tile**, and in the **Outputs blade**, click on **Add** 449 | - Enter the following settings then click on **Create**: 450 | - Output Alias = _`TemperatureAlertToEventHub`_ 451 | - Sink = _`Event Hub`_ 452 | - Subscription = _`Provide table settings storage manually`_ 453 | - Service Bus Namespace = _`SparkFun2Suite`_ 454 | - Event Hub Name = _`thingdeveventhub`_ (The Event Hub you made earlier) 455 | - Event Hub Policy Name = _`readwrite`_ 456 | - Event Hub Policy Key = _`Primary Key for readwrite Policy name`_ (That's the one you wrote down after creating the event hub) 457 | - Partition Key Column = _`0`_ 458 | - Event Serialization format = _`JSON`_ 459 | - Encoding = _`UTF-8`_ 460 | - Format = _`Line separated`_ 461 | - Back in the** Stream Analytics blade**, start the job by clicking on the **Start **button at the top 462 | 463 | *** 464 | **Note:** Make sure to **stop** your Command Center jobs once you have when you take a break or finish to avoid unnecessary Azure consumption! (See: [Troubleshooting](#troubleshooting)) 465 | *** 466 | 467 | 468 | 469 | ## 2.8 Node Application Setup 470 | 471 | - If you do not have it already, install Node.js and NPM. 472 | - Windows and Mac installers can be found here: https://nodejs.org/en/download/ 473 | - Ensure that you select the options to install NPM and add to your PATH. 474 | - Linux users can use the commands: 475 | 476 | ``` 477 | sudo apt-get update 478 | sudo apt-get install nodejs 479 | sudo apt-get install npm 480 | ``` 481 | 482 | - Additionally, make sure you have cloned the project repository locally by issuing the following command in your desired directory: 483 | 484 | ``` 485 | git clone https://github.com/Azure-Samples/iot-hub-c-thingdev-getstartedkit.git 486 | ``` 487 | 488 | - Open the `command_center_node` folder in your command prompt (`cd /command_center_node`) and install the required modules by running the following: 489 | 490 | ``` 491 | npm install -g bower 492 | npm install 493 | bower install 494 | ``` 495 | 496 | - Open the `config.json` file and replace the information with your project. See the following for instructions on how to retrieve those values. 497 | 498 | - eventhubName: 499 | - Open the [Classic Azure Management Portal](https://manage.windowsazure.com) 500 | - Open the Service Bus namespace you created earlier 501 | - Switch to the **EVENT HUBS** page 502 | - You can see and copy the name of your event hub from that page 503 | - ehConnString: 504 | - Click on the name of the event hub from above to open it 505 | - Click on the "CONNECTION INFORMATION" button along the bottom. 506 | - From there, click the button to copy the readwrite shared access policy connection string. 507 | - deviceConnString: 508 | - Use the information on the [Manage IoT Hub](https://github.com/Azure/azure-iot-sdks/blob/master/doc/manage_iot_hub.md) to retrieve your device connection string using either the Device Explorer or iothub-explorer tools. 509 | - iotHubConnString: 510 | - In the [Azure Portal](https://portal.azure.com) 511 | - Open the IoT Hub you created previously. 512 | - Open the "Settings" blade 513 | - Click on the "Shared access policies" setting 514 | - Click on the "service" policy 515 | - Copy the primary connection string for the policy 516 | - storageAccountName: 517 | - In the [Azure Portal](https://portal.azure.com) 518 | - Open the classic Storage Account you created previously to copy its name 519 | - storageAccountKey: 520 | - Click on the name of the storage account above to open it 521 | - Click the "Settings" button to open the Settings blade 522 | - Click on the "Keys" setting 523 | - Click the button next to the "PRIMARY ACCESS KEY" top copy it 524 | - storageTableName: 525 | - This must match the name of the table that was used in the Stream Analytics table storage output above. 526 | - If you used the instructions above, you would have named it ***`TemperatureRecords`*** 527 | - If you named it something else, enter the name you used instead. 528 | 529 | ``` 530 | { 531 | "port": "3000", 532 | "eventHubName": "event-hub-name", 533 | "ehConnString": "Endpoint=sb://name.servicebus.windows.net/;SharedAccessKeyName=readwrite;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", 534 | "deviceId": "iot-hub-device-name", 535 | "iotHubConnString": "HostName=iot-hub-name.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", 536 | "storageAcountName": "aaaaaaaaaaa", 537 | "storageAccountKey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa==", 538 | "storageTable": "TemperatureRecords" 539 | } 540 | ``` 541 | 542 | - Now it is time to run it! Enter the following command: 543 | 544 | ``` 545 | node server.js 546 | ``` 547 | 548 | - You should then see something similar to: 549 | 550 | ``` 551 | app running on http://localhost:3000 552 | client connected 553 | ``` 554 | 555 | - Visit the url in your browser and you will see the Node app running! 556 | 557 | To deploy this project to the cloud using Azure, you can reference [Creating a Node.js web app in Azure App Service](https://azure.microsoft.com/en-us/documentation/articles/web-sites-nodejs-develop-deploy-mac/). 558 | 559 | Next, we will update your device so that it can interact with all the things you just created. 560 | 561 | 562 | 563 | ## 2.9 Add the SparkFun ESP8266 Thing Dev Kit to the Arduino IDE 564 | 565 | You will need to install the SparkFun ESP8266 Thing Dev Kit board extension for the Arduino IDE: 566 | 567 | - Follow the instructions here: https://learn.sparkfun.com/tutorials/esp8266-thing-development-board-hookup-guide. There you will see how to add a URL pointing to Spark's repository of board extensions, how to make the SparkFun ESP8266 Thing Dev Kit board selectable under the **Tools** menu, and how to get the Blink sketch to run. 568 | - After going through this, you should have a working sample with a blinking light on your board. 569 | - If you can’t upload the sample, reconnect the device, then the power switch to OFF. Press the upload button, and flip the switch back to ON. 570 | 571 | 572 | 573 | ## 2.10 Install Library Dependencies 574 | 575 | For this project, we'll also need the following libraries: 576 | 577 | - DHT Sensor Library 578 | - Adafruit DHT Unified 579 | - AzureIoTHub 580 | - AzureIoTUtility 581 | - AzureIoTProtocol_MQTT 582 | 583 | To install them, click on the `Sketch -> Include Library -> Manage Libraries`. Search for each library using the box in the upper-right to filter your search, click on the found library, and click the "Install" button. 584 | 585 | The Adafruit Sensor library is also needed. This can be downloaded [here](https://github.com/adafruit/Adafruit_Sensor). Instructions for manually installing a library can be found [here](https://www.arduino.cc/en/Guide/Libraries). 586 | 587 | 588 | 589 | ## 2.11 Modify the Command Center sample 590 | 591 | - Unzip the example code, and double-click the file `command_center.ino` to open the project in the Arduino IDE. 592 | - You will be prompted to creat a folder. Do this, and move the other files in the folder into the newly created child folder 593 | - Look for the following lines of code: 594 | 595 | ``` 596 | static const char ssid[] = "[Your WiFi network SSID or name]"; 597 | static const char pass[] = "[Your WiFi network WPA password or WEP key]"; 598 | static const char* connectionString = "[Device Connection String]"; 599 | ``` 600 | 601 | - Replace the placeholders with your WiFi name (SSID), WiFi password, and the device connection string you created at the beginning of this tutorial.  602 | - Save with `Control-s` 603 | 604 | - In the same project, click on the `command_center.c` tab to see that file. 605 | - Look for the following lines of code: 606 | 607 | ``` 608 | static const char DeviceId[] = "[Device Name]"; 609 | static const char connectionString[] = "[Device Connection String]"; 610 | ``` 611 | 612 | - Replace the placeholders with your Device ID and connection string you created at the beginning of this tutorial.  613 | - Save with `Control-s` 614 | 615 | 616 | 617 | ## 2.12 Build Your Command Center Sample 618 | 619 | - Build and upload the code using **Sketch ->  Upload**. 620 | 621 | *** 622 | **Note**: As of 1.6.8, the Arduino IDE doesn't properly show "Upload Completed", even when it succeeds. 623 | *** 624 | 625 | - There should now be a green LED on your SparkFun ESP8266 Thing Dev Kit. Re-select the COM port if necessary, and then open the Serial Monitor. After 15 seconds you should see a measurements update. 626 | - Data is now being sent off at regular intervals to Microsoft Azure. When it detects something out of range, you will see the LED you’ve set up turn from green to red! 627 | - You can click the green button (labeled "Turn on") and the red button (labeled "Turn off") in the application to toggle the green and red LEDs in your kit. 628 | 629 | Head back to your Node application and you will have a fully functional command center, complete with a history of sensor data, alerts that display when the temperature got outside a certain range, and commands that you can send to your device remotely. 630 | 631 | *** 632 | **Note:** Make sure to **stop** your Command Center jobs once you have when you finish to avoid unnecessary Azure consumption! (See: [Troubleshooting](#troubleshooting)) 633 | *** 634 | 635 | 636 | 637 | ## 2.13 Next steps 638 | 639 | Please visit our [Azure IoT Dev Center](https://azure.microsoft.com/en-us/develop/iot/) for more samples and documentation on Azure IoT. 640 | 641 | # Troubleshooting 642 | 643 | ## Stopping Provisioned Services 644 | 645 | - In the [Microsoft Azure Portal](https://portal.azure.com/) 646 | - Click on "All Resources" 647 | - For each Stream Analytics and Web App resource: 648 | - Click on the resource and click the "Stop" button in the new blade that appears 649 | - For each IoT Hub resource: 650 | - Click on the resource and click the "Devices" button in the new blade that appears 651 | - Click on each device in the list and click the "Disable" button that appears in the new blade at the bottom 652 | 653 | ## Data is not showing up in the Node.js application 654 | 655 | In this section we will explain how to see the data flowing from the Arduino application to the Node.js application: 656 | - Arduino application: In the Arduino IDE go to Tools -> Serial Monitor 657 | - IoT Hub: Use [Device Explorer](https://github.com/Azure/azure-iot-sdks/blob/master/tools/DeviceExplorer/doc/how_to_use_device_explorer.md) 658 | - Azure Storage Table: Use [Azure Storage Explorer](http://storageexplorer.com/) 659 | -------------------------------------------------------------------------------- /command_center/command_center.c: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "sensor.h" 14 | #include "command_center.h" 15 | 16 | /* This sample uses the _LL APIs of iothub_client for example purposes. 17 | That does not mean that HTTP or MQTT only works with the _LL APIs. 18 | Simply changing the using the convenience layer (functions not having _LL) 19 | and removing calls to _DoWork will yield the same results. */ 20 | 21 | #include "AzureIoTHub.h" 22 | #include "sdk/schemaserializer.h" 23 | 24 | /* CODEFIRST_OK is the new name for IOT_AGENT_OK. The follow #ifndef helps during the name migration. Remove it when the migration ends. */ 25 | #ifndef IOT_AGENT_OK 26 | #define IOT_AGENT_OK CODEFIRST_OK 27 | #endif // ! IOT_AGENT_OK 28 | 29 | //static const char* connectionString = "HostName=[host].azure-devices.net;DeviceId=[device];SharedAccessKey=[key]"; 30 | static const char DeviceId[] = "[Device Name]"; 31 | static const char connectionString[] = "[Device Connection String]"; 32 | 33 | static int redLedPin = 12; 34 | static int redLedState = LOW; 35 | static int greenLedPin = 13; 36 | static int greenLedState = LOW; 37 | 38 | // Define the Model 39 | BEGIN_NAMESPACE(WeatherStation); 40 | 41 | DECLARE_MODEL(ContosoAnemometer, 42 | WITH_DATA(ascii_char_ptr, DeviceId), 43 | WITH_DATA(int, EventTime), 44 | WITH_DATA(int, MTemperature), 45 | WITH_DATA(int, Humidity), 46 | WITH_ACTION(TurnFanOn), 47 | WITH_ACTION(TurnFanOff) 48 | ); 49 | 50 | END_NAMESPACE(WeatherStation); 51 | 52 | EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device) 53 | { 54 | (void)device; 55 | 56 | LogInfo("Toggling red LED.\r\n"); 57 | if (redLedState != LOW) 58 | { 59 | redLedState = LOW; 60 | } 61 | else 62 | { 63 | redLedState = HIGH; 64 | } 65 | digitalWrite(redLedPin, redLedState); 66 | 67 | return EXECUTE_COMMAND_SUCCESS; 68 | } 69 | 70 | EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device) 71 | { 72 | (void)device; 73 | 74 | LogInfo("Toggling green LED.\r\n"); 75 | if (greenLedState != LOW) 76 | { 77 | greenLedState = LOW; 78 | } 79 | else 80 | { 81 | greenLedState = HIGH; 82 | } 83 | digitalWrite(greenLedPin, greenLedState); 84 | 85 | return EXECUTE_COMMAND_SUCCESS; 86 | } 87 | 88 | void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) 89 | { 90 | int messageTrackingId = (intptr_t)userContextCallback; 91 | 92 | LogInfo("Message Id: %d Received.\r\n", messageTrackingId); 93 | 94 | LogInfo("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); 95 | } 96 | 97 | static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size) 98 | { 99 | static unsigned int messageTrackingId; 100 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size); 101 | if (messageHandle == NULL) 102 | { 103 | LogInfo("unable to create a new IoTHubMessage\r\n"); 104 | } 105 | else 106 | { 107 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK) 108 | { 109 | LogInfo("failed to hand over the message to IoTHubClient"); 110 | } 111 | else 112 | { 113 | LogInfo("IoTHubClient accepted the message for delivery\r\n"); 114 | } 115 | IoTHubMessage_Destroy(messageHandle); 116 | } 117 | free((void*)buffer); 118 | messageTrackingId++; 119 | } 120 | 121 | /*this function "links" IoTHub to the serialization library*/ 122 | static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) 123 | { 124 | LogInfo("Command Received\r\n"); 125 | IOTHUBMESSAGE_DISPOSITION_RESULT result; 126 | const unsigned char* buffer; 127 | size_t size; 128 | if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) 129 | { 130 | LogInfo("unable to IoTHubMessage_GetByteArray\r\n"); 131 | result = EXECUTE_COMMAND_ERROR; 132 | } 133 | else 134 | { 135 | /*buffer is not zero terminated*/ 136 | char* temp = malloc(size + 1); 137 | if (temp == NULL) 138 | { 139 | LogInfo("failed to malloc\r\n"); 140 | result = EXECUTE_COMMAND_ERROR; 141 | } 142 | else 143 | { 144 | memcpy(temp, buffer, size); 145 | temp[size] = '\0'; 146 | EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp); 147 | result = 148 | (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED : 149 | (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED : 150 | IOTHUBMESSAGE_REJECTED; 151 | free(temp); 152 | } 153 | } 154 | return result; 155 | } 156 | 157 | void command_center_run(void) 158 | { 159 | initSensor(); 160 | 161 | digitalWrite(redLedPin, redLedState); 162 | pinMode(redLedPin, OUTPUT); 163 | 164 | digitalWrite(greenLedPin, greenLedState); 165 | pinMode(greenLedPin, OUTPUT); 166 | 167 | if (serializer_init(NULL) != SERIALIZER_OK) 168 | { 169 | LogInfo("Failed on serializer_init\r\n"); 170 | } 171 | else 172 | { 173 | IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol); 174 | srand((unsigned int)time(NULL)); 175 | int avgWindSpeed = 10.0; 176 | 177 | if (iotHubClientHandle == NULL) 178 | { 179 | LogInfo("Failed on IoTHubClient_LL_Create\r\n"); 180 | } 181 | else 182 | { 183 | unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/ 184 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) 185 | { 186 | LogInfo("failure to set option \"MinimumPollingTime\"\r\n"); 187 | } 188 | 189 | #ifdef MBED_BUILD_TIMESTAMP 190 | // For mbed add the certificate information 191 | if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) 192 | { 193 | LogInfo("failure to set option \"TrustedCerts\"\r\n"); 194 | } 195 | #endif // MBED_BUILD_TIMESTAMP 196 | 197 | ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer); 198 | if (myWeather == NULL) 199 | { 200 | LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n"); 201 | } 202 | else 203 | { 204 | if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) 205 | { 206 | LogInfo("unable to IoTHubClient_SetMessageCallback\r\n"); 207 | } 208 | else 209 | { 210 | 211 | /* wait for commands */ 212 | long Prev_time_ms = millis(); 213 | char buff[11]; 214 | int timeNow = 0; 215 | 216 | while (1) 217 | { 218 | long Curr_time_ms = millis(); 219 | if (Curr_time_ms >= Prev_time_ms + 5000) 220 | { 221 | Prev_time_ms = Curr_time_ms; 222 | 223 | timeNow = (int)time(NULL); 224 | //sprintf(buff, "%d", timeNow); 225 | 226 | float Temp_c__f, Humi_pct__f; 227 | getNextSample(&Temp_c__f, &Humi_pct__f); 228 | 229 | myWeather->DeviceId = DeviceId; 230 | myWeather->EventTime = timeNow; 231 | myWeather->MTemperature = (int)Temp_c__f; 232 | myWeather->Humidity = (int)Humi_pct__f; 233 | 234 | LogInfo("Result: %s | %d | %d | %d \r\n", myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature, myWeather->Humidity); 235 | 236 | unsigned char* destination; 237 | size_t destinationSize; 238 | 239 | if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature, myWeather->Humidity) != IOT_AGENT_OK) 240 | { 241 | LogInfo("Failed to serialize\r\n"); 242 | } 243 | else 244 | { 245 | IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); 246 | if (messageHandle == NULL) 247 | { 248 | LogInfo("unable to create a new IoTHubMessage\r\n"); 249 | } 250 | else 251 | { 252 | if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) 253 | { 254 | LogInfo("failed to hand over the message to IoTHubClient\r\n"); 255 | } 256 | else 257 | { 258 | LogInfo("IoTHubClient accepted the message for delivery\r\n"); 259 | } 260 | 261 | IoTHubMessage_Destroy(messageHandle); 262 | } 263 | free(destination); 264 | } 265 | 266 | } 267 | 268 | IoTHubClient_LL_DoWork(iotHubClientHandle); 269 | ThreadAPI_Sleep(100); 270 | } 271 | } 272 | 273 | DESTROY_MODEL_INSTANCE(myWeather); 274 | } 275 | IoTHubClient_LL_Destroy(iotHubClientHandle); 276 | } 277 | serializer_deinit(); 278 | } 279 | } 280 | 281 | 282 | -------------------------------------------------------------------------------- /command_center/command_center.h: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Copyright (c) Microsoft. All rights reserved. 3 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 4 | 5 | #ifndef _cmd_ctr_HTTP_H 6 | #define _cmd_ctr_HTTP_H 7 | 8 | #define MAX_CONNECTION_STRING_LEN (255) 9 | 10 | #ifdef __cplusplus 11 | extern "C" { 12 | #endif 13 | 14 | /////////////////////////////////////////////////////////////////////////////////////////////////// 15 | void command_center_run(void); 16 | 17 | #ifdef __cplusplus 18 | } 19 | #endif 20 | 21 | #endif//_cmd_ctr_HTTP_H 22 | 23 | -------------------------------------------------------------------------------- /command_center/command_center.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 | // This example only works with Arduino IDE 1.6.8 or later. 5 | 6 | #include 7 | #include 8 | #include "command_center.h" 9 | #include 10 | #ifdef AzureIoTUtilityVersion 11 | #include 12 | #endif 13 | 14 | const char ssid[] = "[SSID]"; // your WiFi SSID (name) 15 | const char pass[] = "[PASSWORD]"; // your WiFi password (use for WPA, or use as key for WEP) 16 | const char connectionString[] = "HostName=[HubName].azure-devices.net;DeviceId=[DeviceName];SharedAccessKey=[KEY]"; 17 | int status = WL_IDLE_STATUS; 18 | 19 | /////////////////////////////////////////////////////////////////////////////////////////////////// 20 | void setup() { 21 | initSerial(); 22 | initWifi(); 23 | initTime(); 24 | 25 | // This function doesn't exit. 26 | command_center_run(); 27 | } 28 | 29 | /////////////////////////////////////////////////////////////////////////////////////////////////// 30 | void loop() { 31 | // Not used. 32 | } 33 | 34 | /////////////////////////////////////////////////////////////////////////////////////////////////// 35 | void initSerial() { 36 | // Start serial and initialize stdout 37 | Serial.begin(115200); 38 | Serial.setDebugOutput(true); 39 | } 40 | 41 | /////////////////////////////////////////////////////////////////////////////////////////////////// 42 | void initWifi() { 43 | // Attempt to connect to Wifi network: 44 | Serial.print("Attempting to connect to SSID: "); 45 | Serial.println(ssid); 46 | 47 | // Connect to WPA/WPA2 network. Change this line if using open or WEP network: 48 | status = WiFi.begin(ssid, pass); 49 | 50 | while (WiFi.status() != WL_CONNECTED) { 51 | delay(500); 52 | Serial.print("."); 53 | } 54 | 55 | Serial.println("Connected to wifi"); 56 | } 57 | 58 | /////////////////////////////////////////////////////////////////////////////////////////////////// 59 | void initTime() { 60 | time_t epochTime; 61 | 62 | configTime(0, 0, "pool.ntp.org", "time.nist.gov"); 63 | 64 | while (true) { 65 | epochTime = time(NULL); 66 | 67 | if (epochTime == 0) { 68 | Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); 69 | delay(2000); 70 | } else { 71 | Serial.print("Fetched NTP epoch time is: "); 72 | Serial.println(epochTime); 73 | break; 74 | } 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /command_center/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 | -------------------------------------------------------------------------------- /command_center/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 | -------------------------------------------------------------------------------- /command_center_node/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /bower_components 3 | /.vscode 4 | -------------------------------------------------------------------------------- /command_center_node/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "controller", 3 | "description": "", 4 | "main": "server.js", 5 | "license": "ISC", 6 | "moduleType": [], 7 | "homepage": "", 8 | "ignore": [ 9 | "**/.*", 10 | "node_modules", 11 | "bower_components", 12 | "test", 13 | "tests" 14 | ], 15 | "dependencies": { 16 | "angular": "^1.5.2", 17 | "bootstrap": "^3.3.6" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /command_center_node/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "port": "3000", 3 | "eventHubName": "event-hub-name", 4 | "ehConnString": "Endpoint=sb://name.servicebus.windows.net/;SharedAccessKeyName=readwrite;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", 5 | "deviceConnString": "HostName=name.azure-devices.net;DeviceId=device-id;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaa==", 6 | "iotHubConnString": "HostName=name.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", 7 | "storageAcountName": "aaaaaaaaaaa", 8 | "storageAccountKey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa==", 9 | "storageTable": "storage-table-name" 10 | } -------------------------------------------------------------------------------- /command_center_node/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "controller", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "azure-iot-common": "^1.0.1", 14 | "azure-event-hubs": "0.0.1", 15 | "azure-iot-device": "^1.0.1", 16 | "azure-iothub": "^1.0.2", 17 | "azure-storage": "^0.9.0", 18 | "body-parser": "^1.15.0", 19 | "express": "^4.13.4", 20 | "nconf": "^0.8.4" 21 | }, 22 | "devDependencies": { 23 | "gulp": "^3.9.1" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /command_center_node/public/index.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Azure IoT Hub 6 | 7 | 8 | 9 | 10 | 27 | 28 | 29 | 30 | 31 | 50 | 51 | 52 | 53 | 54 | 55 |
56 |
57 |

Current Temperature

The last recorded reading on device {{ latest_reading.deviceid }} was: 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 |
TemperatureTime
{{ latest_reading.temperature | number }}°C{{ latest_reading.eventtime | date : 'medium' }}
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 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
TemperatureTime
{{ t.temperature | number }}°C{{ t.eventtime | date : 'medium' }}
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 | --------------------------------------------------------------------------------