248 views|0 replies

9

Posts

1

Resources
The OP
 

【Follow me Season 2 Episode 2】MQTT protocol access to the open source smart home platform HA [Copy link]

  This post was last edited by cqutmianma on 2024-9-29 22:06

1. Installation of Home Assistant

For ease of operation, Docker is used to install it directly on the computer.

Download the Docker installation package from the official website : https://www.docker.com/products/docker-desktop/ .

After installing Docker, you need to pull the Home Assistant image in Docker. You can refer to an article by a big blogger for a detailed introduction to the use of the command line. I will only show the effect here.

https://bbs.eeworld.com.cn/thread-1293807-1-1.html

(1) The first step is to use cmd to search for the image

docker search home-assistant

(2) The second step is to pull the latest image

docker pull homeassistant/home-assistant

Waiting for a long time to pull the Home Assistant image from Docker.

(3) The third step is to create a container

HA_container is the customizable container name, and D:/ProgramData/HA is the customizable configuration save path (note the right slash)

docker run -d --name="HA_container" -v D:/ProgramData/HA:/config -p 8123:8123 homeassistant/home-assistant

(4) In the last step, enter http://localhost:8123/ in the browser and you will see the success.

Then register a user and enter the homepage, as follows:

2. Installation of EMQX

(1) The first step is to pull the EMQX image in Docker

Enter the command line in CMD and select the first one to install

docker search emqx
docker pull emqx

Then there is another long wait for the pull

(2) The second step is to create an EMQX container

Enter the following command in cmd, where HA is the customizable container name and D:/ProgramData/HA is the customizable configuration save path (note the right slash)

(3) The third step is to test whether EMQX is OK

Enter the URL http://localhost:18083/ in the browser. Default account: admin Default password: public. The successful interface is as follows

(4) Setting up EMQ

Create our built-in database by default all the way

Create another user

Then open docker and you can see the home assistant and EMQ we installed

(5) Then connect EMQ and HA

Find the EMQ cluster overview. Find the node information as follows

Open HA and add MQTT settings

Fill in the proxy name with the address obtained in EMQ, and then create it.

Going back to EMQ, you can find that HA has been connected to EMQ through MQTT, indicating that HA and EMQ have been successfully linked.

3. Realize WIFI networking function

Do it step by step. If you want to upload data via MQTT, you need to learn how to connect the board to the Internet via WIFI first.

Just use the official example of the development board to connect as shown below. We just need to modify the corresponding parameters.

/*
  This example connects to an unencrypted WiFi network.
  Then it prints the MAC address of the WiFi module,
  the IP address obtained, and other network details.

  created 13 July 2010
  by dlf (Metodo2 srl)
  modified 31 May 2012
  by Tom Igoe

  Find the full UNO R4 WiFi Network documentation here:
  https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples#connect-with-wpa
 */
#include <WiFiS3.h>

#include "arduino_secrets.h" 
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();

}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  printCurrentNet();
}

void printWifiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  
  Serial.println(ip);

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:
  byte bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

void printMacAddress(byte mac[]) {
  for (int i = 0; i < 6; i++) {
    if (i > 0) {
      Serial.print(":");
    }
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
  }
  Serial.println();
}

The only modification is to replace SECRET_SSID and SECRET_PASS with your home WIFI name and password respectively. Note: Do not use 5G WIFI, use 2.4G WIFI. If you cannot connect to 5G WIFI, it should be because the hardware does not support it.

Modify as follows:

#define SECRET_SSID "ChinaNet-T6zw"
#define SECRET_PASS "chu7p4s9"

Compile and download, open the serial monitor, you can see that the MAC address and WIFI strength have been obtained, indicating that the connection is successful

4. Preparation for MQTT data upload

Then you need to start preparing MQTT related things

(1) Preparation for downloading MQTT BOX

MQTTBUX is a client that allows us to view the data published by MQTT during debugging. The download link is as follows:

https://apps.microsoft.com/detail/9nblggh55jzg?hl=zh-mo&gl=MO

After installation, you can use it after some basic configuration.

The account and password of the MQTT server are what we set earlier, and the server address is the local IP address of our computer. EMQ (MQTT server) is installed on your local computer through docker, and all addresses are local computer addresses, which can be checked directly using the ipconfig command. If EMQ is installed on a Raspberry Pi, you need to fill in the IP address of the Raspberry Pi.

