2025年2月23日日曜日

mqtt pedia :: Raspi,ESP32,ESP8266,raspicow(ble also)?

https://mqttx.app/web-client#/recent_connections/32a3a13e-7aef-4224-8ddc-6226007aa6ca でGUI版がうごく

-------------------mqttx / mosquito client-------------------https://qiita.com/emqx_japan/items/634a5b91f0b760664711 にある

mqttx client for desktop::arm64version get and click deb file for install success!

cf 

https://qiita.com/ekzemplaro/items/168a4a98fe65aa24abb9 でbroker.emqx.ioに

sample/imageTopicをsubしておいて(mqttxにて)mosquitto.shでpubして成功

----------------------------------------------------------------

https://www.emqx.com/ja/blog/use-mqtt-with-raspberry-pi より

# subscriber.py

from gpiozero import LED # もらったメッセージでLED操作する

from time import sleep,time #そのため、この2行必要

import paho.mqtt.client as mqtt

led = LED(17)


def on_connect(client, userdata, flags, rc):

    print(f"Connected with result code {rc}")

    # Subscribe, which need to put into on_connect

    # If reconnect after losing the connection with the broker, 

 # it will continue to subscribe to the raspberry/topic topic

    client.subscribe("raspberry/topic")


# The callback function, it will be triggered when receiving messages

def on_message(client, userdata, msg):

    print(f"{msg.topic} {msg.payload}")

    if msg.payload == b'4':

        led.on()

        sleep(10)

        led.off()

client = mqtt.Client()

client.on_connect = on_connect

client.on_message = on_message

# Set the will message, when the Raspberry Pi is powered off, or the network is interrupted abnormally, it will send the will message to other clients

client.will_set('rasp', b'{"status": "Off"}')

# Create connection, the three parameters are broker address, broker port number, and keep-alive time respectively

client.connect("broker.emqx.io", 1883, 60)

# Set the network loop blocking, it will not actively end the program before calling disconnect() or the program crash

client.loop_forever()

上記を起動しておいて、下記を実行するとサブにでてくる

# publish.py

import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")

    # Send a message to the raspberry/topic every 1 second, 5 times in a row
    for i in range(5):
        # The four parameters are topic, sending content, QoS and whether retaining the message respectively
        client.publish('raspberry/topic', payload=i, qos=0, retain=False)
        print(f"send {i} to raspberry/topic")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)

client.loop_forever()

-------mqtt and esp32------------------------------------

https://diysmartmatter.com/archives/355 にてモスキートクライアントをインスト

https://qiita.com/koichi_baseball/items/8fa9e0bdbe6d0aebe57d also refferd!

broker.emqx.ioにかえて成功 -t # でなく -t test/# -vだった 上記パブサブ成功

https://qiita.com/emqx_japan/items/6ddf82d90c506312d875 をインストして

mosquitto_sub -h broker.emqx.io -t emqx/esp32 -v でサブモードで

こんにちは、ESP32です ^^ うけとれた

mosquitto_pub -h broker.emqx.io -t emqx/esp32  -m goodbye でパブモードで

goodbyeおくれた

-------------mqtt and esp8266------------------------------------------------

  https://qiita.com/emqx_japan/items/f74e9d108c7ecaa4f2ddを改変して成功

公開emqxブローカーへのコネクションはどんな名前でもログインOK

esp8266/ledなどのトピックをつくる!mqttx画面でplain textモードになっていること!

#include <ESP8266WiFi.h>

#include <PubSubClient.h>


// GPIO 5 D1

#define LED 5


// WiFi

const char *ssid = "HUAWEI@nova@lite@3+"; // WiFi名を入力

const char *password = "99991111";  // WiFiパスワードを入力


// MQTTブローカー

const char *mqtt_broker = "broker.emqx.io";

const char *topic = "esp8266/led";

const char *mqtt_username = "emqx";

const char *mqtt_password = "public";

const int mqtt_port = 1883;


bool ledState = false;


WiFiClient espClient;

PubSubClient client(espClient);


void setup() {

    

    // ソフトウェアシリアルのボーレートを115200に設定;

    Serial.begin(115200);

    delay(1000); // 安定性のために遅延


    // WiFiネットワークに接続

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {

        delay(500);

        Serial.println("WiFiに接続中...");

    }

    Serial.println("WiFiネットワークに接続しました");


    // LEDピンを出力として設定

    pinMode(LED, OUTPUT);

    digitalWrite(LED,HIGH);

    delay(1000);

    digitalWrite(LED, LOW);  // 最初はLEDを消灯


    // MQTTブローカーに接続

    client.setServer(mqtt_broker, mqtt_port);

    client.setCallback(callback);

    while (!client.connected()) {

        String client_id = "esp8266-client-";

        client_id += String(WiFi.macAddress());

        Serial.printf("クライアント %s が公開MQTTブローカーに接続しています\n", client_id.c_str());

        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {

            Serial.println("公開EMQX MQTTブローカーに接続しました");

        } else {

            Serial.print("失敗しました ステート ");

            Serial.print(client.state());

            delay(2000);

        }

    }


    // メッセージの公開と購読

    client.publish(topic, "hello emqx");

    client.subscribe(topic);

}


void callback(char *topic, byte *payload, unsigned int length) {

    Serial.print("トピックにメッセージが到着: ");

    Serial.println(topic);

    Serial.print("メッセージ: ");

    String message;

    for (int i = 0; i < length; i++) {

        message += (char) payload[i];  // byteをStringに変換

    }

    Serial.println(message);

    if (message.indexOf("on")==1 && !ledState) { // replaced by me

        Serial.println("ledon");

        digitalWrite(LED, HIGH);  // LEDを点灯

        ledState = true;

    }

    if (message.indexOf("off")==1 && ledState) {   // replaced by me

          Serial.println("ledoff");

        digitalWrite(LED, LOW); // LEDを消灯

        ledState = false;

    }

    Serial.println();

    Serial.println("-----------------------");

}


void loop() {

    client.loop();

    delay(100); // ループの各反復で短い遅延

}

0 件のコメント:

コメントを投稿