用机器人写了一个esphome的代码,用于将接收到的MQTT字符串转化为十六进制然后用串口发送;不同的topic设置不同的帧头。 复制到esphome中提示报错,检查了好多遍也没有发现问题出在哪?特请教指点。
esphome:
name: test11
friendly_name: test11
esp8266:
board: esp01_1m
# Enable logging
logger:
# Enable Home Assistant API
api:
encryption:
key: "******************"
ota:
password: "********************"
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Test11 Fallback Hotspot"
password: "xsV4FctkoFsO"
mqtt:
broker: "MQTT服务器地址"
username: "MQTT用户名"
password: "MQTT密码"
uart:
tx_pin: TX
baud_rate: 9600
globals:
- id: topic_data
type: string[]
size: 10
sensor:
- platform: mqtt
name: "MQTT 数据"
state_topic: "mqtt_to_hex/#"
on_value:
then:
- lambda: |-
std::string topic = id(state.get_topic());
if (topic.length()13) {
return;
}
std::string data_str = state.get_value_string();
int topic_id = std::stoi(topic.substr(11));
float data = data_str.toFloat();
int data_int = (int)(data * 10);
// 将数据转化为十六进制字符串
std::stringstream stream;
stream::hex < data_int;
std::string data_hex = stream.str();
// 保证数据长度为2
if (data_hex.length() == 1) {
data_hex = "0" + data_hex;
}
// 计算帧头和帧尾
std::string header = "AA 55 " + data_hex.substr(0, 1) + std::to_string(topic_id) + " + data_hex.substr(1) + " ";
int sum = 0;
for (int i = 0; i < header.length(); i += 3) {
sum += std::stoi(header.substr(i, 2), nullptr, 16);
}
header += std::to_string(sum % 256) + " 55 AA";
// 发送串口数据
ESP_LOGD("mqtt_to_hex", "Sending data: %s", header.c_str());
uart.write(reinterpret_cast<const uint8_t*>(header.c_str()), header.length());
# 将订阅的topic保存到全局变量中,供lambda表达式使用
- lambda: |-
int i = 0;
for (; i < 10; i++) {
if (topic_data[i] == "") {
topic_data[i] = id(state.get_topic());
break;
}
}
if (i == 10) {
ESP_LOGW("mqtt_to_hex", "Too many topics to subscribe");
}
# 取消订阅时将对应的topic从全局变量中删除
- mqtt.publish:
topic: "mqtt_to_hex/unsubscribe"
payload: !lambda |-
std::string topic = id(state.get_topic());
for (int i = 0; i < 10; i++) {
if (topic_data[i] == topic) {
topic_data[i] = "";
break;
}
}
# 订阅mqtt_to_hex/#以获取所有数据
- platform: mqtt
name: "MQTT 订阅"
state_topic: "mqtt_to_hex/subscribe"
icon: "mdi:arrow-down"
on_value:
then:
- mqtt.subscribe:
topic: "mqtt_to_hex/#"
automation:
- trigger:
platform: mqtt
topic: mqtt_to_hex/unsubscribe
action:
- mqtt.publish:
topic: "mqtt_to_hex/unsubscribed"
payload: !lambda |-
std::string topic = id(trigger.topic);
for (int i = 0; i < 10; i++) {
if (topic_data[i] == topic) {
topic_data[i] = "";
break;
}
}
|