Невозможно отправить публичные sh сообщения от esp8266 Raspberry (Broker) с помощью MQTT. Ошибка получения сокета Отключение - PullRequest
0 голосов
/ 09 марта 2020

Я пытаюсь отправить и получить сообщения от Raspberry Pi (брокер) на Arduino-ESP8266 (клиент) с помощью MQTT. То, чего я пытаюсь достичь, пока довольно просто. Посредник отправляет команду запуска, и клиент при получении сообщения должен отправить случайное число обратно. Я могу прочитать сообщение, отправленное брокером, но сообщения от клиента никогда не отправляются. Вот код, который я использую

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(19, 18); //RX, TX
#endif
#define MQTT_KEEPALIVE 10
#include <PubSubClient.h>

IPAddress server(192, 168, 0, 105);
char ssid[] = "user1956";
char password[] = "******";
int status = WL_IDLE_STATUS; //wifi radio's status

//MQTT
//const char* mqtt_topic = "Rpi_Master";
const char* mqtt_username = "pi";
const char* mqtt_password = "********";
//client Id
const char* clientID = "A_2";


//Variables for numbers
long randNumber1;
String rn1;
char rn1_char[50];

WiFiEspClient wifiClient;
PubSubClient client(wifiClient); //1883 is the listener port for the broker

void setup() {
  // Initilize serial for debugging
  Serial.begin(115200);
  //initilize serial for ESP module
  Serial1.begin(115200);
  //initilize the ESP module
  WiFi.init(&Serial1);
  if (WiFi.status() == WL_NO_SHIELD)
  {
    Serial.println("WiFi shield not present");
    while (true);
  }
  while (status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to WPA SSID : ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
  }
  Serial.println("You are connected to the network");
  client.setServer(server, 1883);
  client.setCallback(callback);
  //Allow the hardware to sort itself
  delay(1500);
  randomSeed(50);
}

void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Message Received: [");
  Serial.print(topic);
  Serial.println("]");
  Serial.print("Message is:");
  String message = (char *)payload;
  Serial.println(message);
  else if (!strncmp((char *)payload, "B1", length)) //Start code can be changed to any string value in place of 1
  {
    client.publish("Ad_B", "OK");
    generateRandomData();
  }
  else if (!strncmp((char *)payload, "B2", length)) //Start code can be changed to any string value in place of 1
  {
    client.publish("Ad_B", "OK");
    generateRandomData();
  }
}
void loop()
{
  if (!client.connected())
  {
    reconnect();
  }
  client.loop();
  delay(1000);

}

void reconnect()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT Connection...");
    //Attempt to Connect
    if (client.connect(clientID, mqtt_username, mqtt_password))
    {
      Serial.println("connected");
      //Once connected publish an announcement
      client.publish("Ad_B", "Ready");
      //and resubscribe
      client.subscribe("Rpi_Master"); //This name can be changed
    }
    else
    {
      Serial.print("failed, rc = ");
      Serial.print(client.state());
      Serial.println("Trying again in 5 seconds");
      //Wait for 5 seconds before retrying
      delay(5000);
    }
  }
}
void generateRandomData(){
   randNumber1 = random(0,0); //(14000,15000)
  //Serial.println(randNumber1); // print a random number from 0to 299
  rn1 = String(randNumber1);
  rn1.toCharArray(rn1_char, rn1.length() + 1);

  client.publish("LC_B_1", rn1_char);
  client.publish("Ad_B", "End"); 
}

Это вывод получаемого от меня последовательного монитора:

07:45:42.016 -> [WiFiEsp] Initializing ESP module
07:45:45.430 -> [WiFiEsp] Initilization successful - 1.5.4
07:45:45.430 -> Attempting to connect to WPA SSID : No Free Wifi
07:45:50.464 -> [WiFiEsp] Connected to No Free Wifi
07:45:50.464 -> You are connected to the network
07:45:51.940 -> Attempting MQTT Connection...[WiFiEsp] Connecting to 192.168.0.105
07:45:52.084 -> connected
07:46:31.926 -> Message Received: [Rpi_Master]
07:46:31.926 -> Message is:B2ter
07:46:37.438 -> [WiFiEsp] TIMEOUT: 20
08:20:58.967 -> [WiFiEsp] >>> TIMEOUT >>>

Клиент не может публиковать sh любые сообщения , Журнал Mosquitto показывает PINGREQ и RINGRESP для произвольного идентификатора, и client.publi sh останавливается со следующим сообщением в журнале - Socket Error on Client <Some Random Client Id>, Disconnecting. Прикрепил скриншот журнала. Есть ли способ узнать, что такое неизвестный клиент? Пожалуйста, помогите мне разобраться в этом вопросе. Спасибо.

Unknown Client Id

1 Ответ

0 голосов
/ 09 марта 2020

Вы generateRandom() функциональные блоки (15 секунд) дольше, чем время ожидания активности (10 секунд), и это блокирует функцию client.loop(), поэтому она не сможет отправлять пакеты поддержки активности.

...