4refr0nt / iot-manager-demo

Demo sketches for IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
MIT License
66 stars 31 forks source link

use sim800 and iotmanager #29

Closed iranweld closed 4 years ago

iranweld commented 4 years ago

Hi

how its possible we use sim800 and esp8266 for MQTT by 4refr0nt projects

`#define TINY_GSM_MODEM_SIM800

// Set serial for debug console (to the Serial Monitor, default speed 115200)

// Set serial for AT commands (to the module) // Use Hardware Serial on Mega, Leonardo, Micro //#define SerialAT Serial1

// or Software Serial on Uno, Nano

define SerialMon Serial

include

include

include

SoftwareSerial SerialAT(8, 7); // RX, TX

// See all AT commands, if wanted //#define DUMP_AT_COMMANDS

// Define the serial console for debug prints, if needed

define TINY_GSM_DEBUG SerialMon

// Range to attempt to autobaud

define GSM_AUTOBAUD_MIN 9600

define GSM_AUTOBAUD_MAX 115200

// Add a reception delay - may be needed for a fast processor at a slow baud rate //#define TINY_GSM_YIELD() { delay(2); }

// Define how you're planning to connect to the internet

define TINY_GSM_USE_GPRS true

define TINY_GSM_USE_WIFI false

// set GSM PIN, if any

define GSM_PIN ""

// Your GPRS credentials, if any const char apn[] = "mtnirancell"; const char gprsUser[] = ""; const char gprsPass[] = "";

int r ;

const char* deviceid = "iot912560" ;

// Your WiFi connection credentials, if applicable const char wifiSSID[] = "YourSSID"; const char wifiPass[] = "YourWiFiPass";

// MQTT details const char* broker = "m12.cloudmqtt.com";

const char topicLed = "/IoTmanager/led"; const char topicInit = "/IoTmanager/init"; const char* topicLedStatus = "/IoTmanager/ledStatus";

// Just in case someone defined the wrong thing..

if TINY_GSM_USE_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS

undef TINY_GSM_USE_GPRS

undef TINY_GSM_USE_WIFI

define TINY_GSM_USE_GPRS false

define TINY_GSM_USE_WIFI true

endif

if TINY_GSM_USE_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI

undef TINY_GSM_USE_GPRS

undef TINY_GSM_USE_WIFI

define TINY_GSM_USE_GPRS true

define TINY_GSM_USE_WIFI false

endif

ifdef DUMP_AT_COMMANDS

include

StreamDebugger debugger(SerialAT, SerialMon); TinyGsm modem(debugger);

else

TinyGsm modem(SerialAT);

endif

TinyGsmClient client(modem); PubSubClient mqtt(client);

define LED_PIN 13

int ledStatus = LOW;

long lastReconnectAttempt = 0;

void mqttCallback(char topic, byte payload, unsigned int len) { SerialMon.print("Message arrived ["); SerialMon.print(topic); SerialMon.print("]: "); SerialMon.write(payload, len); SerialMon.println();

// Only proceed if incoming message's topic matches if (String(topic) == "/IoTmanager" ) { ledStatus = !ledStatus; digitalWrite(LED_PIN, ledStatus); mqtt.publish("/IoTmanager/iot912/status", "{\"status\":\"iot5814\"}"); } }

boolean mqttConnect() { SerialMon.print("Connecting to "); SerialMon.print(broker);

// Connect to MQTT Broker // boolean status = mqtt.connect("/IoTmanager");

// Or, if you want to authenticate MQTT: boolean status = mqtt.connect(deviceid, "test", "test");

if (status == false) { SerialMon.println(" fail"); return false; } SerialMon.println(" success"); mqtt.publish(topicInit, "/IoTmanager started"); mqtt.subscribe("/IoTmanager/#"); return mqtt.connected(); }

void setup() { // Set console baud rate SerialMon.begin(115200); delay(10);

pinMode(LED_PIN, OUTPUT);

// !!!!!!!!!!! // Set your reset, enable, power pins here // !!!!!!!!!!!

SerialMon.println("Wait...");

// Set GSM module baud rate // TinyGsmAutoBaud(SerialAT,GSM_AUTOBAUD_MIN,GSM_AUTOBAUD_MAX); SerialAT.begin(9600); delay(3000);

// Restart takes quite some time // To skip it, call init() instead of restart() SerialMon.println("Initializing modem..."); modem.restart(); // modem.init();

String modemInfo = modem.getModemInfo(); SerialMon.print("Modem Info: "); SerialMon.println(modemInfo);

if TINY_GSM_USE_GPRS

// Unlock your SIM card with a PIN if needed if ( GSM_PIN && modem.getSimStatus() != 3 ) { modem.simUnlock(GSM_PIN); }

endif

if TINY_GSM_USE_WIFI

// Wifi connection parameters must be set before waiting for the network

SerialMon.print(F("Setting SSID/password...")); if (!modem.networkConnect(wifiSSID, wifiPass)) { SerialMon.println(" fail"); delay(10000); return; } SerialMon.println(" success");

endif

if TINY_GSM_USE_GPRS && defined TINY_GSM_MODEM_XBEE

// The XBee must run the gprsConnect function BEFORE waiting for network! modem.gprsConnect(apn, gprsUser, gprsPass);

endif

SerialMon.print("Waiting for network..."); if (!modem.waitForNetwork()) { SerialMon.println(" fail"); delay(5000); return; } SerialMon.println(" success");

if (modem.isNetworkConnected()) { SerialMon.println("Network connected"); }

if TINY_GSM_USE_GPRS

// GPRS connection parameters are usually set after network registration SerialMon.print(F("Connecting to ")); SerialMon.print(apn); if (!modem.gprsConnect(apn, gprsUser, gprsPass)) { SerialMon.println(" fail"); delay(10000); return; } SerialMon.println(" success");

if (modem.isGprsConnected()) { SerialMon.println("GPRS connected"); }

endif

// MQTT Broker setup mqtt.setServer(broker, 10515); mqtt.setCallback(mqttCallback); }

void loop() {

if (!mqtt.connected()) { SerialMon.println("=== MQTT NOT CONNECTED ===");

r++;

if (r>=10 ){modem.restart();r=0;}
// Reconnect every 10 seconds
unsigned long t = millis();
if (t - lastReconnectAttempt > 10000L) {
  lastReconnectAttempt = t;
  if (mqttConnect()) {
    lastReconnectAttempt = 0;
  }
}
delay(100);
return;

}

mqtt.loop(); }`

