This commit is contained in:
Dominic Betts 2018-05-08 11:22:00 +01:00
Родитель 8462bd3b62
Коммит 9a1abc5306
126 изменённых файлов: 5692 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,660 @@
# Connect your device to the remote monitoring preconfigured solution (Linux)
## Scenario overview
In this scenario, you create a device that sends the following telemetry to the remote monitoring [preconfigured solution][lnk-what-are-preconfig-solutions]:
* External temperature
* Internal temperature
* Humidity
For simplicity, the code on the device generates sample values, but we encourage you to extend the sample by connecting real sensors to your device and sending real telemetry.
The device is also able to respond to methods invoked from the solution dashboard and desired property values set in the solution dashboard.
To complete this tutorial, you need an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
## Before you start
Before you write any code for your device, you must provision your remote monitoring preconfigured solution and provision a new custom device in that solution.
### Provision your remote monitoring preconfigured solution
The device you create in this tutorial sends data to an instance of the [remote monitoring][lnk-remote-monitoring] preconfigured solution. If you haven't already provisioned the remote monitoring preconfigured solution in your Azure account, use the following steps:
1. On the <https://www.azureiotsuite.com/> page, click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** panel to create your solution.
3. On the **Create Remote monitoring solution** page, enter a **Solution name** of your choice, select the **Region** you want to deploy to, and select the Azure subscription to want to use. Then click **Create solution**.
4. Wait until the provisioning process completes.
> The preconfigured solutions use billable Azure services. Be sure to remove the preconfigured solution from your subscription when you are done with it to avoid any unnecessary charges. You can completely remove a preconfigured solution from your subscription by visiting the <https://www.azureiotsuite.com/> page.
>
>
When the provisioning process for the remote monitoring solution finishes, click **Launch** to open the solution dashboard in your browser.
![Solution dashboard][img-dashboard]
### Provision your device in the remote monitoring solution
> If you have already provisioned a device in your solution, you can skip this step. You need to know the device credentials when you create the client application.
>
>
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
To add a device to your remote monitoring solution, complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
2. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
3. Choose **Let me define my own Device ID**. Enter a Device ID such as **mydevice**, click **Check ID** to verify that name isn't already in use, and then click **Create** to provision the device.
![Add device ID][3]
4. Make a note the device credentials (Device ID, IoT Hub Hostname, and Device Key). Your client application needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
5. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-dashboard]: ./media/iot-suite-v1-selector-connecting/dashboard.png
[1]: ./media/iot-suite-v1-selector-connecting/suite0.png
[2]: ./media/iot-suite-v1-selector-connecting/suite1.png
[3]: ./media/iot-suite-v1-selector-connecting/suite2.png
[4]: ./media/iot-suite-v1-selector-connecting/suite3.png
[lnk-what-are-preconfig-solutions]: ../articles/iot-suite/iot-suite-v1-what-are-preconfigured-solutions.md
[lnk-remote-monitoring]: ../articles/iot-suite/iot-suite-v1-remote-monitoring-sample-walkthrough.md
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Build and run a sample C client Linux
The following steps show you how to create a client application that communicates with the remote monitoring preconfigured solution. This application is written in C and built and run on Ubuntu Linux.
To complete these steps, you need a device running Ubuntu version 15.04 or 15.10. Before proceeding, install the prerequisite packages on your Ubuntu device using the following command:
```
sudo apt-get install cmake gcc g++
```
## Install the client libraries on your device
The Azure IoT Hub client libraries are available as a package you can install on your Ubuntu device using the **apt-get** command. Complete the following steps to install the package that contains the IoT Hub client library and header files on your Ubuntu computer:
1. In a shell, add the AzureIoT repository to your computer:
```
sudo add-apt-repository ppa:aziotsdklinux/ppa-azureiot
sudo apt-get update
```
2. Install the azure-iot-sdk-c-dev package
```
sudo apt-get install -y azure-iot-sdk-c-dev
```
## Install the Parson JSON parser
The IoT Hub client libraries use the Parson JSON parser to parse message payloads. In a suitable folder on your computer, clone the Parson GitHub repository using the following command:
```
git clone https://github.com/kgabis/parson.git
```
## Prepare your project
On your Ubuntu machine, create a folder called **remote\_monitoring**. In the **remote\_monitoring** folder:
- Create the four files **main.c**, **remote\_monitoring.c**, **remote\_monitoring.h**, and **CMakeLists.txt**.
- Create folder called **parson**.
Copy the files **parson.c** and **parson.h** from your local copy of the Parson repository into the **remote\_monitoring/parson** folder.
In a text editor, open the **remote\_monitoring.c** file. Add the following `#include` statements:
```
#include "iothubtransportmqtt.h"
#include "schemalib.h"
#include "iothub_client.h"
#include "serializer_devicetwin.h"
#include "schemaserializer.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/platform.h"
#include "parson.h"
```
## Specify the behavior of the IoT device
The IoT Hub serializer client library uses a model to specify the format of the messages the device exchanges with IoT Hub.
1. Add the following variable declarations after the `#include` statements. Replace the placeholder values `[Device Id]` and `[Device connection string]` with the values you noted for the physical device you added to the remote monitoring solution:
```c
static const char* deviceId = "[Device Id]";
static const char* connectionString = "[Device connection string]";
```
1. Add the following code to define the model that enables the device to communicate with IoT Hub. This model specifies that the device:
- Can send temperature, pressure, and humidity as telemetry.
- Can send reported properties, to the device twin in IoT Hub. These reported properties include information about the telemetry schema and supported methods.
- Can receive and act on desired properties set in the device twin in IoT Hub.
- Can respond to the **Reboot**, **FirmwareUpdate**, **EmergencyValveRelease**, and **IncreasePressure** direct methods invoked from the UI. The device sends information about the direct methods it supports using reported properties.
```c
// Define the Model
BEGIN_NAMESPACE(Contoso);
DECLARE_STRUCT(MessageSchema,
ascii_char_ptr, Name,
ascii_char_ptr, Format,
ascii_char_ptr_no_quotes, Fields
)
DECLARE_STRUCT(TelemetrySchema,
ascii_char_ptr, Interval,
ascii_char_ptr, MessageTemplate,
MessageSchema, MessageSchema
)
DECLARE_STRUCT(TelemetryProperties,
TelemetrySchema, TemperatureSchema,
TelemetrySchema, HumiditySchema,
TelemetrySchema, PressureSchema
)
DECLARE_DEVICETWIN_MODEL(Chiller,
/* Telemetry (temperature, external temperature and humidity) */
WITH_DATA(double, temperature),
WITH_DATA(ascii_char_ptr, temperature_unit),
WITH_DATA(double, pressure),
WITH_DATA(ascii_char_ptr, pressure_unit),
WITH_DATA(double, humidity),
WITH_DATA(ascii_char_ptr, humidity_unit),
/* Manage firmware update process */
WITH_DATA(ascii_char_ptr, new_firmware_URI),
WITH_DATA(ascii_char_ptr, new_firmware_version),
/* Device twin properties */
WITH_REPORTED_PROPERTY(ascii_char_ptr, Protocol),
WITH_REPORTED_PROPERTY(ascii_char_ptr, SupportedMethods),
WITH_REPORTED_PROPERTY(TelemetryProperties, Telemetry),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Type),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Firmware),
WITH_REPORTED_PROPERTY(ascii_char_ptr, FirmwareUpdateStatus),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Location),
WITH_REPORTED_PROPERTY(double, Latitiude),
WITH_REPORTED_PROPERTY(double, Longitude),
WITH_DESIRED_PROPERTY(ascii_char_ptr, Interval, onDesiredInterval),
/* Direct methods implemented by the device */
WITH_METHOD(Reboot),
WITH_METHOD(FirmwareUpdate, ascii_char_ptr, Firmware, ascii_char_ptr, FirmwareUri),
WITH_METHOD(EmergencyValveRelease),
WITH_METHOD(IncreasePressure)
);
END_NAMESPACE(Contoso);
```
## Implement the behavior of the device
Now add code that implements the behavior defined in the model.
1. Add the following callback handler that runs when the device has sent new reported property values to the solution accelerator:
```c
/* Callback after sending reported properties */
void deviceTwinCallback(int status_code, void* userContextCallback)
{
(void)(userContextCallback);
printf("IoTHub: reported properties delivered with status_code = %u\n", status_code);
}
```
1. Add the following function that simulates a firmware update process:
```c
static int do_firmware_update(void *param)
{
Chiller *chiller = (Chiller *)param;
printf("do_firmware_update('URI: %s, Version: %s')\r\n", chiller->new_firmware_URI, chiller->new_firmware_version);
printf("Simulating download phase...\r\n");
chiller->FirmwareUpdateStatus = "downloading";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
printf("Simulating applying phase...\r\n");
chiller->FirmwareUpdateStatus = "applying";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
printf("Simulating reboot phase...\r\n");
chiller->FirmwareUpdateStatus = "rebooting";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
chiller->Firmware = _strdup(chiller->new_firmware_version);
chiller->FirmwareUpdateStatus = "waiting";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
return 0;
}
```
1. Add the following function that handles the desired properties set in the solution dashboard. These desired properties are defined in the model:
```c
void onDesiredInterval(void* argument)
{
/* By convention 'argument' is of the type of the MODEL */
Chiller* chiller = argument;
printf("Received a new desired Interval value: %s \r\n", chiller->Interval);
}
```
1. Add the following functions that handle the direct methods invoked through the IoT hub. These direct methods are defined in the model:
```c
/* Handlers for direct methods */
METHODRETURN_HANDLE Reboot(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Rebooting\"");
printf("Received reboot request\r\n");
return result;
}
METHODRETURN_HANDLE FirmwareUpdate(Chiller* chiller, ascii_char_ptr Firmware, ascii_char_ptr FirmwareUri)
{
printf("Recieved firmware update request request\r\n");
METHODRETURN_HANDLE result = NULL;
if (chiller->FirmwareUpdateStatus != "waiting")
{
LogError("Attempting to initiate a firmware update out of order");
result = MethodReturn_Create(400, "\"Attempting to initiate a firmware update out of order\"");
}
else
{
chiller->new_firmware_version = _strdup(Firmware);
chiller->new_firmware_URI = _strdup(FirmwareUri);
THREAD_HANDLE thread_apply;
THREADAPI_RESULT t_result = ThreadAPI_Create(&thread_apply, do_firmware_update, chiller);
if (t_result == THREADAPI_OK)
{
result = MethodReturn_Create(201, "\"Starting firmware update thread\"");
}
else
{
LogError("Failed to start firmware update thread");
result = MethodReturn_Create(500, "\"Failed to start firmware update thread\"");
}
}
return result;
}
METHODRETURN_HANDLE EmergencyValveRelease(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Releasing Emergency Valve\"");
printf("Recieved emergency valve release request\r\n");
return result;
}
METHODRETURN_HANDLE IncreasePressure(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Increasing Pressure\"");
printf("Received increase pressure request\r\n");
return result;
}
```
1. Add the following function that adds a property to a device-to-cloud message:
```c
/* Add message property */
static void addProperty(MAP_HANDLE propMap, char* propName, char* propValue)
{
if (Map_AddOrUpdate(propMap, propName, propValue) != MAP_OK)
{
(void)printf("ERROR: Map_AddOrUpdate Failed on %s!\r\n", propName);
}
}
```
1. Add the following function that sends a message with properties to the solution accelerator:
```c
static void sendMessage(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size, char* schema)
{
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
if (messageHandle == NULL)
{
printf("unable to create a new IoTHubMessage\r\n");
}
else
{
// Add properties
MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);
addProperty(propMap, "$$MessageSchema", schema);
addProperty(propMap, "$$ContentType", "JSON");
time_t now = time(0);
struct tm* timeinfo;
#pragma warning(disable: 4996)
timeinfo = gmtime(&now);
char timebuff[50];
strftime(timebuff, 50, "%Y-%m-%dT%H:%M:%SZ", timeinfo);
addProperty(propMap, "$$CreationTimeUtc", timebuff);
if (IoTHubClient_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
{
printf("failed to hand over the message to IoTHubClient");
}
else
{
printf("IoTHubClient accepted the message for delivery\r\n");
}
IoTHubMessage_Destroy(messageHandle);
}
free((void*)buffer);
}
```
1. Add the following function to connect your device to the solution accelerator in the cloud, and exchange data. This function performs the following steps:
- Initializes the platform.
- Registers the Contoso namespace with the serialization library.
- Initializes the client with the device connection string.
- Create an instance of the **Chiller** model.
- Creates and sends reported property values.
- Creates a loop to send telemetry every five seconds while the firmware update status is **waiting**.
- Deinitializes all resources.
```c
void remote_monitoring_run(void)
{
if (platform_init() != 0)
{
printf("Failed to initialize the platform.\r\n");
}
else
{
if (SERIALIZER_REGISTER_NAMESPACE(Contoso) == NULL)
{
printf("Unable to SERIALIZER_REGISTER_NAMESPACE\r\n");
}
else
{
IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol);
if (iotHubClientHandle == NULL)
{
printf("Failure in IoTHubClient_CreateFromConnectionString\r\n");
}
else
{
Chiller* chiller = IoTHubDeviceTwin_CreateChiller(iotHubClientHandle);
if (chiller == NULL)
{
printf("Failure in IoTHubDeviceTwin_CreateChiller\r\n");
}
else
{
/* Set values for reported properties */
chiller->Protocol = "MQTT";
chiller->SupportedMethods = "Reboot,FirmwareUpdate,EmergencyValveRelease,IncreasePressure";
chiller->Telemetry.TemperatureSchema.Interval = "00:00:05";
chiller->Telemetry.TemperatureSchema.MessageTemplate = "{\"temperature\":${temperature},\"temperature_unit\":\"${temperature_unit}\"}";
chiller->Telemetry.TemperatureSchema.MessageSchema.Name = "chiller-temperature;v1";
chiller->Telemetry.TemperatureSchema.MessageSchema.Format = "JSON";
chiller->Telemetry.TemperatureSchema.MessageSchema.Fields = "{\"temperature\":\"Double\",\"temperature_unit\":\"Text\"}";
chiller->Telemetry.HumiditySchema.Interval = "00:00:05";
chiller->Telemetry.HumiditySchema.MessageTemplate = "{\"humidity\":${humidity},\"humidity_unit\":\"${humidity_unit}\"}";
chiller->Telemetry.HumiditySchema.MessageSchema.Name = "chiller-humidity;v1";
chiller->Telemetry.HumiditySchema.MessageSchema.Format = "JSON";
chiller->Telemetry.HumiditySchema.MessageSchema.Fields = "{\"humidity\":\"Double\",\"humidity_unit\":\"Text\"}";
chiller->Telemetry.PressureSchema.Interval = "00:00:05";
chiller->Telemetry.PressureSchema.MessageTemplate = "{\"pressure\":${pressure},\"pressure_unit\":\"${pressure_unit}\"}";
chiller->Telemetry.PressureSchema.MessageSchema.Name = "chiller-pressure;v1";
chiller->Telemetry.PressureSchema.MessageSchema.Format = "JSON";
chiller->Telemetry.PressureSchema.MessageSchema.Fields = "{\"pressure\":\"Double\",\"pressure_unit\":\"Text\"}";
chiller->Type = "Chiller";
chiller->Firmware = "1.0.0";
chiller->FirmwareUpdateStatus = "waiting";
chiller->Location = "Building 44";
chiller->Latitiude = 47.638928;
chiller->Longitude = -122.13476;
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
else
{
/* Send telemetry */
chiller->temperature_unit = "F";
chiller->pressure_unit = "psig";
chiller->humidity_unit = "%";
srand((unsigned int)time(NULL));
while (1)
{
chiller->temperature = 50 + ((rand() % 10) - 5);
chiller->pressure = 55 + ((rand() % 10) - 5);
chiller->humidity = 30 + ((rand() % 10) - 5);
unsigned char*buffer;
size_t bufferSize;
if (chiller->FirmwareUpdateStatus == "waiting")
{
(void)printf("Sending sensor value Temperature = %f %s,\r\n", chiller->temperature, chiller->temperature_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->temperature, chiller->temperature_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.TemperatureSchema.MessageSchema.Name);
}
(void)printf("Sending sensor value Humidity = %f %s,\r\n", chiller->humidity, chiller->humidity_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->humidity, chiller->humidity_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.HumiditySchema.MessageSchema.Name);
}
(void)printf("Sending sensor value Pressure = %f %s,\r\n", chiller->pressure, chiller->pressure_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->pressure, chiller->pressure_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.PressureSchema.MessageSchema.Name);
}
}
ThreadAPI_Sleep(5000);
}
IoTHubDeviceTwin_DestroyChiller(chiller);
}
}
IoTHubClient_Destroy(iotHubClientHandle);
}
serializer_deinit();
}
}
platform_deinit();
}
```
For reference, here is a sample **Telemetry** message sent to the solution accelerator:
```
Device: [myCDevice],
Data:[{"humidity":50.000000000000000, "humidity_unit":"%"}]
Properties:
'$$MessageSchema': 'chiller-humidity;v1'
'$$ContentType': 'JSON'
'$$CreationTimeUtc': '2017-09-12T09:17:13Z'
```
## Call the remote\_monitoring\_run function
In a text editor, open the **remote_monitoring.h** file. Add the following code:
```
void remote_monitoring_run(void);
```
In a text editor, open the **main.c** file. Add the following code:
```
#include "remote_monitoring.h"
int main(void)
{
remote_monitoring_run();
return 0;
}
```
## Build and run the application
The following steps describe how to use *CMake* to build your client application.
1. In a text editor, open the **CMakeLists.txt** file in the **remote_monitoring** folder.
1. Add the following instructions to define how to build your client application:
```
macro(compileAsC99)
if (CMAKE_VERSION VERSION_LESS "3.1")
if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
set (CMAKE_C_FLAGS "--std=c99 ${CMAKE_C_FLAGS}")
set (CMAKE_CXX_FLAGS "--std=c++11 ${CMAKE_CXX_FLAGS}")
endif()
else()
set (CMAKE_C_STANDARD 99)
set (CMAKE_CXX_STANDARD 11)
endif()
endmacro(compileAsC99)
cmake_minimum_required(VERSION 2.8.11)
compileAsC99()
set(AZUREIOT_INC_FOLDER "${CMAKE_SOURCE_DIR}" "${CMAKE_SOURCE_DIR}/parson" "/usr/include/azureiot" "/usr/include/azureiot/inc")
include_directories(${AZUREIOT_INC_FOLDER})
set(sample_application_c_files
./parson/parson.c
./remote_monitoring.c
./main.c
)
set(sample_application_h_files
./parson/parson.h
./remote_monitoring.h
)
add_executable(sample_app ${sample_application_c_files} ${sample_application_h_files})
target_link_libraries(sample_app
serializer
iothub_client
iothub_client_mqtt_transport
aziotsharedutil
umqtt
pthread
curl
ssl
crypto
m
)
```
1. In the **remote_monitoring** folder, create a folder to store the *make* files that CMake generates and then run the **cmake** and **make** commands as follows:
```
mkdir cmake
cd cmake
cmake ../
make
```
1. Run the client application and send telemetry to IoT Hub:
```
./sample_app
```
## View device telemetry in the dashboard
The dashboard in the remote monitoring solution enables you to view the telemetry your devices send to IoT Hub.
1. In your browser, return to the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. In the **Devices list**, you should see that the status of your device is **Running**. If not, click **Enable Device** in the **Device Details** panel.
![View device status][18]
3. Click **Dashboard** to return to the dashboard, select your device in the **Device to View** drop-down to view its telemetry. The telemetry from the sample application is 50 units for internal temperature, 55 units for external temperature, and 50 units for humidity.
![View device telemetry][img-telemetry]
## Invoke a method on your device
The dashboard in the remote monitoring solution enables you to invoke methods on your devices through IoT Hub. For example, in the remote monitoring solution you can invoke a method to simulate rebooting a device.
1. In the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. Click **Device ID** for your device in the **Devices list**.
3. In the **Device details** panel, click **Methods**.
![Device methods][13]
4. In the **Method** drop-down, select **InitiateFirmwareUpdate**, and then in **FWPACKAGEURI** enter a dummy URL. Click **Invoke Method** to call the method on the device.
![Invoke a device method][14]
5. You see a message in the console running your device code when the device handles the method. The results of the method are added to the history in the solution portal:
![View method history][img-method-history]
## Next steps
The article [Customizing preconfigured solutions][lnk-customize] describes some ways you can extend this sample. Possible extensions include using real sensors and implementing additional commands.
You can learn more about the [permissions on the azureiotsuite.com site][lnk-permissions].
[13]: ./media/iot-suite-v1-visualize-connecting/suite4.png
[14]: ./media/iot-suite-v1-visualize-connecting/suite7-1.png
[18]: ./media/iot-suite-v1-visualize-connecting/suite10.png
[img-telemetry]: ./media/iot-suite-v1-visualize-connecting/telemetry.png
[img-method-history]: ./media/iot-suite-v1-visualize-connecting/history.png
[lnk-customize]: ../articles/iot-suite/iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md

Просмотреть файл

