• Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Вопрос посылка сообщения от ESP8266 в браузер\app inventor

shavrin777

New member
так, у меня код по прежнему не компилируется попробуй ты
Код:
#include "ESP8266MQTTClient.h"
#include <PubSubClient.h>
//#include <WebPage.h>

const char* mqtt_server = "iot.eclipse.org";

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

const char* ssid = "";
const char* password = "";

float var1 = 1;
float var2 = 123;
float var3 = 3;

String WebPage = "<html lang='ru'> <head> <meta charset='utf-8'>  <script src='https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js' type='text/javascript'></script>  <script> var year; var mon; var wday; var day; var hour; var min; var sec; </script> <script> // Create a client instance client = new Paho.MQTT.Client('iot.eclipse.org', Number(80), '/ws','syhtrrt');  // set callback handlers client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived;  // connect the client client.connect({onSuccess:onConnect});   // called when the client connects function onConnect() {    // Once a connection has been made, make a subscription and send a message.   console.log('onConnect');   client.subscribe('NOTHING/var1');   client.subscribe('NOTHING/var2');   client.subscribe('NOTHING/var3'); }  // called when the client loses its connection function onConnectionLost(responseObject) {   if (responseObject.errorCode !== 0) {     console.log('onConnectionLost:'+responseObject.errorMessage);   }   client.connect({onSuccess:onConnect}); }  // called when a message arrives function onMessageArrived(message) {    if(message.destinationName == 'NOTHING/var1') {var1 = message.payloadString}   if(message.destinationName == 'NOTHING/var2') {var2 = message.payloadString}   if(message.destinationName == 'NOTHING/var3') {var3 = message.payloadString}   document.getElementById('var1').innerText=wday;   document.getElementById('var2').innerText=mon;   document.getElementById('var3').innerText=year;   console.log('onMessageArrived: '+message.payloadString+' '+message.destinationName);  } </script> </head> <body>  <div class='time'>1=<span id='var1'></span>:2=<span id='var2'></span>:3=<span id='var3'></span></div> "

ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
   }
  
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  
    server.on("/", [](){
    server.send(200, "text/html", WebPage);
    });
  
    server.begin();

  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  

    client.publish("NOTHING/var1", "NOTHING/var1", 0, 1);
    client.publish("NOTHING/var2", "NOTHING/var1", 0, 1);
    client.publish("NOTHING/var3", "NOTHING/var1", 0, 1);

    client.subscribe("NOTHING/var1", 0);
    client.subscribe("NOTHING/var2", 0);
    client.subscribe("NOTHING/var3", 0);
    client.subscribe("NOTHING/c", 0);
  
}

void loop() {
    server.handleClient();
    if (Serial.available() > 0){
      char c[] = {(char)Serial.read()};
      mqtt.publish("NOTHING/c", String(c), 0, 1);
    }
  
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
нужна библиотека PubSubClient.h : эскиз -> incude libary -> manage lib -> в поиске PubSubClient
 
Сверху Снизу