How to connect an ESP8266 device securely to a web frontend? - security

I want to develop a product, a home smart thermostat which will have a web interface. The web interface would make requests to the thermostat which is controlled by an ESP8266-based wemos mini d1. And I would like to connect the frontend and the backend securely if it will be a product.
I tried making the backend to accept https requests and generated the key and cert using openssl. But when I ran the program, only the http site loaded in the browser and the https didn't (not even a 'not secure' page). I used the local ip address in the browser like this: https://192.168.1.5/
BearSSL::ESP8266WebServerSecure server(443);
ESP8266WebServer serverHTTP(800);
void serveHomepage() {
server.send(200, "text/plain", "Hello world https");
}
void serveHomepageHttp() {
serverHTTP.send(200, "text/plain", "Hello world http");
}
void setup() {
connectToWifi();
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
serverHTTP.on("/", serveHomepageHttp);
serverHTTP.begin();
server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
server.on("/", serveHomepage);
server.begin();
}
void loop(){
server.handleClient();
serverHTTP.handleClient();
}
I barely found any documentation or a full demo, I followed this article: https://www.onetransistor.eu/2019/04/https-server-on-esp8266-nodemcu.html
I also read that https is relatively memory and cpu intense, so I would rather connect the esp8266 with http to a proxy/gateway server which has HTTPS support (but is not on the same network), and then that to the frontend:
Frontend -> HTTPS request to central server -> HTTP request to esp8266
I don't really know if it is secure enough, but I assume that the users that use my product have a secure home wifi and my server provider is also reliable.
So, what are my opportunities, if I want to provide my users good security with an ESP8266? Is the https proxy server mentioned above a secure enough solution?

yes it is possible to get a secure HTTPS connection with D1 Mini and it works great:
Please try this code, insert your interface mainly in handleRoot():
/*
HelloServerBearSSL - Simple HTTPS server example
This example demonstrates a basic ESP8266WebServerSecure HTTPS server
that can serve "/" and "/inline" and generate detailed 404 (not found)
HTTP respoinses. Be sure to update the SSID and PASSWORD before running
to allow connection to your WiFi network.
Adapted by Earle F. Philhower, III, from the HelloServer.ino example.
This example is released into the public domain.
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServerSecure.h>
#include <ESP8266mDNS.h>
#include <umm_malloc/umm_malloc.h>
#include <umm_malloc/umm_heap_select.h>
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
BearSSL::ESP8266WebServerSecure server(443);
BearSSL::ServerSessions serverCache(5);
static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC
VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx
EDAOBgNVBAoMB1ByaXZhZG8xGjAYBgNVBAMMEXNlcnZlci56bGFiZWwuY29tMR8w
HQYJKoZIhvcNAQkBFhBlYXJsZUB6bGFiZWwuY29tMB4XDTE4MDMwNjA1NDg0NFoX
DTE5MDMwNjA1NDg0NFowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3Rh
dGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAPVKBwbZ+KDSl40YCDkP6y8Sv4iNGvEOZg8Y
X7sGvf/xZH7UiCBWPFIRpNmDSaZ3yjsmFqm6sLiYSGSdrBCFqdt9NTp2r7hga6Sj
oASSZY4B9pf+GblDy5m10KDx90BFKXdPMCLT+o76Nx9PpCvw13A848wHNG3bpBgI
t+w/vJCX3bkRn8yEYAU6GdMbYe7v446hX3kY5UmgeJFr9xz1kq6AzYrMt/UHhNzO
S+QckJaY0OGWvmTNspY3xCbbFtIDkCdBS8CZAw+itnofvnWWKQEXlt6otPh5njwy
+O1t/Q+Z7OMDYQaH02IQx3188/kW3FzOY32knER1uzjmRO+jhA8CAwEAATANBgkq
hkiG9w0BAQsFAAOCAQEAnDrROGRETB0woIcI1+acY1yRq4yAcH2/hdq2MoM+DCyM
E8CJaOznGR9ND0ImWpTZqomHOUkOBpvu7u315blQZcLbL1LfHJGRTCHVhvVrcyEb
fWTnRtAQdlirUm/obwXIitoz64VSbIVzcqqfg9C6ZREB9JbEX98/9Wp2gVY+31oC
JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m
+TGimzSdeWDvGBRWZHXczC2zD4aoE5vrl+GD2i++c6yjL/otHfYyUpzUfbI2hMAA
5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg==
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI
IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z
uUPLmbXQoPH3QEUpd08wItP6jvo3H0+kK/DXcDzjzAc0bdukGAi37D+8kJfduRGf
zIRgBToZ0xth7u/jjqFfeRjlSaB4kWv3HPWSroDNisy39QeE3M5L5ByQlpjQ4Za+
ZM2yljfEJtsW0gOQJ0FLwJkDD6K2eh++dZYpAReW3qi0+HmePDL47W39D5ns4wNh
BofTYhDHfXzz+RbcXM5jfaScRHW7OOZE76OEDwIDAQABAoIBAQDKov5NFbNFQNR8
djcM1O7Is6dRaqiwLeH4ZH1pZ3d9QnFwKanPdQ5eCj9yhfhJMrr5xEyCqT0nMn7T
yEIGYDXjontfsf8WxWkH2TjvrfWBrHOIOx4LJEvFzyLsYxiMmtZXvy6YByD+Dw2M
q2GH/24rRdI2klkozIOyazluTXU8yOsSGxHr/aOa9/sZISgLmaGOOuKI/3Zqjdhr
eHeSqoQFt3xXa8jw01YubQUDw/4cv9rk2ytTdAoQUimiKtgtjsggpP1LTq4xcuqN
d4jWhTcnorWpbD2cVLxrEbnSR3VuBCJEZv5axg5ZPxLEnlcId8vMtvTRb5nzzszn
geYUWDPhAoGBAPyKVNqqwQl44oIeiuRM2FYenMt4voVaz3ExJX2JysrG0jtCPv+Y
84R6Cv3nfITz3EZDWp5sW3OwoGr77lF7Tv9tD6BptEmgBeuca3SHIdhG2MR+tLyx
/tkIAarxQcTGsZaSqra3gXOJCMz9h2P5dxpdU+0yeMmOEnAqgQ8qtNBfAoGBAPim
RAtnrd0WSlCgqVGYFCvDh1kD5QTNbZc+1PcBHbVV45EmJ2fLXnlDeplIZJdYxmzu
DMOxZBYgfeLY9exje00eZJNSj/csjJQqiRftrbvYY7m5njX1kM5K8x4HlynQTDkg
rtKO0YZJxxmjRTbFGMegh1SLlFLRIMtehNhOgipRAoGBAPnEEpJGCS9GGLfaX0HW
YqwiEK8Il12q57mqgsq7ag7NPwWOymHesxHV5mMh/Dw+NyBi4xAGWRh9mtrUmeqK
iyICik773Gxo0RIqnPgd4jJWN3N3YWeynzulOIkJnSNx5BforOCTc3uCD2s2YB5X
jx1LKoNQxLeLRN8cmpIWicf/AoGBANjRSsZTKwV9WWIDJoHyxav/vPb+8WYFp8lZ
zaRxQbGM6nn4NiZI7OF62N3uhWB/1c7IqTK/bVHqFTuJCrCNcsgld3gLZ2QWYaMV
kCPgaj1BjHw4AmB0+EcajfKilcqtSroJ6MfMJ6IclVOizkjbByeTsE4lxDmPCDSt
/9MKanBxAoGAY9xo741Pn9WUxDyRplww606ccdNf/ksHWNc/Y2B5SPwxxSnIq8nO
j01SmsCUYVFAgZVOTiiycakjYLzxlc6p8BxSVqy6LlJqn95N8OXoQ+bkwUux/ekg
gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk=
-----END RSA PRIVATE KEY-----
)EOF";
const int led = 13;
void handleRoot() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hello from esp8266 over HTTPS!");
digitalWrite(led, 0);
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup(void){
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
// Cache SSL sessions to accelerate the TLS handshake.
server.getServer().setCache(&serverCache);
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTPS server started");
}
extern "C" void stack_thunk_dump_stack();
void processKey(Print& out, int hotKey) {
switch (hotKey) {
case 'd': {
HeapSelectDram ephemeral;
umm_info(NULL, true);
break;
}
case 'i': {
HeapSelectIram ephemeral;
umm_info(NULL, true);
break;
}
case 'h': {
{
HeapSelectIram ephemeral;
Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap());
}
{
HeapSelectDram ephemeral;
Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap());
}
break;
}
#ifdef DEBUG_ESP_PORT
// From this context stack_thunk_dump_stack() will only work when Serial
// debug is enabled.
case 'p':
out.println(F("Calling stack_thunk_dump_stack();"));
stack_thunk_dump_stack();
break;
#endif
case 'R':
out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n"));
ESP.restart();
break;
case '\r':
out.println();
case '\n':
break;
case '?':
out.println();
out.println(F("Press a key + <enter>"));
out.println(F(" h - Free Heap Report;"));
out.println(F(" i - iRAM umm_info(null, true);"));
out.println(F(" d - dRAM umm_info(null, true);"));
#ifdef DEBUG_ESP_PORT
out.println(F(" p - call stack_thunk_dump_stack();"));
#endif
out.println(F(" R - Restart, ESP.restart();"));
out.println(F(" ? - Print Help"));
out.println();
break;
default:
out.printf_P(PSTR("\"%c\" - Not an option? / ? - help"), hotKey);
out.println();
processKey(out, '?');
break;
}
}
void loop(void){
server.handleClient();
MDNS.update();
if (Serial.available() > 0) {
int hotKey = Serial.read();
processKey(Serial, hotKey);
}
}

Related

MH-z19 giving -1 value after some time

I'm trying make an mqtt co2 sensor for home assistant. And I got it to work, but only for a couple of hours. At some point it starts giving me -1 values instead of the proper co2 value. What could this be?
Below my code:
#include <Arduino.h>
#include <Mhz19.h>
#include <SoftwareSerial.h>
SoftwareSerial softwareSerial(D3, D4);
Mhz19 sensor;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ID";
const char* password = "pw";
const char* MQTT_BROKER = "192.168.1.25";//"test.mosquitto.org";
int mqttPort = 1883;
const char* mqttUser ="mqtt-user";
const char* mqttPassword ="pw";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("Connected to Wi-Fi");
}
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("Test1", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed MQTT connection with state: ");
Serial.println(client.state());
// Re-try in 3 seconds
delay(3000);
}
}
// Once connected, publish an announcement, and subscribe
client.publish("sensor/test", "Hello from ...");
client.subscribe("sensor/test");
}
void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi network
client.setServer(MQTT_BROKER, mqttPort);
//client.setCallback(callback);
reconnect(); // Connect to MQTT broker
softwareSerial.begin(9600);
sensor.begin(&softwareSerial);
sensor.setMeasuringRange(Mhz19MeasuringRange::Ppm_5000);
sensor.enableAutoBaseCalibration();
Serial.println("Preheating..."); // Preheating, 3 minutes
while (!sensor.isReady()) {
delay(50);
}
Serial.println("Sensor Ready...");
}
void loop() {
if (!client.connected()) { reconnect(); }
//client.publish("Time", ctime(&now));
auto carbonDioxide = sensor.getCarbonDioxide();
if (carbonDioxide >= 0) {
Serial.println(String(carbonDioxide) + " ppm");
}
char co2String[8];
dtostrf(carbonDioxide, 1,0, co2String);
//Serial.println(co2String);
client.publish("Floating/climate/CO2", co2String);
delay(2000);
}
I also tried flashing it via ESPHome, but then I run into issues from UART. The chip doesn't work propperly as long as the sensor is connected to it.
The sensor may not be receiving enough current. Try connecting the sensor directly to a separate breadboard power supply. The sensor seems to have a warm up time. Try waiting for longer with the independent power supply connected. I hope this will solve your issue.
Thank You,
Naveen PS

ESP8266 is not getting connected to my deployed websocket on heroku

I have deployed a nodejs websocket on heroku. But my ESP8266 cannot get connected to that websocket. Before deploying that websocket on heroku, i tried it out locally and it worked pretty well. ESP8266 also got connected to it without any error. Then I made some changes in nodejs socket (before deploying) in order to run it on heroku. i just don't understand what's wrong with this esp8266 code
ESP8266's Code
#include <ESP8266WiFi.h>
#include <WebSocketClient.h>
boolean handshakeFailed = 0;
String data = "";
char path[] = "/"; //identifier of this device
const char *ssid = ""; //<-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
const char *password = ""; // <-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
char *host = "example.herokuapp.com"; //replace this ip address with the ip address of your Node.Js server
const int espport = 3000;
WebSocketClient webSocketClient;
unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long interval = 300; //interval for sending data to the websocket server in ms
// Use WiFiClient class to create TCP connections
WiFiClient client;
void setup()
{
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(1000);
wsconnect();
// wifi_set_sleep_type(LIGHT_SLEEP_T);
}
void loop()
{
if (client.connected())
{
currentMillis = millis();
webSocketClient.getData(data);
if (data.length() > 0)
{
Serial.println(data);
//*************send log data to server in certain interval************************************
//currentMillis=millis();
if (abs(currentMillis - previousMillis) >= interval)
{
previousMillis = currentMillis;
data = (String)analogRead(A0); //read adc values, this will give random value, since no sensor is connected.
//For this project we are pretending that these random values are sensor values
webSocketClient.sendData(data); //send sensor data to websocket server
}
}
else
{
}
delay(5);
}
}
void wsconnect()
{
// Connect to the websocket server
if (client.connect(host, espport))
{
Serial.println("WebSocket Connected");
}
else
{
Serial.println("Connection failed.");
delay(1000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
// Handshake with the server
webSocketClient.path = path;
webSocketClient.host = host;
if (webSocketClient.handshake(client))
{
Serial.println("Handshake successful");
}
else
{
Serial.println("Handshake failed.");
delay(4000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
}

Cannot set hostname for ESP8266

I am facing a problem, as setting host name for my ESP8266 is not working. Even though when I'm trying to connect through default host name "ESP_xxxx", it's not working.
Actually when I upload my code with my mobile hotspot SSID and password then it's working fine, but as soon as I gave the SSID and password of my router then it's not working.
Here's my code (setup part):
#include <ESP8266WiFi.h>
const char* ssid = "xxxxxx";
const char* password = "xxxxxx";
int ledPin = 13; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.hostname("xyz");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println(WiFi.hostname());
}
Try this:
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h" //https://github.com/tzapu/WiFiManager
void configModeCallback (WiFiManager *myWiFiManager)
{
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
Serial.println(myWiFiManager->getConfigPortalSSID());
}
//
void setup()
{
Serial.begin(115200);
//
WiFiManager wifiManager;
WiFi.hostname("myhostname");
//
//wifiManager.resetSettings();
//
//
wifiManager.setAPCallback(configModeCallback);
if (!wifiManager.autoConnect("myhostname"))
{
Serial.println("failed to connect and hit timeout");
// reset
ESP.reset();
delay(1000);
}
//
Serial.println("connected...yeey :)");
}
void loop()
{
//
}
Stumbled upon this issue and below is the code which works for me.
WiFi.disconnect(true);
WiFi.begin(ssid, password);
WiFi.setHostname(device);`
Also came across below code, with this line the module is not receiving any IP. Hence deleted it.
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
Running on Arduino 1.8.15 and esp8266 board version 3.0.1
Try using mDNS instead.
Include the mDNS library
#include <ESP8266mDNS.h>
Then in the setup after you connected to WiFi, start mDNS like this.
if (!MDNS.begin("your-desired-hostname")) {
Serial.println("Error setting up MDNS responder!");
}

Http get request using Arduino and Azure mobile services

I have hooked up my arduino with Azure mobile services and http post request is working fine where I am able to send data from sensor. But when using a http get request to access data from the tables, I am landing up with this data whereas I should be getting a json data in the Serial Window.
X-cache-Lookup: MISS from Webmaster:8080
Here is the code that is on my Arduino. I have no idea where I am wrong.
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>
#define RESPONSE_JSON_DATA_LINENNO 10
// Ethernet shield MAC address (sticker in the back)
byte mac[] = { 0xA4, 0x5D, 0x36, 0x6A, 0xE1, 0xE1 };
int qq=0;
const char* server= "avirup.azure-mobile.net";
const char* table_name= "iottest";
const char* ams_key="rkIEUqVlFrgtmqNeMmaamgUQywwMjE42";
char stat;
EthernetClient client;
char fin='0';
char buffer[64];
int charIndex=0;
StaticJsonBuffer<200> jsonbuffer;
void send_request()
{
Serial.println("\nconnecting...");
if (client.connect(server, 80)) {
Serial.print("sending ");
// GET URI
sprintf(buffer, "GET /tables/%s HTTP/1.1", table_name);
Serial.println(buffer);
client.println(buffer);
// Host header
sprintf(buffer, "Host: %s", server);
client.println(buffer);
// Azure Mobile Services application key
sprintf(buffer, "X-ZUMO-APPLICATION: %s", ams_key);
client.println(buffer);
// JSON content type
client.println("Content-Type: application/json");
//POST body
sprintf(buffer, "", "");
//Content length
client.print("Content-Length: ");
client.println(strlen(buffer));
Serial.print("Content length: ");
Serial.println(strlen(buffer));
// End of headers
client.println();
// Request body
client.println(buffer);
}
else {
Serial.
println("connection failed");
}
}
/*
** Wait for response
*/
void wait_response()
{
while (!client.available()) {
if (!client.connected()) {
return;
}
}
}
/*
** Read the response and dump to serial
*/
// Read the response and dump to serial
void read_response()
{
int jsonStringLength;
int jsonBufferCntr=0;
int numline=RESPONSE_JSON_DATA_LINENNO;
//Ignore the response except for the 10th line
while (client.available()) {
char c = client.read();
if (c == '\n')
{
numline -=1;
}
else
{
if (numline == 0 )
{
//Capture the 10th line in the response
//To do: Could be more deterministic about this:
// Expect certain content, checks and balances etc.
buffer[jsonBufferCntr++] = c;
buffer[jsonBufferCntr] = '\0';
}
}
}
Serial.println("Received:");
Serial.println(buffer);
Serial.println("");
}
/*
** Close the connection
*/
void parse()
{
//char json[] = "{\"id\":\"34CCC60D-15D2-4B53-AB8E-FF3745FDC945\",\"control\":1}";
JsonObject& root = jsonbuffer.parseObject(buffer);
if(!root.success())
{
Serial.println("PARSING FAILED!!!");
return;
}
//fin= root["control"][0];
int f= root["control"][0];
Serial.println("Decoded: ");
Serial.println(f);
}
void end_request()
{
client.stop();
}
/*
** Arduino Setup
*/
void setup()
{
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
if (Ethernet.begin(mac) == 0) {
Serial.println("ethernet failed");
for (;;) ;
}
// give the Ethernet shield a second to initialize:
delay(1000);
}
/*
** Arduino Loop
*/
void loop()
{
send_request();
wait_response();
read_response();
end_request();
delay(1000);
}