@ -0,0 +1,339 @@
# Connect your device to the remote monitoring preconfigured solution (Node.js)
## Scenario overview
In this scenario, you create a device that sends the following telemetry to the remote monitoring [preconfigured solution][lnk-what-are-preconfig-solutions]:
* External temperature
* Internal temperature
* Humidity
For simplicity, the code on the device generates sample values, but we encourage you to extend the sample by connecting real sensors to your device and sending real telemetry.
The device is also able to respond to methods invoked from the solution dashboard and desired property values set in the solution dashboard.
To complete this tutorial, you need an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
## Before you start
Before you write any code for your device, you must provision your remote monitoring preconfigured solution and provision a new custom device in that solution.
### Provision your remote monitoring preconfigured solution
The device you create in this tutorial sends data to an instance of the [remote monitoring][lnk-remote-monitoring] preconfigured solution. If you haven't already provisioned the remote monitoring preconfigured solution in your Azure account, use the following steps:
1. On the <https://www.azureiotsuite.com/> page, click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** panel to create your solution.
3. On the **Create Remote monitoring solution** page, enter a **Solution name** of your choice, select the **Region** you want to deploy to, and select the Azure subscription to want to use. Then click **Create solution**.
4. Wait until the provisioning process completes.
> The preconfigured solutions use billable Azure services. Be sure to remove the preconfigured solution from your subscription when you are done with it to avoid any unnecessary charges. You can completely remove a preconfigured solution from your subscription by visiting the <https://www.azureiotsuite.com/> page.
>
>
When the provisioning process for the remote monitoring solution finishes, click **Launch** to open the solution dashboard in your browser.
![Solution dashboard][img-dashboard]
### Provision your device in the remote monitoring solution
> If you have already provisioned a device in your solution, you can skip this step. You need to know the device credentials when you create the client application.
>
>
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
To add a device to your remote monitoring solution, complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
2. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
3. Choose **Let me define my own Device ID**. Enter a Device ID such as **mydevice**, click **Check ID** to verify that name isn't already in use, and then click **Create** to provision the device.
![Add device ID][3]
4. Make a note the device credentials (Device ID, IoT Hub Hostname, and Device Key). Your client application needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
5. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-dashboard]: ./media/iot-suite-v1-selector-connecting/dashboard.png
[1]: ./media/iot-suite-v1-selector-connecting/suite0.png
[2]: ./media/iot-suite-v1-selector-connecting/suite1.png
[3]: ./media/iot-suite-v1-selector-connecting/suite2.png
[4]: ./media/iot-suite-v1-selector-connecting/suite3.png
[lnk-what-are-preconfig-solutions]: ../articles/iot-suite/iot-suite-v1-what-are-preconfigured-solutions.md
[lnk-remote-monitoring]: ../articles/iot-suite/iot-suite-v1-remote-monitoring-sample-walkthrough.md
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Create a node.js sample solution
Ensure that Node.js version 0.11.5 or later is installed on your development machine. You can run `node --version` at the command line to check the version.
1. Create a folder called **RemoteMonitoring** on your development machine. Navigate to this folder in your command-line environment.
1. Run the following commands to download and install the packages you need to complete the sample app:
```
npm init
npm install azure-iot-device azure-iot-device-mqtt --save
```
1. In the **RemoteMonitoring** folder, create a file called **remote_monitoring.js**. Open this file in a text editor.
1. In the **remote_monitoring.js** file, add the following `require` statements:
```nodejs
'use strict';
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var ConnectionString = require('azure-iot-device').ConnectionString;
var Message = require('azure-iot-device').Message;
```
1. Add the following variable declarations after the `require` statements. Replace the placeholder values [Device Id] and [Device Key] with values you noted for your device in the remote monitoring solution dashboard. Use the IoT Hub Hostname from the solution dashboard to replace [IoTHub Name]. For example, if your IoT Hub Hostname is **contoso.azure-devices.net**, replace [IoTHub Name] with **contoso**:
```nodejs
var connectionString = 'HostName=[IoTHub Name].azure-devices.net;DeviceId=[Device Id];SharedAccessKey=[Device Key]';
var deviceId = ConnectionString.parse(connectionString).DeviceId;
```
1. Add the following variables to define some base telemetry data:
```nodejs
var temperature = 50;
var humidity = 50;
var externalTemperature = 55;
```
1. Add the following helper function to print operation results:
```nodejs
function printErrorFor(op) {
return function printError(err) {
if (err) console.log(op + ' error: ' + err.toString());
};
}
```
1. Add the following helper function to use to randomize the telemetry values:
```nodejs
function generateRandomIncrement() {
return ((Math.random() * 2) - 1);
}
```
1. Add the following definition for the **DeviceInfo** object the device sends on startup:
```nodejs
var deviceMetaData = {
'ObjectType': 'DeviceInfo',
'IsSimulatedDevice': 0,
'Version': '1.0',
'DeviceProperties': {
'DeviceID': deviceId,
'HubEnabledState': 1
}
};
```
1. Add the following definition for the device twin reported values. This definition includes descriptions of the direct methods the device supports:
```nodejs
var reportedProperties = {
"Device": {
"DeviceState": "normal",
"Location": {
"Latitude": 47.642877,
"Longitude": -122.125497
}
},
"Config": {
"TemperatureMeanValue": 56.7,
"TelemetryInterval": 45
},
"System": {
"Manufacturer": "Contoso Inc.",
"FirmwareVersion": "2.22",
"InstalledRAM": "8 MB",
"ModelNumber": "DB-14",
"Platform": "Plat 9.75",
"Processor": "i3-9",
"SerialNumber": "SER99"
},
"Location": {
"Latitude": 47.642877,
"Longitude": -122.125497
},
"SupportedMethods": {
"Reboot": "Reboot the device",
"InitiateFirmwareUpdate--FwPackageURI-string": "Updates device Firmware. Use parameter FwPackageURI to specifiy the URI of the firmware file"
},
}
```
1. Add the following function to handle the **Reboot** direct method call:
```nodejs
function onReboot(request, response) {
// Implement actual logic here.
console.log('Simulated reboot...');
// Complete the response
response.send(200, "Rebooting device", function(err) {
if(!!err) {
console.error('An error occurred when sending a method response:\n' + err.toString());
} else {
console.log('Response to method \'' + request.methodName + '\' sent successfully.' );
}
});
}
```
1. Add the following function to handle the **InitiateFirmwareUpdate** direct method call. This direct method uses a parameter to specify the location of the firmware image to download, and initiates the firmware update on the device asynchronously:
```nodejs
function onInitiateFirmwareUpdate(request, response) {
console.log('Simulated firmware update initiated, using: ' + request.payload.FwPackageURI);
// Complete the response
response.send(200, "Firmware update initiated", function(err) {
if(!!err) {
console.error('An error occurred when sending a method response:\n' + err.toString());
} else {
console.log('Response to method \'' + request.methodName + '\' sent successfully.' );
}
});
// Add logic here to perform the firmware update asynchronously
}
```
1. Add the following code to create a client instance:
```nodejs
var client = Client.fromConnectionString(connectionString, Protocol);
```
1. Add the following code to:
* Open the connection.
* Send the **DeviceInfo** object.
* Set up a handler for desired properties.
* Send reported properties.
* Register handlers for the direct methods.
* Start sending telemetry.
```nodejs
client.open(function (err) {
if (err) {
printErrorFor('open')(err);
} else {
console.log('Sending device metadata:\n' + JSON.stringify(deviceMetaData));
client.sendEvent(new Message(JSON.stringify(deviceMetaData)), printErrorFor('send metadata'));
// Create device twin
client.getTwin(function(err, twin) {
if (err) {
console.error('Could not get device twin');
} else {
console.log('Device twin created');
twin.on('properties.desired', function(delta) {
console.log('Received new desired properties:');
console.log(JSON.stringify(delta));
});
// Send reported properties
twin.properties.reported.update(reportedProperties, function(err) {
if (err) throw err;
console.log('twin state reported');
});
// Register handlers for direct methods
client.onDeviceMethod('Reboot', onReboot);
client.onDeviceMethod('InitiateFirmwareUpdate', onInitiateFirmwareUpdate);
}
});
// Start sending telemetry
var sendInterval = setInterval(function () {
temperature += generateRandomIncrement();
externalTemperature += generateRandomIncrement();
humidity += generateRandomIncrement();
var data = JSON.stringify({
'DeviceID': deviceId,
'Temperature': temperature,
'Humidity': humidity,
'ExternalTemperature': externalTemperature
});
console.log('Sending device event data:\n' + data);
client.sendEvent(new Message(data), printErrorFor('send event'));
}, 5000);
client.on('error', function (err) {
printErrorFor('client')(err);
if (sendInterval) clearInterval(sendInterval);
client.close(printErrorFor('client.close'));
});
}
});
```
1. Save the changes to the **remote_monitoring.js** file.
1. Run the following command at a command prompt to launch the sample application:
```
node remote_monitoring.js
```
## View device telemetry in the dashboard
The dashboard in the remote monitoring solution enables you to view the telemetry your devices send to IoT Hub.
1. In your browser, return to the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. In the **Devices list**, you should see that the status of your device is **Running**. If not, click **Enable Device** in the **Device Details** panel.
![View device status][18]
3. Click **Dashboard** to return to the dashboard, select your device in the **Device to View** drop-down to view its telemetry. The telemetry from the sample application is 50 units for internal temperature, 55 units for external temperature, and 50 units for humidity.
![View device telemetry][img-telemetry]
## Invoke a method on your device
The dashboard in the remote monitoring solution enables you to invoke methods on your devices through IoT Hub. For example, in the remote monitoring solution you can invoke a method to simulate rebooting a device.
1. In the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. Click **Device ID** for your device in the **Devices list**.
3. In the **Device details** panel, click **Methods**.
![Device methods][13]
4. In the **Method** drop-down, select **InitiateFirmwareUpdate**, and then in **FWPACKAGEURI** enter a dummy URL. Click **Invoke Method** to call the method on the device.
![Invoke a device method][14]
5. You see a message in the console running your device code when the device handles the method. The results of the method are added to the history in the solution portal:
![View method history][img-method-history]
## Next steps
The article [Customizing preconfigured solutions][lnk-customize] describes some ways you can extend this sample. Possible extensions include using real sensors and implementing additional commands.
You can learn more about the [permissions on the azureiotsuite.com site][lnk-permissions].
[13]: ./media/iot-suite-v1-visualize-connecting/suite4.png
[14]: ./media/iot-suite-v1-visualize-connecting/suite7-1.png
[18]: ./media/iot-suite-v1-visualize-connecting/suite10.png
[img-telemetry]: ./media/iot-suite-v1-visualize-connecting/telemetry.png
[img-method-history]: ./media/iot-suite-v1-visualize-connecting/history.png
[lnk-customize]: ../articles/iot-suite/iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-github-repo]: https://github.com/azure/azure-iot-sdk-node
[lnk-github-prepare]: https://github.com/Azure/azure-iot-sdk-node/blob/master/doc/node-devbox-setup.md

Просмотреть файл

@ -0,0 +1,587 @@
# Connect your device to the remote monitoring preconfigured solution (Windows)
## Scenario overview
In this scenario, you create a device that sends the following telemetry to the remote monitoring [preconfigured solution][lnk-what-are-preconfig-solutions]:
* External temperature
* Internal temperature
* Humidity
For simplicity, the code on the device generates sample values, but we encourage you to extend the sample by connecting real sensors to your device and sending real telemetry.
The device is also able to respond to methods invoked from the solution dashboard and desired property values set in the solution dashboard.
To complete this tutorial, you need an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
## Before you start
Before you write any code for your device, you must provision your remote monitoring preconfigured solution and provision a new custom device in that solution.
### Provision your remote monitoring preconfigured solution
The device you create in this tutorial sends data to an instance of the [remote monitoring][lnk-remote-monitoring] preconfigured solution. If you haven't already provisioned the remote monitoring preconfigured solution in your Azure account, use the following steps:
1. On the <https://www.azureiotsuite.com/> page, click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** panel to create your solution.
3. On the **Create Remote monitoring solution** page, enter a **Solution name** of your choice, select the **Region** you want to deploy to, and select the Azure subscription to want to use. Then click **Create solution**.
4. Wait until the provisioning process completes.
> The preconfigured solutions use billable Azure services. Be sure to remove the preconfigured solution from your subscription when you are done with it to avoid any unnecessary charges. You can completely remove a preconfigured solution from your subscription by visiting the <https://www.azureiotsuite.com/> page.
>
>
When the provisioning process for the remote monitoring solution finishes, click **Launch** to open the solution dashboard in your browser.
![Solution dashboard][img-dashboard]
### Provision your device in the remote monitoring solution
> If you have already provisioned a device in your solution, you can skip this step. You need to know the device credentials when you create the client application.
>
>
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
To add a device to your remote monitoring solution, complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
2. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
3. Choose **Let me define my own Device ID**. Enter a Device ID such as **mydevice**, click **Check ID** to verify that name isn't already in use, and then click **Create** to provision the device.
![Add device ID][3]
4. Make a note the device credentials (Device ID, IoT Hub Hostname, and Device Key). Your client application needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
5. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-dashboard]: ./media/iot-suite-v1-selector-connecting/dashboard.png
[1]: ./media/iot-suite-v1-selector-connecting/suite0.png
[2]: ./media/iot-suite-v1-selector-connecting/suite1.png
[3]: ./media/iot-suite-v1-selector-connecting/suite2.png
[4]: ./media/iot-suite-v1-selector-connecting/suite3.png
[lnk-what-are-preconfig-solutions]: ../articles/iot-suite/iot-suite-v1-what-are-preconfigured-solutions.md
[lnk-remote-monitoring]: ../articles/iot-suite/iot-suite-v1-remote-monitoring-sample-walkthrough.md
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Create a C sample solution on Windows
The following steps show you how to create a client application that communicates with the remote monitoring preconfigured solution. This application is written in C and built and run on Windows.
Create a starter project in Visual Studio 2015 or Visual Studio 2017 and add the IoT Hub device client NuGet packages:
1. In Visual Studio, create a C console application using the Visual C++ **Win32 Console Application** template. Name the project **RMDevice**.
2. On the **Application Settings** page in the **Win32 Application Wizard**, ensure that **Console application** is selected, and uncheck **Precompiled header** and **Security Development Lifecycle (SDL) checks**.
3. In **Solution Explorer**, delete the files stdafx.h, targetver.h, and stdafx.cpp.
4. In **Solution Explorer**, rename the file RMDevice.cpp to RMDevice.c.
5. In **Solution Explorer**, right-click on the **RMDevice** project and then click **Manage NuGet packages**. Click **Browse**, then search for and install the following NuGet packages:
* Microsoft.Azure.IoTHub.Serializer
* Microsoft.Azure.IoTHub.IoTHubClient
* Microsoft.Azure.IoTHub.MqttTransport
6. In **Solution Explorer**, right-click on the **RMDevice** project and then click **Properties** to open the project's **Property Pages** dialog box. For details, see [Setting Visual C++ Project Properties][lnk-c-project-properties].
7. Click the **Linker** folder, then click the **Input** property page.
8. Add **crypt32.lib** to the **Additional Dependencies** property. Click **OK** and then **OK** again to save the project property values.
Add the Parson JSON library to the **RMDevice** project and add the required `#include` statements:
1. In a suitable folder on your computer, clone the Parson GitHub repository using the following command:
```
git clone https://github.com/kgabis/parson.git
```
1. Copy the parson.h and parson.c files from the local copy of the Parson repository to your **RMDevice** project folder.
1. In Visual Studio, right-click the **RMDevice** project, click **Add**, and then click **Existing Item**.
1. In the **Add Existing Item** dialog, select the parson.h and parson.c files in the **RMDevice** project folder. Then click **Add** to add these two files to your project.
1. In Visual Studio, open the RMDevice.c file. Replace the existing `#include` statements with the following code:
```c
#include "iothubtransportmqtt.h"
#include "schemalib.h"
#include "iothub_client.h"
#include "serializer_devicetwin.h"
#include "schemaserializer.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/platform.h"
#include "parson.h"
```
> Now you can verify that your project has the correct dependencies set up by building it.
## Specify the behavior of the IoT device
The IoT Hub serializer client library uses a model to specify the format of the messages the device exchanges with IoT Hub.
1. Add the following variable declarations after the `#include` statements. Replace the placeholder values `[Device Id]` and `[Device connection string]` with the values you noted for the physical device you added to the remote monitoring solution:
```c
static const char* deviceId = "[Device Id]";
static const char* connectionString = "[Device connection string]";
```
1. Add the following code to define the model that enables the device to communicate with IoT Hub. This model specifies that the device:
- Can send temperature, pressure, and humidity as telemetry.
- Can send reported properties, to the device twin in IoT Hub. These reported properties include information about the telemetry schema and supported methods.
- Can receive and act on desired properties set in the device twin in IoT Hub.
- Can respond to the **Reboot**, **FirmwareUpdate**, **EmergencyValveRelease**, and **IncreasePressure** direct methods invoked from the UI. The device sends information about the direct methods it supports using reported properties.
```c
// Define the Model
BEGIN_NAMESPACE(Contoso);
DECLARE_STRUCT(MessageSchema,
ascii_char_ptr, Name,
ascii_char_ptr, Format,
ascii_char_ptr_no_quotes, Fields
)
DECLARE_STRUCT(TelemetrySchema,
ascii_char_ptr, Interval,
ascii_char_ptr, MessageTemplate,
MessageSchema, MessageSchema
)
DECLARE_STRUCT(TelemetryProperties,
TelemetrySchema, TemperatureSchema,
TelemetrySchema, HumiditySchema,
TelemetrySchema, PressureSchema
)
DECLARE_DEVICETWIN_MODEL(Chiller,
/* Telemetry (temperature, external temperature and humidity) */
WITH_DATA(double, temperature),
WITH_DATA(ascii_char_ptr, temperature_unit),
WITH_DATA(double, pressure),
WITH_DATA(ascii_char_ptr, pressure_unit),
WITH_DATA(double, humidity),
WITH_DATA(ascii_char_ptr, humidity_unit),
/* Manage firmware update process */
WITH_DATA(ascii_char_ptr, new_firmware_URI),
WITH_DATA(ascii_char_ptr, new_firmware_version),
/* Device twin properties */
WITH_REPORTED_PROPERTY(ascii_char_ptr, Protocol),
WITH_REPORTED_PROPERTY(ascii_char_ptr, SupportedMethods),
WITH_REPORTED_PROPERTY(TelemetryProperties, Telemetry),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Type),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Firmware),
WITH_REPORTED_PROPERTY(ascii_char_ptr, FirmwareUpdateStatus),
WITH_REPORTED_PROPERTY(ascii_char_ptr, Location),
WITH_REPORTED_PROPERTY(double, Latitiude),
WITH_REPORTED_PROPERTY(double, Longitude),
WITH_DESIRED_PROPERTY(ascii_char_ptr, Interval, onDesiredInterval),
/* Direct methods implemented by the device */
WITH_METHOD(Reboot),
WITH_METHOD(FirmwareUpdate, ascii_char_ptr, Firmware, ascii_char_ptr, FirmwareUri),
WITH_METHOD(EmergencyValveRelease),
WITH_METHOD(IncreasePressure)
);
END_NAMESPACE(Contoso);
```
## Implement the behavior of the device
Now add code that implements the behavior defined in the model.
1. Add the following callback handler that runs when the device has sent new reported property values to the solution accelerator:
```c
/* Callback after sending reported properties */
void deviceTwinCallback(int status_code, void* userContextCallback)
{
(void)(userContextCallback);
printf("IoTHub: reported properties delivered with status_code = %u\n", status_code);
}
```
1. Add the following function that simulates a firmware update process:
```c
static int do_firmware_update(void *param)
{
Chiller *chiller = (Chiller *)param;
printf("do_firmware_update('URI: %s, Version: %s')\r\n", chiller->new_firmware_URI, chiller->new_firmware_version);
printf("Simulating download phase...\r\n");
chiller->FirmwareUpdateStatus = "downloading";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
printf("Simulating applying phase...\r\n");
chiller->FirmwareUpdateStatus = "applying";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
printf("Simulating reboot phase...\r\n");
chiller->FirmwareUpdateStatus = "rebooting";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
ThreadAPI_Sleep(5000);
chiller->Firmware = _strdup(chiller->new_firmware_version);
chiller->FirmwareUpdateStatus = "waiting";
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
return 0;
}
```
1. Add the following function that handles the desired properties set in the solution dashboard. These desired properties are defined in the model:
```c
void onDesiredInterval(void* argument)
{
/* By convention 'argument' is of the type of the MODEL */
Chiller* chiller = argument;
printf("Received a new desired Interval value: %s \r\n", chiller->Interval);
}
```
1. Add the following functions that handle the direct methods invoked through the IoT hub. These direct methods are defined in the model:
```c
/* Handlers for direct methods */
METHODRETURN_HANDLE Reboot(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Rebooting\"");
printf("Received reboot request\r\n");
return result;
}
METHODRETURN_HANDLE FirmwareUpdate(Chiller* chiller, ascii_char_ptr Firmware, ascii_char_ptr FirmwareUri)
{
printf("Recieved firmware update request request\r\n");
METHODRETURN_HANDLE result = NULL;
if (chiller->FirmwareUpdateStatus != "waiting")
{
LogError("Attempting to initiate a firmware update out of order");
result = MethodReturn_Create(400, "\"Attempting to initiate a firmware update out of order\"");
}
else
{
chiller->new_firmware_version = _strdup(Firmware);
chiller->new_firmware_URI = _strdup(FirmwareUri);
THREAD_HANDLE thread_apply;
THREADAPI_RESULT t_result = ThreadAPI_Create(&thread_apply, do_firmware_update, chiller);
if (t_result == THREADAPI_OK)
{
result = MethodReturn_Create(201, "\"Starting firmware update thread\"");
}
else
{
LogError("Failed to start firmware update thread");
result = MethodReturn_Create(500, "\"Failed to start firmware update thread\"");
}
}
return result;
}
METHODRETURN_HANDLE EmergencyValveRelease(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Releasing Emergency Valve\"");
printf("Recieved emergency valve release request\r\n");
return result;
}
METHODRETURN_HANDLE IncreasePressure(Chiller* chiller)
{
(void)(chiller);
METHODRETURN_HANDLE result = MethodReturn_Create(201, "\"Increasing Pressure\"");
printf("Received increase pressure request\r\n");
return result;
}
```
1. Add the following function that adds a property to a device-to-cloud message:
```c
/* Add message property */
static void addProperty(MAP_HANDLE propMap, char* propName, char* propValue)
{
if (Map_AddOrUpdate(propMap, propName, propValue) != MAP_OK)
{
(void)printf("ERROR: Map_AddOrUpdate Failed on %s!\r\n", propName);
}
}
```
1. Add the following function that sends a message with properties to the solution accelerator:
```c
static void sendMessage(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size, char* schema)
{
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
if (messageHandle == NULL)
{
printf("unable to create a new IoTHubMessage\r\n");
}
else
{
// Add properties
MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);
addProperty(propMap, "$$MessageSchema", schema);
addProperty(propMap, "$$ContentType", "JSON");
time_t now = time(0);
struct tm* timeinfo;
#pragma warning(disable: 4996)
timeinfo = gmtime(&now);
char timebuff[50];
strftime(timebuff, 50, "%Y-%m-%dT%H:%M:%SZ", timeinfo);
addProperty(propMap, "$$CreationTimeUtc", timebuff);
if (IoTHubClient_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
{
printf("failed to hand over the message to IoTHubClient");
}
else
{
printf("IoTHubClient accepted the message for delivery\r\n");
}
IoTHubMessage_Destroy(messageHandle);
}
free((void*)buffer);
}
```
1. Add the following function to connect your device to the solution accelerator in the cloud, and exchange data. This function performs the following steps:
- Initializes the platform.
- Registers the Contoso namespace with the serialization library.
- Initializes the client with the device connection string.
- Create an instance of the **Chiller** model.
- Creates and sends reported property values.
- Creates a loop to send telemetry every five seconds while the firmware update status is **waiting**.
- Deinitializes all resources.
```c
void remote_monitoring_run(void)
{
if (platform_init() != 0)
{
printf("Failed to initialize the platform.\r\n");
}
else
{
if (SERIALIZER_REGISTER_NAMESPACE(Contoso) == NULL)
{
printf("Unable to SERIALIZER_REGISTER_NAMESPACE\r\n");
}
else
{
IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol);
if (iotHubClientHandle == NULL)
{
printf("Failure in IoTHubClient_CreateFromConnectionString\r\n");
}
else
{
Chiller* chiller = IoTHubDeviceTwin_CreateChiller(iotHubClientHandle);
if (chiller == NULL)
{
printf("Failure in IoTHubDeviceTwin_CreateChiller\r\n");
}
else
{
/* Set values for reported properties */
chiller->Protocol = "MQTT";
chiller->SupportedMethods = "Reboot,FirmwareUpdate,EmergencyValveRelease,IncreasePressure";
chiller->Telemetry.TemperatureSchema.Interval = "00:00:05";
chiller->Telemetry.TemperatureSchema.MessageTemplate = "{\"temperature\":${temperature},\"temperature_unit\":\"${temperature_unit}\"}";
chiller->Telemetry.TemperatureSchema.MessageSchema.Name = "chiller-temperature;v1";
chiller->Telemetry.TemperatureSchema.MessageSchema.Format = "JSON";
chiller->Telemetry.TemperatureSchema.MessageSchema.Fields = "{\"temperature\":\"Double\",\"temperature_unit\":\"Text\"}";
chiller->Telemetry.HumiditySchema.Interval = "00:00:05";
chiller->Telemetry.HumiditySchema.MessageTemplate = "{\"humidity\":${humidity},\"humidity_unit\":\"${humidity_unit}\"}";
chiller->Telemetry.HumiditySchema.MessageSchema.Name = "chiller-humidity;v1";
chiller->Telemetry.HumiditySchema.MessageSchema.Format = "JSON";
chiller->Telemetry.HumiditySchema.MessageSchema.Fields = "{\"humidity\":\"Double\",\"humidity_unit\":\"Text\"}";
chiller->Telemetry.PressureSchema.Interval = "00:00:05";
chiller->Telemetry.PressureSchema.MessageTemplate = "{\"pressure\":${pressure},\"pressure_unit\":\"${pressure_unit}\"}";
chiller->Telemetry.PressureSchema.MessageSchema.Name = "chiller-pressure;v1";
chiller->Telemetry.PressureSchema.MessageSchema.Format = "JSON";
chiller->Telemetry.PressureSchema.MessageSchema.Fields = "{\"pressure\":\"Double\",\"pressure_unit\":\"Text\"}";
chiller->Type = "Chiller";
chiller->Firmware = "1.0.0";
chiller->FirmwareUpdateStatus = "waiting";
chiller->Location = "Building 44";
chiller->Latitiude = 47.638928;
chiller->Longitude = -122.13476;
/* Send reported properties to IoT Hub */
if (IoTHubDeviceTwin_SendReportedStateChiller(chiller, deviceTwinCallback, NULL) != IOTHUB_CLIENT_OK)
{
printf("Failed sending serialized reported state\r\n");
}
else
{
/* Send telemetry */
chiller->temperature_unit = "F";
chiller->pressure_unit = "psig";
chiller->humidity_unit = "%";
srand((unsigned int)time(NULL));
while (1)
{
chiller->temperature = 50 + ((rand() % 10) - 5);
chiller->pressure = 55 + ((rand() % 10) - 5);
chiller->humidity = 30 + ((rand() % 10) - 5);
unsigned char*buffer;
size_t bufferSize;
if (chiller->FirmwareUpdateStatus == "waiting")
{
(void)printf("Sending sensor value Temperature = %f %s,\r\n", chiller->temperature, chiller->temperature_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->temperature, chiller->temperature_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.TemperatureSchema.MessageSchema.Name);
}
(void)printf("Sending sensor value Humidity = %f %s,\r\n", chiller->humidity, chiller->humidity_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->humidity, chiller->humidity_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.HumiditySchema.MessageSchema.Name);
}
(void)printf("Sending sensor value Pressure = %f %s,\r\n", chiller->pressure, chiller->pressure_unit);
if (SERIALIZE(&buffer, &bufferSize, chiller->pressure, chiller->pressure_unit) != CODEFIRST_OK)
{
(void)printf("Failed sending sensor value\r\n");
}
else
{
sendMessage(iotHubClientHandle, buffer, bufferSize, chiller->Telemetry.PressureSchema.MessageSchema.Name);
}
}
ThreadAPI_Sleep(5000);
}
IoTHubDeviceTwin_DestroyChiller(chiller);
}
}
IoTHubClient_Destroy(iotHubClientHandle);
}
serializer_deinit();
}
}
platform_deinit();
}
```
For reference, here is a sample **Telemetry** message sent to the solution accelerator:
```
Device: [myCDevice],
Data:[{"humidity":50.000000000000000, "humidity_unit":"%"}]
Properties:
'$$MessageSchema': 'chiller-humidity;v1'
'$$ContentType': 'JSON'
'$$CreationTimeUtc': '2017-09-12T09:17:13Z'
```
## Build and run the sample
Add code to invoke the **remote\_monitoring\_run** function and then build and run the device application.
1. Replace the **main** function with following code to invoke the **remote\_monitoring\_run** function:
```c
int main()
{
remote_monitoring_run();
return 0;
}
```
1. Click **Build** and then **Build Solution** to build the device application.
1. In **Solution Explorer**, right-click the **RMDevice** project, click **Debug**, and then click **Start new instance** to run the sample. The console displays messages as the application sends sample telemetry to the preconfigured solution, receives desired property values set in the solution dashboard, and responds to methods invoked from the solution dashboard.
## View device telemetry in the dashboard
The dashboard in the remote monitoring solution enables you to view the telemetry your devices send to IoT Hub.
1. In your browser, return to the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. In the **Devices list**, you should see that the status of your device is **Running**. If not, click **Enable Device** in the **Device Details** panel.
![View device status][18]
3. Click **Dashboard** to return to the dashboard, select your device in the **Device to View** drop-down to view its telemetry. The telemetry from the sample application is 50 units for internal temperature, 55 units for external temperature, and 50 units for humidity.
![View device telemetry][img-telemetry]
## Invoke a method on your device
The dashboard in the remote monitoring solution enables you to invoke methods on your devices through IoT Hub. For example, in the remote monitoring solution you can invoke a method to simulate rebooting a device.
1. In the remote monitoring solution dashboard, click **Devices** in the left-hand panel to navigate to the **Devices list**.
2. Click **Device ID** for your device in the **Devices list**.
3. In the **Device details** panel, click **Methods**.
![Device methods][13]
4. In the **Method** drop-down, select **InitiateFirmwareUpdate**, and then in **FWPACKAGEURI** enter a dummy URL. Click **Invoke Method** to call the method on the device.
![Invoke a device method][14]
5. You see a message in the console running your device code when the device handles the method. The results of the method are added to the history in the solution portal:
![View method history][img-method-history]
## Next steps
The article [Customizing preconfigured solutions][lnk-customize] describes some ways you can extend this sample. Possible extensions include using real sensors and implementing additional commands.
You can learn more about the [permissions on the azureiotsuite.com site][lnk-permissions].
[13]: ./media/iot-suite-v1-visualize-connecting/suite4.png
[14]: ./media/iot-suite-v1-visualize-connecting/suite7-1.png
[18]: ./media/iot-suite-v1-visualize-connecting/suite10.png
[img-telemetry]: ./media/iot-suite-v1-visualize-connecting/telemetry.png
[img-method-history]: ./media/iot-suite-v1-visualize-connecting/history.png
[lnk-customize]: ../articles/iot-suite/iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-c-project-properties]: https://msdn.microsoft.com/library/669zx6zc.aspx

