Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
iot manager thingspeak arduino ota and ICSC
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <SimpleTimer.h>
#include <ICSC.h>
#include <ArduinoOTA.h>
#include <FS.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <OneWire.h>
#include <DallasTemperature.h>
const uint16_t aport = 23; // standard port
WiFiServer TelnetServer(aport);
WiFiClient TelnetClient;
ICSC icsc(Serial, 2);
SimpleTimer timer;
#define ONE_WIRE_BUS D5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
DeviceAddress sensor4 = {0x28, 0xFF, 0x59, 0xD1, 0x64, 0x15, 0x01, 0xD6};
String API_KEY = " ";
const char* SERVERTHING = "api.thingspeak.com";
String TEMP;
String datawire[15];
String datawiret[15];
String inputsrt;
float Told = 0;
int rangetempt = 0;
int rangetemps = 0;
float Temperature = 0;
float Temperatureold = 0;
int w1 = 0;
int w2 = 0;
int w3 = 0;
int w4 = 0;
byte ttemp = 2;
byte stemp = 4;
int ledboil=0;
int ledturbo=0;
int ledservo=0;
int lednasos=0;
const int interval = 30; // 10 минут
int tm=interval;
String sendwire;
const char *ssid = " "; // cannot be longer than 32 characters!
const char *pass = " "; // WiFi password
String prefix = "/IoTmanager"; // global prefix for all topics - must be some as mobile device
String deviceID = "dev01"; // thing ID - unique device id in our project
WiFiClient clientthing;
WiFiClient wclient;
// config for cloud mqtt broker by DNS hostname ( for example, cloudmqtt.com use: m20.cloudmqtt.com - EU, m11.cloudmqtt.com - USA )
String mqttServerName = "m20.cloudmqtt.com"; // for cloud broker - by hostname, from CloudMQTT account data
int mqttport = ; // default 1883, but CloudMQTT.com use other, for example: 13191, 23191 (SSL), 33191 (WebSockets) - use from CloudMQTT account data
String mqttuser = " "; // from CloudMQTT account data
String mqttpass = " "; // from CloudMQTT account data
PubSubClient client(wclient, mqttServerName, mqttport); // for cloud broker - by hostname
String val;
String ids = "";
int newValue, newtime, oldtime, freeheap;
const int nWidgets = 12;
String sTopic [nWidgets];
String stat [nWidgets];
int pin [nWidgets];
String thing_config[nWidgets];
StaticJsonBuffer<8024> jsonBuffer;
JsonObject& json_status = jsonBuffer.createObject();
String string_status;
void FreeHEAP() {
if ( ESP.getFreeHeap() < freeheap ) {
if ( ( freeheap != 100000) ) {
TelnetClient.print("Memory leak detected! old free heap = ");
TelnetClient.print(freeheap);
TelnetClient.print(", new value = ");
TelnetClient.println(ESP.getFreeHeap());
}
freeheap = ESP.getFreeHeap();
}
}
void thingsent()
{
if (clientthing.connect(SERVERTHING, 80)) {
//
// float t = Temperature;
// String t=Temperature;
String TEMP = "field1=" + String(datawire[1])+"&field2=" + String(datawire[2])+"&field3=" + String(datawire[3])+"&field4=" + String(datawire[8])+"&field5=" + String(datawire[9])+"&field7=" + String(Temperature);
//
clientthing.print("POST /update HTTP/1.1\n");
clientthing.print("Host: api.thingspeak.com\n");
clientthing.print("Connection: close\n");
clientthing.print("X-THINGSPEAKAPIKEY: " + API_KEY + "\n");
clientthing.print("Content-Type: application/x-www-form-urlencoded\n");
clientthing.print("Content-Length: ");
clientthing.print(TEMP.length());
clientthing.print("\n\n");
clientthing.print(TEMP);
// DEBUG SERIAL
// TelnetClient.print("Value: ");
// TelnetClient.println(TEMP);
if (TelnetClient.connected()) {
TelnetClient.print("Value: ");
TelnetClient.println(TEMP);
}
}
clientthing.stop();
}
String setStatus ( String s ) {
json_status["status"] = s;
string_status = "";
json_status.printTo(string_status);
return string_status;
}
String setStatus ( int s ) {
json_status["status"] = s;
string_status = "";
json_status.printTo(string_status);
return string_status;
}
void initVar() {
// pin [0] = A0; // ADC
sTopic[0] = prefix + "/" + deviceID + "/tb";
stat [0] = setStatus (0);
sTopic[1] = prefix + "/" + deviceID + "/tkotel";
stat [1] = setStatus (0);
sTopic[2] = prefix + "/" + deviceID + "/tobr";
stat [2] = setStatus (0);
sTopic[3] = prefix + "/" + deviceID + "/tturbo";
stat [3] = setStatus (0);
sTopic[4] = prefix + "/" + deviceID + "/tservo";
stat [4] = setStatus (0);
sTopic[5] = prefix + "/" + deviceID + "/lboil";
stat [5] = setStatus (0);
sTopic[6] = prefix + "/" + deviceID + "/lturbo";
stat [6] = setStatus (0);
sTopic[7] = prefix + "/" + deviceID + "/lservo";
stat [7] = setStatus (0);
sTopic[8] = prefix + "/" + deviceID + "/dturbo";
stat [8] = setStatus (0);
sTopic[9] = prefix + "/" + deviceID + "/dservo";
stat [9] = setStatus (0);
sTopic[10] = prefix + "/" + deviceID + "/ee";
stat [10] = setStatus (0);
sTopic[11] = prefix + "/" + deviceID + "/mytemp";
stat [11] = setStatus (0);
JsonObject& root1 = jsonBuffer.createObject();
JsonObject& root2 = jsonBuffer.createObject();
JsonObject& root3 = jsonBuffer.createObject();
JsonObject& root4 = jsonBuffer.createObject();
JsonObject& root5 = jsonBuffer.createObject();
JsonObject& root6 = jsonBuffer.createObject();
JsonObject& root7 = jsonBuffer.createObject();
JsonObject& root8 = jsonBuffer.createObject();
JsonObject& root9 = jsonBuffer.createObject();
JsonObject& root10 = jsonBuffer.createObject();
JsonObject& root11 = jsonBuffer.createObject();
JsonObject& root12 = jsonBuffer.createObject();
JsonObject& cfg = jsonBuffer.createObject();
root2["id"] = 0;
root2["page"] = "Kotel";
root2["widget"] = "display-value";
root2["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root2["style1"] = ""; // style for 1st div
root2["descr"] = "Котел"; // text for description
root2["class2"] = "assertive"; // class for description from Widgets Guide - Color classes
root2["style2"] = "font-size:20px;padding-top:6px;padding-bottom:3px;font-weight:bold;"; // style for description
root2["topic"] = sTopic[1];
root2["class3"] = ""; // class for 3 div - SVG
root2["style3"] = "float:center;"; // style for 3 div - SVG
root2["height"] = "26"; // SVG height without "px"
root2["color"] = "#FF0000"; // color for active segments
root2["inactive_color"] = "#414141"; // color for inactive segments
root2["digits_count"] = 4; // how many digits
root2.printTo(thing_config[1]);
root12["id"] = 1;
root12["page"] = "Kotel";
root12["widget"] = "display-value";
root12["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root12["style1"] = ""; // style for 1st div
root12["descr"] = "Спальня"; // text for description
root12["class2"] = "stable"; // class for description from Widgets Guide - Color classes
root12["style2"] = "font-size:20px;padding-top:6px;padding-bottom:3px;font-weight:bold;"; // style for description
root12["topic"] = sTopic[11];
root12["class3"] = ""; // class for 3 div - SVG
root12["style3"] = "float:center;"; // style for 3 div - SVG
root12["height"] = "26"; // SVG height without "px"
root12["color"] = "#FFFFFF"; // color for active segments
root12["inactive_color"] = "#414141"; // color for inactive segments
root12["digits_count"] = 4; // how many digits
root12.printTo(thing_config[11]);
root1["id"] = 2;
root1["page"] = "Kotel";
root1["widget"] = "display-value";
root1["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root1["style1"] = ""; // style for 1st div
root1["descr"] = "Бойлер"; // text for description
root1["class2"] = "calm"; // class for description from Widgets Guide - Color classes
root1["style2"] = "font-size:18px;padding-top:5px;padding-bottom:3px;font-weight:bold;"; // style for description
root1["topic"] = sTopic[0];
root1["class3"] = ""; // class for 3 div - SVG
root1["style3"] = "float:center;"; // style for 3 div - SVG
root1["height"] = "16"; // SVG height without "px"
root1["color"] = "#55B1FC"; // color for active segments
root1["inactive_color"] = "#414141"; // color for inactive segments
root1["digits_count"] = 4; // how many digits
root1.printTo(thing_config[0]);
root3["id"] = 3;
root3["page"] = "Kotel";
root3["widget"] = "display-value";
root3["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root3["style1"] = ""; // style for 1st div
root3["descr"] = "Обратка"; // text for description
root3["class2"] = "balanced"; // class for description from Widgets Guide - Color classes
root3["style2"] = "font-size:18px;padding-top:5px;padding-bottom:3px;font-weight:bold;"; // style for description
root3["topic"] = sTopic[2];
root3["class3"] = ""; // class for 3 div - SVG
root3["style3"] = "float:center;"; // style for 3 div - SVG
root3["height"] = "16"; // SVG height without "px"
root3["color"] = "#45F32E"; // color for active segments
root3["inactive_color"] = "#414141"; // color for inactive segments
root3["digits_count"] = 4; // how many digits
root3.printTo(thing_config[2]);
root4["id"] = 4;
root4["page"] = "Kotel";
root4["widget"] = "display-value";
root4["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root4["style1"] = ""; // style for 1st div
root4["descr"] = "Турбо"; // text for description
root4["class2"] = "energized"; // class for description from Widgets Guide - Color classes
root4["style2"] = "font-size:18px;padding-top:5px;padding-bottom:3px;font-weight:bold;"; // style for description
root4["topic"] = sTopic[3];
root4["class3"] = ""; // class for 3 div - SVG
root4["style3"] = "float:center;"; // style for 3 div - SVG
root4["height"] = "25"; // SVG height without "px"
root4["color"] = "#FFB215"; // color for active segments
root4["inactive_color"] = "#414141"; // color for inactive segments
root4["digits_count"] = 2; // how many digits
root4.printTo(thing_config[3]);
root5["id"] = 5;
root5["page"] = "Kotel";
root5["widget"] = "display-value";
root5["class1"] = "no-border text-center col-xs-6"; // class for 1st div
root5["style1"] = ""; // style for 1st div
root5["descr"] = "Серво"; // text for description
root5["class2"] = "assertive"; // class for description from Widgets Guide - Color classes
root5["style2"] = "font-size:18px;padding-top:5px;padding-bottom:3px;font-weight:bold;"; // style for description
root5["topic"] = sTopic[4];
root5["class3"] = ""; // class for 3 div - SVG
root5["style3"] = "float:center;"; // style for 3 div - SVG
root5["height"] = "25"; // SVG height without "px"
root5["color"] = "#FF3535"; // color for active segments
root5["inactive_color"] = "#414141"; // color for inactive segments
root5["digits_count"] = 2; // how many digits
root5.printTo(thing_config[4]);
root6["id"] = 6;
root6["page"] = "Kotel";
root6["widget"] = "toggle";
root6["descr"] = "boil"; // text for description
root6["topic"] = sTopic[5];
root6["color"] ="blue";
root6["defaultVal"] =0;
root6.printTo(thing_config[5]);
root7["id"] = 7;
root7["page"] = "Kotel";
root7["widget"] = "toggle";
root7["descr"] = "turbo"; // text for description
root7["topic"] = sTopic[6];
root7["color"] ="red";
root7["defaultVal"] =0;
root7.printTo(thing_config[6]);
root8["id"] = 8;
root8["page"] = "Kotel";
root8["widget"] = "toggle";
root8["descr"] = "servo"; // text for description
root8["topic"] = sTopic[7];
root8["color"] ="yellow";
root8["defaultVal"] =0;
root8.printTo(thing_config[7]);
root9["id"] = 9;
root9["page"] = "Kotel";
root9["widget"] = "range";
root9["descr"] = "turbo"; // text for description
root9["topic"] = sTopic[8];
root9["color"] ="yellow";
root9["defaultVal"] =0;
root9["style"] ="range-calm";
root9["badge"] ="badge-assertive";
root9.printTo(thing_config[8]);
root10["id"] = 91;
root10["page"] = "Kotel";
root10["widget"] = "range";
root10["descr"] = "servo"; // text for description
root10["topic"] = sTopic[9];
root10["color"] ="yellow";
root10["defaultVal"] =0;
root10["style"] ="range-calm";
root10["badge"] ="badge-assertive";
root10.printTo(thing_config[9]);
root11["id"] = 92;
root11["page"] = "Kotel";
root11["widget"] = "toggle";
root11["descr"] = "Записать"; // text for description
root11["topic"] = sTopic[10];
root11["color"] ="blue";
root11["defaultVal"] =0;
root11.printTo(thing_config[10]);
}
void pubStatus(String t, String payload) {
if (client.publish(t + "/status", payload)) {
TelnetClient.println("Publish new status for " + t + ", value: " + payload);
} else {
TelnetClient.println("Publish new status for " + t + " FAIL!");
}
FreeHEAP();
}
void pubConfig() {
bool success;
success = client.publish(MQTT::Publish(prefix, deviceID).set_qos(1));
if (success) {
delay(500);
for (int i = 0; i < nWidgets; i = i + 1) {
success = client.publish(MQTT::Publish(prefix + "/" + deviceID + "/config", thing_config[i]).set_qos(1));
if (success) {
TelnetClient.println("Publish config: Success (" + thing_config[i] + ")");
} else {
TelnetClient.println("Publish config FAIL! (" + thing_config[i] + ")");
}
delay(150);
}
}
if (success) {
TelnetClient.println("Publish config: Success");
} else {
TelnetClient.println("Publish config: FAIL");
}
stat[0] = setStatus( 1 );
stat[1] = setStatus( 1 );
stat[2] = setStatus( 1 );
stat[3] = setStatus( 1 );
stat[4] = setStatus( 1 );
stat[5] = setStatus( 1 );
stat[6] = setStatus( 1 );
stat[7] = setStatus( 1 );
//stat[8] = setStatus( 1 );
//stat[9] = setStatus( 1 );
stat[11] = setStatus( 1 );
for (int i = 0; i < nWidgets; i = i + 1) {
pubStatus(sTopic[i], stat[i]);
delay(100);
}
}
void callback(const MQTT::Publish& sub) {
TelnetClient.print("Get data from subscribed topic ");
TelnetClient.print(sub.topic());
TelnetClient.print(" => ");
TelnetClient.println(sub.payload_string());
if (sub.topic() == sTopic[8] + "/control") {
String x = sub.payload_string();
rangetempt=x.toInt();
stat[8] = setStatus(x);
pubStatus(sTopic[8], stat[8]);
}
else if (sub.topic() == sTopic[9] + "/control") {
String x = sub.payload_string();
rangetemps=x.toInt();
stat[9] = setStatus(x);
pubStatus(sTopic[9], stat[9]);
}
else if (sub.topic() == sTopic[10] + "/control") {
if (sub.payload_string() == "1") {
w3 = 1; // inverted
stat[10] = setStatus(String(w3));
} else {
w3 = 0;
stat[10] = setStatus(String(w3));
}
pubStatus(sTopic[10], stat[10]);
}
else if (sub.topic() == prefix + "/ids") {
ids = sub.payload_string();
}
if ( sub.payload_string() == "HELLO" ) { // handshaking
pubConfig();
}
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void pressed(unsigned char src, char command, unsigned char len, char *data)
{
// TelnetClient.println(data);
inputsrt=String(data);
for(int i=0;i<=10;i++){
datawire[i]=getValue(inputsrt, ':', i);
// TelnetClient.println(datawire[i]);
ledboil=datawire[4].toInt();
ledturbo=datawire[5].toInt();
lednasos=datawire[6].toInt();
ledservo=datawire[7].toInt();
}
}
void senditoc()
{
if (rangetempt<100)
{
w1=0;
}
else if (rangetempt>100 && rangetempt<200)
{
w1=1;
}
else if (rangetempt>200 && rangetempt<300)
{
w1=2;
}
else if (rangetempt>300 && rangetempt<400)
{
w1=3;
}
else if (rangetempt>400 && rangetempt<500)
{
w1=4;
}
else if (rangetempt>500 && rangetempt<600)
{
w1=5;
}
else if (rangetempt>600 && rangetempt<700)
{
w1=6;
}
else if (rangetempt>700 && rangetempt<800)
{
w1=-1;
}
else if (rangetempt>800 && rangetempt<900)
{
w1=-2;
}
else if (rangetempt>900 )
{
w1=-3;
}
if (rangetemps<100)
{
w2=0;
}
else if (rangetemps>100 && rangetemps<200)
{
w2=1;
}
else if (rangetemps>200 && rangetemps<300)
{
w2=2;
}
else if (rangetemps>300 && rangetemps<400)
{
w2=3;
}
else if (rangetemps>400 && rangetemps<500)
{
w2=4;
}
else if (rangetemps>500 && rangetemps<600)
{
w2=5;
}
else if (rangetemps>600 && rangetemps<700)
{
w2=6;
}
else if (rangetemps>700 && rangetemps<800)
{
w2=-1;
}
else if (rangetemps>800 && rangetemps<900)
{
w2=-2;
}
else if (rangetemps>900 )
{
w2=-3;
}
String sendwire= ":"+ String(w1)+ ":"+ String(w2)+ ":"+ String(w3)+ ":"+ String(w4)+ ":"+ String(ttemp)+ ":"+ String(stemp)+ ":";
char charBuf[100];
sendwire.toCharArray(charBuf, 100);
icsc.send(1, 'R', charBuf);
// icsc.broadcast('R', 1, (char *)&charBuf);
TelnetClient.println(sendwire);
if(w3==1)
{
w3 = 0;
stat[10] = setStatus(String(w3));
pubStatus(sTopic[10], stat[10]);
}
}
void iotloop()
{
DS18B20.requestTemperatures();
Temperature = DS18B20.getTempC(sensor4);
if (client.connected()) {
stat[0] = setStatus( datawire[1] );
pubStatus(sTopic[0], stat[0] ); ;
stat[1] = setStatus(datawire[2] );
pubStatus(sTopic[1], stat[1] );
stat[2] = setStatus( datawire[3] );
pubStatus(sTopic[2], stat[2] );
stat[3] = setStatus( datawire[8] );
pubStatus(sTopic[3], stat[3] );
stat[4] = setStatus( datawire[9] );
pubStatus(sTopic[4], stat[4] );
stat[5] = setStatus(datawire[4] );
pubStatus(sTopic[5], stat[5] );
stat[6] = setStatus(datawire[5] );
pubStatus(sTopic[6], stat[6] );
stat[7] = setStatus( datawire[7] );
pubStatus(sTopic[7], stat[7] );
stat[11] = setStatus( String(Temperature) );
pubStatus(sTopic[11], stat[11] );
}
}
void iotreboot()
{
ESP.restart();
}
void pau()
{
tm--;
TelnetClient.print("timer-");
TelnetClient.println(tm);
if (tm<0)
{
tm=30;
}
}
void setup() {
timer.setInterval(29000L, thingsent);
timer.setInterval(10000L, senditoc);
timer.setInterval(10000L, iotloop);
timer.setInterval(600000L, iotreboot);
timer.setInterval(5000L, pau);
DS18B20.begin();
DS18B20.setResolution(sensor4, 12);
DS18B20.setWaitForConversion(false);
DS18B20.requestTemperatures();
WiFi.mode(WIFI_STA);
initVar();
oldtime = 0;
Serial.begin(115200);
delay(10);
TelnetClient.println();
TelnetClient.println();
TelnetClient.println("MQTT client started.");
FreeHEAP();
freeheap = 100000;
WiFi.disconnect();
WiFi.printDiag(Serial);
icsc.begin();
icsc.registerCommand('P', &pressed);
WiFi.begin(ssid, pass);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
ArduinoOTA.onStart([]() {
TelnetClient.println("Start");
});
ArduinoOTA.onEnd([]() {
TelnetClient.println("End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
TelnetClient.printf("Progress: %u%%\n", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
TelnetClient.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) TelnetClient.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) TelnetClient.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) TelnetClient.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) TelnetClient.println("Receive Failed");
else if (error == OTA_END_ERROR) TelnetClient.println("End Failed");
});
ArduinoOTA.begin();
TelnetClient.println("Ready");
TelnetClient.print("IP address: ");
TelnetClient.println(WiFi.localIP());
TelnetServer.begin();
TelnetServer.setNoDelay(true);
}
void loop() {
icsc.process();
timer.run();
// send info to Telnet
if (!TelnetClient) {
TelnetClient = TelnetServer.available();
if (TelnetClient.connected()) {
TelnetClient.println("Telnet 1");
}
}
if (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
return;
if(tm==0)
{
ESP.restart();
}
}
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
TelnetClient.println("Connecting to MQTT server ...");
bool success;
if (mqttuser.length() > 0) {
success = client.connect( MQTT::Connect( deviceID ).set_auth(mqttuser, mqttpass) );
} else {
success = client.connect( deviceID );
}
if (success) {
client.set_callback(callback);
TelnetClient.println("Connect to MQTT server: Success");
client.subscribe(prefix); // for receiving HELLO messages and handshaking
client.subscribe(sTopic[8] + "/control"); // for receiving messages
client.subscribe(sTopic[9] + "/control"); // for receiving messages
client.subscribe(sTopic[10] + "/control"); // for receiving messages
pubConfig();
} else {
TelnetClient.println("Connect to MQTT server: FAIL");
delay(1000);
if (tm==0)
{
ESP.restart();
}
}
}
if (client.connected()) {
/*
newtime = millis();
if (newtime - oldtime > 10000) { // read ADC and publish data every 10 sec
stat[0] = setStatus( 11 );
pubStatus(sTopic[0], stat[0] );
stat[1] = setStatus( "22" );
pubStatus(sTopic[1], stat[1] );
oldtime = newtime;
}
*/
client.loop();
}
}
// Handle OTA server.
ArduinoOTA.handle();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment