Skip to content

Instantly share code, notes, and snippets.

@forGGe
Last active May 8, 2023 01:48
Show Gist options
  • Save forGGe/24a1f7f0c8549004d41e9a6aa904d38c to your computer and use it in GitHub Desktop.
Save forGGe/24a1f7f0c8549004d41e9a6aa904d38c to your computer and use it in GitHub Desktop.
ThingsBoard and Mbed IoT application for STM32 B-L475E-IOT01A board, article: https://forgge.github.io/B-L475E-IOT01A-thingsboard-read-temperature-and-humidity-using-mbed.html
// main.cpp
#include "mbed.h"
#include "ISM43362Interface.h"
#include "TCPSocket.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"
#include "HTS221Sensor.h"
// Definitions ---------------------------------------------------------
// Change it with your WiFi network name
#define WIFI_NETWORK_NAME "<YOUR_WIFI_NETWORK_HERE>"
// Change it with your WiFi password name
#define WIFI_NETWORK_PASSWORD "<YOUR_WIFI_NETWORK_PASSWORD_HERE>"
#define WIFI_SECURITY NSAPI_SECURITY_WPA_WPA2
#define MQTT_HOST "demo.thingsboard.io"
#define MQTT_PORT 1883
#define MQTT_TOPIC "v1/devices/me/telemetry"
// Network adapter for Paho MQTT library -------------------------------
class MQTTNetwork
{
public:
MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) {
socket = new TCPSocket();
}
~MQTTNetwork() {
delete socket;
}
int read(unsigned char* buffer, int len, int timeout) {
return socket->recv(buffer, len);
}
int write(unsigned char* buffer, int len, int timeout) {
return socket->send(buffer, len);
}
int connect(const char* hostname, int port) {
socket->open(network);
return socket->connect(hostname, port);
}
int disconnect() {
return socket->close();
}
private:
NetworkInterface* network;
TCPSocket* socket;
};
int main()
{
int count = 0;
ISM43362Interface wifi(MBED_CONF_APP_WIFI_SPI_MOSI,
MBED_CONF_APP_WIFI_SPI_MISO,
MBED_CONF_APP_WIFI_SPI_SCLK,
MBED_CONF_APP_WIFI_SPI_NSS,
MBED_CONF_APP_WIFI_RESET,
MBED_CONF_APP_WIFI_DATAREADY,
MBED_CONF_APP_WIFI_WAKEUP, false);
// Scanning WiFi networks ------------------------------------------
WiFiAccessPoint *ap;
count = wifi.scan(NULL, 0);
printf("%d networks available.\n", count);
/* Limit number of network arbitrary to 15 */
count = count < 15 ? count : 15;
ap = new WiFiAccessPoint[count];
count = wifi.scan(ap, count);
for (int i = 0; i < count; i++) {
printf("Network: %s RSSI: %hhd\n", ap[i].get_ssid(), ap[i].get_rssi());
}
delete[] ap;
// Connecting to WiFi network --------------------------------------
printf("\nConnecting to %s...\n", WIFI_NETWORK_NAME);
int ret = wifi.connect(WIFI_NETWORK_NAME, WIFI_NETWORK_PASSWORD, WIFI_SECURITY);
if (ret != 0) {
printf("\nConnection error\n");
return -1;
}
printf("Success\n\n");
printf("MAC: %s\n", wifi.get_mac_address());
printf("IP: %s\n", wifi.get_ip_address());
printf("Netmask: %s\n", wifi.get_netmask());
printf("Gateway: %s\n", wifi.get_gateway());
printf("RSSI: %d\n\n", wifi.get_rssi());
// Connect to ThingsBoard ----------------------------------------------
MQTTNetwork network(&wifi);
MQTT::Client<MQTTNetwork, Countdown> client(network);
char assess_token[] = "<YOUR_ACCESS_TOKEN_HERE>";
MQTTPacket_connectData conn_data = MQTTPacket_connectData_initializer;
conn_data.username.cstring = assess_token;
if (network.connect(MQTT_HOST, MQTT_PORT) < 0) {
printf("failed to connect to " MQTT_HOST "\n");
return -1;
}
if (client.connect(conn_data) < 0) {
printf("failed to send MQTT connect message\n");
return -1;
}
printf("successfully connect!\n\n");
// Initialize sensors --------------------------------------------------
uint8_t id;
DevI2C i2c_2(PB_11, PB_10);
HTS221Sensor hum_temp(&i2c_2);
hum_temp.init(NULL);
hum_temp.enable();
hum_temp.read_id(&id);
printf("HTS221 humidity & temperature sensor = 0x%X\r\n", id);
// Get data from sensors -----------------------------------------------
for (;;) {
float temp, humid;
hum_temp.get_temperature(&temp);
hum_temp.get_humidity(&humid);
printf("HTS221: [temp] %.2f C, [hum] %.2f%%\r\n", temp, humid);
char msg[256];
int n = snprintf(msg, sizeof(msg),
"{\"temperature\":%f, \"humidity\":%f, \"active\": false}",
temp, humid);
void *payload = reinterpret_cast<void*>(msg);
size_t payload_len = n;
printf("publish to: %s %d %s\r\n", MQTT_HOST, MQTT_PORT, MQTT_TOPIC);
if (client.publish(MQTT_TOPIC, payload, n) < 0) {
printf("failed to publish MQTT message");
}
wait_ms(5000);
}
// Shouldn't get there, but let's leave it anyway --------------------------------------------------------------------------
client.disconnect();
wifi.disconnect();
printf("\ndone\n");
return 0;
}
{
"macros": [
"MBED_CONF_APP_MAIN_STACK_SIZE=6000",
"MBED_CONF_APP_THREAD_STACK_SIZE=6000",
"DEVICE_STDIO_MESSAGES=1"
],
"config": {
"wifi-shield": {
"help": "Options are internal, WIFI_IDW0XX1",
"value": "internal"
},
"wifi-tx": {
"help": "TX pin for serial connection to external device",
"value": "D1"
},
"wifi-rx": {
"help": "RX pin for serial connection to external device",
"value": "D0"
},
"wifi-spi_miso": {
"help": "SPI-MISO connection to external device",
"value": "PC_11"
},
"wifi-spi_mosi": {
"help": "SPI-MOSI connection to external device",
"value": "PC_12"
},
"wifi-spi_sclk": {
"help": "SPI-CLOCK connection to external device",
"value": "PC_10"
},
"wifi-spi_nss": {
"help": "SPI chip select of external device",
"value": "PE_0"
},
"wifi-reset": {
"help": "WIFI module reset pin",
"value": "PE_8"
},
"wifi-dataready": {
"help": "WIFI module data ready pin",
"value": "PE_1"
},
"wifi-wakeup": {
"help": "WIFI module wakeup pin",
"value": "PB_12"
}
},
"target_overrides": {
"*": {
"platform.stdio-baud-rate": 115200,
"platform.stdio-convert-newlines": true
},
"DISCO_L475VG_IOT1A": {
"wifi-spi_miso": "PC_11",
"wifi-spi_mosi": "PC_12",
"wifi-spi_sclk": "PC_10",
"wifi-spi_nss": "PE_0",
"wifi-reset": "PE_8",
"wifi-dataready": "PE_1",
"wifi-wakeup": "PB_12"
}
}
}
{
"title": "STM32 IoT Kit dashboard",
"configuration": {
"widgets": {
"bf33af9b-f840-0440-f258-bce055fff304": {
"isSystemType": true,
"bundleAlias": "charts",
"typeAlias": "basic_timeseries",
"type": "timeseries",
"title": "New widget",
"sizeX": 8,
"sizeY": 5,
"config": {
"datasources": [
{
"type": "entity",
"dataKeys": [
{
"name": "humidity",
"type": "timeseries",
"label": "humidity",
"color": "#2196f3",
"settings": {
"showLines": true,
"fillLines": false,
"showPoints": false,
"tooltipValueFormatter": "",
"showSeparateAxis": false,
"axisTitle": "",
"axisTickDecimals": 0,
"axisPosition": "left",
"axisTicksFormatter": ""
},
"_hash": 0.01464221283315692
},
{
"name": "temperature",
"type": "timeseries",
"label": "temperature",
"color": "#4caf50",
"settings": {
"showLines": true,
"fillLines": false,
"showPoints": false,
"tooltipValueFormatter": "",
"showSeparateAxis": false,
"axisTitle": "",
"axisTickDecimals": 0,
"axisPosition": "left",
"axisTicksFormatter": ""
},
"_hash": 0.8201548016278053
}
],
"entityAliasId": "21829d87-db1c-508f-c295-e1902a56d4bb"
}
],
"timewindow": {
"realtime": {
"timewindowMs": 60000
}
},
"showTitle": true,
"backgroundColor": "#fff",
"color": "rgba(0, 0, 0, 0.87)",
"padding": "8px",
"settings": {
"shadowSize": 4,
"fontColor": "#545454",
"fontSize": 10,
"xaxis": {
"showLabels": true,
"color": "#545454"
},
"yaxis": {
"showLabels": true,
"color": "#545454"
},
"grid": {
"color": "#545454",
"tickColor": "#DDDDDD",
"verticalLines": true,
"horizontalLines": true,
"outlineWidth": 1
},
"stack": false,
"tooltipIndividual": false
},
"title": "New Timeseries - Flot",
"dropShadow": true,
"enableFullscreen": true,
"titleStyle": {
"fontSize": "16px",
"fontWeight": 400
},
"mobileHeight": null,
"widgetStyle": {},
"useDashboardTimewindow": true,
"showLegend": true,
"actions": {}
},
"id": "bf33af9b-f840-0440-f258-bce055fff304"
}
},
"states": {
"default": {
"name": "STM32 IoT Kit dashboard",
"root": true,
"layouts": {
"main": {
"widgets": {
"bf33af9b-f840-0440-f258-bce055fff304": {
"sizeX": 8,
"sizeY": 5,
"mobileHeight": null,
"row": 0,
"col": 0
}
},
"gridSettings": {
"backgroundColor": "#eeeeee",
"color": "rgba(0,0,0,0.870588)",
"columns": 24,
"margins": [
10,
10
],
"backgroundSizeMode": "100%"
}
}
}
}
},
"entityAliases": {
"21829d87-db1c-508f-c295-e1902a56d4bb": {
"id": "21829d87-db1c-508f-c295-e1902a56d4bb",
"alias": "IoT Kit alias",
"filter": {
"type": "singleEntity",
"resolveMultiple": false,
"singleEntity": {
"entityType": "DEVICE",
"id": "217e62b0-3dc6-11e8-82d4-c3b186e30863"
}
}
}
},
"timewindow": {
"displayValue": "",
"selectedTab": 0,
"realtime": {
"interval": 1000,
"timewindowMs": 60000
},
"history": {
"historyType": 0,
"interval": 1000,
"timewindowMs": 60000,
"fixedTimewindow": {
"startTimeMs": 1523774931204,
"endTimeMs": 1523861331204
}
},
"aggregation": {
"type": "AVG",
"limit": 200
}
},
"settings": {
"stateControllerId": "entity",
"showTitle": false,
"showDashboardsSelect": true,
"showEntitiesSelect": true,
"showDashboardTimewindow": true,
"showDashboardExport": true,
"toolbarAlwaysOpen": true
}
},
"name": "STM32 IoT Kit dashboard"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment