dream/ 十二月 17, 2018/ Arduino, C/C++, ESP8266, MQTT协议, 嵌入式, 树莓派/ 0评论

本文介绍了在 arduino IDE 烧写ESP8266并作为MQTT设备接入到树莓派上运行的home assistant的过程。

一. 环境

arduino IDE,ESP8266,树莓派3B+,Home Assistant 0.83.2

二. arduino IDE编写ESP8266固件并写入

添加PubSubClient库到arduino IDE,打开 工具->管理库 搜索库 PubSubClient by Nick O’Leary 并安装。

编写ESP8266程序代码,并烧写。

示例为一个发布ESP8266工作秒数的传感器。示例代码如下。

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

long serial_speed = 115200;
const char* ssid = "dtswifi";
const char* password = "password";
const char* mqtt_server = "192.168.43.144";
int mqtt_port = 1883;
const char* user_name = "homeassistant";
const char* user_password = "password";
const char* topic_subscribe = "homeassistant/sensor_test/rezero";
const char* topic_publish = "homeassistant/sensor_test/data";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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();
  if((char)payload[0] == '1'){
    ESP.reset(); 
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),user_name,user_password)) {
      Serial.println("connected");
      client.subscribe(topic_subscribe);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(serial_speed);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 1000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 50, "%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish(topic_publish, msg);
  }
}

关于如果烧写,请参考使用arduino IDE烧写ESP8266

三. 在home assistant中添加传感器sensor_test

mqtt使用mosquitto服务。为mosquitto创建一个新用户homeassistant并设置密码。

sudo mosquitto_passwd /etc/mosquitto/pwfile homeassistant

远程连接到树莓派,并修改配置文件/home/homeassistant/.homeassistant/configuration.yaml,在传感器sensor中添加一项。如下。

#mqtt localhost:1883
mqtt:
  broker: 192.168.43.144
  port: 1883
  client_id: home-assistant
  keepalive: 60
  username: homeassistant   #mqtt用户名
  password: yourPassword    #mqtt密码
  discovery: true
  tls_insecure: false
sensor:
  - platform: mqtt
    name: "sensot_test"
    qos: 0
    unit_of_measurement: 秒
    expire_after: 2     #两秒数据过期
    state_topic: "homeassistant/sensor_test/data"
    optimistic: false
    retain: true

关于home assistant的配置,请参考home assistant手册。

四. 重启mqtt和homeassistant服务或者重启树莓派

sudo service mosquitto restart
sudo service home-assistant@homeassistant restart

sudo reboot

五. 测试

打开串口监视器,可以看到ESP8266输出的log。

打开homeassistant前端网页,效果如图所示:

发布消息也可以把数据归零。

mosquitto_pub -h 192.168.43.144 -u homeassistant -P password -t homeassistant/sensor_test/rezero -m "1"

参考链接:

https://github.com/knolleary/pubsubclient

https://home-assistant.cc/component/mqtt/

http://esp8266.github.io/Arduino/versions/2.1.0/doc/reference.html

点击数:2353

Share this Post

说点什么

avatar
300
  订阅  
提醒