title | description | services | author | manager | ms.author | ms.date | ms.topic | ms.service | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Tutorial develop C module for Linux - Azure IoT Edge | Microsoft Docs |
This tutorial shows you how to create an IoT Edge module with C code and deploy it to a Linux device running IoT Edge |
iot-edge |
shizn |
philmea |
xshi |
11/07/2019 |
tutorial |
iot-edge |
mvc |
Use Visual Studio Code to develop C code and deploy it to a Linux device running Azure IoT Edge.
You can use IoT Edge modules to deploy code that implements your business logic directly to your IoT Edge devices. This tutorial walks you through creating and deploying an IoT Edge module that filters sensor data. In this tutorial, you learn how to:
[!div class="checklist"]
- Use Visual Studio Code to create an IoT Edge module in C
- Use Visual Studio Code and Docker to create a docker image and publish it to a container registry
- Deploy the module to your IoT Edge device
- View generated data
The IoT Edge module that you create in this tutorial filters the temperature data generated by your device. It only sends messages upstream if the temperature is above a specified threshold. This type of analysis at the edge is useful for reducing the amount of data communicated to and stored in the cloud.
[!INCLUDE quickstarts-free-trial-note]
This tutorial demonstrates how to develop a module in C using Visual Studio Code, and how to deploy it to a Linux device. If you're developing modules for Windows devices, go to Develop a C IoT Edge module for Windows devices instead.
Use the following table to understand your options for developing and deploying C modules to Linux:
C | Visual Studio Code | Visual Studio |
---|---|---|
Linux AMD64 | ![]() |
![]() |
Linux ARM32 | ![]() |
![]() |
Before beginning this tutorial, you should have gone through the previous tutorial to set up your development environment for Linux container development: Develop IoT Edge modules for Linux devices. By completing that tutorial, you should have the following prerequisites in place:
- A free or standard-tier IoT Hub in Azure.
- A Linux device running Azure IoT Edge
- A container registry, like Azure Container Registry.
- Visual Studio Code configured with the Azure IoT Tools.
- Docker CE configured to run Linux containers.
To develop an IoT Edge module in C, install the following additional prerequisites on your development machine:
- C/C++ extension for Visual Studio Code.
The following steps create an IoT Edge module project for C by using Visual Studio Code and the Azure IoT Tools extension. Once you have a project template created, add new code so that the module filters out messages based on their reported properties.
Create a C solution template that you can customize with your own code.
-
Select View > Command Palette to open the VS Code command palette.
-
In the command palette, type and run the command Azure: Sign in and follow the instructions to sign in your Azure account. If you've already signed in, you can skip this step.
-
In the command palette, type and run the command Azure IoT Edge: New IoT Edge solution. Follow the prompts in the command palette to create your solution.
Field Value Select folder Choose the location on your development machine for VS Code to create the solution files. Provide a solution name Enter a descriptive name for your solution or accept the default EdgeSolution. Select module template Choose C Module. Provide a module name Name your module CModule. Provide Docker image repository for the module An image repository includes the name of your container registry and the name of your container image. Your container image is prepopulated from the name you provided in the last step. Replace localhost:5000 with the login server value from your Azure container registry. You can retrieve the login server from the Overview page of your container registry in the Azure portal.
The final image repository looks like <registry name>.azurecr.io/cmodule.
The environment file stores the credentials for your container registry and shares them with the IoT Edge runtime. The runtime needs these credentials to pull your private images onto the IoT Edge device.
- In the VS Code explorer, open the .env file.
- Update the fields with the username and password values that you copied from your Azure container registry.
- Save this file.
Currently, Visual Studio Code can develop C modules for Linux AMD64 and Linux ARM32v7 devices. You need to select which architecture you're targeting with each solution, because the container is built and run differently for each architecture type. The default is Linux AMD64.
-
Open the command palette and search for Azure IoT Edge: Set Default Target Platform for Edge Solution, or select the shortcut icon in the side bar at the bottom of the window.
-
In the command palette, select the target architecture from the list of options. For this tutorial, we're using an Ubuntu virtual machine as the IoT Edge device, so will keep the default amd64.
The default module code receives messages on an input queue and passes them along through an output queue. Let's add some additional code so that the module processes the messages at the edge before forwarding them to IoT Hub. Update the module so that it analyzes the temperature data in each message, and only sends the message to IoT Hub if the temperature exceeds a certain threshold.
-
The data from the sensor in this scenario comes in JSON format. To filter messages in JSON format, import a JSON library for C. This tutorial uses Parson.
-
Download the Parson GitHub repository. Copy the parson.c and parson.h files into the CModule folder.
-
Open modules > CModule > CMakeLists.txt. At the top of the file, import the Parson files as a library called my_parson.
add_library(my_parson parson.c parson.h )
-
Add
my_parson
to the list of libraries in the target_link_libraries function of CMakeLists.txt. -
Save the CMakeLists.txt file.
-
Open modules > CModule > main.c. At the bottom of the list of include statements, add a new one to include
parson.h
for JSON support:#include "parson.h"
-
-
In the main.c file, add a global variable called
temperatureThreshold
after the include section. This variable sets the value that the measured temperature must exceed in order for the data to be sent to IoT Hub.static double temperatureThreshold = 25;
-
Find the
CreateMessageInstance
function in main.c. Replace the inner if-else statement with the following code that adds a few lines of functionality:if ((messageInstance->messageHandle = IoTHubMessage_Clone(message)) == NULL) { free(messageInstance); messageInstance = NULL; } else { messageInstance->messageTrackingId = messagesReceivedByInput1Queue; MAP_HANDLE propMap = IoTHubMessage_Properties(messageInstance->messageHandle); if (Map_AddOrUpdate(propMap, "MessageType", "Alert") != MAP_OK) { printf("ERROR: Map_AddOrUpdate Failed!\r\n"); } }
The new lines of code in the else statement add a new property to the message, which labels the message as an alert. This code labels all messages as alerts, because we'll add functionality that only sends messages to IoT Hub if they report high temperatures.
-
Replace the entire
InputQueue1Callback
function with the following code. This function implements the actual messaging filter. When a message is received, it checks whether the reported temperature exceeds the threshold. If yes, then it forwards the message through its output queue. If not, then it ignores the message.static unsigned char *bytearray_to_str(const unsigned char *buffer, size_t len) { unsigned char *ret = (unsigned char *)malloc(len + 1); memcpy(ret, buffer, len); ret[len] = '\0'; return ret; } static IOTHUBMESSAGE_DISPOSITION_RESULT InputQueue1Callback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) { IOTHUBMESSAGE_DISPOSITION_RESULT result; IOTHUB_CLIENT_RESULT clientResult; IOTHUB_MODULE_CLIENT_LL_HANDLE iotHubModuleClientHandle = (IOTHUB_MODULE_CLIENT_LL_HANDLE)userContextCallback; unsigned const char* messageBody; size_t contentSize; if (IoTHubMessage_GetByteArray(message, &messageBody, &contentSize) == IOTHUB_MESSAGE_OK) { messageBody = bytearray_to_str(messageBody, contentSize); } else { messageBody = "<null>"; } printf("Received Message [%zu]\r\n Data: [%s]\r\n", messagesReceivedByInput1Queue, messageBody); // Check if the message reports temperatures higher than the threshold JSON_Value *root_value = json_parse_string(messageBody); JSON_Object *root_object = json_value_get_object(root_value); double temperature; if (json_object_dotget_value(root_object, "machine.temperature") != NULL && (temperature = json_object_dotget_number(root_object, "machine.temperature")) > temperatureThreshold) { printf("Machine temperature %f exceeds threshold %f\r\n", temperature, temperatureThreshold); // This message should be sent to next stop in the pipeline, namely "output1". What happens at "outpu1" is determined // by the configuration of the Edge routing table setup. MESSAGE_INSTANCE *messageInstance = CreateMessageInstance(message); if (NULL == messageInstance) { result = IOTHUBMESSAGE_ABANDONED; } else { printf("Sending message (%zu) to the next stage in pipeline\n", messagesReceivedByInput1Queue); clientResult = IoTHubModuleClient_LL_SendEventToOutputAsync(iotHubModuleClientHandle, messageInstance->messageHandle, "output1", SendConfirmationCallback, (void *)messageInstance); if (clientResult != IOTHUB_CLIENT_OK) { IoTHubMessage_Destroy(messageInstance->messageHandle); free(messageInstance); printf("IoTHubModuleClient_LL_SendEventToOutputAsync failed on sending msg#=%zu, err=%d\n", messagesReceivedByInput1Queue, clientResult); result = IOTHUBMESSAGE_ABANDONED; } else { result = IOTHUBMESSAGE_ACCEPTED; } } } else { printf("Not sending message (%zu) to the next stage in pipeline.\r\n", messagesReceivedByInput1Queue); result = IOTHUBMESSAGE_ACCEPTED; } messagesReceivedByInput1Queue++; return result; }
-
Add a
moduleTwinCallback
function. This method receives updates on the desired properties from the module twin, and updates the temperatureThreshold variable to match. All modules have their own module twin, which lets you configure the code running inside a module directly from the cloud.static void moduleTwinCallback(DEVICE_TWIN_UPDATE_STATE update_state, const unsigned char* payLoad, size_t size, void* userContextCallback) { printf("\r\nTwin callback called with (state=%s, size=%zu):\r\n%s\r\n", MU_ENUM_TO_STRING(DEVICE_TWIN_UPDATE_STATE, update_state), size, payLoad); JSON_Value *root_value = json_parse_string(payLoad); JSON_Object *root_object = json_value_get_object(root_value); if (json_object_dotget_value(root_object, "desired.TemperatureThreshold") != NULL) { temperatureThreshold = json_object_dotget_number(root_object, "desired.TemperatureThreshold"); } if (json_object_get_value(root_object, "TemperatureThreshold") != NULL) { temperatureThreshold = json_object_get_number(root_object, "TemperatureThreshold"); } }
-
Find the
SetupCallbacksForModule
function. Replace the function with the following code that adds an else if statement to check if the module twin has been updated.static int SetupCallbacksForModule(IOTHUB_MODULE_CLIENT_LL_HANDLE iotHubModuleClientHandle) { int ret; if (IoTHubModuleClient_LL_SetInputMessageCallback(iotHubModuleClientHandle, "input1", InputQueue1Callback, (void*)iotHubModuleClientHandle) != IOTHUB_CLIENT_OK) { printf("ERROR: IoTHubModuleClient_LL_SetInputMessageCallback(\"input1\")..........FAILED!\r\n"); ret = MU_FAILURE; } else if (IoTHubModuleClient_LL_SetModuleTwinCallback(iotHubModuleClientHandle, moduleTwinCallback, (void*)iotHubModuleClientHandle) != IOTHUB_CLIENT_OK) { printf("ERROR: IoTHubModuleClient_LL_SetModuleTwinCallback(default)..........FAILED!\r\n"); ret = MU_FAILURE; } else { ret = 0; } return ret; }
-
Save the main.c file.
-
In the VS Code explorer, open the deployment.template.json file in your IoT Edge solution workspace.
-
Add the CModule module twin to the deployment manifest. Insert the following JSON content at the bottom of the
moduleContent
section, after the$edgeHub
module twin:"CModule": { "properties.desired":{ "TemperatureThreshold":25 } }
-
Save the deployment.template.json file.
In the previous section, you created an IoT Edge solution and added code to the CModule that will filter out messages where the reported machine temperature is within the acceptable limits. Now you need to build the solution as a container image and push it to your container registry.
-
Open the VS Code terminal by selecting View > Terminal.
-
Sign in to Docker by entering the following command in the terminal. Sign in with the username, password, and login server from your Azure container registry. You can retrieve these values from the Access keys section of your registry in the Azure portal.
docker login -u <ACR username> -p <ACR password> <ACR login server>
You may receive a security warning recommending the use of
--password-stdin
. While that best practice is recommended for production scenarios, it's outside the scope of this tutorial. For more information, see the docker login reference. -
In the VS Code explorer, right-click the deployment.template.json file and select Build and Push IoT Edge solution.
The build and push command starts three operations. First, it creates a new folder in the solution called config that holds the full deployment manifest, built out of information in the deployment template and other solution files. Second, it runs
docker build
to build the container image based on the appropriate dockerfile for your target architecture. Then, it runsdocker push
to push the image repository to your container registry.
Use the Visual Studio Code explorer and the Azure IoT Tools extension to deploy the module project to your IoT Edge device. You already have a deployment manifest prepared for your scenario, the deployment.json file in the config folder. All you need to do now is select a device to receive the deployment.
Make sure that your IoT Edge device is up and running.
-
In the Visual Studio Code explorer, expand the Azure IoT Hub Devices section to see your list of IoT devices.
-
Right-click the name of your IoT Edge device, then select Create Deployment for Single Device.
-
Select the deployment.json file in the config folder and then click Select Edge Deployment Manifest. Do not use the deployment.template.json file.
-
Click the refresh button. You should see the new CModule running along with the SimulatedTemperatureSensor module and the $edgeAgent and $edgeHub.
Once you apply the deployment manifest to your IoT Edge device, the IoT Edge runtime on the device collects the new deployment information and starts executing on it. Any modules running on the device that aren't included in the deployment manifest are stopped. Any modules missing from the device are started.
You can view the status of your IoT Edge device using the Azure IoT Hub Devices section of the Visual Studio Code explorer. Expand the details of your device to see a list of deployed and running modules.
-
In the Visual Studio Code explorer, right-click the name of your IoT Edge device and select Start Monitoring Built-in Event Endpoint.
-
View the messages arriving at your IoT Hub. It may take a while for the messages to arrive, because the IoT Edge device has to receive its new deployment and start all the modules. Then, the changes we made to the CModule code wait until the machine temperature reaches 25 degrees before sending messages. It also adds the message type Alert to any messages that reach that temperature threshold.
We used the CModule module twin in the deployment manifest to set the temperature threshold at 25 degrees. You can use the module twin to change the functionality without having to update the module code.
-
In Visual Studio Code, expand the details under your IoT Edge device to see the running modules.
-
Right-click CModule and select Edit module twin.
-
Find TemperatureThreshold in the desired properties. Change its value to a new temperature 5 degrees to 10 degrees higher than the latest reported temperature.
-
Save the module twin file.
-
Right-click anywhere in the module twin editing pane and select Update module twin.
-
Monitor the incoming device-to-cloud messages. You should see the messages stop until the new temperature threshold is reached.
If you plan to continue to the next recommended article, you can keep the resources and configurations that you created and reuse them. You can also keep using the same IoT Edge device as a test device.
Otherwise, you can delete the local configurations and the Azure resources that you used in this article to avoid charges.
[!INCLUDE iot-edge-clean-up-cloud-resources]
In this tutorial, you created an IoT Edge module that contains code to filter raw data generated by your IoT Edge device. When you're ready to build your own modules, you can learn more about developing your own IoT Edge modules or how to develop modules with Visual Studio Code. For examples of IoT Edge modules, including the simulated temperature module, see IoT Edge module samples and IoT C SDK samples.
You can continue on to the next tutorials to learn how Azure IoT Edge can help you deploy Azure cloud services to process and analyze data at the edge.
[!div class="nextstepaction"] Functions Stream Analytics Machine Learning Custom Vision Service