4refr0nt commented 4 years ago

Hi! You must use topics with simple rule: prefix/device/widget, for example: /IoTmanager/sim800/led and publish config JSON to topic /IoTmanager/sim800/led/config once, after receiving HELLO message from mobile device from topic /IoTmanager. Then, you pubish only changed LED state to topic /IoTmanager/sim800/led/status -> {"status":'LED OFF'} You can see https://github.com/4refr0nt/iotmanager-heroku/blob/master/index.js#L50

iranweld commented 4 years ago

Hello Mr 4refr0nt

Thanks for your Answer And your nice MQTT projects

My problem is for use of your PubSubClient.h in project

http://uupload.ir/view/bre9_untitled.png

include

TinyGsmClient wclient(modem); //PubSubClient mqtt(client); PubSubClient client(wclient, mqttServerName, mqttport); // for cloud broker - by hostname

i get error for define in this line

PubSubClient client(wclient, mqttServerName, mqttport); // for cloud broker - by hostname

4refr0nt commented 4 years ago

For mqtt part (not for IoT Manager 2.0, its for IoT Manager 1.5) may be useful https://github.com/DmitryBorisenko33/esp8266_iot-manager_modules_firmware

iranweld commented 4 years ago

Hi Mr Victor

Thanks for your Answer My problem solved without change firmware. I first used Arduino UNO and sim800 , memory UNO is very low for this cod.

