|
本帖最后由 yunsean 于 2021-5-15 09:02 编辑
注意,是小米体重秤,不是体脂秤。
描述:
本来esphome已经支持小米体重秤的接入,但是有两个问题:
第一个,搞不懂写这个代码的人是没有理解中国斤和公斤的换算关系还是其他原因,反正就是逻辑有问题,上原始代码原图:
测试开始的时候一直感觉数据不对,看这个代码,没搞懂是要换算成公斤还是斤或者其他单位。
然后,就想办法修改他的代码,直接在系统环境中搜索xiaomi_miscale.cpp文件,找到位置:
/usr/local/lib/python3.8/site-packages/esphome/components/xiaomi_miscale/xiaomi_miscale.cpp
打开修改之:
``` c++
// weight, 2 bytes, 16-bit unsigned integer, 1 kg
const int16_t weight = (uint16_t(data[1]) | (uint16_t(data[2]) << 8));
if ((data[0] & 0x10) == 0x10)
result.weight = weight * 0.01f * 0.5; // unit 'jin'
else if ((data[0] & 0x03) == 0x03)
result.weight = weight * 0.01f * 0.453592; // unit 'lbs'
else
result.weight = weight * 0.01f;
return true;
```
修改后,按照esphome官网的介绍,基本可以工作了(注意。
但是:
第二个问题:没有处理稳态和人下来后的问题,现象就是人在上边晃(还没有稳定的时候),home assistant中的数据一直在变,如果自动化检测数据变化就播报,会把TTS给累死。
当然,可以继续修改,不过这个时候发现esphome还有一个强大之处:可以使用esp32_ble_tracker直接读取蓝牙的广播消息,所以,想到上边这种修改esphome源码的方法,如果esphome升级,那么就得重新修改,毕竟不是长远之计,所以打算绕路:
放弃xiaomi_miscale组件,直接使用esp32_ble_tracker的on_ble_service_data_advertise来实现,官网说明:
https://esphome.io/components/es ... vice-data-advertise
最终实现(注意是修改esphom配置,不再改源码了,上边的修改也不需要了,因为压根儿不用它):globals:
- id: is_stabilized
type: bool
restore_value: no
initial_value: '0'
- id: load_remove
type: bool
restore_value: no
initial_value: '1'
- id: last_weight
type: float
restore_value: no
initial_value: '0'
esp32_ble_tracker:
on_ble_service_data_advertise:
- mac_address: '88:0F:10:99:5D:CC'
service_uuid: 181D
then:
- lambda: |-
bool isStabilized = ((int)x[0] & 0x20) != 0;
bool loadRemoved = ((int)x[0] & 0x80) != 0;
float weight = (int(x[1]) | (int(x[2]) << 8)) * 0.01;
if (((int)x[0] & 0x10) == 0x10)
weight = weight * 0.5;
else if (((int)x[0] & 0x03) == 0x03)
weight = weight * 0.453592;
if (isStabilized)
id(weight_mi_scale).publish_state(weight);
else if (loadRemoved && !id(load_remove) && id(last_weight) > 0)
id(weight_mi_scale).publish_state(id(last_weight));
id(last_weight) = weight;
id(load_remove) = loadRemoved;
id(is_stabilized) = isStabilized;
sensor:
- platform: template
name: Weight Mi Scale
id: weight_mi_scale
unit_of_measurement: 'kg'
icon: mdi:weight-kilogram
accuracy_decimals: 2
on_value:
then:
- lambda: |-
if (id(weight_mi_scale).state >= 60 && id(weight_mi_scale).state <= 70) {
return id(weight_dad).publish_state(x);
} else if (id(weight_mi_scale).state >= 20 && id(weight_mi_scale).state < 30) {
return id(weight_baby).publish_state(x);
} else {
return id(weight_other).publish_state(x);
}
- platform: template
name: Weight Dad
id: weight_dad
unit_of_measurement: 'kg'
icon: mdi:weight-kilogram
accuracy_decimals: 2
- platform: template
name: Weight Baby
id: weight_baby
unit_of_measurement: 'kg'
icon: mdi:weight-kilogram
accuracy_decimals: 2
后边的根据体重识别人,的方式,来自于xiaomi_scale组件,参考:
https://esphome.io/components/sensor/xiaomi_miscale.html
esphome很神奇!
|
评分
-
查看全部评分
|