Просмотреть файл

@ -0,0 +1,281 @@
# Create a custom rule in the remote monitoring preconfigured solution
## Introduction
In the preconfigured solutions, you can configure [rules that trigger when a telemetry value for a device reaches a specific threshold][lnk-builtin-rule]. [Use dynamic telemetry with the remote monitoring preconfigured solution][lnk-dynamic-telemetry] describes how you can add custom telemetry values, such as *ExternalTemperature* to your solution. This article shows you how to create custom rule for dynamic telemetry types in your solution.
This tutorial uses a simple Node.js simulated device to generate dynamic telemetry to send to the preconfigured solution back end. You then add custom rules in the **RemoteMonitoring** Visual Studio solution and deploy this customized back end to your Azure subscription.
To complete this tutorial, you need:
* An active Azure subscription. If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk_free_trial].
* [Node.js][lnk-node] version 0.12.x or later to create a simulated device.
* Visual Studio 2015 or Visual Studio 2017 to modify the preconfigured solution back end with your new rules.
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
Make a note of the solution name you chose for your deployment. You need this solution name later in this tutorial.
## Configure the Node.js simulated device
1. On the remote monitoring dashboard, click **+ Add a device** and then add a *custom device*. Make a note of the IoT Hub hostname, device id, and device key. You need them later in this tutorial when you prepare the remote_monitoring.js device client application.
2. Ensure that Node.js version 0.12.x or later is installed on your development machine. Run `node --version` at a command prompt or in a shell to check the version. For information about using a package manager to install Node.js on Linux, see [Installing Node.js via package manager][node-linux].
3. When you have installed Node.js, clone the latest version of the [azure-iot-sdk-node][lnk-github-repo] repository to your development machine. Always use the **master** branch for the latest version of the libraries and samples.
4. From your local copy of the [azure-iot-sdk-node][lnk-github-repo] repository, copy the following two files from the node/device/samples folder to an empty folder on your development machine:
* packages.json
* remote_monitoring.js
5. Open the remote_monitoring.js file and look for the following variable definition:
```
var connectionString = "[IoT Hub device connection string]";
```
6. Replace **[IoT Hub device connection string]** with your device connection string. Use the values for your IoT Hub hostname, device id, and device key that you made a note of in step 1. A device connection string has the following format:
```
HostName={your IoT Hub hostname};DeviceId={your device id};SharedAccessKey={your device key}
```
If your IoT Hub hostname is **contoso** and your device id is **mydevice**, your connection string looks like the following snippet:
```
var connectionString = "HostName=contoso.azure-devices.net;DeviceId=mydevice;SharedAccessKey=2s ... =="
```
7. Save the file. Run the following commands in a shell or command prompt in the folder that contains these files to install the necessary packages and then run the sample application:
```
npm install
node remote_monitoring.js
```
## Observe dynamic telemetry in action
The dashboard shows the temperature and humidity telemetry from the existing simulated devices:
![The default dashboard][image1]
If you select the Node.js simulated device you ran in the previous section, you see temperature, humidity, and external temperature telemetry:
![Add external temperature to the dashboard][image2]
The remote monitoring solution automatically detects the additional external temperature telemetry type and adds it to the chart on the dashboard.
[node-linux]: https://github.com/nodejs/node-v0.x-archive/wiki/Installing-Node.js-via-package-manager
[lnk-github-repo]: https://github.com/Azure/azure-iot-sdk-node
[image1]: media/iot-suite-v1-send-external-temperature/image1.png
[image2]: media/iot-suite-v1-send-external-temperature/image2.png
You can stop the Node.js console app when you have verified that it is sending **ExternalTemperature** telemetry to the preconfigured solution. Keep the console window open because you run this Node.js console app again after you add the custom rule to the solution.
## Rule storage locations
Information about rules is persisted in two locations:
* **DeviceRulesNormalizedTable** table – This table stores a normalized reference to the rules defined by the solution portal. When the solution portal displays device rules, it queries this table for the rule definitions.
* **DeviceRules** blob – This blob stores all the rules defined for all registered devices and is defined as a reference input to the Azure Stream Analytics jobs.
 
When you update an existing rule or define a new rule in the solution portal, both the table and blob are updated to reflect the changes. The rule definition displayed in the portal comes from the table store, and the rule definition referenced by the Stream Analytics jobs comes from the blob.
## Update the RemoteMonitoring Visual Studio solution
The following steps show you how to modify the RemoteMonitoring Visual Studio solution to include a new rule that uses the **ExternalTemperature** telemetry sent from the simulated device:
1. If you have not already done so, clone the **azure-iot-remote-monitoring** repository to a suitable location on your local machine using the following Git command:
```
git clone https://github.com/Azure/azure-iot-remote-monitoring.git
```
2. In Visual Studio, open the RemoteMonitoring.sln file from your local copy of the **azure-iot-remote-monitoring** repository.
3. Open the file Infrastructure\Models\DeviceRuleBlobEntity.cs and add an **ExternalTemperature** property as follows:
```csharp
public double? Temperature { get; set; }
public double? Humidity { get; set; }
public double? ExternalTemperature { get; set; }
```
4. In the same file, add an **ExternalTemperatureRuleOutput** property as follows:
```csharp
public string TemperatureRuleOutput { get; set; }
public string HumidityRuleOutput { get; set; }
public string ExternalTemperatureRuleOutput { get; set; }
```
5. Open the file Infrastructure\Models\DeviceRuleDataFields.cs and add the following **ExternalTemperature** property after the existing **Humidity** property:
```csharp
public static string ExternalTemperature
{
    get { return "ExternalTemperature"; }
}
```
6. In the same file, update the **_availableDataFields** method to include **ExternalTemperature** as follows:
```csharp
private static List<string> _availableDataFields = new List<string>
{                   
    Temperature, Humidity, ExternalTemperature
};
```
7. Open the file Infrastructure\Repository\DeviceRulesRepository.cs and modify the **BuildBlobEntityListFromTableRows** method as follows:
```csharp
else if (rule.DataField == DeviceRuleDataFields.Humidity)
{
entity.Humidity = rule.Threshold;
entity.HumidityRuleOutput = rule.RuleOutput;
}
else if (rule.DataField == DeviceRuleDataFields.ExternalTemperature)
{
entity.ExternalTemperature = rule.Threshold;
entity.ExternalTemperatureRuleOutput = rule.RuleOutput;
}
```
## Rebuild and redeploy the solution.
You can now deploy the updated solution to your Azure subscription.
1. Open an elevated command prompt and navigate to the root of your local copy of the azure-iot-remote-monitoring repository.
2. To deploy your updated solution, run the following command substituting **{deployment name}** with the name of your preconfigured solution deployment that you noted previously:
```
build.cmd cloud release {deployment name}
```
## Update the Stream Analytics job
When the deployment is complete, you can update the Stream Analytics job to use the new rule definitions.
1. In the Azure portal, navigate to the resource group that contains your preconfigured solution resources. This resource group has the same name you specified for the solution during the deployment.
2. Navigate to the {deployment name}-Rules Stream Analytics job.
3. Click **Stop** to stop the Stream Analytics job from running. (You must wait for the streaming job to stop before you can edit the query).
4. Click **Query**. Edit the query to include the **SELECT** statement for **ExternalTemperature**. The following sample shows the complete query with the new **SELECT** statement:
```
WITH AlarmsData AS
(
SELECT
     Stream.IoTHub.ConnectionDeviceId AS DeviceId,
     'Temperature' as ReadingType,
     Stream.Temperature as Reading,
     Ref.Temperature as Threshold,
     Ref.TemperatureRuleOutput as RuleOutput,
     Stream.EventEnqueuedUtcTime AS [Time]
FROM IoTTelemetryStream Stream
JOIN DeviceRulesBlob Ref ON Stream.IoTHub.ConnectionDeviceId = Ref.DeviceID
WHERE
     Ref.Temperature IS NOT null AND Stream.Temperature > Ref.Temperature
 
UNION ALL
 
SELECT
     Stream.IoTHub.ConnectionDeviceId AS DeviceId,
     'Humidity' as ReadingType,
     Stream.Humidity as Reading,
     Ref.Humidity as Threshold,
     Ref.HumidityRuleOutput as RuleOutput,
     Stream.EventEnqueuedUtcTime AS [Time]
FROM IoTTelemetryStream Stream
JOIN DeviceRulesBlob Ref ON Stream.IoTHub.ConnectionDeviceId = Ref.DeviceID
WHERE
     Ref.Humidity IS NOT null AND Stream.Humidity > Ref.Humidity
 
UNION ALL
 
SELECT
     Stream.IoTHub.ConnectionDeviceId AS DeviceId,
     'ExternalTemperature' as ReadingType,
     Stream.ExternalTemperature as Reading,
     Ref.ExternalTemperature as Threshold,
     Ref.ExternalTemperatureRuleOutput as RuleOutput,
     Stream.EventEnqueuedUtcTime AS [Time]
FROM IoTTelemetryStream Stream
JOIN DeviceRulesBlob Ref ON Stream.IoTHub.ConnectionDeviceId = Ref.DeviceID
WHERE
     Ref.ExternalTemperature IS NOT null AND Stream.ExternalTemperature > Ref.ExternalTemperature
)
 
SELECT *
INTO DeviceRulesMonitoring
FROM AlarmsData
 
SELECT *
INTO DeviceRulesHub
FROM AlarmsData
```
5. Click **Save** to change the updated rule query.
6. Click **Start** to start the Stream Analytics job running again.
## Add your new rule in the dashboard
You can now add the **ExternalTemperature** rule to a device in the solution dashboard.
1. Navigate to the solution portal.
2. Navigate to the **Devices** panel.
3. Locate the custom device you created that sends **ExternalTemperature** telemetry and on the **Device Details** panel, click **Add Rule**.
4. Select **ExternalTemperature** in **Data Field**.
5. Set **Threshold** to 56. Then click **Save and view rules**.
6. Return to the dashboard to view the alarm history.
7. In the console window you left open, start the Node.js console app to begin sending **ExternalTemperature** telemetry data.
8. Notice that the **Alarm History** table shows new alarms when the new rule is triggered.
 
## Additional information
Changing the operator **>** is more complex and goes beyond the steps outlined in this tutorial. While you can change the Stream Analytics job to use whatever operator you like, reflecting that operator in the solution portal is a more complex task.
## Next steps
Now that you've seen how to create custom rules, you can learn more about the preconfigured solutions:
- [Connect Logic App to your Azure IoT Suite Remote Monitoring preconfigured solution][lnk-logic-app]
- [Device information metadata in the remote monitoring preconfigured solution][lnk-devinfo].
[lnk-devinfo]: iot-suite-v1-remote-monitoring-device-info.md
[lnk_free_trial]: http://azure.microsoft.com/pricing/free-trial/
[lnk-node]: http://nodejs.org
[lnk-builtin-rule]: iot-suite-v1-getstarted-preconfigured-solutions.md#view-alarms
[lnk-dynamic-telemetry]: iot-suite-v1-dynamic-telemetry.md
[lnk-logic-app]: iot-suite-v1-logic-apps-tutorial.md

Просмотреть файл

@ -0,0 +1,252 @@
# Use dynamic telemetry with the remote monitoring preconfigured solution
Dynamic telemetry enables you to visualize any telemetry sent to the remote monitoring preconfigured solution. The simulated devices that deploy with the preconfigured solution send temperature and humidity telemetry, which you can visualize on the dashboard. If you customize existing simulated devices, create new simulated devices, or connect physical devices to the preconfigured solution you can send other telemetry values such as the external temperature, RPM, or windspeed. You can then visualize this additional telemetry on the dashboard.
This tutorial uses a simple Node.js simulated device that you can easily modify to experiment with dynamic telemetry.
To complete this tutorial, youll need:
* An active Azure subscription. If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk_free_trial].
* [Node.js][lnk-node] version 0.12.x or later.
You can complete this tutorial on any operating system, such as Windows or Linux, where you can install Node.js.
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
## Configure the Node.js simulated device
1. On the remote monitoring dashboard, click **+ Add a device** and then add a *custom device*. Make a note of the IoT Hub hostname, device id, and device key. You need them later in this tutorial when you prepare the remote_monitoring.js device client application.
2. Ensure that Node.js version 0.12.x or later is installed on your development machine. Run `node --version` at a command prompt or in a shell to check the version. For information about using a package manager to install Node.js on Linux, see [Installing Node.js via package manager][node-linux].
3. When you have installed Node.js, clone the latest version of the [azure-iot-sdk-node][lnk-github-repo] repository to your development machine. Always use the **master** branch for the latest version of the libraries and samples.
4. From your local copy of the [azure-iot-sdk-node][lnk-github-repo] repository, copy the following two files from the node/device/samples folder to an empty folder on your development machine:
* packages.json
* remote_monitoring.js
5. Open the remote_monitoring.js file and look for the following variable definition:
```
var connectionString = "[IoT Hub device connection string]";
```
6. Replace **[IoT Hub device connection string]** with your device connection string. Use the values for your IoT Hub hostname, device id, and device key that you made a note of in step 1. A device connection string has the following format:
```
HostName={your IoT Hub hostname};DeviceId={your device id};SharedAccessKey={your device key}
```
If your IoT Hub hostname is **contoso** and your device id is **mydevice**, your connection string looks like the following snippet:
```
var connectionString = "HostName=contoso.azure-devices.net;DeviceId=mydevice;SharedAccessKey=2s ... =="
```
7. Save the file. Run the following commands in a shell or command prompt in the folder that contains these files to install the necessary packages and then run the sample application:
```
npm install
node remote_monitoring.js
```
## Observe dynamic telemetry in action
The dashboard shows the temperature and humidity telemetry from the existing simulated devices:
![The default dashboard][image1]
If you select the Node.js simulated device you ran in the previous section, you see temperature, humidity, and external temperature telemetry:
![Add external temperature to the dashboard][image2]
The remote monitoring solution automatically detects the additional external temperature telemetry type and adds it to the chart on the dashboard.
[node-linux]: https://github.com/nodejs/node-v0.x-archive/wiki/Installing-Node.js-via-package-manager
[lnk-github-repo]: https://github.com/Azure/azure-iot-sdk-node
[image1]: media/iot-suite-v1-send-external-temperature/image1.png
[image2]: media/iot-suite-v1-send-external-temperature/image2.png
## Add a telemetry type
The next step is to replace the telemetry generated by the Node.js simulated device with a new set of values:
1. Stop the Node.js simulated device by typing **Ctrl+C** in your command prompt or shell.
2. In the remote_monitoring.js file, you can see the base data values for the existing temperature, humidity, and external temperature telemetry. Add a base data value for **rpm** as follows:
```nodejs
// Sensors data
var temperature = 50;
var humidity = 50;
var externalTemperature = 55;
var rpm = 200;
```
3. The Node.js simulated device uses the **generateRandomIncrement** function in the remote_monitoring.js file to add a random increment to the base data values. Randomize the **rpm** value by adding a line of code after the existing randomizations as follows:
```nodejs
temperature += generateRandomIncrement();
externalTemperature += generateRandomIncrement();
humidity += generateRandomIncrement();
rpm += generateRandomIncrement();
```
4. Add the new rpm value to the JSON payload the device sends to IoT Hub:
```nodejs
var data = JSON.stringify({
'DeviceID': deviceId,
'Temperature': temperature,
'Humidity': humidity,
'ExternalTemperature': externalTemperature,
'RPM': rpm
});
```
5. Run the Node.js simulated device using the following command:
`node remote_monitoring.js`
6. Observe the new RPM telemetry type that displays on the chart in the dashboard:
![Add RPM to the dashboard][image3]
> You may need to disable and then enable the Node.js device on the **Devices** page in the dashboard to see the change immediately.
## Customize the dashboard display
The **Device-Info** message can include metadata about the telemetry the device can send to IoT Hub. This metadata can specify the telemetry types the device sends. Modify the **deviceMetaData** value in the remote_monitoring.js file to include a **Telemetry** definition following the **Commands** definition. The following code snippet shows the **Commands** definition (be sure to add a `,` after the **Commands** definition):
```nodejs
'Commands': [{
'Name': 'SetTemperature',
'Parameters': [{
'Name': 'Temperature',
'Type': 'double'
}]
},
{
'Name': 'SetHumidity',
'Parameters': [{
'Name': 'Humidity',
'Type': 'double'
}]
}],
'Telemetry': [{
'Name': 'Temperature',
'Type': 'double'
},
{
'Name': 'Humidity',
'Type': 'double'
},
{
'Name': 'ExternalTemperature',
'Type': 'double'
}]
```
> The remote monitoring solution uses a case-insensitive match to compare the metadata definition with data in the telemetry stream.
Adding a **Telemetry** definition as shown in the preceding code snippet does not change the behavior of the dashboard. However, the metadata can also include a **DisplayName** attribute to customize the display in the dashboard. Update the **Telemetry** metadata definition as shown in the following snippet:
```nodejs
'Telemetry': [
{
'Name': 'Temperature',
'Type': 'double',
'DisplayName': 'Temperature (C*)'
},
{
'Name': 'Humidity',
'Type': 'double',
'DisplayName': 'Humidity (relative)'
},
{
'Name': 'ExternalTemperature',
'Type': 'double',
'DisplayName': 'Outdoor Temperature (C*)'
}
]
```
The following screenshot shows how this change modifies the chart legend on the dashboard:
![Customize the chart legend][image4]
> You may need to disable and then enable the Node.js device on the **Devices** page in the dashboard to see the change immediately.
## Filter the telemetry types
By default, the chart on the dashboard shows every data series in the telemetry stream. You can use the **Device-Info** metadata to suppress the display of specific telemetry types on the chart.
To make the chart show only Temperature and Humidity telemetry, omit **ExternalTemperature** from the **Device-Info** **Telemetry** metadata as follows:
```nodejs
'Telemetry': [
{
'Name': 'Temperature',
'Type': 'double',
'DisplayName': 'Temperature (C*)'
},
{
'Name': 'Humidity',
'Type': 'double',
'DisplayName': 'Humidity (relative)'
},
//{
// 'Name': 'ExternalTemperature',
// 'Type': 'double',
// 'DisplayName': 'Outdoor Temperature (C*)'
//}
]
```
The **Outdoor Temperature** no longer displays on the chart:
![Filter the telemetry on the dashboard][image5]
This change only affects the chart display. The **ExternalTemperature** data values are still stored and made available for any backend processing.
> You may need to disable and then enable the Node.js device on the **Devices** page in the dashboard to see the change immediately.
## Handle errors
For a data stream to display on the chart, its **Type** in the **Device-Info** metadata must match the data type of the telemetry values. For example, if the metadata specifies that the **Type** of humidity data is **int** and a **double** is found in the telemetry stream then the humidity telemetry does not display on the chart. However, the **Humidity** values are still stored and made available for any back-end processing.
## Next steps
Now that you've seen how to use dynamic telemetry, you can learn more about how the preconfigured solutions use device information: [Device information metadata in the remote monitoring preconfigured solution][lnk-devinfo].
[lnk-devinfo]: iot-suite-v1-remote-monitoring-device-info.md
[image3]: media/iot-suite-v1-dynamic-telemetry/image3.png
[image4]: media/iot-suite-v1-dynamic-telemetry/image4.png
[image5]: media/iot-suite-v1-dynamic-telemetry/image5.png
[lnk_free_trial]: http://azure.microsoft.com/pricing/free-trial/
[lnk-node]: http://nodejs.org

Просмотреть файл