I sheared this cod for other people

don't forget use voltage divider for input TX from sim800 to ESP8266

<

define TINY_GSM_MODEM_SIM800

include

include

include

include

SoftwareSerial SerialAT(8, 7); // RX, TX

// Define the serial console for debug prints, if needed

define TINY_GSM_DEBUG Serial

// Range to attempt to autobaud

define GSM_AUTOBAUD_MIN 9600

define GSM_AUTOBAUD_MAX 115200

// Add a reception delay - may be needed for a fast processor at a slow baud rate //#define TINY_GSM_YIELD() { delay(2); }

// Define how you're planning to connect to the internet

define TINY_GSM_USE_GPRS true

define TINY_GSM_USE_WIFI false

// set GSM PIN, if any

define GSM_PIN ""

// Your GPRS credentials, if any const char apn[] = "mtn"; const char gprsUser[] = ""; const char gprsPass[] = "";

   // WiFi password

String prefix = "/IoTmanager"; // global prefix for all topics - must be some as mobile device //String deviceID = "dev03"; // thing ID - unique device id in our project String deviceID = "iot912"; //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 = "mxx.cloudmqtt.com"; // for cloud broker - by hostname, from CloudMQTT account data int mqttport = 10519; // default 1883, but CloudMQTT.com use other, for example: 13191, 23191 (SSL), 33191 (WebSockets) - use from CloudMQTT account data String mqttuser = "test"; // from CloudMQTT account data String mqttpass = "test";

// Just in case someone defined the wrong thing..

if TINY_GSM_USE_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS

undef TINY_GSM_USE_GPRS

undef TINY_GSM_USE_WIFI

define TINY_GSM_USE_GPRS false

define TINY_GSM_USE_WIFI true

endif

if TINY_GSM_USE_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI

undef TINY_GSM_USE_GPRS

undef TINY_GSM_USE_WIFI

define TINY_GSM_USE_GPRS true

define TINY_GSM_USE_WIFI false

endif

ifdef DUMP_AT_COMMANDS

include

StreamDebugger debugger(SerialAT, Serial); TinyGsm modem(debugger);

else

TinyGsm modem(SerialAT);

endif

TinyGsmClient wclient(modem); //PubSubClient mqtt(client);

define LED_PIN 13

int ledStatus = LOW;

long lastReconnectAttempt = 0;

// from CloudMQTT account data PubSubClient client(wclient, mqttServerName, mqttport); // for cloud broker - by hostname

String val; String ids = ""; int newValue, newtime, oldtime; int k=150;

const int nWidgets = 1; String sTopic [nWidgets]; String stat [nWidgets]; int pin [nWidgets]; String thing_config[nWidgets];

DynamicJsonBuffer jsonBuffer; //StaticJsonBuffer<1024> jsonBuffer; JsonObject& json_status = jsonBuffer.createObject();

String string_status;

String setStatus ( String s ) { String string_status = "{\"status\":\"" + s + "\"}"; return string_status; }

String setStatus ( int s ) { String string_status = "{\"status\":\"" + String(s) + "\"}"; return string_status; }

