dotnet / MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
MIT License
4.48k stars 1.07k forks source link

Unable to connect to server with esp8266 #1251

Closed Grand-0 closed 3 years ago

Grand-0 commented 3 years ago

Unable to connect to server with esp8266 on C++

Hello everyone! I wrote an Asp.Net Core based mqtt server following this example https://github.com/Atlas-LiftTech/MQTTnet.AspNetCore.AttributeRouting/tree/master/ExampleServer. I pushed this broker on hosting. And I trying connecting to broker with esp8266 using Arduino IDE and C++ code. But I didn't connect to the broker. I've changed my connection strings many times, but still can't connect to the broker.

I wrote console application on C# to check the connection string and yes, I connect to the broker using this string. Perhaps the question is very stupid, but I would be very pleased to get help from knowledgeable guys.

This is code Configuration my broker.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<ChainService>();

            string connectionDB = Configuration.GetConnectionString("SqlDatabaseConnection");

            services.AddDbContext<DataContext>(options => options.UseSqlServer(connectionDB));

            services.AddControllers();
            // подключаем поддержку контроллеров mqtt
            services.AddMqttControllers();

            // настройка сервера под Mqtt
            services.AddHostedMqttServerWithServices(s =>
            {
                // ставим стандартную маршрутизацию
                s.WithDefaultEndpoint();
                // во избежание ошибок неразрешаем серверу принимать сообщения несуществующих топиков
                s.WithAttributeRouting(allowUnmatchedRoutes: false);

                // включаем поддержку постоянных сеансов
                s.WithPersistentSessions();

            }).AddMqttConnectionHandler()
            .AddConnections();
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                // добавляем маршрутизатор контрольных точек для mqtt контроллеров
                endpoints.MapMqtt("/Broker");
            });
        }

This is my sketch for esp8266

#include <MQTT.h>
#include <PubSubClient.h>

#include <ESP8266WiFi.h>

#define MQTT_client "CleverSocket"

// настройки домашней сети
const char *network_name = "ZTE_2.4G_A3b3pk";  // Название точки достпа 
const char *network_password = "ZTEGC4320ADB"; // Пароль от точки 

// настройки для MQTT брокера
const char *mqtt_server = "a2507-95ed.p.d-f.pw:80/Broker"; // адрес сервера MQTT
const int mqtt_port = 80; // Порт для подключения к серверу MQTT
const char *mqtt_user = ""; // Логин от сервера MQTT 
const char *mqtt_pass = ""; // Пароль от сервера MQTT
const char *mqtt_hanldler="api/cleverSocket/handler"; // топик для получения данных
const char *data_topic="api/cleverSocket/paramQuickly"; // топик для публикации отчёта

int pause = 300; // переменная для паузы между отправками данных

WiFiClient wclient;      
PubSubClient client(wclient, mqtt_server, mqtt_port);

// получение данных с сервера и отработка
void callback(const MQTT::Publish& pub)    
{
    String topic = pub.topic();
    Serial.print("Connect to topic");
    Serial.print(topic);                // выводим в сериал порт название топика
    Serial.print(" => ");
    String payload = pub.payload_string(); // чтение данных из топика
    Serial.print(payload);   // выводим в сериал порт значение полученных данных
    Serial.println(); 
    // действия над светодиодом в зависимости от данных из топика
    if (topic==mqtt_hanldler) 
    {
      for(int i = 0; i < 100; i++){
          digitalWrite(LED_BUILTIN, LOW);
          delay(500);
          digitalWrite(LED_BUILTIN, HIGH);
          delay(300); 
      }
    }
}

// Функция отправки показаний
void SendResponse() {
  // пока пусто
}

void setup() {
  Serial.begin(9600);
  Serial1.setDebugOutput(true);
  delay(10);
  Serial.println();
  Serial.println();

  client.set_callback(callback);

  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  Serial.println("Connect To WIFI");

  if (WiFi.status() != WL_CONNECTED) { // если соединения нет
        Serial.print("Connecting to ");
        Serial.print(network_name);
        WiFi.begin(network_name, network_password);// подключаемся к wi-fi

        if (WiFi.waitForConnectResult() != WL_CONNECTED) { // ждем окончания подключения
            return;
        }

        Serial.println("Wifi Connected!");
    }
    else{
        Serial.println("Wifi Connected!"); 
    }

    // подключаемся к MQTT серверу
    if (WiFi.status() == WL_CONNECTED) { // если есть подключение к wi-fi
        Serial.println("Connect to MQTTBrocker to route");
        Serial.print(mqtt_server);
        while (!client.connected()) { // если нет подключения к серверу MQTT
            if (client.connect("CleverSocketClient")) {
                Serial.println("connected");
                client.publish(mqtt_hanldler,"Hello world!"); // подписка на топик handler
                client.subscribe("api/cleverSocket/handler");
            } else {
                Serial.print(".");
            }
        }
    }
}

a2507-95ed.p.d-f.pw:80/Broker - path to my broker.

I also tried such connection variations but there are no results.

const char *mqtt_server = "a2507-95ed.p.d-f.pw/Broker"; 
const int mqtt_port = 80; 

PubSubClient client(wclient, mqtt_server, mqtt_port);
const char *mqtt_server = "a2507-95ed.p.d-f.pw:80/Broker"; 

PubSubClient client(wclient, mqtt_server);
const char *mqtt_server = "a2507-95ed.p.d-f.pw"; 
const int mqtt_port = 80; 

PubSubClient client(wclient, mqtt_server, mqtt_port);

This is code console application on C#.

        public static void OnConnected(MqttClientConnectedEventArgs con)
        {
            Console.WriteLine("Connected to server - ", con.AuthenticateResult.ResultCode);
        }

        static void Main(string[] args)
        {
            Allow();
            Console.ReadKey();
        }

        public static async void Allow()
        {
            Console.WriteLine("Start MQTTClientApp");

            var mqttClient = new MqttFactory().CreateMqttClient();

            var options = new MqttClientOptionsBuilder()
                .WithWebSocketServer("a2507-95ed.p.d-f.pw:80/Broker")
                .Build();

            await mqttClient.ConnectAsync(options, CancellationToken.None);

            mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnConnected);
        }
    }
}

I am immensely grateful that you took your time to my question)))

chkr1011 commented 3 years ago

The ESP8266 is not able to connect with a WebSocket MQTT broker. The library PubSubClient can only connect to a TCP MQTT broker. Please try with a console application and a MQTT server created with the MqttFactory instead. If this works the ESP code runs fine. The ESP32 has support for WebSockets out of the box. If the problem persists please reopen this ticket.