After setting it up, just subscribe to a topic

Here we subscribe to the topic UNO/arduino/myAnalogInput/stat_t. When the development board sends data to this topic, the client will receive it.

(2) Install the ArduinoMqttClient library in Arduino IDE

The details are as follows

5. Code practice to implement data on MQTT

The voltage value of the sin signal output by the DAC of the A0 interface is read through the ADC A3 interface, and then this value is published through the MQTT protocol.

The actual physical connections are as follows:

The specific implementation code is as follows

#include <ArduinoMqttClient.h>
#include <WiFiS3.h>
#include <WiFiClient.h>
#include "Arduino_LED_Matrix.h"  /*包含官方的驱动库*/
#include "analogWave.h" // 包含波形输出的模拟文件

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "ChinaNet-T6zw";  //WIFI名字
char pass[] = "chu7p4s9";       //WIFI密码
int status = WL_IDLE_STATUS;

//实例化
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
analogWave wave(DAC);   //实例化一个对象

const char broker[] = "192.168.1.11";                //MQTT服务器地址
int port = 1883;                                     //MQTT服务器端口
const char topic[] = "UNO/arduino/myAnalogInput/stat_t";  //发布的主题
const char mqttuser[] = "lang.you";                  //MQTT服务器的用户名
const char mqttpassword[] = "123456789";        //MQTT服务器密码

//set interval for sending messages (milliseconds)
const long interval = 8000;
unsigned long previousMillis = 0;

int count = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(2000000);
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }

  //A0 DAC 输出一个波形
  wave.sine(50);     //产生一个50HZ的sin波形
  wave.amplitude(0.25); //设置幅度值为4.7 的1/4

  // 设置ADC的分辨率
  analogReadResolution(14); //change to 14-bit resolution


  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to WPA SSID: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    // failed, retry
    Serial.print(".");
    delay(5000);
  }

  Serial.println("You're connected to the network");
  Serial.println();

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  mqttClient.setUsernamePassword(mqttuser, mqttpassword);

  while (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
    delay(1000);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();
}

void loop() {
  // call poll() regularly to allow the library to send MQTT keep alive which
  // avoids being disconnected by the broker

  mqttClient.poll();

  //通过ADC采集 A0上输出的sin波形
  float Rvalue = analogRead(A3) * 4.7/16383;  //读取A0引脚的值  A3和 A0连接 14bit ADC采样
  mqttClient.beginMessage(topic);
  mqttClient.print(Rvalue);   //把读取的值进行上传到MQTT服务器
  mqttClient.endMessage();
  delay(10);
}

Check MQTT BOX and subscribe to the data under the UNO/arduino/myAnalogInput/stat_t topic. You can see that the data is being pushed and refreshed.

Open HA to check the uploaded voltage data and it is always refreshing.

Let's take a look at the voltage value of the sin signal displayed on our actual HA

Why does my HA display this value here? In fact, you can refer to the configuration of the live broadcast master. For details, see the link below. The configuration.yaml file is actually configured. Add the following code to save.

https://bbs.eeworld.com.cn/thread-1293807-1-1.html

mqtt:
  - button:
      - unique_id: arduino uno button A
        name: "Arduino Click me A"
        command_topic: "UNO/arduino/myButtonA/cmd_t"
        payload_press: "restart"
      - unique_id: arduino uno button B
        name: "Arduino Click me B"
        command_topic: "UNO/arduino/myButtonB/cmd_t"
        payload_press: "restart"
  - sensor:
      - unique_id: arduino uno Time
        name: "arduino Time"
        state_topic: "UNO/arduino/myUptime/stat_t"
        suggested_display_precision: 1
        unit_of_measurement: "s"
        value_template: "{{ value }}"

      - unique_id: arduino uno Voltage
        name: "arduino Volt"
        state_topic: "UNO/arduino/myAnalogInput/stat_t"
        suggested_display_precision: 3
        unit_of_measurement: "V"
        value_template: "{{ value }}"

Let’s take a look at EMQ

It actually shows 3 devices connected, one is our board, one is HA, and one is MQTT BOX. All three are connected to the MQTT server as MQTT clients.

6. Video display and final engineering code


unor4_mqtt.7z

1.43 KB, downloads: 0

本次MQTT实验代码

This post is from DigiKey Technology Zone
 
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list