void initVar() {

pin [0] = A0; // ADC sTopic[0] = prefix + "/" + deviceID + "/ADC"; stat [0] = setStatus (0);

JsonObject& root = jsonBuffer.createObject(); JsonObject& cfg = jsonBuffer.createObject();

root["id"] = 1; root["page"] = "Water Level"; root["widget"] = "fillgauge"; root["class1"] = "no-border text-center"; // class for 1st div root["style1"] = ""; // style for 1st div root["descr"] = "Water level"; // text for description root["class2"] = "assertive text-center"; // class for description from http://ionicframework.com/docs/components/#colors root["style2"] = "font-size:20px;font-weight:bold;padding-bottom:10px;padding-top:10px;"; // style for description root["topic"] = sTopic[0]; root["width"] = "200px"; // SVG width root["height"] = "200px"; // SVG height root["class3"] = "text-center"; // class for 3 div - SVG root["style3"] = ""; // style for 3 div - SVG

// fillgauge SVG config details see http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6 cfg["circleThickness"] = 0.05; cfg["circleColor"] = "#FF7777"; cfg["textColor"] = "#FF4444"; cfg["waveTextColor"] = "#FFAAAA"; cfg["waveColor"] = "#FFDDDD"; cfg["textVertPosition"] = 0.2; cfg["waveAnimateTime"] = 1000; cfg["waveHeight"] = 0.05; cfg["waveAnimate"] = true; cfg["waveRise"] = true; cfg["waveHeightScaling"]= false; cfg["waveOffset"] = 0.25; cfg["textSize"] = 0.8; cfg["displayPercent"] = false; cfg["minValue"] = 0; cfg["maxValue"] = 1000; cfg["waveCount"] = 2;

root["widgetConfig"] = cfg; root.printTo(thing_config[1]); Serial.println(thing_config[1]); root["id"] = 2; root["page"] = "Water Level"; root["widget"] = "fillgauge"; root["class1"] = "no-border text-center"; // class for 1st div root["style1"] = ""; // style for 1st div root["descr"] = "fuel level"; // text for description root["class2"] = "assertive text-center"; // class for description from http://ionicframework.com/docs/components/#colors root["style2"] = "font-size:20px;font-weight:bold;padding-bottom:10px;padding-top:10px;"; // style for description root["topic"] = sTopic[0]; root["width"] = "200px"; // SVG width root["height"] = "200px"; // SVG height root["class3"] = "text-center"; // class for 3 div - SVG root["style3"] = ""; // style for 3 div - SVG

// fillgauge SVG config details see http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6 cfg["circleThickness"] = 0.05; cfg["circleColor"] = "#FF7777"; cfg["textColor"] = "#FF4444"; cfg["waveTextColor"] = "#FFAAAA"; cfg["waveColor"] = "#FFDDDD"; cfg["textVertPosition"] = 0.2; cfg["waveAnimateTime"] = 500; cfg["waveHeight"] = 0.05; cfg["waveAnimate"] = true; cfg["waveRise"] = true; cfg["waveHeightScaling"]= false; cfg["waveOffset"] = 0.5; cfg["textSize"] = 0.8; cfg["displayPercent"] = false; cfg["minValue"] = 0; cfg["maxValue"] = 1000; cfg["waveCount"] = 3;

root["widgetConfig"] = cfg; root.printTo(thing_config[2]); Serial.println(thing_config[2]);

root["id"] = 3; root["widget"] = "gauge"; root["topic"] = sTopic[0]; root["class1"] = "item no-border no-padding text-center"; root["descr"] = "maxValue 300";

cfg["type"]  = "semi";
cfg["size"]   = 300;
cfg["thick"]  = 20;
cfg["maximum"]= 300;
cfg["color"]  = "#11c1f3";
cfg["backgroundColor"]= "rgba(0,0,0, 0.2)";

root["widgetConfig"] = cfg; root.printTo(thing_config[3]); Serial.println(thing_config[3]);

thing_config[0] ="{\"id\":\"0\",\"page\":\"Water Level\",\"widget\":\"anydata\",\"topic\":\"/IoTmanager/Dom/calling\",\"descr\":\"IoTmanager\",\"class1\":\"text-center\",\"style1\":\"padding-top:10px;\",\"class2\":\"rounded\",\"style2\":\"background-color:blue;color:red;font-size:20px;font-weight:bold;padding:10px 0px;border:2px solid white;border-radius:15px;\",\"class3\":\"\",\"style3\":\"display:none;\"}"; }

void pubStatus(String t, String payload) {
if (client.publish(t + "/status", payload)) { Serial.println("Publish new status for " + t + ", value: " + payload); } else { Serial.println("Publish new status for " + t + " FAIL!"); }

} 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++) { success = client.publish(MQTT::Publish(prefix + "/" + deviceID + "/config", thing_config[i]).set_qos(1)); if (success) { Serial.println("Publish config: Success (" + thing_config[i] + ")"); } else { Serial.println("Publish config FAIL! (" + thing_config[i] + ")"); } delay(150); }

//success = client.publish(MQTT::Publish(prefix + "/" + deviceID + "/config", thing_config[2]).set_retain(0).set_qos(1)); } if (success) { Serial.println("Publish config: Success"); } else { Serial.println("Publish config: FAIL"); }

// nWidgets for (int i = 0; i < 2; i = i + 1) { pubStatus(sTopic[i], stat[i]); delay(100); }

} void callback(const MQTT::Publish& sub) { Serial.print("Get data from subscribed topic "); Serial.print(sub.topic()); Serial.print(" => "); Serial.println(sub.payload_string());

if ( sub.payload_string() == "HELLO" ) { // handshaking pubConfig(); } }

void setup() { // Set console baud rate Serial.begin(115200); delay(10);

pinMode(LED_PIN, OUTPUT);

// !!!!!!!!!!! // Set your reset, enable, power pins here // !!!!!!!!!!!

Serial.println("Wait...");

// Set GSM module baud rate // TinyGsmAutoBaud(SerialAT,GSM_AUTOBAUD_MIN,GSM_AUTOBAUD_MAX); SerialAT.begin(9600); delay(3000);

// Restart takes quite some time // To skip it, call init() instead of restart() Serial.println("Initializing modem..."); //modem.restart(); modem.init();

String modemInfo = modem.getModemInfo(); Serial.print("Modem Info: "); Serial.println(modemInfo);

if TINY_GSM_USE_GPRS

// Unlock your SIM card with a PIN if needed if ( GSM_PIN && modem.getSimStatus() != 3 ) { modem.simUnlock(GSM_PIN); }

endif

if TINY_GSM_USE_WIFI

// Wifi connection parameters must be set before waiting for the network

Serial.print(F("Setting SSID/password...")); if (!modem.networkConnect(wifiSSID, wifiPass)) { Serial.println(" fail"); delay(10000); return; } Serial.println(" success");

endif

if TINY_GSM_USE_GPRS && defined TINY_GSM_MODEM_XBEE

// The XBee must run the gprsConnect function BEFORE waiting for network! modem.gprsConnect(apn, gprsUser, gprsPass);

endif

Serial.print("Waiting for network..."); if (!modem.waitForNetwork()) { Serial.println(" fail"); delay(5000); return; } Serial.println(" success");

if (modem.isNetworkConnected()) { Serial.println("Network connected"); }

if TINY_GSM_USE_GPRS

// GPRS connection parameters are usually set after network registration Serial.print(F("Connecting to ")); Serial.print(apn); if (!modem.gprsConnect(apn, gprsUser, gprsPass)) { Serial.println(" fail"); delay(10000); return; } Serial.println(" success");

if (modem.isGprsConnected()) { Serial.println("GPRS connected"); }

endif

initVar();

oldtime = 0;

delay(10); Serial.println(); Serial.println(); Serial.println("MQTT client started.");

}

void loop() {

if (!client.connected()) {
  Serial.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);
    Serial.println("Connect to MQTT server: Success");
    client.subscribe(prefix); // for receiving HELLO messages and handshaking
    client.subscribe(prefix + "/" +  deviceID + "/#");
    pubConfig();
  } else {
    Serial.println("Connect to MQTT server: FAIL");   
    delay(1000);
    return;
  }

}

if (client.connected()) {
  client.loop();

        newtime = millis();
  if (newtime - oldtime > 10000) { // read ADC and publish data every 10 sec

    stat[0] = setStatus(  k );
    pubStatus(sTopic[0], stat[0] );
    k++;
     if (k>=1000) {k=500;}
    oldtime = newtime;
  }
}

}>