IoT Hub Sending messages - Azure-Sphere-DevX/AzureSphereDevX.Examples GitHub Wiki
Sending messages to Azure IoT Hub and IoT Central
Examples
Code example, sending messages
Config app_manifest.json sample
- Set ID Scope
- Set Allowed connections
- Set DeviceAuthentication
Functions
bool dx_isAzureConnected(void);
bool dx_azurePublish(const void* message, size_t messageLength, DX_MESSAGE_PROPERTY** messageProperties, size_t messagePropertyCount, DX_MESSAGE_CONTENT_PROPERTIES* messageContentProperties);
DX_MESSAGE_CONTENT_PROPERTIES* messageContentProperties);
void dx_azureConnect(DX_USER_CONFIG* userConfig, const char* networkInterface, const char* plugAndPlayModelId);
void dx_azureToDeviceStop(void);
Structures
typedef struct DX_MESSAGE_PROPERTY
{
const char* key;
const char* value;
} DX_MESSAGE_PROPERTY;
typedef struct DX_MESSAGE_CONTENT_PROPERTIES
{
const char* contentEncoding;
const char* contentType;
} DX_MESSAGE_CONTENT_PROPERTIES;
dx_config.h
typedef enum {
DX_CONNECTION_TYPE_NOT_DEFINED = 0,
DX_CONNECTION_TYPE_DPS = 1,
DX_CONNECTION_TYPE_DIRECT = 2
} ConnectionType;
typedef struct {
const char* idScope;
const char* connectionString;
ConnectionType connectionType;
} DX_USER_CONFIG;
Usage
Declare message template, and optionally message and content properties
static const char* msgTemplate = "{ \"Temperature\":%3.2f, \"Humidity\":%3.1f, \"Pressure\":%3.1f }";
static DX_MESSAGE_PROPERTY* telemetryMessageProperties[] = {
&(DX_MESSAGE_PROPERTY) { .key = "appid", .value = "hvac" },
&(DX_MESSAGE_PROPERTY) {.key = "type", .value = "telemetry" },
&(DX_MESSAGE_PROPERTY) {.key = "schema", .value = "1" }
};
static DX_MESSAGE_CONTENT_PROPERTIES telemetryContentProperties = {
.contentEncoding = "utf-8",
.contentType = "application/json"
};
Open connetion to Azure IoT Hub or IoT Central
dx_azureConnect(&dx_config, NETWORK_INTERFACE, IOT_PLUG_AND_PLAY_MODEL_ID);
Send message with no properties
bool serialization_result = dx_jsonSerialize(msgBuffer, sizeof(msgBuffer), 4,
DX_JSON_INT, "MsgId", msgId++,
DX_JSON_DOUBLE, "Temperature", temperature,
DX_JSON_DOUBLE, "Humidity", humidity,
DX_JSON_DOUBLE, "Pressure", pressure);
if (serialization_result) {
Log_Debug("%s\n", msgBuffer);
dx_azurePublish(msgBuffer, strlen(msgBuffer), NULL, 0, NULL);
} else {
Log_Debug("JSON Serialization failed: Buffer too small\n");
}
Send message with properties
bool serialization_result = dx_jsonSerialize(msgBuffer, sizeof(msgBuffer), 4,
DX_JSON_INT, "MsgId", msgId++,
DX_JSON_DOUBLE, "Temperature", temperature,
DX_JSON_DOUBLE, "Humidity", humidity,
DX_JSON_DOUBLE, "Pressure", pressure);
if (serialization_result) {
Log_Debug("%s\n", msgBuffer);
dx_azurePublish(msgBuffer, strlen(msgBuffer), messageProperties, NELEMS(messageProperties), &contentProperties);
} else {
Log_Debug("JSON Serialization failed: Buffer too small\n");
}