@ -0,0 +1,102 @@
# Frequently asked questions for IoT Suite
See also, the connected factory specific [FAQ](iot-suite-faq-cf.md).
### Where can I find the source code for the preconfigured solutions?
The source code is stored in the following GitHub repositories:
* [Remote monitoring preconfigured solution][lnk-remote-monitoring-github]
* [Predictive maintenance preconfigured solution][lnk-predictive-maintenance-github]
* [Connected factory preconfigured solution](https://github.com/Azure/azure-iot-connected-factory)
### How do I update to the latest version of the remote monitoring preconfigured solution that uses the IoT Hub device management features?
* If you deploy a preconfigured solution from the https://www.azureiotsuite.com/ site, it always deploys a new instance of the latest version of the solution.
* If you deploy a preconfigured solution using the command line, you can update an existing deployment with new code. See [Cloud deployment][lnk-cloud-deployment] in the GitHub [repository][lnk-remote-monitoring-github].
### How can I add support for a new device method to the remote monitoring preconfigured solution?
See the section [Add support for a new method to the simulator][lnk-add-method] in the [Customize a preconfigured solution][lnk-customize] article.
### The simulated device is ignoring my desired property changes, why?
In the remote monitoring preconfigured solution, the simulated device code only uses the **Desired.Config.TemperatureMeanValue** and **Desired.Config.TelemetryInterval** desired properties to update the reported properties. All other desired property change requests are ignored.
### My device does not appear in the list of devices in the solution dashboard, why?
The list of devices in the solution dashboard uses a query to return the list of devices. Currently, a query cannot return more than 10K devices. Try making the search criteria for your query more restrictive.
### What's the difference between deleting a resource group in the Azure portal and clicking delete on a preconfigured solution in azureiotsuite.com?
* If you delete the preconfigured solution in [azureiotsuite.com][lnk-azureiotsuite], you delete all the resources that were provisioned when you created the preconfigured solution. If you added additional resources to the resource group, these resources are also deleted.
* If you delete the resource group in the [Azure portal][lnk-azure-portal], you only delete the resources in that resource group. You also need to delete the Azure Active Directory application associated with the preconfigured solution in the [Azure portal][lnk-azure-portal].
### How many IoT Hub instances can I provision in a subscription?
By default you can provision [10 IoT hubs per subscription][link-azuresublimits]. You can create an [Azure support ticket][link-azuresupportticket] to raise this limit. As a result, since every preconfigured solution provisions a new IoT Hub, you can only provision up to 10 preconfigured solutions in a given subscription.
### How many Azure Cosmos DB instances can I provision in a subscription?
Fifty. You can create an [Azure support ticket][link-azuresupportticket] to raise this limit, but by default, you can only provision 50 Cosmos DB instances per subscription.
### How many Free Bing Maps APIs can I provision in a subscription?
Two. You can create only two Internal Transactions Level 1 Bing Maps for Enterprise plans in an Azure subscription. The remote monitoring solution is provisioned by default with the Internal Transactions Level 1 plan. As a result, you can only provision up to two remote monitoring solutions in a subscription with no modifications.
### I have a remote monitoring solution deployment with a static map, how do I add an interactive Bing map?
1. Get your Bing Maps API for Enterprise QueryKey from [Azure portal][lnk-azure-portal]:
1. Navigate to the Resource Group where your Bing Maps API for Enterprise is in the [Azure portal][lnk-azure-portal].
2. Click **All Settings**, then **Key Management**.
3. You can see two keys: **MasterKey** and **QueryKey**. Copy the value for **QueryKey**.
> Don't have a Bing Maps API for Enterprise account? Create one in the [Azure portal][lnk-azure-portal] by clicking + New, searching for Bing Maps API for Enterprise and follow prompts to create.
>
>
2. Pull down the latest code from the [Azure-IoT-Remote-Monitoring][lnk-remote-monitoring-github].
3. Run a local or cloud deployment following the command-line deployment guidance in the /docs/ folder in the repository.
4. After you've run a local or cloud deployment, look in your root folder for the *.user.config file created during deployment. Open this file in a text editor.
5. Change the following line to include the value you copied from your **QueryKey**:
`<setting name="MapApiQueryKey" value="" />`
### Can I create a preconfigured solution if I have Microsoft Azure for DreamSpark?
> Microsoft Azure for DreamSpark is now known as Microsoft Imagine for students.
Currently, you cannot create a preconfigured solution with a [Microsoft Azure for DreamSpark](https://azure.microsoft.com/pricing/member-offers/imagine/) account. However, you can create a [free trial account for Azure](https://azure.microsoft.com/free/) in just a couple of minutes that enables you create a preconfigured solution.
### Can I create a preconfigured solution if I have Cloud Solution Provider (CSP) subscription?
Currently, you cannot create a preconfigured solution with a Cloud Solution Provider (CSP) subscription. However, you can create a [free trial account for Azure][lnk-30daytrial] in just a couple of minutes that enables you create a preconfigured solution.
### How do I delete an Azure AD tenant?
See Eric Golpe's blog post [Walkthrough of Deleting an Azure AD Tenant][lnk-delete-aad-tennant].
### Next steps
You can also explore some of the other features and capabilities of the IoT Suite preconfigured solutions:
* [Predictive maintenance preconfigured solution overview][lnk-predictive-overview]
* [Connected factory preconfigured solution overview](iot-suite-connected-factory-overview.md)
* [IoT security from the ground up][lnk-security-groundup]
[lnk-predictive-overview]: iot-suite-predictive-overview.md
[lnk-security-groundup]: securing-iot-ground-up.md
[link-azuresupportticket]: https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade
[link-azuresublimits]: https://azure.microsoft.com/documentation/articles/azure-subscription-service-limits/#iot-hub-limits
[lnk-azure-portal]: https://portal.azure.com
[lnk-azureiotsuite]: https://www.azureiotsuite.com/
[lnk-remote-monitoring-github]: https://github.com/Azure/azure-iot-remote-monitoring
[lnk-dreamspark]: https://www.dreamspark.com/Product/Product.aspx?productid=99
[lnk-30daytrial]: https://azure.microsoft.com/free/
[lnk-delete-aad-tennant]: http://blogs.msdn.com/b/ericgolpe/archive/2015/04/30/walkthrough-of-deleting-an-azure-ad-tenant.aspx
[lnk-cloud-deployment]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/cloud-deployment.md
[lnk-add-method]: iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md#add-support-for-a-new-method-to-the-simulator
[lnk-customize]: iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md
[lnk-remote-monitoring-github]: https://github.com/Azure/azure-iot-remote-monitoring
[lnk-predictive-maintenance-github]: https://github.com/Azure/azure-iot-predictive-maintenance

Просмотреть файл

@ -0,0 +1,418 @@
# Get started with the preconfigured solutions
Azure IoT Suite [preconfigured solutions][lnk-preconfigured-solutions] combine multiple Azure IoT services to deliver end-to-end solutions that implement common IoT business scenarios. The *remote monitoring* preconfigured solution connects to and monitors your devices. You can use the solution to analyze the stream of data from your devices and to improve business outcomes by making processes respond automatically to that stream of data.
This tutorial shows you how to provision the remote monitoring preconfigured solution. It also walks you through the basic features of the preconfigured solution. You can access many of these features from the solution *dashboard* that deploys as part of the preconfigured solution:
![Remote monitoring preconfigured solution dashboard][img-dashboard]
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk_free_trial].
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
## Scenario overview
When you deploy the remote monitoring preconfigured solution, it is prepopulated with resources that enable you to step through a common remote monitoring scenario. In this scenario, several devices connected to the solution are reporting unexpected temperature values. The following sections show you how to:
* Identify the devices sending unexpected temperature values.
* Configure these devices to send more detailed telemetry.
* Fix the problem by updating the firmware on these devices.
* Verify that your action has resolved the issue.
A key feature of this scenario is that you can perform all these actions remotely from the solution dashboard. You do not need physical access to the devices.
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and configure rules.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
The dashboard displays the following information:
* A map that displays the location of each device connected to the solution. When you first run the solution, there are 25 simulated devices. The simulated devices are implemented as Azure WebJobs, and the solution uses the Bing Maps API to plot information on the map. See the [FAQ][lnk-faq] to learn how to make the map dynamic.
* A **Telemetry History** panel that plots humidity and temperature telemetry from a selected device in near real time and displays aggregate data such as maximum, minimum, and average humidity.
* An **Alarm History** panel that shows recent alarm events when a telemetry value has exceeded a threshold. You can define your own alarms in addition to the examples created by the preconfigured solution.
* A **Jobs** panel that displays information about scheduled jobs. You can schedule your own jobs on **Management jobs** page.
## View alarms
The alarm history panel shows you that five devices are reporting higher than expected telemetry values.
![TODO Alarm history on the solution dashboard][img-alarms]
> These alarms are generated by a rule that is included in the preconfigured solution. This rule generates an alert when the temperature value sent by a device exceeds 60. You can define your own rules and actions by choosing [Rules](#add-a-rule) and [Actions](#add-an-action) in the left-hand menu.
## View devices
The *devices* list shows all the registered devices in the solution. From the device list you can view and edit device metadata, add or remove devices, and invoke methods on devices. You can filter and sort the list of devices in the device list. You can also customize the columns shown in the device list.
1. Choose **Devices** to show the device list for this solution.
![View the device list in the solution portal][img-devicelist]
1. The device list initially shows 25 simulated devices created by the provisioning process. You can add additional simulated and physical devices to the solution.
1. To view the details of a device, choose a device in the device list.
![View the device details in the solution portal][img-devicedetails]
The **Device Details** panel contains six sections:
* A collection of links that enable you to customize the device icon, disable the device, add a rule, invoke a method, or send a command. For a comparison of commands (device-to-cloud messages) and methods (direct methods), see [Cloud-to-device communications guidance][lnk-c2d-guidance].
* The **Device Twin - Tags** section enables you to edit tag values for the device. You can display tag values in the device list and use tag values to filter the device list.
* The **Device Twin - Desired Properties** section enables you to set property values to be sent to the device.
* The **Device Twin - Reported Properties** section shows property values sent from the device.
* The **Device Properties** section shows information from the identity registry such as the device id and authentication keys.
* The **Recent Jobs** section shows information about any jobs that have recently targeted this device.
## Filter the device list
You can use a filter to display only those devices that are sending unexpected temperature values. The remote monitoring preconfigured solution includes the **Unhealthy devices** filter to show devices with a mean temperature value greater than 60. You can also [create your own filters](#add-a-filter).
1. Choose **Open saved filter** to display a list of available filters. Then choose **Unhealthy devices** to apply the filter:
![Display the list of filters][img-unhealthy-filter]
1. The device list now shows only devices with a mean temperature value greater than 60.
![View the filtered device list showing unhealthy devices][img-filtered-unhealthy-list]
## Update desired properties
You have now identified a set of devices that may need remediation. However, you decide that the data frequency of 15 seconds is not sufficient for a clear diagnosis of the issue. Changing the telemetry frequency to five seconds to provide you with more data points to better diagnose the issue. You can push this configuration change to your remote devices from the solution portal. You can make the change once, evaluate the impact, and then act on the results.
Follow these steps to run a job that changes the **TelemetryInterval** desired property for the affected devices. When the devices receive the new **TelemetryInterval** property value, they change their configuration to send telemetry every five seconds instead of every 15 seconds:
1. While you are showing the list of unhealthy devices in the device list, choose **Job Scheduler**, then **Edit Device Twin**.
1. Call the job **Change telemetry interval**.
1. Change the value of the **Desired Property** name **desired.Config.TelemetryInterval** to five seconds.
1. Choose **Schedule**.
![Change the TelemetryInterval property to five seconds][img-change-interval]
1. You can monitor the progress of the job on the **Management Jobs** page in the portal.
> If you want to change a desired property value for an individual device, use the **Desired Properties** section in the **Device Details** panel instead of running a job.
This job sets the value of the **TelemetryInterval** desired property in the device twin for all the devices selected by the filter. The devices retrieve this value from the device twin and update their behavior. When a device retrieves and processes a desired property from a device twin, it sets the corresponding reported value property.
## Invoke methods
While the job runs, you notice in the list of unhealthy devices that all these devices have old (less than version 1.6) firmware versions.
![View the reported firmware version for the unhealthy devices][img-old-firmware]
This firmware version may be the root cause of the unexpected temperature values because you know that other healthy devices were recently updated to version 2.0. You can use the built-in **Old firmware devices** filter to identify any devices with old firmware versions. From the portal, you can then remotely update all the devices still running old firmware versions:
1. Choose **Open saved filter** to display a list of available filters. Then choose **Old firmware devices** to apply the filter:
![Display the list of filters][img-old-filter]
1. The device list now shows only devices with old firmware versions. This list includes the five devices identified by the **Unhealthy devices** filter and three additional devices:
![View the filtered device list showing old devices][img-filtered-old-list]
1. Choose **Job Scheduler**, then **Invoke Method**.
1. Set **Job Name** to **Firmware update to version 2.0**.
1. Choose **InitiateFirmwareUpdate** as the **Method**.
1. Set the **FwPackageUri** parameter to **https://iotrmassets.blob.core.windows.net/firmwares/FW20.bin**.
1. Choose **Schedule**. The default is for the job to run now.
![Create job to update the firmware of the selected devices][img-method-update]
> If you want to invoke a method on an individual device, choose **Methods** in the **Device Details** panel instead of running a job.
This job invokes the **InitiateFirmwareUpdate** direct method on all the devices selected by the filter. Devices respond immediately to IoT Hub and then initiate the firmware update process asynchronously. The devices provide status information about the firmware update process through reported property values, as shown in the following screenshots. Choose the **Refresh** icon to update the information in the device and job lists:
![Job list showing the firmware update list running][img-update-1]
![Device list showing firmware update status][img-update-2]
![Job list showing the firmware update list complete][img-update-3]
> In a production environment, you can schedule jobs to run during a designated maintenance window.
## Scenario review
In this scenario, you identified a potential issue with some of your remote devices using the alarm history on the dashboard and a filter. You then used the filter and a job to remotely configure the devices to provide more information to help diagnose the issue. Finally, you used a filter and a job to schedule maintenance on the affected devices. If you return to the dashboard, you can check that there are no longer any alarms coming from devices in your solution. You can use a filter to verify that the firmware is up-to-date on all the devices in your solution and that there are no more unhealthy devices:
![Filter showing that all devices have up-to-date firmware][img-updated]
![Filter showing that all devices are healthy][img-healthy]
## Other features
The following sections describe some additional features of the remote monitoring preconfigured solution that are not described as part of the previous scenario.
### Customize columns
You can customize the information shown in the device list by choosing **Column editor**. You can add and remove columns that display reported property and tag values. You can also reorder and rename columns:
![Column editor ion the device list][img-columneditor]
### Customize the device icon
You can customize the device icon displayed in the device list from the **Device Details** panel as follows:
1. Choose the pencil icon to open the **Edit image** panel for a device:
![Open device image editor][img-startimageedit]
1. Either upload a new image or use one of the existing images and then choose **Save**:
![Edit device image editor][img-imageedit]
1. The image you selected now displays in the **Icon** column for the device.
> The image is stored in blob storage. A tag in the device twin contains a link to the image in blob storage.
### Add a device
When you deploy the preconfigured solution, you automatically provision 25 sample devices that you can see in the device list. These devices are *simulated devices* running in an Azure WebJob. Simulated devices make it easy for you to experiment with the preconfigured solution without the need to deploy real, physical devices. If you do want to connect a real device to the solution, see the [Connect your device to the remote monitoring preconfigured solution][lnk-connect-rm] tutorial.
The following steps show you how to add a simulated device to the solution:
1. Navigate back to the device list.
1. To add a device, choose **+ Add A Device** in the bottom left corner.
![Add a device to the preconfigured solution][img-adddevice]
1. Choose **Add New** on the **Simulated Device** tile.
![Set new device details in dashboard][img-addnew]
In addition to creating a new simulated device, you can also add a physical device if you choose to create a **Custom Device**. To learn more about connecting physical devices to the solution, see [Connect your device to the IoT Suite remote monitoring preconfigured solution][lnk-connect-rm].
1. Select **Let me define my own Device ID**, and enter a unique device ID name such as **mydevice_01**.
1. Choose **Create**.
![Save a new device][img-definedevice]
1. In step 3 of **Add a simulated device**, choose **Done** to return to the device list.
1. You can view your device **Running** in the device list.
![View new device in device list][img-runningnew]
1. You can also view the simulated telemetry from your new device on the dashboard:
![View telemetry from new device][img-runningnew-2]
### Disable and delete a device
You can disable a device, and after it is disabled you can remove it:
![Disable and remove a device][img-disable]
### Add a rule
There are no rules for the new device you just added. In this section, you add a rule that triggers an alarm when the temperature reported by the new device exceeds 47 degrees. Before you start, notice that the telemetry history for the new device on the dashboard shows the device temperature never exceeds 45 degrees.
1. Navigate back to the device list.
1. To add a rule for the device, select your new device in the **Devices List**, and then choose **Add rule**.
1. Create a rule that uses **Temperature** as the data field and uses **AlarmTemp** as the output when the temperature exceeds 47 degrees:
![Add a device rule][img-adddevicerule]
1. To save your changes, choose **Save and View Rules**.
1. Choose **Commands** in the device details pane for the new device.
![Add a device rule][img-adddevicerule2]
1. Select **ChangeSetPointTemp** from the command list and set **SetPointTemp** to 45. Then choose **Send Command**:
![Add a device rule][img-adddevicerule3]
1. Navigate back to the dashboard. After a short time, you will see a new entry in the **Alarm History** pane when the temperature reported by your new device exceeds the 47-degree threshold:
![Add a device rule][img-adddevicerule4]
1. You can review and edit all your rules on the **Rules** page of the dashboard:
![List device rules][img-rules]
1. You can review and edit all the actions that can be taken in response to a rule on the **Actions** page of the dashboard:
![List device actions][img-actions]
> It is possible to define actions that can send an email message or SMS in response to a rule or integrate with a line-of-business system through a [Logic App][lnk-logic-apps]. For more information, see the [Connect Logic App to your Azure IoT Suite Remote Monitoring preconfigured solution][lnk-logicapptutorial].
### Manage filters
In the device list, you can create, save, and reload filters to display a customized list of devices connected to your hub. To create a filter:
1. Choose the edit filter icon above the list of devices:
![Open the filter editor][img-editfiltericon]
1. In the **Filter editor**, add the fields, operators, and values to filter the device list. You can add multiple clauses to refine your filter. Choose **Filter** to apply the filter:
![Create a filter][img-filtereditor]
1. In this example, the list is filtered by manufacturer and model number:
![Filtered list][img-filterelist]
1. To save your filter with a custom name, choose the **Save as** icon:
![Save a filter][img-savefilter]
1. To reapply a filter you saved previously, choose the **Open saved filter** icon:
![Open a filter][img-openfilter]
You can create filters based on device id, device state, desired properties, reported properties, and tags. You add your own custom tags to a device in the **Tags** section of the **Device Details** panel, or run a job to update tags on multiple devices.
> In the **Filter editor**, you can use the **Advanced view** to edit the query text directly.
### Commands
From the **Device Details** panel, you can send commands to the device. When a device first starts, it sends information about the commands it supports to the solution. For a discussion of the differences between commands and methods, see [Azure IoT Hub cloud-to-device options][lnk-c2d-guidance].
1. Choose **Commands** in the **Device Details** panel for the selected device:
![Device commands in dashboard][img-devicecommands]
1. Select **PingDevice** from the command list.
1. Choose **Send Command**.
1. You can see the status of the command in the command history.
![Command status in dashboard][img-pingcommand]
The solution tracks the status of each command it sends. Initially the result is **Pending**. When the device reports that it has executed the command, the result is set to **Success**.
## Behind the scenes
When you deploy a preconfigured solution, the deployment process creates multiple resources in the Azure subscription you selected. You can view these resources in the Azure [portal][lnk-portal]. The deployment process creates a **resource group** with a name based on the name you choose for your preconfigured solution:
![Preconfigured solution in the Azure portal][img-portal]
You can view the settings of each resource by selecting it in the list of resources in the resource group.
You can also view the source code for the preconfigured solution. The remote monitoring preconfigured solution source code is in the [azure-iot-remote-monitoring][lnk-rmgithub] GitHub repository:
* The **DeviceAdministration** folder contains the source code for the dashboard.
* The **Simulator** folder contains the source code for the simulated device.
* The **EventProcessor** folder contains the source code for the back-end process that handles the incoming telemetry.
When you are done, you can delete the preconfigured solution from your Azure subscription on the [azureiotsuite.com][lnk-azureiotsuite] site. This site enables you to easily delete all the resources that were provisioned when you created the preconfigured solution.
> To ensure that you delete everything related to the preconfigured solution, delete it on the [azureiotsuite.com][lnk-azureiotsuite] site and do not delete the resource group in the portal.
## Next Steps
Now that youve deployed a working preconfigured solution, you can continue getting started with IoT Suite by reading the following articles:
* [Remote monitoring preconfigured solution walkthrough][lnk-rm-walkthrough]
* [Connect your device to the remote monitoring preconfigured solution][lnk-connect-rm]
* [Permissions on the azureiotsuite.com site][lnk-permissions]
[img-launch-solution]: media/iot-suite-v1-getstarted-preconfigured-solutions/launch.png
[img-dashboard]: media/iot-suite-v1-getstarted-preconfigured-solutions/dashboard.png
[img-menu]: media/iot-suite-v1-getstarted-preconfigured-solutions/menu.png
[img-devicelist]: media/iot-suite-v1-getstarted-preconfigured-solutions/devicelist.png
[img-alarms]: media/iot-suite-v1-getstarted-preconfigured-solutions/alarms.png
[img-devicedetails]: media/iot-suite-v1-getstarted-preconfigured-solutions/devicedetails.png
[img-devicecommands]: media/iot-suite-v1-getstarted-preconfigured-solutions/devicecommands.png
[img-pingcommand]: media/iot-suite-v1-getstarted-preconfigured-solutions/pingcommand.png
[img-adddevice]: media/iot-suite-v1-getstarted-preconfigured-solutions/adddevice.png
[img-addnew]: media/iot-suite-v1-getstarted-preconfigured-solutions/addnew.png
[img-definedevice]: media/iot-suite-v1-getstarted-preconfigured-solutions/definedevice.png
[img-runningnew]: media/iot-suite-v1-getstarted-preconfigured-solutions/runningnew.png
[img-runningnew-2]: media/iot-suite-v1-getstarted-preconfigured-solutions/runningnew2.png
[img-rules]: media/iot-suite-v1-getstarted-preconfigured-solutions/rules.png
[img-adddevicerule]: media/iot-suite-v1-getstarted-preconfigured-solutions/addrule.png
[img-adddevicerule2]: media/iot-suite-v1-getstarted-preconfigured-solutions/addrule2.png
[img-adddevicerule3]: media/iot-suite-v1-getstarted-preconfigured-solutions/addrule3.png
[img-adddevicerule4]: media/iot-suite-v1-getstarted-preconfigured-solutions/addrule4.png
[img-actions]: media/iot-suite-v1-getstarted-preconfigured-solutions/actions.png
[img-portal]: media/iot-suite-v1-getstarted-preconfigured-solutions/portal.png
[img-disable]: media/iot-suite-v1-getstarted-preconfigured-solutions/solutionportal_08.png
[img-columneditor]: media/iot-suite-v1-getstarted-preconfigured-solutions/columneditor.png
[img-startimageedit]: media/iot-suite-v1-getstarted-preconfigured-solutions/imagedit1.png
[img-imageedit]: media/iot-suite-v1-getstarted-preconfigured-solutions/imagedit2.png
[img-editfiltericon]: media/iot-suite-v1-getstarted-preconfigured-solutions/editfiltericon.png
[img-filtereditor]: media/iot-suite-v1-getstarted-preconfigured-solutions/filtereditor.png
[img-filterelist]: media/iot-suite-v1-getstarted-preconfigured-solutions/filteredlist.png
[img-savefilter]: media/iot-suite-v1-getstarted-preconfigured-solutions/savefilter.png
[img-openfilter]: media/iot-suite-v1-getstarted-preconfigured-solutions/openfilter.png
[img-unhealthy-filter]: media/iot-suite-v1-getstarted-preconfigured-solutions/unhealthyfilter.png
[img-filtered-unhealthy-list]: media/iot-suite-v1-getstarted-preconfigured-solutions/unhealthylist.png
[img-change-interval]: media/iot-suite-v1-getstarted-preconfigured-solutions/changeinterval.png
[img-old-firmware]: media/iot-suite-v1-getstarted-preconfigured-solutions/noticeold.png
[img-old-filter]: media/iot-suite-v1-getstarted-preconfigured-solutions/oldfilter.png
[img-filtered-old-list]: media/iot-suite-v1-getstarted-preconfigured-solutions/oldlist.png
[img-method-update]: media/iot-suite-v1-getstarted-preconfigured-solutions/methodupdate.png
[img-update-1]: media/iot-suite-v1-getstarted-preconfigured-solutions/jobupdate1.png
[img-update-2]: media/iot-suite-v1-getstarted-preconfigured-solutions/jobupdate2.png
[img-update-3]: media/iot-suite-v1-getstarted-preconfigured-solutions/jobupdate3.png
[img-updated]: media/iot-suite-v1-getstarted-preconfigured-solutions/updated.png
[img-healthy]: media/iot-suite-v1-getstarted-preconfigured-solutions/healthy.png
[lnk_free_trial]: http://azure.microsoft.com/pricing/free-trial/
[lnk-preconfigured-solutions]: iot-suite-v1-what-are-preconfigured-solutions.md
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-logic-apps]: https://azure.microsoft.com/documentation/services/app-service/logic/
[lnk-portal]: http://portal.azure.com/
[lnk-rmgithub]: https://github.com/Azure/azure-iot-remote-monitoring
[lnk-logicapptutorial]: iot-suite-v1-logic-apps-tutorial.md
[lnk-rm-walkthrough]: iot-suite-v1-remote-monitoring-sample-walkthrough.md
[lnk-connect-rm]: iot-suite-v1-connecting-devices.md
[lnk-permissions]: iot-suite-v1-permissions.md
[lnk-c2d-guidance]: ../iot-hub/iot-hub-devguide-c2d-guidance.md
[lnk-faq]: iot-suite-v1-faq.md

Просмотреть файл

@ -0,0 +1,232 @@
# Customize a preconfigured solution
The preconfigured solutions provided with the Azure IoT Suite demonstrate the services within the suite working together to deliver an end-to-end solution. From this starting point, there are various places in which you can extend and customize the solution for specific scenarios. The following sections describe these common customization points.
## Find the source code
The source code for the preconfigured solutions is available on GitHub in the following repositories:
* Remote Monitoring: [https://www.github.com/Azure/azure-iot-remote-monitoring](https://github.com/Azure/azure-iot-remote-monitoring)
* Predictive Maintenance: [https://github.com/Azure/azure-iot-predictive-maintenance](https://github.com/Azure/azure-iot-predictive-maintenance)
* Connected factory: [https://github.com/Azure/azure-iot-connected-factory](https://github.com/Azure/azure-iot-connected-factory)
The source code for the preconfigured solutions is provided to demonstrate the patterns and practices used to implement the end-to-end functionality of an IoT solution using Azure IoT Suite. You can find more information about how to build and deploy the solutions in the GitHub repositories.
## Change the preconfigured rules
The remote monitoring solution includes three [Azure Stream Analytics](https://azure.microsoft.com/services/stream-analytics/) jobs to handle device information, telemetry, and rules logic in the solution.
The three stream analytics jobs and their syntax are described in depth in the [Remote monitoring preconfigured solution walkthrough](iot-suite-v1-remote-monitoring-sample-walkthrough.md).
You can edit these jobs directly to alter the logic, or add logic specific to your scenario. You can find the Stream Analytics jobs as follows:
1. Go to [Azure portal](https://portal.azure.com).
2. Navigate to the resource group with the same name as your IoT solution.
3. Select the Azure Stream Analytics job you'd like to modify.
4. Stop the job by selecting **Stop** in the set of commands.
5. Edit the inputs, query, and outputs.
A simple modification is to change the query for the **Rules** job to use a **"<"** instead of a **">"**. The solution portal still shows **">"** when you edit a rule, but notice how the behavior is flipped due to the change in the underlying job.
6. Start the job
> The remote monitoring dashboard depends on specific data, so altering the jobs can cause the dashboard to fail.
## Add your own rules
In addition to changing the preconfigured Azure Stream Analytics jobs, you can use the Azure portal to add new jobs or add new queries to existing jobs.
## Customize devices
One of the most common extension activities is working with devices specific to your scenario. There are several methods for working with devices. These methods include altering a simulated device to match your scenario, or using the [IoT Device SDK][IoT Device SDK] to connect your physical device to the solution.
For a step-by-step guide to adding devices, see the [Iot Suite Connecting Devices](iot-suite-v1-connecting-devices.md) article and the [remote monitoring C SDK Sample](https://github.com/Azure/azure-iot-sdk-c/tree/master/serializer/samples/remote_monitoring). This sample is designed to work with the remote monitoring preconfigured solution.
### Create your own simulated device
Included in the [remote monitoring solution source code](https://github.com/Azure/azure-iot-remote-monitoring), is a .NET simulator. This simulator is the one provisioned as part of the solution and you can alter it to send different metadata, telemetry, and respond to different commands and methods.
The preconfigured simulator in the remote monitoring preconfigured solution simulates a cooler device that emits temperature and humidity telemetry. You can modify the simulator in the [Simulator.WebJob](https://github.com/Azure/azure-iot-remote-monitoring/tree/master/Simulator/Simulator.WebJob) project when you've forked the GitHub repository.
### Available locations for simulated devices
The default set of locations is in Seattle/Redmond, Washington, United States of America. You can change these locations in [SampleDeviceFactory.cs][lnk-sample-device-factory].
### Add a desired property update handler to the simulator
You can set a value for a desired property for a device in the solution portal. It is the responsibility of the device to handle the property change request when the device retrieves the desired property value. To add support for a property value change through a desired property, you need to add a handler to the simulator.
The simulator contains handlers for the **SetPointTemp** and **TelemetryInterval** properties that you can update by setting desired values in the solution portal.
The following example shows the handler for the **SetPointTemp** desired property in the **CoolerDevice** class:
```csharp
protected async Task OnSetPointTempUpdate(object value)
{
var telemetry = _telemetryController as ITelemetryWithSetPointTemperature;
telemetry.SetPointTemperature = Convert.ToDouble(value);
await SetReportedPropertyAsync(SetPointTempPropertyName, telemetry.SetPointTemperature);
}
```
This method updates the telemetry point temperature and then reports the change back to IoT Hub by setting a reported property.
You can add your own handlers for your own properties by following the pattern in the preceding example.
You must also bind the desired property to the handler as shown in the following example from the **CoolerDevice** constructor:
```csharp
_desiredPropertyUpdateHandlers.Add(SetPointTempPropertyName, OnSetPointTempUpdate);
```
Note that **SetPointTempPropertyName** is a constant defined as "Config.SetPointTemp".
### Add support for a new method to the simulator
You can customize the simulator to add support for a new [method (direct method)][lnk-direct-methods]. There are two key steps required:
- The simulator must notify the IoT hub in the preconfigured solution with details of the method.
- The simulator must include code to handle the method call when you invoke it from the **Device details** panel in the solution explorer or through a job.
The remote monitoring preconfigured solution uses *reported properties* to send details of supported methods to IoT hub. The solution back end maintains a list of all the methods supported by each device along with a history of method invocations. You can view this information about devices and invoke methods in the solution portal.
To notify the IoT hub that a device supports a method, the device must add details of the method to the **SupportedMethods** node in the reported properties:
```json
"SupportedMethods": {
"<method signature>": "<method description>",
"<method signature>": "<method description>"
}
```
The method signature has the following format: `<method name>--<parameter #0 name>-<parameter #1 type>-...-<parameter #n name>-<parameter #n type>`. For example, to specify the **InitiateFirmwareUpdate** method expects a string parameter named **FwPackageURI**, use the following method signature:
```json
InitiateFirmwareUpate--FwPackageURI-string: "description of method"
```
For a list of supported parameter types, see the **CommandTypes** class in the Infrastructure project.
To delete a method, set the method signature to `null` in the reported properties.
> The solution back end only updates information about supported methods when it receives a *device information* message from the device.
The following code sample from the **SampleDeviceFactory** class in the Common project shows how to add a method to the list of **SupportedMethods** in the reported properties sent by the device:
```csharp
device.Commands.Add(new Command(
"InitiateFirmwareUpdate",
DeliveryType.Method,
"Updates device Firmware. Use parameter 'FwPackageUri' to specifiy the URI of the firmware file, e.g. https://iotrmassets.blob.core.windows.net/firmwares/FW20.bin",
new[] { new Parameter("FwPackageUri", "string") }
));
```
This code snippet adds details of the **InitiateFirmwareUpdate** method including text to display in the solution portal and details of the required method parameters.
The simulator sends reported properties, including the list of supported methods, to IoT Hub when the simulator starts.
Add a handler to the simulator code for each method it supports. You can see the existing handlers in the **CoolerDevice** class in the Simulator.WebJob project. The following example shows the handler for **InitiateFirmwareUpdate** method:
```csharp
public async Task<MethodResponse> OnInitiateFirmwareUpdate(MethodRequest methodRequest, object userContext)
{
if (_deviceManagementTask != null && !_deviceManagementTask.IsCompleted)
{
return await Task.FromResult(BuildMethodRespose(new
{
Message = "Device is busy"
}, 409));
}
try
{
var operation = new FirmwareUpdate(methodRequest);
_deviceManagementTask = operation.Run(Transport).ContinueWith(async task =>
{
// after firmware completed, we reset telemetry
var telemetry = _telemetryController as ITelemetryWithTemperatureMeanValue;
if (telemetry != null)
{
telemetry.TemperatureMeanValue = 34.5;
}
await UpdateReportedTemperatureMeanValue();
});
return await Task.FromResult(BuildMethodRespose(new
{
Message = "FirmwareUpdate accepted",
Uri = operation.Uri
}));
}
catch (Exception ex)
{
return await Task.FromResult(BuildMethodRespose(new
{
Message = ex.Message
}, 400));
}
}
```
Method handler names must start with `On` followed by the name of the method. The **methodRequest** parameter contains any parameters passed with the method invocation from the solution back end. The return value must be of type **Task&lt;MethodResponse&gt;**. The **BuildMethodResponse** utility method helps you create the return value.
Inside the method handler, you could:
- Start an asynchronous task.
- Retrieve desired properties from the *device twin* in IoT Hub.
- Update a single reported property using the **SetReportedPropertyAsync** method in the **CoolerDevice** class.
- Update multiple reported properties by creating a **TwinCollection** instance and calling the **Transport.UpdateReportedPropertiesAsync** method.
The preceding firmware update example performs the following steps:
- Checks the device is able to accept the firmware update request.
- Asynchronously initiates the firmware update operation and resets the telemetry when the operation is complete.
- Immediately returns the "FirmwareUpdate accepted" message to indicate the request was accepted by the device.
### Build and use your own (physical) device
The [Azure IoT SDKs](https://github.com/Azure/azure-iot-sdks) provide libraries for connecting numerous device types (languages and operating systems) into IoT solutions.
## Modify dashboard limits
### Number of devices displayed in dashboard dropdown
The default is 200. You can change this number in [DashboardController.cs][lnk-dashboard-controller].
### Number of pins to display in Bing Map control
The default is 200. You can change this number in [TelemetryApiController.cs][lnk-telemetry-api-controller-01].
### Time period of telemetry graph
The default is 10 minutes. You can change this value in [TelmetryApiController.cs][lnk-telemetry-api-controller-02].
## Feedback
Do you have a customization you'd like to see covered in this document? Add feature suggestions to [User Voice](https://feedback.azure.com/forums/321918-azure-iot), or comment on this article.
## Next steps
To learn more about the options for customizing the preconfigured solutions, see:
* [Connect Logic App to your Azure IoT Suite Remote Monitoring preconfigured solution][lnk-logicapp]
* [Use dynamic telemetry with the remote monitoring preconfigured solution][lnk-dynamic]
* [Device information metadata in the remote monitoring preconfigured solution][lnk-devinfo]
* [Customize how the connected factory solution displays data from your OPC UA servers][lnk-cf-customize]
[lnk-logicapp]: iot-suite-v1-logic-apps-tutorial.md
[lnk-dynamic]: iot-suite-v1-dynamic-telemetry.md
[lnk-devinfo]: iot-suite-v1-remote-monitoring-device-info.md
[IoT Device SDK]: https://azure.microsoft.com/documentation/articles/iot-hub-sdks-summary/
[lnk-permissions]: iot-suite-v1-permissions.md
[lnk-dashboard-controller]: https://github.com/Azure/azure-iot-remote-monitoring/blob/3fd43b8a9f7e0f2774d73f3569439063705cebe4/DeviceAdministration/Web/Controllers/DashboardController.cs#L27
[lnk-telemetry-api-controller-01]: https://github.com/Azure/azure-iot-remote-monitoring/blob/3fd43b8a9f7e0f2774d73f3569439063705cebe4/DeviceAdministration/Web/WebApiControllers/TelemetryApiController.cs#L27
[lnk-telemetry-api-controller-02]: https://github.com/Azure/azure-iot-remote-monitoring/blob/e7003339f73e21d3930f71ceba1e74fb5c0d9ea0/DeviceAdministration/Web/WebApiControllers/TelemetryApiController.cs#L25
[lnk-sample-device-factory]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Common/Factory/SampleDeviceFactory.cs#L40
[lnk-direct-methods]: ../iot-hub/iot-hub-devguide-direct-methods.md
[lnk-cf-customize]: iot-suite-connected-factory-customize.md

Просмотреть файл

@ -0,0 +1,150 @@
# Tutorial: Connect Logic App to your Azure IoT Suite Remote Monitoring preconfigured solution
The [Microsoft Azure IoT Suite][lnk-internetofthings] remote monitoring preconfigured solution is a great way to get started quickly with an end-to-end feature set that exemplifies an IoT solution. This tutorial walks you through how to add Logic App to your Microsoft Azure IoT Suite remote monitoring preconfigured solution. These steps demonstrate how you can take your IoT solution even further by connecting it to a business process.
*If youre looking for a walkthrough on how to provision a remote monitoring preconfigured solution, see [Tutorial: Get started with the IoT preconfigured solutions][lnk-getstarted].*
Before you start this tutorial, you should:
* Provision the remote monitoring preconfigured solution in your Azure subscription.
* Create a SendGrid account to enable you to send an email that triggers your business process. You can sign up for a free trial account at [SendGrid](https://sendgrid.com/) by clicking **Try for Free**. After you have registered for your free trial account, you need to create an [API key](https://sendgrid.com/docs/User_Guide/Settings/api_keys.html) in SendGrid that grants permissions to send mail. You need this API key later in the tutorial.
To complete this tutorial, you need Visual Studio 2015 or Visual Studio 2017 to modify the actions in the preconfigured solution back end.
Assuming youve already provisioned your remote monitoring preconfigured solution, navigate to the resource group for that solution in the [Azure portal][lnk-azureportal]. The resource group has the same name as the solution name you chose when you provisioned your remote monitoring solution. In the resource group, you can see all the provisioned Azure resources for your solution. The following screenshot shows an example **Resource group** blade for a remote monitoring preconfigured solution:
![](media/iot-suite-v1-logic-apps-tutorial/resourcegroup.png)
To begin, set up the logic app to use with the preconfigured solution.
## Set up the Logic App
1. Click **Add** at the top of your resource group blade in the Azure portal.
2. Search for **Logic App**, select it and then click **Create**.
3. Fill out the **Name** and use the same **Subscription** and **Resource group** that you used when you provisioned your remote monitoring solution. Click **Create**.
![](media/iot-suite-v1-logic-apps-tutorial/createlogicapp.png)
4. When your deployment completes, you can see the Logic App is listed as a resource in your resource group.
5. Click the Logic App to navigate to the Logic App blade, select the **Blank Logic App** template to open the **Logic Apps Designer**.
![](media/iot-suite-v1-logic-apps-tutorial/logicappsdesigner.png)
6. Select **Request**. This action specifies that an incoming HTTP request with a specific JSON formatted payload acts as a trigger.
7. Paste the following code into the Request Body JSON Schema:
```json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "/",
"properties": {
"DeviceId": {
"id": "DeviceId",
"type": "string"
},
"measuredValue": {
"id": "measuredValue",
"type": "integer"
},
"measurementName": {
"id": "measurementName",
"type": "string"
}
},
"required": [
"DeviceId",
"measurementName",
"measuredValue"
],
"type": "object"
}
```
> You can copy the URL for the HTTP post after you save the logic app, but first you must add an action.
>
>
8. Click **+ New step** under your manual trigger. Then click **Add an action**.
![](media/iot-suite-v1-logic-apps-tutorial/logicappcode.png)
9. Search for **SendGrid - Send email** and click it.
![](media/iot-suite-v1-logic-apps-tutorial/logicappaction.png)
10. Enter a name for the connection, such as **SendGridConnection**, enter the **SendGrid API Key** you created when you set up your SendGrid account, and click **Create**.
![](media/iot-suite-v1-logic-apps-tutorial/sendgridconnection.png)
11. Add email addresses you own to both the **From** and **To** fields. Add **Remote monitoring alert [DeviceId]** to the **Subject** field. In the **Email Body** field, add **Device [DeviceId] has reported [measurementName] with value [measuredValue].** You can add **[DeviceId]**, **[measurementName]**, and **[measuredValue]** by clicking in the **You can insert data from previous steps** section.
![](media/iot-suite-v1-logic-apps-tutorial/sendgridaction.png)
12. Click **Save** in the top menu.
13. Click the **Request** trigger and copy the **Http Post to this URL** value. You need this URL later in this tutorial.
> Logic Apps enable you to run [many different types of action][lnk-logic-apps-actions] including actions in Office 365.
>
>
## Set up the EventProcessor Web Job
In this section, you connect your preconfigured solution to the Logic App you created. To complete this task, you add the URL to trigger the Logic App to the action that fires when a device sensor value exceeds a threshold.
1. Use your git client to clone the latest version of the [azure-iot-remote-monitoring github repository][lnk-rmgithub]. For example:
```cmd
git clone https://github.com/Azure/azure-iot-remote-monitoring.git
```
2. In Visual Studio, open the **RemoteMonitoring.sln** from the local copy of the repository.
3. Open the **ActionRepository.cs** file in the **Infrastructure\\Repository** folder.
4. Update the **actionIds** dictionary with the **Http Post to this URL** you noted from your Logic App as follows:
```csharp
private Dictionary<string,string> actionIds = new Dictionary<string, string>()
{
{ "Send Message", "<Http Post to this URL>" },
{ "Raise Alarm", "<Http Post to this URL>" }
};
```
5. Save the changes in solution and exit Visual Studio.
## Deploy from the command line
In this section, you deploy your updated version of the remote monitoring solution to replace the version currently running in Azure.
1. Following the [dev set-up][lnk-devsetup] instructions to set up your environment for deployment.
2. To deploy locally, follow the [local deployment][lnk-localdeploy] instructions.
3. To deploy to the cloud and update your existing cloud deployment, follow the [cloud deployment][lnk-clouddeploy] instructions. Use the name of your original deployment as the deployment name. For example if the original deployment was called **demologicapp**, use the following command:
```cmd
build.cmd cloud release demologicapp
```
When the build script runs, be sure to use the same Azure account, subscription, region, and Active Directory instance you used when you provisioned the solution.
## See your Logic App in action
The remote monitoring preconfigured solution has two rules set up by default when you provision a solution. Both rules are on the **SampleDevice001** device:
* Temperature > 38.00
* Humidity > 48.00
The temperature rule triggers the **Raise Alarm** action and the Humidity rule triggers the **SendMessage** action. Assuming you used the same URL for both actions the **ActionRepository** class, your logic app triggers for either rule. Both rules use SendGrid to send an email to the **To** address with details of the alert.
> The Logic App continues to trigger every time the threshold is met. To avoid unnecessary emails, you can either disable the rules in your solution portal or disable the Logic App in the [Azure portal][lnk-azureportal].
>
>
In addition to receiving emails, you can also see when the Logic App runs in the portal:
![](media/iot-suite-v1-logic-apps-tutorial/logicapprun.png)
## Next steps
Now that you've used a Logic App to connect the preconfigured solution to a business process, you can learn more about the options for customizing the preconfigured solutions:
* [Use dynamic telemetry with the remote monitoring preconfigured solution][lnk-dynamic]
* [Device information metadata in the remote monitoring preconfigured solution][lnk-devinfo]
[lnk-dynamic]: iot-suite-v1-dynamic-telemetry.md
[lnk-devinfo]: iot-suite-v1-remote-monitoring-device-info.md
[lnk-internetofthings]: https://azure.microsoft.com/documentation/suites/iot-suite/
[lnk-getstarted]: iot-suite-v1-getstarted-preconfigured-solutions.md
[lnk-azureportal]: https://portal.azure.com
[lnk-logic-apps-actions]: ../connectors/apis-list.md
[lnk-rmgithub]: https://github.com/Azure/azure-iot-remote-monitoring
[lnk-devsetup]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/dev-setup.md
[lnk-localdeploy]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/local-deployment.md
[lnk-clouddeploy]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/cloud-deployment.md

Просмотреть файл

@ -0,0 +1,134 @@
# Permissions on the azureiotsuite.com site
## What happens when you sign in
The first time you sign in at [azureiotsuite.com][lnk-azureiotsuite], the site determines the permission levels you have based on the currently selected Azure Active Directory (AAD) tenant and Azure subscription.
1. First, to populate the list of tenants seen next to your username, the site finds out from Azure which AAD tenants you belong to. Currently, the site can only obtain user tokens for one tenant at a time. Therefore, when you switch tenants using the dropdown in the top right corner, the site logs you in to that tenant to obtain the tokens for that tenant.
2. Next, the site finds out from Azure which subscriptions you have associated with the selected tenant. You see the available subscriptions when you create a new preconfigured solution.
3. Finally, the site retrieves all the resources in the subscriptions and resource groups tagged as preconfigured solutions and populates the tiles on the home page.
The following sections describe the roles that control access to the preconfigured solutions.
## AAD roles
The AAD roles control the ability provision preconfigured solutions and manage users in a preconfigured solution.
You can find more information about administrator roles in AAD in [Assigning administrator roles in Azure AD][lnk-aad-admin]. The current article focuses on the **Global Administrator** and the **User** directory roles as used by the preconfigured solutions.
### Global administrator
There can be many global administrators per AAD tenant:
* When you create an AAD tenant, you are by default the global administrator of that tenant.
* The global administrator can provision a preconfigured solution and is assigned an **Admin** role for the application inside their AAD tenant.
* If another user in the same AAD tenant creates an application, the default role granted to the global administrator is **ReadOnly**.
* A global administrator can assign users to roles for applications using the [Azure portal][lnk-portal].
### Domain user
There can be many domain users per AAD tenant:
* A domain user can provision a preconfigured solution through the [azureiotsuite.com][lnk-azureiotsuite] site. By default, the domain user is granted the **Admin** role in the provisioned application.
* A domain user can create an application using the build.cmd script in the [azure-iot-remote-monitoring][lnk-rm-github-repo], [azure-iot-predictive-maintenance][lnk-pm-github-repo], or [azure-iot-connected-factory][lnk-cf-github-repo] repository. However, the default role granted to the domain user is **ReadOnly**, because a domain user does not have permission to assign roles.
* If another user in the AAD tenant creates an application, the domain user is assigned the **ReadOnly** role by default for that application.
* A domain user cannot assign roles for applications; therefore a domain user cannot add users or roles for users for an application even if they provisioned it.
### Guest User
There can be many guest users per AAD tenant. Guest users have a limited set of rights in the AAD tenant. As a result, guest users cannot provision a preconfigured solution in the AAD tenant.
For more information about users and roles in AAD, see the following resources:
* [Create users in Azure AD][lnk-create-edit-users]
* [Assign users to apps][lnk-assign-app-roles]
## Azure subscription administrator roles
The Azure admin roles control the ability to map an Azure subscription to an AD tenant.
Find out more about the Azure admin roles in the article [How to add or change Azure Co-Administrator, Service Administrator, and Account Administrator][lnk-admin-roles].
## Application roles
The application roles control access to devices in your preconfigured solution.
There are two defined roles and one implicit role defined in a provisioned application:
* **Admin:** Has full control to add, manage, remove devices, and modify settings.
* **ReadOnly:** Can view devices, rules, actions, jobs, and telemetry.
You can find the permissions assigned to each role in the [RolePermissions.cs][lnk-resource-cs] source file.
### Changing application roles for a user
You can use the following procedure to make a user in your Active Directory an administrator of your preconfigured solution.
You must be an AAD global administrator to change roles for a user:
1. Go to the [Azure portal][lnk-portal].
2. Select **Azure Active Directory**.
3. Make sure you are using the directory you chose on azureiotsuite.com when you provisioned your solution. If you have multiple directories associated with your subscription, you can switch between them if you click your account name at the top-right of the portal.
4. Click **Enterprise applications**, then **All applications**.
4. Show **All applications** with **Any** status. Then search for an application with name of your preconfigured solution.
5. Click the name of the application that matches your preconfigured solution name.
6. Click **Users and groups**.
7. Select the user you want to switch roles.
8. Click **Assign** and select the role (such as **Admin**) you'd like to assign to the user, click the check mark.
## FAQ
### I'm a service administrator and I'd like to change the directory mapping between my subscription and a specific AAD tenant. How do I complete this task?
See [To add an existing subscription to your Azure AD directory](../active-directory/active-directory-how-subscriptions-associated-directory.md#to-associate-an-existing-subscription-to-your-azure-ad-directory)
### I'm a domain user/member on the AAD tenant and I've created a preconfigured solution. How do I get assigned a role for my application?
Ask a global administrator to make you a global administrator on the AAD tenant and then assign roles to users yourself. Alternatively, ask a global administrator to assign you a role directly. If you'd like to change the AAD tenant your preconfigured solution has been deployed to, see the next question.
### How do I switch the AAD tenant my remote monitoring preconfigured solution and application are assigned to?
You can run a cloud deployment from <https://github.com/Azure/azure-iot-remote-monitoring> and redeploy with a newly created AAD tenant. Because you are, by default, a global administrator when you create an AAD tenant, you have permissions to add users and assign roles to those users.
1. Create an AAD directory in the [Azure portal][lnk-portal].
2. Go to <https://github.com/Azure/azure-iot-remote-monitoring>.
3. Run `build.cmd cloud [debug | release] {name of previously deployed remote monitoring solution}` (For example, `build.cmd cloud debug myRMSolution`)
4. When prompted, set the **tenantid** to be your newly created tenant instead of your previous tenant.
### I want to change a Service Administrator or Co-Administrator when logged in with an organisational account
See the support article [Changing Service Administrator and Co-Administrator when logged in with an organisational account][lnk-service-admins].
### Why am I seeing this error? "Your account does not have the proper permissions to create a solution. Please check with your account administrator or try with a different account."
Look at the following diagram for guidance:
![][img-flowchart]
> If you continue to see the error after validating you are a global administrator on the AAD tenant and a co-administrator on the subscription, have your account administrator remove the user and reassign necessary permissions in this order. First, add the user as a global administrator and then add user as a co-administrator on the Azure subscription. If issues persist, contact [Help & Support][lnk-help-support].
### Why am I seeing this error when I have an Azure subscription? "An Azure subscription is required to create pre-configured solutions. You can create a free trial account in just a couple of minutes."
If you're certain you have an Azure subscription, validate the tenant mapping for your subscription and ensure the correct tenant is selected in the dropdown. If youve validated the desired tenant is correct, follow the preceding diagram and validate the mapping of your subscription and this AAD tenant.
## Next steps
To continue learning about IoT Suite, see how you can [customize a preconfigured solution][lnk-customize].
[img-flowchart]: media/iot-suite-v1-permissions/flowchart.png
[lnk-azureiotsuite]: https://www.azureiotsuite.com/
[lnk-rm-github-repo]: https://github.com/Azure/azure-iot-remote-monitoring
[lnk-pm-github-repo]: https://github.com/Azure/azure-iot-predictive-maintenance
[lnk-cf-github-repo]: https://github.com/Azure/azure-iot-connected-factory
[lnk-aad-admin]: ../active-directory/active-directory-assign-admin-roles.md
[lnk-portal]: https://portal.azure.com/
[lnk-create-edit-users]: ../active-directory/active-directory-create-users.md
[lnk-assign-app-roles]: ../active-directory/active-directory-coreapps-assign-user-azure-portal.md
[lnk-service-admins]: https://azure.microsoft.com/support/changing-service-admin-and-co-admin/
[lnk-admin-roles]: ../billing/billing-add-change-azure-subscription-administrator.md
[lnk-resource-cs]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/DeviceAdministration/Web/Security/RolePermissions.cs
[lnk-help-support]: https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade
[lnk-customize]: iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md

Просмотреть файл

@ -0,0 +1,353 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and enable remote firmware updates using C
This tutorial shows you how to use the Microsoft Azure IoT Starter Kit for Raspberry Pi 3 to:
* Develop a temperature and humidity reader that can communicate with the cloud.
* Enable and perform a remote firmware update to update the client application on the Raspberry Pi.
The tutorial uses:
* Raspbian OS, the C programming language, and the Microsoft Azure IoT SDK for C to implement a sample device.
* The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
* Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
* Set up your device and sensors to communicate with your computer and the remote monitoring solution.
* Update the sample device code to connect to the remote monitoring solution, and send telemetry that you can view on the solution dashboard.
* Use the sample device code to update the client application.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
- BME280 sensor
- Breadboard
- Jumper wires
- Resistors
- LEDs
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
### Set up the hardware
This tutorial uses the BME280 sensor included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] to generate telemetry data. It uses an LED to indicate when the Raspberry Pi processes a method invocation from the solution dashboard.
The components on the bread board are:
- Red LED
- 220-Ohm resistor (red, red, brown)
- BME280 sensor
The following diagram shows how to connect your hardware:
![Hardware setup for Raspberry Pi][img-connection-diagram]
The following table summarizes the connections from the Raspberry Pi to the components on the breadboard:
| Raspberry Pi | Breadboard |Color |
| ----------------------- | ---------------------- | ------------- |
| GND (Pin 14) | LED -ve pin (18A) | Purple |
| GPCLK0 (Pin 7) | Resistor (25A) | Orange |
| SPI_CE0 (Pin 24) | CS (39A) | Blue |
| SPI_SCLK (Pin 23) | SCK (36A) | Yellow |
| SPI_MISO (Pin 21) | SDO (37A) | White |
| SPI_MOSI (Pin 19) | SDI (38A) | Green |
| GND (Pin 6) | GND (35A) | Black |
| 3.3 V (Pin 1) | 3Vo (34A) | Red |
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
### Enable SPI
Before you can run the sample application, you must enable the Serial Peripheral Interface (SPI) bus on the Raspberry Pi. The Raspberry Pi communicates with the BME280 sensor device over the SPI bus. Use the following command to edit the configuration file:
```sh
sudo nano /boot/config.txt
```
Find the line:
`#dtparam=spi=on`
- To uncomment the line, delete the `#` at the start.
- Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
- To enable SPI, reboot the Raspberry Pi. Rebooting disconnects the terminal, you need to sign in again when the Raspberry Pi restarts:
```sh
sudo reboot
```
[img-connection-diagram]: media/iot-suite-v1-raspberry-pi-kit-prepare-pi/rpi2_remote_monitoring.png
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Clone the repositories
If you haven't done so already, clone the required repositories by running the following commands on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-c-raspberrypi-getstartedkit.git
```
### Update the device connection string
Open the sample configuration file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/advanced/config/deviceinfo
```
Replace the placeholder values with the device ID and IoT Hub information you created and saved at the start of this tutorial.
When you are done, the contents of the deviceinfo file should look like the following example:
```conf
yourdeviceid
HostName=youriothubname.azure-devices.net;DeviceId=yourdeviceid;SharedAccessKey=yourdevicekey
```
Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Build the sample
If you have not already done so, install the prerequisite packages for the Microsoft Azure IoT Device SDK for C by running the following commands in a terminal on the Raspberry Pi:
```sh
sudo apt-get update
sudo apt-get install g++ make cmake git libcurl4-openssl-dev libssl-dev uuid-dev
```
You can now build the sample solution on the Raspberry Pi:
```sh
chmod +x ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/advanced/1.0/build.sh
~/iot-remote-monitoring-c-raspberrypi-getstartedkit/advanced/1.0/build.sh
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo ~/cmake/remote_monitoring/remote_monitoring
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Initiate the firmware update
The firmware update process downloads and installs an updated version of the device client application on the Raspberry Pi. For more information about the firmware update process, see the description of the firmware update pattern in [Overview of device management with IoT Hub][lnk-update-pattern].
You initiate the firmware update process by invoking a method on the device. This method is asynchronous, and returns as soon as the update process begins. The device uses reported properties to notify the solution about the progress of the update.
You invoke methods on your Raspberry Pi from the solution dashboard. When the Raspberry Pi first connects to the remote monitoring solution, it sends information about the methods it supports.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-advanced/telemetry.png
[lnk-update-pattern]: ../articles/iot-hub/iot-hub-device-management-overview.md
1. In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
1. On the **Invoke Method** page, choose **InitiateFirmwareUpdate** in the **Method** dropdown.
1. In the **FWPackageURI** field, enter **https://github.com/Azure-Samples/iot-remote-monitoring-c-raspberrypi-getstartedkit/raw/master/advanced/2.0/package/remote_monitoring.zip**. This archive file contains the implementation of version 2.0 of the firmware.
1. Choose **InvokeMethod**. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard. It then starts the firmware update process by downloading the new version of the firmware:
![Show method history][img-method-history]
## Observe the firmware update process
You can observe the firmware update process as it runs on the device and by viewing the reported properties in the solution dashboard:
1. You can view the progress in of the update process on the Raspberry Pi:
![Show update progress][img-update-progress]
> The remote monitoring app restarts silently when the update completes. Use the command `ps -ef` to verify it is running. If you want to terminate the process, use the `kill` command with the process id.
1. You can view the status of the firmware update, as reported by the device, in the solution portal. The following screenshot shows the status and duration of each stage of the update process, and the new firmware version:
![Show job status][img-job-status]
If you navigate back to the dashboard, you can verify the device is still sending telemetry following the firmware update.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-advanced/app-output.png
[img-update-progress]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-advanced/updateprogress.png
[img-job-status]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-advanced/jobstatus.png
[img-list-devices]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-advanced/listdevices.png
[img-method-history]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-advanced/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,323 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and send telemetry from a real sensor using C
This tutorial shows you how to use the Microsoft Azure IoT Starter Kit for Raspberry Pi 3 to develop a temperature and humidity reader that can communicate with the cloud. The tutorial uses:
- Raspbian OS, the C programming language, and the Microsoft Azure IoT SDK for C to implement a sample device.
- The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
- Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
- Set up your device and sensors to communicate with your computer and the remote monitoring solution.
- Update the sample device code to connect to the remote monitoring solution, and send telemetry that you can view on the solution dashboard.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
- BME280 sensor
- Breadboard
- Jumper wires
- Resistors
- LEDs
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
### Set up the hardware
This tutorial uses the BME280 sensor included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] to generate telemetry data. It uses an LED to indicate when the Raspberry Pi processes a method invocation from the solution dashboard.
The components on the bread board are:
- Red LED
- 220-Ohm resistor (red, red, brown)
- BME280 sensor
The following diagram shows how to connect your hardware:
![Hardware setup for Raspberry Pi][img-connection-diagram]
The following table summarizes the connections from the Raspberry Pi to the components on the breadboard:
| Raspberry Pi | Breadboard |Color |
| ----------------------- | ---------------------- | ------------- |
| GND (Pin 14) | LED -ve pin (18A) | Purple |
| GPCLK0 (Pin 7) | Resistor (25A) | Orange |
| SPI_CE0 (Pin 24) | CS (39A) | Blue |
| SPI_SCLK (Pin 23) | SCK (36A) | Yellow |
| SPI_MISO (Pin 21) | SDO (37A) | White |
| SPI_MOSI (Pin 19) | SDI (38A) | Green |
| GND (Pin 6) | GND (35A) | Black |
| 3.3 V (Pin 1) | 3Vo (34A) | Red |
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
### Enable SPI
Before you can run the sample application, you must enable the Serial Peripheral Interface (SPI) bus on the Raspberry Pi. The Raspberry Pi communicates with the BME280 sensor device over the SPI bus. Use the following command to edit the configuration file:
```sh
sudo nano /boot/config.txt
```
Find the line:
`#dtparam=spi=on`
- To uncomment the line, delete the `#` at the start.
- Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
- To enable SPI, reboot the Raspberry Pi. Rebooting disconnects the terminal, you need to sign in again when the Raspberry Pi restarts:
```sh
sudo reboot
```
[img-connection-diagram]: media/iot-suite-v1-raspberry-pi-kit-prepare-pi/rpi2_remote_monitoring.png
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Clone the repositories
If you haven't already done so, clone the required repositories by running the following commands in a terminal on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-c-raspberrypi-getstartedkit.git
git clone --recursive https://github.com/WiringPi/WiringPi.git
```
### Update the device connection string
Open the sample source file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/basic/remote_monitoring/remote_monitoring.c
```
Locate the following lines:
```c
static const char* deviceId = "[Device Id]";
static const char* connectionString = "HostName=[IoTHub Name].azure-devices.net;DeviceId=[Device Id];SharedAccessKey=[Device Key]";
```
Replace the placeholder values with the device and IoT Hub information you created and saved at the start of this tutorial. Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Build the sample
Install the prerequisite packages for the Microsoft Azure IoT Device SDK for C by running the following commands in a terminal on the Raspberry Pi:
```sh
sudo apt-get update
sudo apt-get install g++ make cmake git libcurl4-openssl-dev libssl-dev uuid-dev
```
You can now build the updated sample solution on the Raspberry Pi:
```sh
chmod +x ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/basic/build.sh
~/iot-remote-monitoring-c-raspberrypi-getstartedkit/basic/build.sh
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo ~/cmake/remote_monitoring/remote_monitoring
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Act on the device
From the solution dashboard, you can invoke methods on your Raspberry Pi. When the Raspberry Pi connects to the remote monitoring solution, it sends information about the methods it supports.
- In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
- On the **Invoke Method** page, choose **LightBlink** in the **Method** dropdown.
- Choose **InvokeMethod**. The LED connected to the Raspberry Pi flashes several times. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard:
![Show method history][img-method-history]
- You can switch the LED on and off using the **ChangeLightStatus** method with a **LightStatusValue** set to **1** for on or **0** for off.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/telemetry.png
[img-list-devices]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/listdevices.png
[img-method-history]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-basic/appoutput.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,267 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and send simulated telemetry using C
This tutorial shows you how to use the Raspberry Pi 3 to simulate temperature and humidity data to send to the cloud. The tutorial uses:
- Raspbian OS, the C programming language, and the Microsoft Azure IoT SDK for C to implement a sample device.
- The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
- Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
- Set up your device to communicate with your computer and the remote monitoring solution.
- Update the sample device code to connect to the remote monitoring solution, and send simulated telemetry that you can view on the solution dashboard.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Clone the repositories
If you haven't already done so, clone the required repositories by running the following commands in a terminal on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-c-raspberrypi-getstartedkit.git
```
### Update the device connection string
Open the sample source file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/simulator/remote_monitoring/remote_monitoring.c
```
Locate the following lines:
```c
static const char* deviceId = "[Device Id]";
static const char* connectionString = "HostName=[IoTHub Name].azure-devices.net;DeviceId=[Device Id];SharedAccessKey=[Device Key]";
```
Replace the placeholder values with the device and IoT Hub information you created and saved at the start of this tutorial. Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Build the sample
Install the prerequisite packages for the Microsoft Azure IoT Device SDK for C by running the following commands in a terminal on the Raspberry Pi:
```sh
sudo apt-get update
sudo apt-get install g++ make cmake git libcurl4-openssl-dev libssl-dev uuid-dev
```
You can now build the updated sample solution on the Raspberry Pi:
```sh
chmod +x ~/iot-remote-monitoring-c-raspberrypi-getstartedkit/simulator/build.sh
~/iot-remote-monitoring-c-raspberrypi-getstartedkit/simulator/build.sh
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo ~/cmake/remote_monitoring/remote_monitoring
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Act on the device
From the solution dashboard, you can invoke methods on your Raspberry Pi. When the Raspberry Pi connects to the remote monitoring solution, it sends information about the methods it supports.
- In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
- On the **Invoke Method** page, choose **LightBlink** in the **Method** dropdown.
- Choose **InvokeMethod**. The simulator prints a message in the console on the Raspberry Pi. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard:
![Show method history][img-method-history]
- You can switch the LED on and off using the **ChangeLightStatus** method with a **LightStatusValue** set to **1** for on or **0** for off.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/telemetry.png
[img-list-devices]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/listdevices.png
[img-method-history]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-c-get-started-simulator/appoutput.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,22 @@
# Connect your Microsoft Azure IoT Raspberry Pi 3 Starter Kit to the remote monitoring solution
The tutorials in this section help you learn how to connect a Raspberry Pi 3 device to the remote monitoring solution. Choose the tutorial appropriate to your preferred programming language and the whether you have the sensor hardware available to use with your Raspberry Pi.
## The tutorials
| Tutorial | Notes | Languages |
| -------- | ----- | --------- |
| Simulated telemetry (Basic)| Simulates sensor data. Uses a standalone Raspberry Pi. | [C][lnk-c-simulator], [Node.js][lnk-node-simulator] |
| Real sensor (Intermediate) | Uses data from a BME280 sensor connected to your Raspberry Pi. | [C][lnk-c-basic], [Node.js][lnk-node-basic] |
| Implement firmware update (Advanced)| Uses data from a BME280 sensor connected to your Raspberry Pi. Enables remote firmware updates on your Raspberry Pi. | [C][lnk-c-advanced], [Node.js][lnk-node-advanced] |
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[lnk-node-simulator]: iot-suite-v1-raspberry-pi-kit-node-get-started-simulator.md
[lnk-node-basic]: iot-suite-v1-raspberry-pi-kit-node-get-started-basic.md
[lnk-node-advanced]: iot-suite-v1-raspberry-pi-kit-node-get-started-advanced.md
[lnk-c-simulator]: iot-suite-v1-raspberry-pi-kit-c-get-started-simulator.md
[lnk-c-basic]: iot-suite-v1-raspberry-pi-kit-c-get-started-basic.md
[lnk-c-advanced]: iot-suite-v1-raspberry-pi-kit-c-get-started-advanced.md

Просмотреть файл

@ -0,0 +1,374 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and enable remote firmware updates using Node.js
This tutorial shows you how to use the Microsoft Azure IoT Starter Kit for Raspberry Pi 3 to:
* Develop a temperature and humidity reader that can communicate with the cloud.
* Enable and perform a remote firmware update to update the client application on the Raspberry Pi.
The tutorial uses:
- Raspbian OS, the Node.js programming language, and the Microsoft Azure IoT SDK for Node.js to implement a sample device.
- The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
- Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
- Set up your device and sensors to communicate with your computer and the remote monitoring solution.
- Update the sample device code to connect to the remote monitoring solution, and send telemetry that you can view on the solution dashboard.
- Use the sample device code to update the client application.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
- BME280 sensor
- Breadboard
- Jumper wires
- Resistors
- LEDs
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
### Set up the hardware
This tutorial uses the BME280 sensor included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] to generate telemetry data. It uses an LED to indicate when the Raspberry Pi processes a method invocation from the solution dashboard.
The components on the bread board are:
- Red LED
- 220-Ohm resistor (red, red, brown)
- BME280 sensor
The following diagram shows how to connect your hardware:
![Hardware setup for Raspberry Pi][img-connection-diagram]
The following table summarizes the connections from the Raspberry Pi to the components on the breadboard:
| Raspberry Pi | Breadboard |Color |
| ----------------------- | ---------------------- | ------------- |
| GND (Pin 14) | LED -ve pin (18A) | Purple |
| GPCLK0 (Pin 7) | Resistor (25A) | Orange |
| SPI_CE0 (Pin 24) | CS (39A) | Blue |
| SPI_SCLK (Pin 23) | SCK (36A) | Yellow |
| SPI_MISO (Pin 21) | SDO (37A) | White |
| SPI_MOSI (Pin 19) | SDI (38A) | Green |
| GND (Pin 6) | GND (35A) | Black |
| 3.3 V (Pin 1) | 3Vo (34A) | Red |
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
### Enable SPI
Before you can run the sample application, you must enable the Serial Peripheral Interface (SPI) bus on the Raspberry Pi. The Raspberry Pi communicates with the BME280 sensor device over the SPI bus. Use the following command to edit the configuration file:
```sh
sudo nano /boot/config.txt
```
Find the line:
`#dtparam=spi=on`
- To uncomment the line, delete the `#` at the start.
- Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
- To enable SPI, reboot the Raspberry Pi. Rebooting disconnects the terminal, you need to sign in again when the Raspberry Pi restarts:
```sh
sudo reboot
```
[img-connection-diagram]: media/iot-suite-v1-raspberry-pi-kit-prepare-pi/rpi2_remote_monitoring.png
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Install Node.js
If you haven't done so already, install Node.js on your Raspberry Pi. The IoT SDK for Node.js requires version 0.11.5 of Node.js or later. The following steps show you how to install Node.js v6.10.2 on your Raspberry Pi:
1. Use the following command to update your Raspberry Pi:
```sh
sudo apt-get update
```
1. Use the following command to download the Node.js binaries to your Raspberry Pi:
```sh
wget https://nodejs.org/dist/v6.10.2/node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to install the binaries:
```sh
sudo tar -C /usr/local --strip-components 1 -xzf node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to verify you have installed Node.js v6.10.2 successfully:
```sh
node --version
```
### Clone the repositories
If you haven't done so already, clone the required repositories by running the following commands on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-node-raspberrypi-getstartedkit.git
```
### Update the device connection string
Open the sample configuration file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/advanced/config/deviceinfo
```
Replace the placeholder values with the device id and IoT Hub information you created and saved at the start of this tutorial.
When you are done, the contents of the deviceinfo file should look like the following example:
```conf
yourdeviceid
HostName=youriothubname.azure-devices.net;DeviceId=yourdeviceid;SharedAccessKey=yourdevicekey
```
Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Run the sample
Run the following commands to install the prerequisite packages for the sample:
```sh
cd ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/advance/1.0
npm install
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo node ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/advanced/1.0/remote_monitoring.js
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Initiate the firmware update
The firmware update process downloads and installs an updated version of the device client application on the Raspberry Pi. For more information about the firmware update process, see the description of the firmware update pattern in [Overview of device management with IoT Hub][lnk-update-pattern].
You initiate the firmware update process by invoking a method on the device. This method is asynchronous, and returns as soon as the update process begins. The device uses reported properties to notify the solution about the progress of the update.
You invoke methods on your Raspberry Pi from the solution dashboard. When the Raspberry Pi first connects to the remote monitoring solution, it sends information about the methods it supports.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-advanced/telemetry.png
[lnk-update-pattern]: ../articles/iot-hub/iot-hub-device-management-overview.md
1. In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
1. On the **Invoke Method** page, choose **InitiateFirmwareUpdate** in the **Method** dropdown.
1. In the **FWPackageURI** field, enter **https://raw.githubusercontent.com/Azure-Samples/iot-remote-monitoring-node-raspberrypi-getstartedkit/master/advanced/2.0/raspberry.js**. This file contains the implementation of version 2.0 of the firmware.
1. Choose **InvokeMethod**. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard. It then starts the firmware update process by downloading the new version of the firmware:
![Show method history][img-method-history]
## Observe the firmware update process
You can observe the firmware update process as it runs on the device and by viewing the reported properties in the solution dashboard:
1. You can view the progress in of the update process on the Raspberry Pi:
![Show update progress][img-update-progress]
> The remote monitoring app restarts silently when the update completes. Use the command `ps -ef` to verify it is running. If you want to terminate the process, use the `kill` command with the process id.
1. You can view the status of the firmware update, as reported by the device, in the solution portal. The following screenshot shows the status and duration of each stage of the update process, and the new firmware version:
![Show job status][img-job-status]
If you navigate back to the dashboard, you can verify the device is still sending telemetry following the firmware update.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-advanced/app-output.png
[img-update-progress]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-advanced/updateprogress.png
[img-job-status]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-advanced/jobstatus.png
[img-list-devices]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-advanced/listdevices.png
[img-method-history]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-advanced/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,342 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and send telemetry from a real sensor using Node.js
This tutorial shows you how to use the Microsoft Azure IoT Starter Kit for Raspberry Pi 3 to develop a temperature and humidity reader that can communicate with the cloud. The tutorial uses:
- Raspbian OS, the Node.js programming language, and the Microsoft Azure IoT SDK for Node.js to implement a sample device.
- The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
- Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
- Set up your device and sensors to communicate with your computer and the remote monitoring solution.
- Update the sample device code to connect to the remote monitoring solution, and send telemetry that you can view on the solution dashboard.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
- BME280 sensor
- Breadboard
- Jumper wires
- Resistors
- LEDs
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
### Set up the hardware
This tutorial uses the BME280 sensor included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] to generate telemetry data. It uses an LED to indicate when the Raspberry Pi processes a method invocation from the solution dashboard.
The components on the bread board are:
- Red LED
- 220-Ohm resistor (red, red, brown)
- BME280 sensor
The following diagram shows how to connect your hardware:
![Hardware setup for Raspberry Pi][img-connection-diagram]
The following table summarizes the connections from the Raspberry Pi to the components on the breadboard:
| Raspberry Pi | Breadboard |Color |
| ----------------------- | ---------------------- | ------------- |
| GND (Pin 14) | LED -ve pin (18A) | Purple |
| GPCLK0 (Pin 7) | Resistor (25A) | Orange |
| SPI_CE0 (Pin 24) | CS (39A) | Blue |
| SPI_SCLK (Pin 23) | SCK (36A) | Yellow |
| SPI_MISO (Pin 21) | SDO (37A) | White |
| SPI_MOSI (Pin 19) | SDI (38A) | Green |
| GND (Pin 6) | GND (35A) | Black |
| 3.3 V (Pin 1) | 3Vo (34A) | Red |
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
### Enable SPI
Before you can run the sample application, you must enable the Serial Peripheral Interface (SPI) bus on the Raspberry Pi. The Raspberry Pi communicates with the BME280 sensor device over the SPI bus. Use the following command to edit the configuration file:
```sh
sudo nano /boot/config.txt
```
Find the line:
`#dtparam=spi=on`
- To uncomment the line, delete the `#` at the start.
- Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
- To enable SPI, reboot the Raspberry Pi. Rebooting disconnects the terminal, you need to sign in again when the Raspberry Pi restarts:
```sh
sudo reboot
```
[img-connection-diagram]: media/iot-suite-v1-raspberry-pi-kit-prepare-pi/rpi2_remote_monitoring.png
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Install Node.js
Install Node.js on your Raspberry Pi. The IoT SDK for Node.js requires version 0.11.5 of Node.js or later. The following steps show you how to install Node.js v6.10.2 on your Raspberry Pi:
1. Use the following command to update your Raspberry Pi:
```sh
sudo apt-get update
```
1. Use the following command to download the Node.js binaries to your Raspberry Pi:
```sh
wget https://nodejs.org/dist/v6.10.2/node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to install the binaries:
```sh
sudo tar -C /usr/local --strip-components 1 -xzf node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to verify you have installed Node.js v6.10.2 successfully:
```sh
node --version
```
### Clone the repositories
If you haven't already done so, clone the required repositories by running the following commands on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-node-raspberrypi-getstartedkit.git`
```
### Update the device connection string
Open the sample source file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/basic/remote_monitoring.js
```
Find the line:
```javascript
var connectionString = 'HostName=[Your IoT hub name].azure-devices.net;DeviceId=[Your device id];SharedAccessKey=[Your device key]';
```
Replace the placeholder values with the device and IoT Hub information you created and saved at the start of this tutorial. Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Run the sample
Run the following commands to install the prerequisite packages for the sample:
```sh
cd ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/basic
npm install
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo node ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/basic/remote_monitoring.js
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Act on the device
From the solution dashboard, you can invoke methods on your Raspberry Pi. When the Raspberry Pi connects to the remote monitoring solution, it sends information about the methods it supports.
- In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
- On the **Invoke Method** page, choose **LightBlink** in the **Method** dropdown.
- Choose **InvokeMethod**. The LED connected to the Raspberry Pi flashes several times. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard:
![Show method history][img-method-history]
- You can switch the LED on and off using the **ChangeLightStatus** method with a **LightStatusValue** set to **1** for on or **0** for off.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/telemetry.png
[img-list-devices]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/listdevices.png
[img-method-history]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-basic/app-output.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,287 @@
# Connect your Raspberry Pi 3 to the remote monitoring solution and send simulated telemetry using Node.js
This tutorial shows you how to use the Raspberry Pi 3 to simulate temperature and humidity data to send to the cloud. The tutorial uses:
- Raspbian OS, the Node.js programming language, and the Microsoft Azure IoT SDK for Node.js to implement a sample device.
- The IoT Suite remote monitoring preconfigured solution as the cloud-based back end.
## Overview
In this tutorial, you complete the following steps:
- Deploy an instance of the remote monitoring preconfigured solution to your Azure subscription. This step automatically deploys and configures multiple Azure services.
- Set up your device to communicate with your computer and the remote monitoring solution.
- Update the sample device code to connect to the remote monitoring solution, and send simulated telemetry that you can view on the solution dashboard.
## Prerequisites
To complete this tutorial, you need an active Azure subscription.
> If you dont have an account, you can create a free trial account in just a couple of minutes. For details, see [Azure Free Trial][lnk-free-trial].
### Required software
You need SSH client on your desktop machine to enable you to remotely access the command line on the Raspberry Pi.
- Windows does not include an SSH client. We recommend using [PuTTY](http://www.putty.org/).
- Most Linux distributions and Mac OS include the command-line SSH utility. For more information, see [SSH Using Linux or Mac OS](https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md).
### Required hardware
A desktop computer to enable you to connect remotely to the command line on the Raspberry Pi.
[Microsoft IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] or equivalent components. This tutorial uses the following items from the kit:
- Raspberry Pi 3
- MicroSD Card (with NOOBS)
- A USB Mini cable
- An Ethernet cable
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
## Provision the solution
If you haven't already provisioned the remote monitoring preconfigured solution in your account:
1. Log on to [azureiotsuite.com][lnk-azureiotsuite] using your Azure account credentials, and click **+** to create a solution.
2. Click **Select** on the **Remote monitoring** tile.
3. Enter a **Solution name** for your remote monitoring preconfigured solution.
4. Select the **Region** and **Subscription** you want to use to provision the solution.
5. Click **Create Solution** to begin the provisioning process. This process typically takes several minutes to run.
### Wait for the provisioning process to complete
1. Click the tile for your solution with **Provisioning** status.
2. Notice the **Provisioning states** as Azure services are deployed in your Azure subscription.
3. Once provisioning completes, the status changes to **Ready**.
4. Click the tile to see the details of your solution in the right-hand pane.
> If you are encountering issues deploying the pre-configured solution, review [Permissions on the azureiotsuite.com site][lnk-permissions] and the [FAQ][lnk-faq]. If the issues persist, create a service ticket on the [portal][lnk-portal].
>
>
Are there details you'd expect to see that aren't listed for your solution? Give us feature suggestions on [User Voice](https://feedback.azure.com/forums/321918-azure-iot).
[lnk-azureiotsuite]: https://www.azureiotsuite.com
[lnk-permissions]: ../articles/iot-suite/iot-suite-v1-permissions.md
[lnk-portal]: http://portal.azure.com/
[lnk-faq]: ../articles/iot-suite/iot-suite-v1-faq.md
> The remote monitoring solution provisions a set of Azure services in your Azure subscription. The deployment reflects a real enterprise architecture. To avoid unnecessary Azure consumption charges, delete your instance of the preconfigured solution at azureiotsuite.com when you have finished with it. If you need the preconfigured solution again, you can easily recreate it. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config].
## View the solution dashboard
The solution dashboard enables you to manage the deployed solution. For example, you can view telemetry, add devices, and invoke methods.
1. When the provisioning is complete and the tile for your preconfigured solution indicates **Ready**, choose **Launch** to open your remote monitoring solution portal in a new tab.
![Launch the preconfigured solution][img-launch-solution]
1. By default, the solution portal shows the *dashboard*. You can navigate to other areas of the solution portal using the menu on the left-hand side of the page.
![Remote monitoring preconfigured solution dashboard][img-menu]
## Add a device
For a device to connect to the preconfigured solution, it must identify itself to IoT Hub using valid credentials. You can retrieve the device credentials from the solution dashboard. You include the device credentials in your client application later in this tutorial.
If you haven't already done so, add a custom device to your remote monitoring solution. Complete the following steps in the solution dashboard:
1. In the lower left-hand corner of the dashboard, click **Add a device**.
![Add a device][1]
1. In the **Custom Device** panel, click **Add new**.
![Add a custom device][2]
1. Choose **Let me define my own Device ID**. Enter a Device ID such as **rasppi**, click **Check ID** to verify you haven't already used the name in your solution, and then click **Create** to provision the device.
![Add device ID][3]
1. Make a note the device credentials (**Device ID**, **IoT Hub Hostname**, and **Device Key**). Your client application on the Raspberry Pi needs these values to connect to the remote monitoring solution. Then click **Done**.
![View device credentials][4]
1. Select your device in the device list in the solution dashboard. Then, in the **Device Details** panel, click **Enable Device**. The status of your device is now **Running**. The remote monitoring solution can now receive telemetry from your device and invoke methods on the device.
[img-launch-solution]: media/iot-suite-v1-raspberry-pi-kit-view-solution/launch.png
[img-menu]: media/iot-suite-v1-raspberry-pi-kit-view-solution/menu.png
[1]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite0.png
[2]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite1.png
[3]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite2.png
[4]: media/iot-suite-v1-raspberry-pi-kit-view-solution/suite3.png
## Prepare your Raspberry Pi
### Install Raspbian
If this is the first time you are using your Raspberry Pi, you need to install the Raspbian operating system using NOOBS on the SD card included in the kit. The [Raspberry Pi Software Guide][lnk-install-raspbian] describes how to install an operating system on your Raspberry Pi. This tutorial assumes you have installed the Raspbian operating system on your Raspberry Pi.
> The SD card included in the [Microsoft Azure IoT Starter Kit for Raspberry Pi 3][lnk-starter-kits] already has NOOBS installed. You can boot the Raspberry Pi from this card and choose to install the Raspbian OS.
To complete the hardware setup, you need to:
- Connect your Raspberry Pi to the power supply included in the kit.
- Connect your Raspberry Pi to your network using the Ethernet cable included in your kit. Alternatively, you can set up [Wireless Connectivity][lnk-pi-wireless] for your Raspberry Pi.
You have now completed the hardware setup of your Raspberry Pi.
### Sign in and access the terminal
You have two options to access a terminal environment on your Raspberry Pi:
- If you have a keyboard and monitor connected to your Raspberry Pi, you can use the Raspbian GUI to access a terminal window.
- Access the command line on your Raspberry Pi using SSH from your desktop machine.
#### Use a terminal Window in the GUI
The default credentials for Raspbian are username **pi** and password **raspberry**. In the task bar in the GUI, you can launch the **Terminal** utility using the icon that looks like a monitor.
#### Sign in with SSH
You can use SSH for command-line access to your Raspberry Pi. The article [SSH (Secure Shell)][lnk-pi-ssh] describes how to configure SSH on your Raspberry Pi, and how to connect from [Windows][lnk-ssh-windows] or [Linux & Mac OS][lnk-ssh-linux].
Sign in with username **pi** and password **raspberry**.
#### Optional: Share a folder on your Raspberry Pi
Optionally, you may want to share a folder on your Raspberry Pi with your desktop environment. Sharing a folder enables you to use your preferred desktop text editor (such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](http://www.sublimetext.com/)) to edit files on your Raspberry Pi instead of using `nano` or `vi`.
To share a folder with Windows, configure a Samba server on the Raspberry Pi. Alternatively, use the built-in [SFTP](https://www.raspberrypi.org/documentation/remote-access/) server with an SFTP client on your desktop.
[lnk-install-raspbian]: https://www.raspberrypi.org/learning/software-guide/quickstart/
[lnk-pi-wireless]: https://www.raspberrypi.org/documentation/configuration/wireless/README.md
[lnk-pi-ssh]: https://www.raspberrypi.org/documentation/remote-access/ssh/README.md
[lnk-ssh-windows]: https://www.raspberrypi.org/documentation/remote-access/ssh/windows.md
[lnk-ssh-linux]: https://www.raspberrypi.org/documentation/remote-access/ssh/unix.md
[lnk-starter-kits]: https://azure.microsoft.com/develop/iot/starter-kits/
## Download and configure the sample
You can now download and configure the remote monitoring client application on your Raspberry Pi.
### Install Node.js
If you haven't done so already, install Node.js on your Raspberry Pi. The IoT SDK for Node.js requires version 0.11.5 of Node.js or later. The following steps show you how to install Node.js v6.10.2 on your Raspberry Pi:
1. Use the following command to update your Raspberry Pi:
```sh
sudo apt-get update
```
1. Use the following command to download the Node.js binaries to your Raspberry Pi:
```sh
wget https://nodejs.org/dist/v6.10.2/node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to install the binaries:
```sh
sudo tar -C /usr/local --strip-components 1 -xzf node-v6.10.2-linux-armv7l.tar.gz
```
1. Use the following command to verify you have installed Node.js v6.10.2 successfully:
```sh
node --version
```
### Clone the repositories
If you haven't already done so, clone the required repositories by running the following commands in a terminal on your Pi:
```sh
cd ~
git clone --recursive https://github.com/Azure-Samples/iot-remote-monitoring-node-raspberrypi-getstartedkit.git
```
### Update the device connection string
Open the sample source file in the **nano** editor using the following command:
```sh
nano ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/simulator/remote_monitoring.js
```
Find the line:
```javascript
var connectionString = 'HostName=[Your IoT hub name].azure-devices.net;DeviceId=[Your device id];SharedAccessKey=[Your device key]';
```
Replace the placeholder values with the device and IoT Hub information you created and saved at the start of this tutorial. Save your changes (**Ctrl-O**, **Enter**) and exit the editor (**Ctrl-X**).
## Run the sample
Run the following commands to install the prerequisite packages for the sample:
```sh
cd ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/simulator
npm install
```
You can now run the sample program on the Raspberry Pi. Enter the command:
```sh
sudo node ~/iot-remote-monitoring-node-raspberrypi-getstartedkit/simulator/remote_monitoring.js
```
The following sample output is an example of the output you see at the command prompt on the Raspberry Pi:
![Output from Raspberry Pi app][img-raspberry-output]
Press **Ctrl-C** to exit the program at any time.
## View the telemetry
The Raspberry Pi is now sending telemetry to the remote monitoring solution. You can view the telemetry on the solution dashboard. You can also send messages to your Raspberry Pi from the solution dashboard.
- Navigate to the solution dashboard.
- Select your device in the **Device to View** dropdown.
- The telemetry from the Raspberry Pi displays on the dashboard.
![Display telemetry from the Raspberry Pi][img-telemetry-display]
## Act on the device
From the solution dashboard, you can invoke methods on your Raspberry Pi. When the Raspberry Pi connects to the remote monitoring solution, it sends information about the methods it supports.
- In the solution dashboard, click **Devices** to visit the **Devices** page. Select your Raspberry Pi in the **Device List**. Then choose **Methods**:
![List devices in dashboard][img-list-devices]
- On the **Invoke Method** page, choose **LightBlink** in the **Method** dropdown.
- Choose **InvokeMethod**. The simulator prints a message in the console on the Raspberry Pi. The app on the Raspberry Pi sends an acknowledgment back to the solution dashboard:
![Show method history][img-method-history]
- You can switch the LED on and off using the **ChangeLightStatus** method with a **LightStatusValue** set to **1** for on or **0** for off.
> If you leave the remote monitoring solution running in your Azure account, you are billed for the time it runs. For more information about reducing consumption while the remote monitoring solution runs, see [Configuring Azure IoT Suite preconfigured solutions for demo purposes][lnk-demo-config]. Delete the preconfigured solution from your Azure account when you have finished using it.
[img-telemetry-display]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/telemetry.png
[img-list-devices]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/listdevices.png
[img-method-history]: media/iot-suite-v1-raspberry-pi-kit-view-telemetry-simulator/methodhistory.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md
## Next steps
Visit the [Azure IoT Dev Center](https://azure.microsoft.com/develop/iot/) for more samples and documentation on Azure IoT.
[img-raspberry-output]: ./media/iot-suite-v1-raspberry-pi-kit-node-get-started-simulator/app-output.png
[lnk-demo-config]: https://github.com/Azure/azure-iot-remote-monitoring/blob/master/Docs/configure-preconfigured-demo.md

Просмотреть файл

@ -0,0 +1,111 @@
# Device information metadata in the remote monitoring preconfigured solution
The Azure IoT Suite remote monitoring preconfigured solution demonstrates an approach for managing device metadata. This article outlines the approach this solution takes to enable you to understand:
* What device metadata the solution stores.
* How the solution manages the device metadata.
## Context
The remote monitoring preconfigured solution uses [Azure IoT Hub][lnk-iot-hub] to enable your devices to send data to the cloud. The solution stores information about devices in three different locations:
| Location | Information stored | Implementation |
| -------- | ------------------ | -------------- |
| Identity registry | Device id, authentication keys, enabled state | Built in to IoT Hub |
| Device twins | Metadata: reported properties, desired properties, tags | Built in to IoT Hub |
| Cosmos DB | Command and method history | Custom for solution |
IoT Hub includes a [device identity registry][lnk-identity-registry] to manage access to an IoT hub and uses [device twins][lnk-device-twin] to manage device metadata. There is also a remote monitoring solution-specific *device registry* that stores command and method history. The remote monitoring solution uses a [Cosmos DB][lnk-docdb] database to implement a custom store for command and method history.
> The remote monitoring preconfigured solution keeps the device identity registry in sync with the information in the Cosmos DB database. Both use the same device id to uniquely identify each device connected to your IoT hub.
## Device metadata
IoT Hub maintains a [device twin][lnk-device-twin] for each simulated and physical device connected to a remote monitoring solution. The solution uses device twins to manage the metadata associated with devices. A device twin is a JSON document maintained by IoT Hub, and the solution uses the IoT Hub API to interact with device twins.
A device twin stores three types of metadata:
- *Reported properties* are sent to an IoT hub by a device. In the remote monitoring solution, simulated devices send reported properties at start-up and in response to **Change device state** commands and methods. You can view reported properties in the **Device list** and **Device details** in the solution portal. Reported properties are read only.
- *Desired properties* are retrieved from the IoT hub by devices. It is the responsibility of the device to make any necessary configuration change on the device. It is also the responsibility of the device to report the change back to the hub as a reported property. You can set a desired property value through the solution portal.
- *Tags* only exist in the device twin and are never synchronized with a device. You can set tag values in the solution portal and use them when you filter the list of devices. The solution also uses a tag to identify the icon to display for a device in the solution portal.
Example reported properties from the simulated devices include manufacturer, model number, latitude, and longitude. Simulated devices also return the list of supported methods as a reported property.
> The simulated device code only uses the **Desired.Config.TemperatureMeanValue** and **Desired.Config.TelemetryInterval** desired properties to update the reported properties sent back to IoT Hub. All other desired property change requests are ignored.
A device information metadata JSON document stored in the device registry Cosmos DB database has the following structure:
```json
{
"DeviceProperties": {
"DeviceID": "deviceid1",
"HubEnabledState": null,
"CreatedTime": "2016-04-25T23:54:01.313802Z",
"DeviceState": "normal",
"UpdatedTime": null
},
"SystemProperties": {
"ICCID": null
},
"Commands": [],
"CommandHistory": [],
"IsSimulatedDevice": false,
"id": "fe81a81c-bcbc-4970-81f4-7f12f2d8bda8"
}
```
> Device information can also include metadata to describe the telemetry the device sends to IoT Hub. The remote monitoring solution uses this telemetry metadata to customize how the dashboard displays [dynamic telemetry][lnk-dynamic-telemetry].
## Lifecycle
When you first create a device in the solution portal, the solution creates an entry in the Cosmos DB database to store command and method history. At this point, the solution also creates an entry for the device in the device identity registry, which generates the keys the device uses to authenticate with IoT Hub. It also creates a device twin.
When a device first connects to the solution, it sends reported properties and a device information message. The reported property values are automatically saved in the device twin. The reported properties include the device manufacturer, model number, serial number, and a list of supported methods. The device information message includes the list of the commands the device supports including information about any command parameters. When the solution receives this message, it updates the device information in the Cosmos DB database.
### View and edit device information in the solution portal
The device list in the solution portal displays the following device properties as columns by default: **Status**, **DeviceId**, **Manufacturer**, **Model Number**, **Serial Number**, **Firmware**, **Platform**, **Processor**, and **Installed RAM**. You can customize the columns by clicking **Column editor**. The device properties **Latitude** and **Longitude** drive the location in the Bing Map on the dashboard.
![Column editor in device list][img-device-list]
In the **Device Details** pane in the solution portal, you can edit desired properties and tags (reported properties are read only).
![Device details pane][img-device-edit]
You can use the solution portal to remove a device from your solution. When you remove a device, the solution removes the device entry from identity registry and then deletes the device twin. The solution also removes information related to the device from the Cosmos DB database. Before you can remove a device, you must disable it.
![Remove device][img-device-remove]
## Device information message processing
Device information messages sent by a device are distinct from telemetry messages. Device information messages include the commands a device can respond to, and any command history. IoT Hub itself has no knowledge of the metadata contained in a device information message and processes the message in the same way it processes any device-to-cloud message. In the remote monitoring solution, an [Azure Stream Analytics][lnk-stream-analytics] (ASA) job reads the messages from IoT Hub. The **DeviceInfo** stream analytics job filters for messages that contain **"ObjectType": "DeviceInfo"** and forwards them to the **EventProcessorHost** host instance that runs in a web job. Logic in the **EventProcessorHost** instance uses the device ID to find the Cosmos DB record for the specific device and update the record.
> A device information message is a standard device-to-cloud message. The solution distinguishes between device information messages and telemetry messages by using ASA queries.
## Next steps
Now you've finished learning how you can customize the preconfigured solutions, you can explore some of the other features and capabilities of the IoT Suite preconfigured solutions:
* [Predictive maintenance preconfigured solution overview][lnk-predictive-overview]
* [Frequently asked questions for IoT Suite][lnk-faq]
* [IoT security from the ground up][lnk-security-groundup]
<!-- Images and links -->
[img-device-list]: media/iot-suite-v1-remote-monitoring-device-info/image1.png
[img-device-edit]: media/iot-suite-v1-remote-monitoring-device-info/image2.png
[img-device-remove]: media/iot-suite-v1-remote-monitoring-device-info/image3.png
[lnk-iot-hub]: https://azure.microsoft.com/documentation/services/iot-hub/
[lnk-identity-registry]: ../iot-hub/iot-hub-devguide-identity-registry.md
[lnk-device-twin]: ../iot-hub/iot-hub-devguide-device-twins.md
[lnk-docdb]: https://azure.microsoft.com/documentation/services/documentdb/
[lnk-stream-analytics]: https://azure.microsoft.com/documentation/services/stream-analytics/
[lnk-dynamic-telemetry]: iot-suite-v1-dynamic-telemetry.md
[lnk-predictive-overview]: iot-suite-predictive-overview.md
[lnk-faq]: iot-suite-v1-faq.md
[lnk-security-groundup]: securing-iot-ground-up.md

Просмотреть файл

@ -0,0 +1,276 @@
# Remote monitoring preconfigured solution walkthrough
The IoT Suite remote monitoring [preconfigured solution][lnk-preconfigured-solutions] is an implementation of an end-to-end monitoring solution for multiple machines running in remote locations. The solution combines key Azure services to provide a generic implementation of the business scenario. You can use the solution as a starting point for your own implementation and [customize][lnk-customize] it to meet your own specific business requirements.
This article walks you through some of the key elements of the remote monitoring solution to enable you to understand how it works. This knowledge helps you to:
* Troubleshoot issues in the solution.
* Plan how to customize to the solution to meet your own specific requirements.
* Design your own IoT solution that uses Azure services.
## Logical architecture
The following diagram outlines the logical components of the preconfigured solution:
![Logical architecture](media/iot-suite-remote-monitoring-sample-walkthrough/remote-monitoring-architecture-updated.png)
## Microservices & Docker Containers
Remote Monitoring is the first of our preconfigured solutions to leverage a
microservices architecture. The solution is available in both [.NET](https://github.com/Azure/azure-iot-pcs-remote-monitoring-dotnet) and [Java](https://github.com/Azure/azure-iot-pcs-remote-monitoring-java).
Microservices have emerged as a prevalent pattern to achieve scale and flexibility
(by allowing containers to be scaled individually), without compromising development speed.
Microservices compartmentalize the code and provide well defined interfaces
making the solution easier to understand and less monolithic. It also further
expands options for partners that want to extend our current
solution accelerators to build finished solutions that can be monetized.
**Learn more about Docker Containers**
* [Install Docker](https://docs.docker.com/engine/installation/)
* [Common Docker Commands for Remote Monitoring](https://github.com/Azure/azure-iot-pcs-remote-monitoring-dotnet/wiki/Developer-Reference-Guide#common-docker-commands)
* [Docker Getting Started](https://docs.docker.com/get-started/)
## Simulated devices
In the preconfigured solution, the simulated device represents a cooling device (such as a building air conditioner or facility air handling unit). When you deploy the preconfigured solution, you also automatically provision four simulated devices that run in an [Azure WebJob][lnk-webjobs]. The simulated devices make it easy for you to explore the behavior of the solution without the need to deploy any physical devices. To deploy a real physical device, see the [Connect your device to the remote monitoring preconfigured solution][lnk-connect-rm] tutorial.
### Device-to-cloud messages
Each simulated device can send the following message types to IoT Hub:
| Message | Description |
| --- | --- |
| Startup |When the device starts, it sends a **device-info** message containing information about itself to the back end. This data includes the device id and a list of the commands and methods the device supports. |
| Presence |A device periodically sends a **presence** message to report whether the device can sense the presence of a sensor. |
| Telemetry |A device periodically sends a **telemetry** message that reports simulated values for the temperature and humidity collected from the device's simulated sensors. |
> The solution stores the list of commands supported by the device in a Cosmos DB database and not in the device twin.
### Properties and device twins
The simulated devices send the following device properties to the [twin][lnk-device-twins] in the IoT hub as *reported properties*. The device sends reported properties at startup and in response to a **Change Device State** command or method.
| Property | Purpose |
| --- | --- |
| Config.TelemetryInterval | Frequency (seconds) the device sends telemetry |
| Config.TemperatureMeanValue | Specifies the mean value for the simulated temperature telemetry |
| Device.DeviceID |Id that is either provided or assigned when a device is created in the solution |
| Device.DeviceState | State reported by the device |
| Device.CreatedTime |Time the device was created in the solution |
| Device.StartupTime |Time the device was started |
| Device.LastDesiredPropertyChange |The version number of the last desired property change |
| Device.Location.Latitude |Latitude location of the device |
| Device.Location.Longitude |Longitude location of the device |
| System.Manufacturer |Device manufacturer |
| System.ModelNumber |Model number of the device |
| System.SerialNumber |Serial number of the device |
| System.FirmwareVersion |Current version of firmware on the device |
| System.Platform |Platform architecture of the device |
| System.Processor |Processor running the device |
| System.InstalledRAM |Amount of RAM installed on the device |
The simulator seeds these properties in simulated devices with sample values. Each time the simulator initializes a simulated device, the device reports the pre-defined metadata to IoT Hub as reported properties. Reported properties can only be updated by the device. To change a reported property, you set a desired property in solution portal. It is the responsibility of the device to:
1. Periodically retrieve desired properties from the IoT hub.
2. Update its configuration with the desired property value.
3. Send the new value back to the hub as a reported property.
From the solution dashboard, you can use *desired properties* to set properties on a device by using the [device twin][lnk-device-twins]. Typically, a device reads a desired property value from the hub to update its internal state and report the change back as a reported property.
> The simulated device code only uses the **Desired.Config.TemperatureMeanValue** and **Desired.Config.TelemetryInterval** desired properties to update the reported properties sent back to IoT Hub. All other desired property change requests are ignored in the simulated device.
### Methods
The simulated devices can handle the following methods ([direct methods][lnk-direct-methods]) invoked from the solution portal through the IoT hub:
| Method | Description |
| --- | --- |
| InitiateFirmwareUpdate |Instructs the device to perform a firmware update |
| Reboot |Instructs the device to reboot |
| FactoryReset |Instructs the device to perform a factory reset |
Some methods use reported properties to report on progress. For example, the **InitiateFirmwareUpdate** method simulates running the update asynchronously on the device. The method returns immediately on the device, while the asynchronous task continues to send status updates back to the solution dashboard using reported properties.
### Commands
The simulated devices can handle the following commands (cloud-to-device messages) sent from the solution portal through the IoT hub:
| Command | Description |
| --- | --- |
| PingDevice |Sends a *ping* to the device to check it is alive |
| StartTelemetry |Starts the device sending telemetry |
| StopTelemetry |Stops the device from sending telemetry |
| ChangeSetPointTemp |Changes the set point value around which the random data is generated |
| DiagnosticTelemetry |Triggers the device simulator to send an additional telemetry value (externalTemp) |
| ChangeDeviceState |Changes an extended state property for the device and sends the device info message from the device |
> For a comparison of these commands (cloud-to-device messages) and methods (direct methods), see [Cloud-to-device communications guidance][lnk-c2d-guidance].
## IoT Hub
The [IoT hub][lnk-iothub] ingests data sent from the devices into the cloud and makes it available to the Azure Stream Analytics (ASA) jobs. Each stream ASA job uses a separate IoT Hub consumer group to read the stream of messages from your devices.
The IoT hub in the solution also:
- Maintains an identity registry that stores the ids and authentication keys of all the devices permitted to connect to the portal. You can enable and disable devices through the identity registry.
- Sends commands to your devices on behalf of the solution portal.
- Invokes methods on your devices on behalf of the solution portal.
- Maintains device twins for all registered devices. A device twin stores the property values reported by a device. A device twin also stores desired properties, set in the solution portal, for the device to retrieve when it next connects.
- Schedules jobs to set properties for multiple devices or invoke methods on multiple devices.
## Azure Stream Analytics
In the remote monitoring solution, [Azure Stream Analytics][lnk-asa] (ASA) dispatches device messages received by the IoT hub to other back-end components for processing or storage. Different ASA jobs perform specific functions based on the content of the messages.
**Job 1: Device Info** filters device information messages from the incoming message stream and sends them to an Event Hub endpoint. A device sends device information messages at startup and in response to a **SendDeviceInfo** command. This job uses the following query definition to identify **device-info** messages:
```
SELECT * FROM DeviceDataStream Partition By PartitionId WHERE ObjectType = 'DeviceInfo'
```
This job sends its output to an Event Hub for further processing.
**Job 2: Rules** evaluates incoming temperature and humidity telemetry values against per-device thresholds. Threshold values are set in the rules editor available in the solution portal. Each device/value pair is stored by timestamp in a blob which Stream Analytics reads in as **Reference Data**. The job compares any non-empty value against the set threshold for the device. If it exceeds the '>' condition, the job outputs an **alarm** event that indicates that the threshold is exceeded and provides the device, value, and timestamp values. This job uses the following query definition to identify telemetry messages that should trigger an alarm:
```
WITH AlarmsData AS
(
SELECT
Stream.IoTHub.ConnectionDeviceId AS DeviceId,
'Temperature' as ReadingType,
Stream.Temperature as Reading,
Ref.Temperature as Threshold,
Ref.TemperatureRuleOutput as RuleOutput,
Stream.EventEnqueuedUtcTime AS [Time]
FROM IoTTelemetryStream Stream
JOIN DeviceRulesBlob Ref ON Stream.IoTHub.ConnectionDeviceId = Ref.DeviceID
WHERE
Ref.Temperature IS NOT null AND Stream.Temperature > Ref.Temperature
UNION ALL
SELECT
Stream.IoTHub.ConnectionDeviceId AS DeviceId,
'Humidity' as ReadingType,
Stream.Humidity as Reading,
Ref.Humidity as Threshold,
Ref.HumidityRuleOutput as RuleOutput,
Stream.EventEnqueuedUtcTime AS [Time]
FROM IoTTelemetryStream Stream
JOIN DeviceRulesBlob Ref ON Stream.IoTHub.ConnectionDeviceId = Ref.DeviceID
WHERE
Ref.Humidity IS NOT null AND Stream.Humidity > Ref.Humidity
)
SELECT *
INTO DeviceRulesMonitoring
FROM AlarmsData
SELECT *
INTO DeviceRulesHub
FROM AlarmsData
```
The job sends its output to an Event Hub for further processing and saves details of each alert to blob storage from where the solution portal can read the alert information.
**Job 3: Telemetry** operates on the incoming device telemetry stream in two ways. The first sends all telemetry messages from the devices to persistent blob storage for long-term storage. The second computes average, minimum, and maximum humidity values over a five-minute sliding window and sends this data to blob storage. The solution portal reads the telemetry data from blob storage to populate the charts. This job uses the following query definition:
```
WITH
[StreamData]
AS (
SELECT
*
FROM [IoTHubStream]
WHERE
[ObjectType] IS NULL -- Filter out device info and command responses
)
SELECT
IoTHub.ConnectionDeviceId AS DeviceId,
Temperature,
Humidity,
ExternalTemperature,
EventProcessedUtcTime,
PartitionId,
EventEnqueuedUtcTime,
*
INTO
[Telemetry]
FROM
[StreamData]
SELECT
IoTHub.ConnectionDeviceId AS DeviceId,
AVG (Humidity) AS [AverageHumidity],
MIN(Humidity) AS [MinimumHumidity],
MAX(Humidity) AS [MaxHumidity],
5.0 AS TimeframeMinutes
INTO
[TelemetrySummary]
FROM [StreamData]
WHERE
[Humidity] IS NOT NULL
GROUP BY
IoTHub.ConnectionDeviceId,
SlidingWindow (mi, 5)
```
## Event Hubs
The **device info** and **rules** ASA jobs output their data to Event Hubs to reliably forward on to the **Event Processor** running in the WebJob.
## Azure storage
The solution uses Azure blob storage to persist all the raw and summarized telemetry data from the devices in the solution. The portal reads the telemetry data from blob storage to populate the charts. To display alerts, the solution portal reads the data from blob storage that records when telemetry values exceeded the configured threshold values. The solution also uses blob storage to record the threshold values you set in the solution portal.
## WebJobs
In addition to hosting the device simulators, the WebJobs in the solution also host the **Event Processor** running in an Azure WebJob that handles command responses. It uses command response messages to update the device command history (stored in the Cosmos DB database).
## Cosmos DB
The solution uses a Cosmos DB database to store information about the devices connected to the solution. This information includes the history of commands sent to devices from the solution portal and of methods invoked from the solution portal.
## Solution portal
The solution portal is a web app deployed as part of the preconfigured solution. The key pages in the solution portal are the dashboard and the device list.
### Dashboard
This page in the web app uses PowerBI javascript controls (See [PowerBI-visuals repo](https://www.github.com/Microsoft/PowerBI-visuals)) to visualize the telemetry data from the devices. The solution uses the ASA telemetry job to write the telemetry data to blob storage.
### Device list
From this page in the solution portal you can:
* Provision a new device. This action sets the unique device id and generates the authentication key. It writes information about the device to both the IoT Hub identity registry and the solution-specific Cosmos DB database.
* Manage device properties. This action includes viewing existing properties and updating with new properties.
* Send commands to a device.
* View the command history for a device.
* Enable and disable devices.
## Next steps
The following TechNet blog posts provide more detail about the remote monitoring preconfigured solution:
* [IoT Suite - Under The Hood - Remote Monitoring](http://social.technet.microsoft.com/wiki/contents/articles/32941.iot-suite-v1-under-the-hood-remote-monitoring.aspx)
* [IoT Suite - Remote Monitoring - Adding Live and Simulated Devices](http://social.technet.microsoft.com/wiki/contents/articles/32975.iot-suite-v1-remote-monitoring-adding-live-and-simulated-devices.aspx)
You can continue getting started with IoT Suite by reading the following articles:
* [Connect your device to the remote monitoring preconfigured solution][lnk-connect-rm]
* [Permissions on the azureiotsuite.com site][lnk-permissions]
[lnk-preconfigured-solutions]: iot-suite-v1-what-are-preconfigured-solutions.md
[lnk-customize]: iot-suite-v1-guidance-on-customizing-preconfigured-solutions.md
[lnk-iothub]: https://azure.microsoft.com/documentation/services/iot-hub/
[lnk-asa]: https://azure.microsoft.com/documentation/services/stream-analytics/
[lnk-webjobs]: https://azure.microsoft.com/documentation/articles/websites-webjobs-resources/
[lnk-connect-rm]: iot-suite-v1-connecting-devices.md
[lnk-permissions]: iot-suite-v1-permissions.md
[lnk-c2d-guidance]: ../iot-hub/iot-hub-devguide-c2d-guidance.md
[lnk-device-twins]: ../iot-hub/iot-hub-devguide-device-twins.md
[lnk-direct-methods]: ../iot-hub/iot-hub-devguide-direct-methods.md

Просмотреть файл

@ -0,0 +1,154 @@
# What are the Azure IoT Suite preconfigured solutions?
The Azure IoT Suite preconfigured solutions are implementations of common IoT solution patterns that you can deploy to Azure using your subscription. You can use the preconfigured solutions:
* As a starting point for your own IoT solutions.
* To learn about common patterns in IoT solution design and development.
Each preconfigured solution is a complete, end-to-end implementation that uses simulated devices to generate telemetry.
You can download the complete source code to customize and extend the solution to meet your specific IoT requirements.
> To deploy one of the preconfigured solutions, visit [Microsoft Azure IoT Suite][lnk-azureiotsuite]. The article [Get started with the IoT preconfigured solutions][lnk-getstarted-preconfigured] provides more information about how to deploy and run one of the solutions.
The following table shows how the solutions map to specific IoT features:
| Solution | Data ingestion | Device identity | Device management | Command and control | Rules and actions | Predictive analytics |
| --- | --- | --- | --- | --- | --- | --- |
| [Remote monitoring][lnk-getstarted-preconfigured] |Yes |Yes |Yes |Yes |Yes |- |
| [Predictive maintenance][lnk-predictive-maintenance] |Yes |Yes |- |Yes |Yes |Yes |
| [Connected factory][lnk-getstarted-factory] |Yes |Yes |Yes |Yes |Yes |- |
* *Data ingestion*: Ingress of data at scale to the cloud.
* *Device identity*: Manage unique device identities and control device access to the solution.
* *Device management*: Manage device metadata and perform operations such as device reboots and firmware upgrades.
* *Command and control*: To cause the device to take an action, send messages to a device from the cloud.
* *Rules and actions*: To act on specific device-to-cloud data, the solution back end uses rules.
* *Predictive analytics*: The solution back end analyzes device-to-cloud data to predict when specific actions should take place. For example, analyzing aircraft engine telemetry to determine when engine maintenance is due.
## Remote Monitoring preconfigured solution overview
We have chosen to discuss the remote monitoring preconfigured solution in this article because it illustrates many common design elements that the other solutions share.
The following diagram illustrates the key elements of the remote monitoring solution. The following sections provide more information about these elements.
![Remote Monitoring preconfigured solution architecture][img-remote-monitoring-arch]
## Devices
When you deploy the remote monitoring preconfigured solution, four simulated devices are pre-provisioned in the solution that simulate a cooling device. These simulated devices have a built-in temperature and humidity model that emits telemetry. These simulated devices are included to:
- Illustrate the end-to-end flow of data through the solution.
- Provide a convenient source of telemetry.
- Provide a target for methods or commands if you are a back-end developer using the solution as a starting point for a custom implementation.
The simulated devices in the solution can respond to the following cloud-to-device communications:
- *Methods ([direct methods][lnk-direct-methods])*: A two-way communication method where a connected device is expected to respond immediately.
- *Commands (cloud-to-device messages)*: A one-way communication method where a device retrieves the command from a durable queue.
For a comparison of these different approaches, see [Cloud-to-device communications guidance][lnk-c2d-guidance].
When a device first connects to IoT Hub in the preconfigured solution, it sends a device information message to the hub. This message enumerates the methods the device can respond to. In the remote monitoring preconfigured solution, simulated devices support these methods:
* *Initiate Firmware Update*: this method initiates an asynchronous task on the device to perform a firmware update. The asynchronous task uses reported properties to deliver status updates to the solution dashboard.
* *Reboot*: this method causes the simulated device to reboot.
* *FactoryReset*: this method triggers a factory reset on the simulated device.
When a device first connects to IoT Hub in the preconfigured solution, it sends a device information message to the hub. This message enumerates the commands the device can respond to. In the remote monitoring preconfigured solution, simulated devices support these commands:
* *Ping Device*: The device responds to this command with an acknowledgement. This command is useful for checking that the device is still active and listening.
* *Start Telemetry*: Instructs the device to start sending telemetry.
* *Stop Telemetry*: Instructs the device to stop sending telemetry.
* *Change Set Point Temperature*: Controls the simulated temperature telemetry values the device sends. This command is useful for testing back-end logic.
* *Diagnostic Telemetry*: Controls if the device should send the external temperature as telemetry.
* *Change Device State*: Sets the device state metadata property that the device reports. This command is useful for testing back-end logic.
You can add more simulated devices to the solution that emit the same telemetry and respond to the same methods and commands.
In addition to responding to commands and methods, the solution uses [device twins][lnk-device-twin]. Devices use device twins to report property values to the solution back end. The solution dashboard uses device twins to set to new desired property values on devices. For example, during the firmware update process the simulated device reports the status of the update using reported properties.
## IoT Hub
In this preconfigured solution, the IoT Hub instance corresponds to the *Cloud Gateway* in a typical [IoT solution architecture][lnk-what-is-azure-iot].
An IoT hub receives telemetry from the devices at a single endpoint. An IoT hub also maintains device-specific endpoints where each device can retrieve the commands that are sent to it.
The IoT hub makes the received telemetry available through the service-side telemetry read endpoint.
The device management capability of IoT Hub enables you to manage your device properties from the solution portal and schedule jobs that perform operations such as:
- Rebooting devices
- Changing device states
- Firmware updates
## Azure Stream Analytics
The preconfigured solution uses three [Azure Stream Analytics][lnk-asa] (ASA) jobs to filter the telemetry stream from the devices:
* *DeviceInfo job* - outputs data to an Event hub that routes device registration-specific messages to the solution device registry. This device registry is an Azure Cosmos DB database. These messages are sent when a device first connects or in response to a **Change device state** command.
* *Telemetry job* - sends all raw telemetry to Azure blob storage for cold storage and calculates telemetry aggregations that display in the solution dashboard.
* *Rules job* - filters the telemetry stream for values that exceed any rule thresholds and outputs the data to an Event hub. When a rule fires, the solution portal dashboard view displays this event as a new row in the alarm history table. These rules can also trigger an action based on the settings defined on the **Rules** and **Actions** views in the solution portal.
In this preconfigured solution, the ASA jobs form part of to the **IoT solution back end** in a typical [IoT solution architecture][lnk-what-is-azure-iot].
## Event processor
In this preconfigured solution, the event processor forms part of the **IoT solution back end** in a typical [IoT solution architecture][lnk-what-is-azure-iot].
The **DeviceInfo** and **Rules** ASA jobs send their output to Event hubs for delivery to other back-end services. The solution uses an [EventProcessorHost][lnk-event-processor] instance, running in a [WebJob][lnk-web-job], to read the messages from these Event hubs. The **EventProcessorHost** uses:
- The **DeviceInfo** data to update the device data in the Cosmos DB database.
- The **Rules** data to invoke the Logic app and update the alerts display in the solution portal.
## Device identity registry, device twin, and Cosmos DB
Every IoT hub includes a [device identity registry][lnk-identity-registry] that stores device keys. IoT Hub uses this information authenticate devices - a device must be registered and have a valid key before it can connect to the hub.
A [device twin][lnk-device-twin] is a JSON document managed by the IoT Hub. A device twin for a device contains:
- Reported properties sent by the device to the hub. You can view these properties in the solution portal.
- Desired properties that you want to send to the device. You can set these properties in the solution portal.
- Tags that exist only in the device twin and not on the device. You can use these tags to filter lists of devices in the solution portal.
This solution uses device twins to manage device metadata. The solution also uses a Cosmos DB database to store additional solution-specific device data such as the commands supported by each device and the command history.
The solution must also keep the information in the device identity registry synchronized with the contents of the Cosmos DB database. The **EventProcessorHost** uses the data from **DeviceInfo** stream analytics job to manage the synchronization.
## Solution portal
![solution portal][img-dashboard]
The solution portal is a web-based UI that is deployed to the cloud as part of the preconfigured solution. It enables you to:
* View telemetry and alarm history in a dashboard.
* Provision new devices.
* Manage and monitor devices.
* Send commands to specific devices.
* Invoke methods on specific devices.
* Manage rules and actions.
* Schedule jobs to run on one or more devices.
In this preconfigured solution, the solution portal forms part of the **IoT solution back end** and part of the **Processing and business connectivity** in the typical [IoT solution architecture][lnk-what-is-azure-iot].
## Next steps
For more information about IoT solution architectures, see [Microsoft Azure IoT services: Reference Architecture][lnk-refarch].
Now you know what a preconfigured solution is, you can get started by deploying the *remote monitoring* preconfigured solution: [Get started with the preconfigured solutions][lnk-getstarted-preconfigured].
[img-remote-monitoring-arch]: ./media/iot-suite-v1-what-are-preconfigured-solutions/remote-monitoring-arch1.png
[img-dashboard]: ./media/iot-suite-v1-what-are-preconfigured-solutions/dashboard.png
[lnk-what-is-azure-iot]: iot-suite-what-is-azure-iot.md
[lnk-asa]: https://azure.microsoft.com/documentation/services/stream-analytics/
[lnk-event-processor]: ../event-hubs/event-hubs-programming-guide.md#event-processor-host
[lnk-web-job]: ../app-service/web-sites-create-web-jobs.md
[lnk-identity-registry]: ../iot-hub/iot-hub-devguide-identity-registry.md
[lnk-predictive-maintenance]: iot-suite-predictive-overview.md
[lnk-azureiotsuite]: https://www.azureiotsuite.com/
[lnk-refarch]: http://download.microsoft.com/download/A/4/D/A4DAD253-BC21-41D3-B9D9-87D2AE6F0719/Microsoft_Azure_IoT_Reference_Architecture.pdf
[lnk-getstarted-preconfigured]: iot-suite-v1-getstarted-preconfigured-solutions.md
[lnk-c2d-guidance]: ../iot-hub/iot-hub-devguide-c2d-guidance.md
[lnk-device-twin]: ../iot-hub/iot-hub-devguide-device-twins.md
[lnk-direct-methods]: ../iot-hub/iot-hub-devguide-direct-methods.md
[lnk-getstarted-factory]: iot-suite-connected-factory-overview.md

Двоичные данные
Tutorials/media/iot-suite-v1-dynamic-telemetry/image3.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 63 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-dynamic-telemetry/image4.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 96 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-dynamic-telemetry/image5.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 70 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 222 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 50 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 253 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 62 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 25 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 118 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 68 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 44 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 63 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 28 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 297 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 184 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 63 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 91 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 185 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 57 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 98 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 141 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 129 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 60 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 24 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 48 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 25 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 73 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 88 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 39 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 114 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 32 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 153 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 185 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 43 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 66 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 51 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 67 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 48 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 36 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 109 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 55 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 62 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 286 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 46 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 65 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 52 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 66 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 25 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 25 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 20 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-logic-apps-tutorial/logicappcode.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 32 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-logic-apps-tutorial/logicapprun.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 50 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 48 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-logic-apps-tutorial/resourcegroup.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 124 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 49 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 18 KiB

Двоичные данные
Tutorials/media/iot-suite-v1-permissions/flowchart.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 95 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 229 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 64 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 53 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 39 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 280 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 229 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 281 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 181 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 62 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 50 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 28 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 326 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 181 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 181 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 198 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 153 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 185 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 227 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 23 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 71 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 75 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 52 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 50 KiB

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше