Брокер MQTT
Я про регистрацию ,а не брокера
так вроде пробовали работу каскады с есп через beebotte.com , работает ... А через наш брокер , ни как ,странно...ФЛпрог поддерживает каскаду , а брокер нет ...,значит он не совсем наш,имхоkramar писал(а): ↑02.01.2021{, 16:36}возможно потому чтоброкер общается стрингами поэтому каскаду не соединить друг с другом.
на beebotte.com также: делаешь кнопку-булеан, но приходит с брокера on-off, или тру-фолс. А каскада ждет 0-1 именно в числовом значении. а там стринг)))
Отправлено спустя 3 минуты 9 секунд:
щас все новые mqtt брокеры везде продвигают каждый свой api.
а мы то привкли к cloud.mqtt....
Так я вроде описал проблему в соответствующей ветке ... или что еще нужно для обращения к создателю ?
Спасибо ,глянуEvgesha писал(а): ↑02.01.2021{, 18:27}С нашим сервером связка с каскада работала, приема правда не добился
viewtopic.php?f=112&t=4141&p=94269&hili ... 800#p94269
Тут описывал
Вы наверное про сим800?. В каскаде же у вас работает и издатель и подписчик (сам на себя)Evgesha писал(а): ↑02.01.2021{, 18:27}С нашим сервером связка с каскада работала, приема правда не добился
viewtopic.php?f=112&t=4141&p=94269&hili ... 800#p94269
Тут описывал
C брокером всегда работают и издатель и подписчик . В том посте шел разговор про работу сим800 и каскада ,вроде
Код: Выделить всё
/**************************************************************
*
* For this example, you need to install PubSubClient library:
* https://github.com/knolleary/pubsubclient/releases/latest
* or from http://librarymanager/all#PubSubClient
*
* TinyGSM Getting Started guide:
* http://tiny.cc/tiny-gsm-readme
*
**************************************************************
* Use Mosquitto client tools to work with MQTT
* Ubuntu/Linux: sudo apt-get install mosquitto-clients
* Windows: https://mosquitto.org/download/
*
* Subscribe for messages:
* mosquitto_sub -h test.mosquitto.org -t GsmClientTest/init -t GsmClientTest/ledStatus -q 1
* Toggle led:
* mosquitto_pub -h test.mosquitto.org -t GsmClientTest/led -q 1 -m "toggle"
*
* You can use Node-RED for wiring together MQTT-enabled devices
* https://nodered.org/
* Also, take a look at these additional Node-RED modules:
* node-red-contrib-blynk-websockets
* node-red-dashboard
*
**************************************************************/
// Select your modem:
#define TINY_GSM_MODEM_SIM800
//#define TINY_GSM_MODEM_SIM900
//#define TINY_GSM_MODEM_A6
//#define TINY_GSM_MODEM_M590
#define ONE_WIRE_BUS 9
#include <TinyGsmClient.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
String MQTT_inputtext; //сообщение
// Your GPRS credentials
// Leave empty, if missing user or pass
int counter = 0;
const char apn[] = "internet.tele2.ru";
const char user[] = "";
const char pass[] = "";
const char cluser[] = "gmnSMc2uDHIjO8CCvf2IeY9UFtT4i0F8";
const char clpass[] = "";
const char clid[] = "fadaf737bb3e4b1f3a09878471b";
// Use Hardware Serial on Mega, Leonardo, Micro
//#define SerialAT Serial1
// or Software Serial on Uno, Nano
#include <SoftwareSerial.h>
SoftwareSerial SerialAT(7, 8); // RX, TX
TinyGsm modem(SerialAT);
TinyGsmClient client(modem);
PubSubClient mqtt(client);
const char* broker = "mqtt.beebotte.com";
const char* topicLed = "Led";
const char* topicInit = "Init";
const char* topicLedStatus = "LedStatus";
const char* temperature = "Temp/Data";
#define LED_PIN1 13
#define LED_PIN2 12
char* ledStatus1 ="Reset1";
char* ledStatus2 ="Reset2";
long lastReconnectAttempt = 0;
const long interval = 30000;
unsigned long previousMillis = 0;
char tempchar[6];
float temp;
void setup() {
sensors.begin();
pinMode(LED_PIN1, OUTPUT);
pinMode(LED_PIN2, OUTPUT);
// Set console baud rate
Serial.begin(115200);
delay(10);
// Set GSM module baud rate
SerialAT.begin(19200);
delay(3000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
Serial.println("Initializing modem...");
modem.restart();
// Unlock your SIM card with a PIN
//modem.simUnlock("1234");
Serial.print("Waiting for network...");
if (!modem.waitForNetwork()) {
Serial.println(" fail");
while (true);
}
Serial.println(" OK");
Serial.print("Connecting to ");
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass)) {
Serial.println(" fail");
while (true);
}
Serial.println(" OK");
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
}
boolean mqttConnect() {
Serial.print("Connecting to ");
Serial.print(broker);
if (!mqtt.connect(clid, cluser, clpass)) {
Serial.println(" fail");
return false;
}
Serial.println(" OK");
mqtt.publish(topicInit, "GsmClient started");
mqtt.subscribe(topicLed);
return mqtt.connected();
}
void loop() {
if (mqtt.connected()) {
mqtt.loop();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
sensors.requestTemperatures();
temp = sensors.getTempCByIndex(0);
dtostrf(temp, 3, 2, tempchar);//преобразуем float - char
String payload = "{\"data\":";
payload += tempchar;
payload += ",\"write\":true";
//payload += counter;
payload += "}";
Serial.println(payload);
mqtt.publish(temperature, (char*) payload.c_str());
}
} else {
// Reconnect every 10 seconds
unsigned long t = millis();
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
}
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
else if (!modem.gprsConnect(apn, user, pass)) {
while (true);
}
}
}
void mqttCallback(char* topic, byte* payload, unsigned int len) {
MQTT_inputtext = "";
for (int i=0;i<len;i++) {
MQTT_inputtext += (char)payload[i]; // составляем строку из байтов, которая пришла в параметрах топика
}
if (String(topic) == topicLed) {
if ((MQTT_inputtext) == "1on" ) {
digitalWrite(LED_PIN1, HIGH);
ledStatus1 = "Led 1 On";
mqtt.publish(topicLedStatus, ledStatus1 );
}
if ((MQTT_inputtext) == "1off" ) {
digitalWrite(LED_PIN1, LOW);
ledStatus1 = "Led 1 Off";
mqtt.publish(topicLedStatus, ledStatus1 );
}
//----------------------
if ((MQTT_inputtext) == "2on" ) {
digitalWrite(LED_PIN2, HIGH);
ledStatus2 = "Led 2 On";
mqtt.publish(topicLedStatus, ledStatus2 );
}
if ((MQTT_inputtext) == "2off" ) {
digitalWrite(LED_PIN2, LOW);
ledStatus2 = "Led 2 Off";
mqtt.publish(topicLedStatus, ledStatus2 );
}
//------------------
if ((MQTT_inputtext) == "stat" ) {
mqtt.publish(topicLedStatus, ledStatus1);
mqtt.publish(topicLedStatus, ledStatus2);
}
}
}
Да преобразования типов я уже сделал ...с помощью блоков Анатолия из Сургута . И прием данных из каскады(издатель) в есп(подписчик) сделал. А вот передача (издатель) есп и подписчик каскада ни как не идет .Anydy писал(а): ↑03.01.2021{, 10:53}Вот набросок делал -- там есть функции преобразования ....пробуйте ... надеюсь блок создать с одним маленьким преобразованием не проблема?Код: Выделить всё
/************************************************************** * * For this example, you need to install PubSubClient library: * https://github.com/knolleary/pubsubclient/releases/latest * or from http://librarymanager/all#PubSubClient * * TinyGSM Getting Started guide: * http://tiny.cc/tiny-gsm-readme * ************************************************************** * Use Mosquitto client tools to work with MQTT * Ubuntu/Linux: sudo apt-get install mosquitto-clients * Windows: https://mosquitto.org/download/ * * Subscribe for messages: * mosquitto_sub -h test.mosquitto.org -t GsmClientTest/init -t GsmClientTest/ledStatus -q 1 * Toggle led: * mosquitto_pub -h test.mosquitto.org -t GsmClientTest/led -q 1 -m "toggle" * * You can use Node-RED for wiring together MQTT-enabled devices * https://nodered.org/ * Also, take a look at these additional Node-RED modules: * node-red-contrib-blynk-websockets * node-red-dashboard * **************************************************************/ // Select your modem: #define TINY_GSM_MODEM_SIM800 //#define TINY_GSM_MODEM_SIM900 //#define TINY_GSM_MODEM_A6 //#define TINY_GSM_MODEM_M590 #define ONE_WIRE_BUS 9 #include <TinyGsmClient.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); String MQTT_inputtext; //сообщение // Your GPRS credentials // Leave empty, if missing user or pass int counter = 0; const char apn[] = "internet.tele2.ru"; const char user[] = ""; const char pass[] = ""; const char cluser[] = "gmnSMc2uDHIjO8CCvf2IeY9UFtT4i0F8"; const char clpass[] = ""; const char clid[] = "fadaf737bb3e4b1f3a09878471b"; // Use Hardware Serial on Mega, Leonardo, Micro //#define SerialAT Serial1 // or Software Serial on Uno, Nano #include <SoftwareSerial.h> SoftwareSerial SerialAT(7, 8); // RX, TX TinyGsm modem(SerialAT); TinyGsmClient client(modem); PubSubClient mqtt(client); const char* broker = "mqtt.beebotte.com"; const char* topicLed = "Led"; const char* topicInit = "Init"; const char* topicLedStatus = "LedStatus"; const char* temperature = "Temp/Data"; #define LED_PIN1 13 #define LED_PIN2 12 char* ledStatus1 ="Reset1"; char* ledStatus2 ="Reset2"; long lastReconnectAttempt = 0; const long interval = 30000; unsigned long previousMillis = 0; char tempchar[6]; float temp; void setup() { sensors.begin(); pinMode(LED_PIN1, OUTPUT); pinMode(LED_PIN2, OUTPUT); // Set console baud rate Serial.begin(115200); delay(10); // Set GSM module baud rate SerialAT.begin(19200); delay(3000); // Restart takes quite some time // To skip it, call init() instead of restart() Serial.println("Initializing modem..."); modem.restart(); // Unlock your SIM card with a PIN //modem.simUnlock("1234"); Serial.print("Waiting for network..."); if (!modem.waitForNetwork()) { Serial.println(" fail"); while (true); } Serial.println(" OK"); Serial.print("Connecting to "); Serial.print(apn); if (!modem.gprsConnect(apn, user, pass)) { Serial.println(" fail"); while (true); } Serial.println(" OK"); // MQTT Broker setup mqtt.setServer(broker, 1883); mqtt.setCallback(mqttCallback); } boolean mqttConnect() { Serial.print("Connecting to "); Serial.print(broker); if (!mqtt.connect(clid, cluser, clpass)) { Serial.println(" fail"); return false; } Serial.println(" OK"); mqtt.publish(topicInit, "GsmClient started"); mqtt.subscribe(topicLed); return mqtt.connected(); } void loop() { if (mqtt.connected()) { mqtt.loop(); unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; sensors.requestTemperatures(); temp = sensors.getTempCByIndex(0); dtostrf(temp, 3, 2, tempchar);//преобразуем float - char String payload = "{\"data\":"; payload += tempchar; payload += ",\"write\":true"; //payload += counter; payload += "}"; Serial.println(payload); mqtt.publish(temperature, (char*) payload.c_str()); } } else { // Reconnect every 10 seconds unsigned long t = millis(); if (t - lastReconnectAttempt > 10000L) { lastReconnectAttempt = t; } if (mqttConnect()) { lastReconnectAttempt = 0; } else if (!modem.gprsConnect(apn, user, pass)) { while (true); } } } void mqttCallback(char* topic, byte* payload, unsigned int len) { MQTT_inputtext = ""; for (int i=0;i<len;i++) { MQTT_inputtext += (char)payload[i]; // составляем строку из байтов, которая пришла в параметрах топика } if (String(topic) == topicLed) { if ((MQTT_inputtext) == "1on" ) { digitalWrite(LED_PIN1, HIGH); ledStatus1 = "Led 1 On"; mqtt.publish(topicLedStatus, ledStatus1 ); } if ((MQTT_inputtext) == "1off" ) { digitalWrite(LED_PIN1, LOW); ledStatus1 = "Led 1 Off"; mqtt.publish(topicLedStatus, ledStatus1 ); } //---------------------- if ((MQTT_inputtext) == "2on" ) { digitalWrite(LED_PIN2, HIGH); ledStatus2 = "Led 2 On"; mqtt.publish(topicLedStatus, ledStatus2 ); } if ((MQTT_inputtext) == "2off" ) { digitalWrite(LED_PIN2, LOW); ledStatus2 = "Led 2 Off"; mqtt.publish(topicLedStatus, ledStatus2 ); } //------------------ if ((MQTT_inputtext) == "stat" ) { mqtt.publish(topicLedStatus, ledStatus1); mqtt.publish(topicLedStatus, ledStatus2); } } }
Вы ошибаетесь ,в блоках MQTT каскады все конвертации стрингов делаются внутри . Нужно только отправлять(принимать) значения boolean ,int, float в есп через штатный конвертер строк SConv