Unexpected String when using BlueMix's Node-RED editor and MQTT->Debug Node

I'm following this tutorial,
http://energia.nu/creating-an-iot-connected-sensor-with-energia-mqtt/
I see the pushed data, but the Node-RED editor constantly prints 'Hello World #XX'. I don't see anything in the code that would suggest where its coming from:
#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h> //only required if using an MCU LaunchPad + CC3100 BoosterPack. Not needed for CC3200 LaunchPad
WiFiClient wclient;
byte server[] = { 198, 41, 30, 241 }; // Public MQTT Brokers: http://mqtt.org/wiki/doku.php/public_brokers
byte ip[] = { 172, 16, 0, 100 };
char sensorRead[4];
#define WIFI_SSID "SSID"
#define WIFI_PWD "WIFIPASSWORD"
PubSubClient client(server, 1883, callback, wclient);
void callback(char* inTopic, byte* payload, unsigned int length){
// Handle callback here
}
void setup()
{
//Initialize serial and wait for port to open:
Serial.begin(115200);
Serial.println("Start WiFi");
WiFi.begin(WIFI_SSID, WIFI_PWD);
while(WiFi.localIP() == INADDR_NONE) {
Serial.print(".");
delay(300);
}
Serial.println("");
printWifiStatus();
}
void loop()
{
// read the input on analog pin:
int sensorValue = analogRead(24);
Serial.println(sensorValue);
// convert into to char array
String str = (String)sensorValue;
int str_len = str.length() + 1; // Length (with one extra character for the null terminator)
char char_array[str_len]; // Prepare the character array (the buffer)
str.toCharArray(char_array, str_len); // Copy it over
// publish data to MQTT broker
if (client.connect("LaunchPadClient")) {
client.publish("outTopic", char_array);
//client.subscribe("inTopic");
Serial.println("Publishing successful!");
client.disconnect();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
Is this because this is a free/trial account? Incidentally, it shows I'm using 512MB/2GB, which seems high... does it include the data sent, or is 512MB just the application size?
You are using a MQTT broker that is public to the world, anybody can publish data to any topic on that broker. The messages are probably coming from somebody else doing similar experiments to yourself.
outTopic is the sort of topic name that many people could be using to test, try changing it to some random string in both the publishing code and the MQTT In node in Node-RED.
As for the size in Bluemix, this is how much memory is assigned to your application, it is unlikely to be actually using anything near that amount at the moment.

Resources