ESP32MQTTClient kütüphanesi

Başlatan DigitalMan, 15 Mayıs 2023, 18:32:05

DigitalMan

Arkadaşlar, ESP8266 içeren NodeMCU modlü ile MQTT broker 'a (ws://test.mosquitto.org:8080/mqtt) websocket kullanarak bağlanmaya çalışıyorum. ESP8266MQTTClient adlı bir kütüphane buldum ve loop içinde mqtt.handle(); fonksiyonunu yazdığımda. bir istisna (exception) oluşuyor ve NodeMCU sürekli reset atıyor. Oluşan istisna mesajı aşağıdadır. Bu kütüphane ile çalışan olup problemi çözebilen arkadaşlardan yardım bekliyorum. Herkese iyi çalışmalar.
User exception (panic/abort/assert)
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Abort called

>>>stack>>>

ctx: cont
sp: 3fffff70 end: 3fffffd0 offset: 0010
3fffff80:  00000000 3ffee9fc 3fffffa0 40211718  
3fffff90:  00000003 00000000 3ffee8a8 401000dc  
3fffffa0:  00000000 0021002f 3ffee8a8 40202498  
3fffffb0:  3fffdad0 00000000 3ffeeba8 4020734c  
3fffffc0:  feefeffe feefeffe 3fffdab0 40100de1  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3424, room 16 
tail 0
chksum 0x2e
load 0x3fff20b8, len 40, room 8 
tail 0
chksum 0x2b
csum 0x2b
v00060070
~ld

mehmet

Harici 5V besleme ekleyip deneyin.
Wi-Fi çalışınca ciddi akım çekiyor.
Olan olmuştur,
olacak olan da olmuştur.
Olacak bir şey yoktur.
---------------------------------------------
http://www.mehmetbilgi.net.tr

DigitalMan

Mehmet bey, ilgin için teşekkürler, aslında mevcut kütüphane ile ne yaptımsa olmadı. Ben de MQTTPubSubClient_Generic.h ve WebSocketsClient_Generic.h adlı kütüphaneleri buldum. şu an sorunsuz haberleşme sağlandı. Yapmak istediğim şey şu. Bir web sayfası görsel ara yüzünden uzaktaki esp8266 nın ölçtüğü verileri anlık izlemek ve kontrol etmek. web tarafında da MQTT.js diye bir kütüphane buldum oda çalıştı. Projem bittiğinde buradan paylaşacağım. İyi çalışmalar.

vkoglu

#3
ESP32 irtibatlı bir sensör vb. bilgisini bilgisayardaki Mqtt Broker dan okumak için bir örnek oluşturdum.
Belki bir arkadaşımıza yardımcı olur.

Amaç : Bilgisayarda VS 2019 c# ile bir broker oluşturmak. ESP32 WROOM 32D deki mqtt client ile mesaj alıp/vermek

Gereklilikler : Bilgisayar Statik IP, Nuget : MQTTnet 3.1.1, Taskların çoğu async

- Form da servis açıp kapatmak için bir groupbox içine iki adet radio button yerleştirdim.

- Veriyi içine yazmak için bir adet textbox,

- sunucu içinden sanal bir mqtt client oluşturup sunucunun çalıştığını test etmek için bir button.

- Menü de exit, Gelen mqtt mesajlarını textbox yazdırmak için timer
// VS C# KISMI
using System;
using System.Net;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MQTTnet.Server;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System.Threading;
namespace MqttSunucu
{
    public partial class Form1 : Form
    {
        public MqttServer mqttServer = (MqttServer)new MqttFactory().CreateMqttServer();
        static String gelenMesaj;
        IPAddress brokerIpAddr;
        public Form1()
        {
            InitializeComponent();
        }
        private async Task TaskStartAsync()
        {
            var option = new MqttServerOptionsBuilder()// Create the options for MQTT Broker
                .WithDefaultEndpointBoundIPAddress(brokerIpAddr)
                .WithDefaultEndpoint()
                .WithApplicationMessageInterceptor(OnNewMessage);
            await mqttServer.StartAsync(option.Build());// Create a new mqtt server 
        }
        static void OnNewMessage(MqttApplicationMessageInterceptorContext context) //static idi
        {
            // Convert Payload to string
            var payload = context.ApplicationMessage?.Payload == null ? null : Encoding.UTF8.GetString(context.ApplicationMessage?.Payload);
            // gelen
            Console.WriteLine(
                " TimeStamp: {0} -- Message: ClientId = {1}, Topic = {2}, Payload = {3}, QoS = {4}, Retain-Flag = {5}",
                DateTime.Now,
                context.ClientId,
                context.ApplicationMessage?.Topic,
                payload,
                context.ApplicationMessage?.QualityOfServiceLevel,
                context.ApplicationMessage?.Retain);
            Form1.gelenMesaj = DateTime.Now + " " + context.ClientId + " " + context.ApplicationMessage?.Topic + " " + payload;//payload;
        }
        public static async Task Publish_Message_From_Broker()
        {
            var mqttClient = new MqttFactory().CreateMqttClient();// Sunucuda sanal bir client oluştur. 
            var mqttClientOptions = new MqttClientOptionsBuilder()
                                        .WithCleanSession()
                                        .WithTcpServer("192.168.0.10")
                                        .Build();
            var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
                Console.WriteLine("The MQTT client is connected.");
            // Create a new message using the builder as usual.
            var message = new MqttApplicationMessageBuilder()
                              .WithTopic("TEST")
                              .WithPayload("deneme from sunucu ve client")
                              .Build();
            await mqttClient.PublishAsync(message, CancellationToken.None);// message send
            await mqttClient.DisconnectAsync();
        }
        [Obsolete]
        private void Form1_Load(object sender, EventArgs e)
        {
            string hostName = Dns.GetHostName(); // Retrive the Name of HOST
            Console.WriteLine(hostName);
            // Get the IP
            string myIP = Dns.GetHostByName(hostName).AddressList
[o].ToString();
            Console.WriteLine("My IP Address is :" + myIP);
            label1.Text = "Broker IP " + myIP;
            brokerIpAddr = IPAddress.Parse(myIP);
            timer1.Enabled=true;
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (mqttServer.IsStarted)
            {
                mqttServer.StopAsync().Wait();
                button2.BackColor = Color.Red;
            }
            Application.Exit();
        }
        private void rbStart_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Start giris");
            button2.BackColor = Color.LightGreen;
            timer1.Start();
            Task.Run(TaskStartAsync);
        }
        private void rbStop_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Servis Stop");
            button2.BackColor = Color.Red;
            timer1.Stop();
            mqttServer.StopAsync().Wait();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (gelenMesaj != null) {
                textBox1.AppendText(Form1.gelenMesaj + System.Environment.NewLine);
                Form1.gelenMesaj = null;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Task.Run(Publish_Message_From_Broker);
        }
    } // class Form1
} // namespace

// ARDUINO KISMI
// https://github.com/ibrahimcahit/ESP8266-MQTT/blob/master/ESP8266%20Arduino%20Codes/EPS8266_and_DHT11_MQTT.ino
// https://github.com/mcselede/homie-lmroy-pubsubclient-mqtt-library
#include <WiFi.h>
#include <PubSubClient.h>
#include <DNSServer.h>
// WIFI Address Part
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPass";
IPAddress staticIP(192, 168, 0, 100);
IPAddress gateway(192, 168, 0, 254);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 0, 254);
// MQTT Part 
IPAddress mqtt_server(192, 168, 0, 10);// Local PC Broker IP = 192.168.0.10
WiFiClient espClient;
PubSubClient client(espClient);
const char* topic= "TEST";
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE    (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup() {
  Serial.begin(115200);
  // WIFI part
  if (WiFi.config(staticIP, gateway, subnet, dns, dns) == false) {
    Serial.println("Configuration failed.");
  }
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("Connecting...\n\n");
  }
  Serial.print("Local IP: ");  Serial.println(WiFi.localIP());
  Serial.print("Subnet Mask: ");  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway IP: ");  Serial.println(WiFi.gatewayIP());
  Serial.print("DNS 1: ");  Serial.println(WiFi.dnsIP(0));
  Serial.print("DNS 2: ");  Serial.println(WiFi.dnsIP(1));
  // MQTT part
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  // Client connect
  client.connect("clientId");
  // Subscribe
  boolean flag1 = client.subscribe(topic); //(const char* topic);
}  // setup
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();
}
void SendMqttMsg() { // test için 1..99 arası sayı gönderiyorum.
  long deger = random(1,100);
  client.publish(topic, String(deger).c_str(), true);
}  // SendMqttMsg
void loop() {
  SendMqttMsg();
  delay(5000);
}  // loop