Skip to content

Instantly share code, notes, and snippets.

@wduraes
Last active August 7, 2021 15:22
Show Gist options
  • Save wduraes/5d482172cbf3154004bae754797541ac to your computer and use it in GitHub Desktop.
Save wduraes/5d482172cbf3154004bae754797541ac to your computer and use it in GitHub Desktop.
Sample telemetry code
/*
How to get this sample to run:
https://github.com/ewertons/azure-sdk-for-c/wiki/How-to-setup-and-run-Azure-SDK-for-Embedded-C-IoT-Hub-client-on-Esp8266-NodeMCU
*/
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <time.h>
#include <PubSubClient.h>
#include <stdlib.h>
#include <string.h>
#include <az_iot_hub_client.h>
#include <az_result.h>
#include <az_span.h>
//adding sensors and libraries
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include "SPI.h"
#define DHTPIN 10 // pin connected to the temperature sensor
#define DHTTYPE DHT11
#include <Adafruit_NeoPixel.h>
#define PIN 2
#define NUMPIXELS 3
#define IOT_CONFIG_WIFI_SSID "SSID"
#define IOT_CONFIG_WIFI_PASSWORD "Password"
#define IOT_CONFIG_HOST "XXXXXXX.azure-devices.net"
#define IOT_CONFIG_DEVICE_ID "XXXXX"
#define IOT_CONFIG_MQTT_PASS "SharedAccessSignature sr=XXXXX.azure-devices.net%2Fdevices%2FzabuHM1UXXXXXXX%3D&se=158999999968"
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
DHT_Unified dht(DHTPIN, DHTTYPE);
#define INTERVAL_MESSAGE 10000 //publish 1 message every 10 seconds
unsigned long time_1 = 5000; //give the MCU 5 seconds to connect before attempting to send the 1st message
const char* ssid = IOT_CONFIG_WIFI_SSID;
const char* password = IOT_CONFIG_WIFI_PASSWORD;
const char* host = IOT_CONFIG_HOST;
const char* device_id = IOT_CONFIG_DEVICE_ID;
const char* MQTT_PASS = IOT_CONFIG_MQTT_PASS;
const int port = 8883;
const char* telemetry_msg = "";
char hum[5];
char temp[5];
char light[4];
char payload[61];
char chipid[5];
String Payload ="";
float Temp;
float Hum;
float Light;
float ChipID;
WiFiClientSecure wifi_client;
PubSubClient mqtt_client(wifi_client);
az_iot_hub_client client;
static void connectToWiFi()
{
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to WIFI SSID ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.hostname(host);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
static void initializeTime()
{
Serial.print("Setting time using SNTP");
configTime(-5 * 3600, 0, "pool.ntp.org", "time.nist.gov");
time_t now = time(NULL);
while (now < 1510592825)
{
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("done!");
}
static void printCurrentTime()
{
time_t now = time(NULL);
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
}
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Received [");
Serial.print(topic);
Serial.print("]: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
}
static void initializeClients()
{
wifi_client.setInsecure();
if (az_failed(az_iot_hub_client_init(&client,az_span_init((uint8_t*)host, strlen(host)),az_span_init((uint8_t*)device_id, strlen(device_id)),NULL)))
{
Serial.println("Failed initializing Azure IoT Hub client");
return;
}
mqtt_client.setServer(host, port);
mqtt_client.setCallback(receivedCallback);
}
static void connectToAzureIoTHub()
{
size_t client_id_length;
char mqtt_client_id[128];
if (az_failed(az_iot_hub_client_get_client_id(&client, mqtt_client_id, sizeof(mqtt_client_id), &client_id_length)))
{
Serial.println("Failed getting client id");
return;
}
mqtt_client_id[client_id_length] = '\0';
char mqtt_username[128];
// Get the MQTT user name used to connect to IoT Hub
if (az_failed(az_iot_hub_client_get_user_name(&client, mqtt_username, sizeof(mqtt_username), NULL)))
{
printf("Failed to get MQTT clientId, return code\n");
return;
}
while (!mqtt_client.connected())
{
time_t now = time(NULL);
Serial.print("Time: ");
Serial.print(ctime(&now));
Serial.print("MQTT connecting ... ");
if (mqtt_client.connect(mqtt_client_id, mqtt_username, MQTT_PASS))
{
Serial.println("connected.");
}
else
{
Serial.print("failed, status code =");
Serial.print(mqtt_client.state());
Serial.println(". Try again in 5 seconds.");
/* Wait 5 seconds before retrying */
delay(5000);
}
}
mqtt_client.subscribe(AZ_IOT_HUB_CLIENT_C2D_SUBSCRIBE_TOPIC);
}
void setup()
{
connectToWiFi();
initializeTime();
printCurrentTime();
initializeClients();
connectToAzureIoTHub();
pinMode(A0, INPUT); //set the pin for the light sensor
dht.begin(); //initialize the ambient sensor
//initialize the neopixels and set them all off
pixels.begin();
pixels.setPixelColor(0, 0, 0, 0);
pixels.setPixelColor(1, 0, 0, 0);
pixels.setPixelColor(2, 0, 0, 0);
pixels.show();
}
void loop()
{
//control timer for Publish, which will be activated by the INTERVAL_MESSAGE variable
if(millis() > time_1 + INTERVAL_MESSAGE)
{
time_1 = millis();
//get Chip ID an unique identifier
ChipID = ESP.getChipId();
dtostrf(ChipID, 5, 0, chipid);
Payload = "{DeviceID:'";
//get temperature and humidity
sensors_event_t event;
dht.temperature().getEvent(&event);
Temp = event.temperature;
dtostrf(Temp, 2, 2, temp);
Payload = Payload + chipid + "',Temperature:" + temp + ",Humidity:";
dht.humidity().getEvent(&event);
Hum = event.relative_humidity;
dtostrf(Hum, 2, 2, hum);
Payload = Payload + hum + ",Light:";
//get light readings from sensor
Light = analogRead(A0);
dtostrf(Light, 4, 0, light);
Payload = Payload + light + "}";
//convert String Payload to a char array
int str_len = Payload.length() + 1;
char char_array[str_len];
Payload.toCharArray(char_array, str_len);
//print payload
Serial.println(" ");
Serial.print("Payload: ");
Serial.println(char_array);
//publish telemetry data
char telemetry_topic[128];
if (az_failed(az_iot_hub_client_telemetry_get_publish_topic(&client, NULL, telemetry_topic, sizeof(telemetry_topic), NULL)))
{
Serial.println("Failed az_iot_hub_client_telemetry_get_publish_topic");
return;
}
mqtt_client.publish(telemetry_topic, char_array, false);
//blink one NeoPixel green to show activity
pixels.setPixelColor(2, 0, 15, 0);
pixels.show();
delay(500);
pixels.setPixelColor(2, 0, 0, 0);
pixels.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment