Coder Social home page Coder Social logo

xiaomi_mi_scale's People

Contributors

andreasbrett avatar anivaniuk avatar bpaulin avatar lolouk44 avatar ned-kelly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xiaomi_mi_scale's Issues

Does xiaomi_mi_scale use the Rpi's built in bluetooth or does it require a dongle

Hi lolouk44, really interested in giving your app a go, but want to make sure I know what's required. I have Rpi3, but don't have a bluetooth dongle. I've had several issues with bluetooth on my RPi (for example, I can't get OSMC to use the internal bluetooth to connect to headphones) and just wanted to double-check before getting started.
Thanks!!!

supervisor log that TIME_INTERVAL does not exist

Describe the bug
i keep seeing in the supervisor log that TIME_INTERVAL does not exist

To Reproduce
Steps to reproduce the behaviour, including error message if any.

Expected behaviour
i dont see any specific fault, just the error messages

Screenshots
image

Scale (please complete the following information):
na

Desktop/Server (please complete the following information):
has os on vmware

Additional context
Add any other context about the problem here.

need json config file , but cannot find this from source code.

Describe the bug
I am follow script directly running guide

Running script directly on your host system (if your platform is not listed/supported):
Note: Python 3.6 or higher is required to run the script manually

Install python requirements (pip3 install -r requirements.txt)
Open wrapper.sh and configure your environment variables to suit your setup.
Add a cron-tab entry to wrapper like so:
@reboot bash /path/to/wrapper.sh
NOTE: Although once started the script runs continuously, it may take a few seconds for the data to be retrieved, computed and sent via mqtt.

To Reproduce
Steps to reproduce the behaviour, including error message if any.

Expected behaviour

run the shell show me error , cannot find json file ,but I can't find out sample json file.

-------------------------------------
2020-09-29 21:48:20 - Starting Xiaomi mi Scale...
2020-09-29 21:48:20 - Loading Config From OS Environment...
Traceback (most recent call last):
  File "/root/xiaomi_mi_scale/src/Xiaomi_Scale.py", line 28, in 
    with open('/data/options.json') as json_file:
FileNotFoundError: [Errno 2] No such file or directory: '/data/options.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/xiaomi_mi_scale/src/Xiaomi_Scale.py", line 165, in 
    if MQTT_DISCOVERY.lower() in ['true', '1', 'y', 'yes']:
AttributeError: 'bool' object has no attribute 'lower'

Screenshots
If applicable, add screenshots to help explain your problem.

Scale (please complete the following information):

  • Name
  • Model #

Desktop/Server (please complete the following information):

  • manually ran after a Git Clone , running on aarch64.

Additional context
Add any other context about the problem here.

Failed with Mi Scale 1

I tried to run code with Mi Scale 1 and it errored out. I believe that line 73 in Xiaomi_Scale.py should be
self._publish(round(measured, 2), unit, "", "")
instead of
self._publish(round(measured, 2, "", ""), unit)

Getting 'bluepy.btle.BTLEDisconnectError: Device disconnected' exception after weighing

I am running the script on RPi3b (no+) with Xiaomi Mi Body Composition Scale 2 (XMTZC05HM) simply as a background process by:

$ sudo python3 Xiaomi_Scale.py

The script starts ok, but after I weigh myself and the data are published to MQTT server, after a while the script crashes with

Traceback (most recent call last):
  File "Xiaomi_Scale.py", line 180, in <module>
    main()
  File "Xiaomi_Scale.py", line 173, in main
    scanner.scan(5)
  File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 854, in scan
    self.stop()
  File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 803, in stop
    self._mgmtCmd(self._cmd()+"end")
  File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 309, in _mgmtCmd
    rsp = self._waitResp('mgmt')
  File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 362, in _waitResp
    raise BTLEDisconnectError("Device disconnected", resp)
bluepy.btle.BTLEDisconnectError: Device disconnected

Mi Scale 1 issue

  File "/opt/miscale/Xiaomi_Scale.py", line 181, in <module>,
Traceback (most recent call last):,
    main(),
  File "/opt/miscale/Xiaomi_Scale.py", line 174, in main,
    scanner.scan(5),
  File "/usr/local/lib/python3.8/site-packages/bluepy/btle.py", line 853, in scan,
    self.process(timeout),
  File "/usr/local/lib/python3.8/site-packages/bluepy/btle.py", line 842, in process,
    self.delegate.handleDiscovery(dev, (dev.updateCount <= 1), isNewData),
  File "/opt/miscale/Xiaomi_Scale.py", line 87, in handleDiscovery,
    self._publish(round(measured, 2), unit, 0, "", ""),
  File "/opt/miscale/Xiaomi_Scale.py", line 161, in _publish,
    message += ',"TimeStamp":"' + mitdatetime + '"',
TypeError: can only concatenate str (not "int") to str

Mi Scale 1
Thanks in advance.

Warning in supervisor log

Describe the bug
I get the following warning in the supervisor log:

WARNING (MainThread) [supervisor.addons.options] Option 'TIME_INTERVAL' does not exist in the schema for Xiaomi Mi Scale (xiaomi_mi_scale)

To Reproduce
Go in supervisor log and check errors

Expected behaviour
No warnings

Screenshots
If applicable, add screenshots to help explain your problem.

Scale (please complete the following information):

  • Name
    Xiaomi Mi Body Composition Scale 2
  • Model #
    XMTZC05HM

Desktop/Server (please complete the following information):

  • Docker or manually ran after a Git Clone?
    Added the repository to HA os
  • Device used to run the Script/Container [e.g. Raspberry Pi, NUC]
    Raspberry with HA Os
  • Bluetooth device used [e.g. Built-in, USB Dongle]
    Builtin rasp BT

Additional context

After updating to new version it stops working

Hi,

I'm very new user of the mi-scale add-on.. I have started today with configuration and have sucess in tranferring data from mi-scale.. After a while it reported to me, that there is update available on 2nd Oct 2022 .. I did the update and since the time no new messages has been received from Mi Scale 2 as I can see in MQTT .. No idea what else shall be updated.

Part of my config:
HCI_DEV: hci0
BLUEPY_PASSIVE_SCAN: false
MISCALE_MAC: 5C:CA:D3:C7:XX:XX
MISCALE_VERSION: 2
MQTT_PREFIX: miscale
MQTT_HOST: core-mosquitto
MQTT_USERNAME: xxxxx
MQTT_PASSWORD: yyyyy
MQTT_PORT: 1883
MQTT_RETAIN: false
MQTT_DISCOVERY: false
MQTT_DISCOVERY_PREFIX: homeassistant
MQTT_TLS_CACERTS: Path to CA Cert File
MQTT_TLS_INSECURE: false
TIME_INTERVAL: 30
USERS:

  • NAME: Radek
    SEX: male

Some ideas what could be wrong with it ?

Many thanks
Radek

Stopped working after latest update

Hi,

First of all, thanks @lolouk44 for this integration. I have been using it for around two months.

Yesterday, I upgraded to the latest version and it stopped working (it does not send the data to MQTT). The following log traces appear continuously:

mi-scale            | Error while running the script, continuing. If you see this message too often/constantly there is probably a real issue...
mi-scale            | Error while running the script, continuing. If you see this message too often/constantly there is probably a real issue...
mi-scale            | Error while running the script, continuing. If you see this message too often/constantly there is probably a real issue...
mi-scale            | Error while running the script, continuing. If you see this message too often/constantly there is probably a real issue...
mi-scale            | Error while running the script, continuing. If you see this message too often/constantly there is probably a real issue...

Details about my setup:

  • xiaomi_mi_scale running with docker-compose using network_mode: host and privileged: true.
  • Running within a Intel NUC using its built-in bluetooth.
  • The bluetooth is working properly as I am able to use it from other services.
  • I also tested using a bluetooth dongle with the same result.
  • It was working fine until I pulled the latest container version.

Could it be related to the passive scanning? πŸ€”

mqtt home assistant sensor error

Describe the bug
Home assistant is giving errors:
2021-10-25 18:01:12 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'BMI' when rendering '{{ value_json['BMI'] }}',
2021-10-25 18:01:12 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'BMI' when rendering '{{ value_json['BMI'] }}',
2021-10-25 18:01:13 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'BMI' when rendering '{{ value_json['BMI'] }}',
2021-10-25 18:01:13 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'BMI' when rendering '{{ value_json['BMI'] }}',
2021-10-25 18:01:13 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'BMI' when rendering '{{ value_json['BMI'] }}',

To Reproduce
Reboot hass

Expected behaviour
no error

Scale (please complete the following information):

  • Name
  • Model # mi body compensation scale 2

Desktop/Server (please complete the following information):
Docker, bluetooth

Additional context
There seems to be an sensor misconfiguration, therefore the error:
Sensor info:

  - platform: mqtt
    name: "Mi-Scale Martin Weight"
    state_topic: "miScale/Martin/weight"
    value_template: "{{ value_json['weight'] }}"
    unit_of_measurement: "kg"
    json_attributes_topic: "miScale/Martin/weight"
    icon: mdi:scale-bathroom
  - platform: mqtt
    name: "Mi-Scale Martin BMI"
    state_topic: "miScale/Martin/weight"
    value_template: "{{ value_json['BMI'] }}"
    icon: mdi:human-pregnant

Repository no longer supported by latest HACS / HASS

Describe the bug
I can't add custom repository to HACS

To Reproduce
Go to HACS -> Integrations -> 3dots -> Custom repositories -> Paste repository URL, choose category and click ADD

Expected behaviour
Repository added to HACS

Desktop/Server (please complete the following information):

  • Home Assistant Operating System
  • Rpi 3
  • Bluetooth device used - Built-in

Additional context
HACS version:
Integration version: | 1.26.2
Frontend version: | 20220714083628

error:
<Integration lolouk44/xiaomi_mi_scale> Repository structure for 0.2.4 is not compliant

Home Assistant 2022.8.6
Supervisor 2022.08.3
Operating System 8.4
Frontend 20220802.0 - latest

visceral_fat value different between json and the xiaomi app

Describe the bug
When getting a measurement, the xiaomi app shows visceral fat 11 whereas the json package says 13.17, not sure if this is normal?

To Reproduce
use the xiaomi app to record a measurement, compare the value in the app for visceral fat and the one transmitted in home assistant mqtt service subscription

Expected behaviour
the two values do not differ rather than the decimal points
image
viber_image_2020-12-13_09-39-19

Scale (please complete the following information):

  • Name Mi Body Composition Scale 2
  • Model XMTZC05HM

Desktop/Server (please complete the following information):

  • Issue observable both via custom installation (wrapper.sh) as well as via HACS
  • Device Raspberry Pi 4
  • Bluetooth -> internal Bluetooth from rPi 4
  • Version 0.1.14

Unable to update

HA returns this error when trying to update:
"Can't install lolouk44/xiaomi-mi-scale-ha-add-on:0.2.7: 404 Client Error for http+docker://localhost/v1.41/images/create?tag=0.2.7&fromImage=lolouk44%2Fxiaomi-mi-scale-ha-add-on: Not Found ("manifest for lolouk44/xiaomi-mi-scale-ha-add-on:0.2.7 not found: manifest unknown: manifest unknown")"

Use with Bidge ESP32 and ESPHome

I would like to ask for an aid to be able to use this project by integrating it with a bridge made with an ESP32 and connected with Home assistant via ESPHome. it's possible?

Why retain scale data?

Is there a reason for retaining the scale data? I understand why retaining the discovery messages is a must but scale measurements should not need to be retained as Home Assistant should pick them up and then they're not needed anymore.

retain=True,

MiScale 1 doesn't report Lbs

Describe the bug
MiScale 1 does not deliver mqtt messaging to Home Assistant when LBS are selected as the designated unit

To Reproduce
Move the slider on the mi scale 1 to the far left, so that it shows the weight as lbs. It will then no longer report the resulting weight to Home Assistant

Expected behaviour
The weight indicated on the scale would be reported in the MQTT message sent to the MQTT broker.

Screenshots

Drawing1

Scale (please complete the following information):

  • Xiaomi Mi Scale
  • Model # xmtzco1hm

Desktop/Server (please complete the following information):

  • The bug occured with a RB3b+ and hassio

Additional context

  • I have had the experience both on Hassio on RP3b and on ubuntu running HA supervised. On built-in bluetooth on the RP3 and on a dongle for Ubuntu

Container fails to start

Describe the bug
mi-scale Version: 0.1.14

Container fails to start with the following exception:

2020-12-03 16:14:48 - Starting Xiaomi mi Scale...
2020-12-03 16:14:48 - Loading Config From OS Environment...
Traceback (most recent call last):
  File "/opt/miscale/Xiaomi_Scale.py", line 28, in <module>
    with open('/data/options.json') as json_file:
FileNotFoundError: [Errno 2] No such file or directory: '/data/options.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/miscale/Xiaomi_Scale.py", line 165, in <module>
    if MQTT_DISCOVERY.lower() in ['true', '1', 'y', 'yes']:
AttributeError: 'bool' object has no attribute 'lower'

To Reproduce
Start mi-scale with the following docker-compose:

version: "3.5"
services:
   mi-scale:
      image: lolouk44/xiaomi-mi-scale:latest
      container_name: mi-scale
      restart: always
      depends_on:
        - mos
      network_mode: host
      privileged: true

      environment:
      - MISCALE_MAC=C4:27:9B:B6:AE:10
      - MQTT_HOST=127.0.0.1
      - MQTT_PREFIX=miScale
      - USER1_GT=70
      - USER1_SEX=male
      - USER1_NAME=Benuhx
      - USER1_HEIGHT=183
      - USER1_DOB=1990-01-01

Run docker logs mi-scale to display the exception

Desktop/Server (please complete the following information):
Docker-compose with Raspberry pi 4 and built-in Bluetooth

Additional Information:
Seems to be the same issue as #31 but the bug is not fixed for me. I've double checked my mi-scale version, it is definitly the latest version 0.1.14 created 7 day ago:

docker images shows:

REPOSITORY                                       TAG                 IMAGE ID            CREATED             SIZE
lolouk44/xiaomi-mi-scale                   latest              ffe67ecaf549        7 days ago          318MB

Script stops working after one measurement

Describe the bug
If I start the script (docker or locally) it worked for one measurement, after "Data Published.." there is no feedback anymore. Even if I wait 10min and try it again. (step on the scale again)

Log:
2023-08-25 18:22:37 - (INFO) -------------------------------------
2023-08-25 18:22:37 - (INFO) Starting Xiaomi mi Scale v0.3.5...
2023-08-25 18:22:37 - (INFO) Loading Config From Options.json...
2023-08-25 18:22:37 - (INFO) No Logging Level Provided, Defaulting to INFO...
2023-08-25 18:22:37 - (WARNING) MQTT Discovery enabled but no MQTT Prefix provided, defaulting to 'homeassistant'...
2023-08-25 18:22:37 - (INFO) Config Loaded...
2023-08-25 18:22:37 - (INFO) MQTT Discovery Setup Completed...
2023-08-25 18:22:37 - (INFO) -------------------------------------
2023-08-25 18:22:37 - (INFO) Initialization Completed, Waiting for Scale...
2023-08-25 18:22:49 - (INFO) Publishing data to topic miscale/Jo/weight: {"weight":79.60,"weight_unit":"kg","bmi":24.57,"basal_metabolism":1632.23,"visceral_fat":13.71,"timestamp":"2023-08-25T18:22:49+00:00"}
2023-08-25 18:22:49 - (INFO) Data Published ...

If I restart the script it will mqtt push the last measurement (without stepping on the scale again): (See log time it starts and pushed instantly the "cached" measurement

2023-08-25 18:33:56 - (INFO) -------------------------------------
2023-08-25 18:33:56 - (INFO) Starting Xiaomi mi Scale v0.3.5...
2023-08-25 18:33:56 - (INFO) Loading Config From Options.json...
2023-08-25 18:33:56 - (INFO) No Logging Level Provided, Defaulting to INFO...
2023-08-25 18:33:56 - (WARNING) MQTT Discovery enabled but no MQTT Prefix provided, defaulting to 'homeassistant'...
2023-08-25 18:33:56 - (INFO) Config Loaded...
2023-08-25 18:33:56 - (INFO) MQTT Discovery Setup Completed...
2023-08-25 18:33:56 - (INFO) -------------------------------------
2023-08-25 18:33:56 - (INFO) Initialization Completed, Waiting for Scale...
2023-08-25 18:33:57 - (INFO) Publishing data to topic miscale/Jo/weight: {"weight":79.40,"weight_unit":"kg","bmi":24.51,"basal_metabolism":1629.24,"visceral_fat":13.61,"timestamp":"2023-08-25T18:33:57+00:00"}
2023-08-25 18:33:57 - (INFO) Data Published ...

To Reproduce
Start Script/Docker -> get on the scale -> scale recognized and send to mqtt broker -> script stop working

Expected behaviour
I guess it should loop and be ready to measure again.

Screenshots
If applicable, add screenshots to help explain your problem.

Scale (please complete the following information):

  • Xiaomi Scale 2
  • XMTZC04HM

Desktop/Server (please complete the following information):

  • Docker or manually ran after a Git Clone? -> Git Clone and run & also Docker container (docker-compose)
  • Device used to run the Script/Container [e.g. Raspberry Pi, NUC] -> Raspberry Pi 3B
  • Bluetooth device used [e.g. Built-in, USB Dongle] -> Built-in

Additional context
Add any other context about the problem here.

error on pulling image.

root@docker_srv:~# docker pull lolouk44/xiaomi-mi-scale:0.1.9
Error response from daemon: manifest for lolouk44/xiaomi-mi-scale:0.1.9 not found: manifest unknown: manifest unknown

discovery messages use miscale as MQTT_PREFIX

I have changed the MQTT_PREFIX in my docker-compose.yaml and was wondering why the discovery message still hat the miscale prefix.
I just realized that the discovery function in Xiaomi_Scale.py uses miscale as hardcoded prefix instead of the environment variable.

Add Weight Guru scale ( BT )

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Would be able to add Weight Guru Scale which also sends data via BT after measurement is complete?

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Not parsing data correctly

I'm seeing this under what is sent...

06
0000181b-0000-1000-8000-00805f9b34fb
57010c9541b1d998
1b180284b207010400343a00000e10

    Sent data to topic miScale/Meghan/weight: {"Weight":"20.55","BMI":"10.00","Basal Metabolism":"722.61","Visceral Fat":"1.00","Lean Body Mass":"48.39","Body Fat":"5.00","Water":"73.50","Bone Mass":"2.35","Muscle Mass":"17.17","Protein":"10.07","TimeStamp":"1970-01-04 00:52:58"}

MIBFS

The print above is me dumping print(data)

You might also note that the scale is identifying as MIBFS under bluetooth

I thought that the scale should be a v2 based on the picture. I'll follow up with any model information I can find.

The timestamp looks completely wrong. Weight should be something like 99kg.

Thoughts? I'm trying to figure out your parsing code and I'm not sure which bits to check. (New to python.)

Body Score isnt right - Zepp Life

Describe the bug
Impedance values are really close to what I see in the app but the body score computed by your code is 16 points above.

Expected Body Score Value: 49
Actual Body Score Value: 65.21

Zepp Life (former xiaomi app) says my BMI is of someone who is overweight. So this should give me a body score deduction value, but it does not happen:

image

Every Impedance metric is extremely close to what I see in the app, so the body score should also be close enough.

I think these values are wrong

bmi_overweight = 28.0
bmi_obese = 32.0

And I also dont understand why maxMalues is lower than minMalus here. Isn't it inverted?

if self.bmi > bmi_overweight:
return self.getMalus(self.bmi, 28.0, 25.0, 5, 10) + 5.0

My bmi deduction score returns 0 because it reaches this line

but it should compute something in this one because my bmi is above 25 and below 30 (overweight)

return self.getMalus(self.bmi, 28.0, 25.0, 5, 10) + 5.0

Template variable warnings

There are a lot of warnings in log

I am using MiScale2

Here is my log :

Log details (WARNING)
Logger: homeassistant.helpers.template
Source: helpers/template.py:2318
First occurred: 15:26:52 (18 occurrences)
Last logged: 15:26:52

Template variable warning: 'dict object' has no attribute 'protein' when rendering '{{ value_json['protein'] }}'
Template variable warning: 'dict object' has no attribute 'metabolic_age' when rendering '{{ value_json['metabolic_age'] }}'
Template variable warning: 'dict object' has no attribute 'body_type' when rendering '{{ value_json['body_type'] }}'
Template variable warning: 'dict object' has no attribute 'lean_body_mass' when rendering '{{ value_json['lean_body_mass'] }}'
Template variable warning: 'dict object' has no attribute 'impedance' when rendering '{{ value_json['impedance'] }}'

My configuration lines look like :

mqtt:
sensor:
- name: "Mesut Protein OranΔ±"
state_topic: "miscale/Mesut/weight"
value_template: "{{ value_json['protein'] }}"
icon: mdi:dumbbell
unit_of_measurement: "%"
json_attributes_topic: "miscale/Mesut/weight"
# Below lines only needed if long term statistics are required
state_class: "measurement"

Support for Mi Body Composition Scale 2 (Model # XMTZC05HM)

My Mi Body Composition Scale show in lescan as MIBFS and it is shown as 'Mi Body Composition Scale 2' (Model # XMTZC05HM).

When I ran wrapper.sh with sudo, I got the following error:
Traceback (most recent call last):
File "/home/pi/xiaomi_mi_scale/Xiaomi_Scale.py", line 183, in
main()
File "/home/pi/xiaomi_mi_scale/Xiaomi_Scale.py", line 180, in main
devices = scanner.scan(5)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 853, in scan
self.process(timeout)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 842, in process
self.delegate.handleDiscovery(dev, (dev.updateCount <= 1), isNewData)
File "/home/pi/xiaomi_mi_scale/Xiaomi_Scale.py", line 113, in handleDiscovery
self._publish(round(measured, 2), unit, str(mitdatetime), miimpedance)
File "/home/pi/xiaomi_mi_scale/Xiaomi_Scale.py", line 153, in _publish
lib = Xiaomi_Scale_Body_Metrics.bodyMetrics(weight, height, age, sex, 0)
File "/home/pi/xiaomi_mi_scale/Xiaomi_Scale_Body_Metrics.py", line 17, in init
raise Exception("Weight is either too low or too high (limits: <10kg and >200kg)")
Exception: Weight is either too low or too high (limits: <10kg and >200kg)

If anyone is willing to guide me on testing it properly to add support to it, it would be great!

Thanks in advance.

Disconnected from MQTT without further errors

I've implemented this script according to the instructions. I couldn't get the script working via crontab (that seems to get reset on hass.io), so I use a home assistant service to trigger a shell script instead. As soon as I trigger the service, this happens in the log for mosquitto.

1565777762: New client connected from [some-ip] as auto-67CD84C1-589C-4DBD-B13E-43E81E26EF8B (p2, c1, k60, u'miscalescript').
1565777767: Socket error on client auto-67CD84C1-589C-4DBD-B13E-43E81E26EF8B, disconnecting.

I know the information in the script is correct, because the client clearly connects. If I do anything else, it doesn't appear in the logs for mosquitto.

Home assistant's logs indicate nothing.

I would love to be able to fix this, because it seems very useful πŸ˜„

Use snake_case in json body

Now in mqtt messages are sent in a very strange json format, where all the fields are like raw data:

Publishing data to topic miScale/kektusini/weight: {"Weight":"83.65","BMI":"24.44","Basal Metabolism":"1733.59","Visceral Fat":"13.63","Lean Body Mass":"64.87","Body Fat":"23.41","Water":"52.54","Bone Mass":"3.27","Muscle Mass":"60.80","Protein":"20.15","Body Type":"Thick-set","Metabolic Age":"32","TimeStamp":"2020-07-03-15:54:09"}

Describe the solution you'd like
It would be better to use the snake_case format to describe json fields:

{
   "weight":"83.65",
   "bmi":"24.44",
   "basal_metabolism":"1733.59",
   "visceral_fat":"13.63",
   "lean_body_mass":"64.87",
   "body_fat":"23.41",
   "water":"52.54",
   "bone_mass":"3.27",
   "muscle_mass":"60.80",
   "protein":"20.15",
   "body_type":"thick-set",
   "metabolic_age":"32",
   "timestamp":"2020-07-03-15:54:09"
}

Script for data processing

Hi,

Based on this project https://github.com/rando-calrissian/esp32_xiaomi_mi_2_hass I modified the code for ESP32 and read scale data to a file (bash script). The format is as follows:
Weight,Impedance,Units,User,Timestamp
58.15,5.45,kg,7,1594556443,5

I would like to ask you to modify the python script (Xiaomi_Scale.py ?) to get the data file:
"Bone" (bone mass in percent),
"Fat" (fat in percent),
"Hydration" (hydration in percent),
"metabolicAge",
"muscle" (muscle mass in percent),
"visceralFat" (visceral fat rating (valid values: 1-60)),
"weight" (weight in kilograms),
"physiqueRating" (physique rating (valid values: 1-9))
"Timestamp" it ok unix-timestamp

It's all about creating a Xiaomi Scale synchronization to Garmin Connect with this project: https://github.com/davidkroell/bodycomposition

I know that maybe too many wishes, but maybe it is not difficult for you, I will be grateful for your help. I am not a programmer, I try to stick several projects together :)

Of course, when everything works, I will want to put it on github :)

Best Regards,
Robert

Issues with Mi Body Composition Scale 2

Describe the bug
Can't get the Mi Body Composition Scale 2 to be discovered. I have paired with the mi fit app and the scale work. When I exec into the container (docker exec -it $dockerId bash) I can confirm that bluetooth works (getting output from hcitool -i hci0 scan and blescan, tried to grep on the mac addr from the app but could not be found). I am also running latest docker container and I can confirm the export vars are set inside in the container from the docker-compose.yml

Expected behaviour
I expect to get some output (I guess?) from docker logs -f and data to mqtt (confirmed connectivity and credentials) and I can't see such with sub to the mqtt topic.

Scale (please complete the following information):

  • Name Mi Body Composition Scale 2
  • Model #XMTZC05HM
  • Firmware 1.0.0.12

Desktop/Server (please complete the following information):

  • Docker
  • NUC
  • Built in

Additional context
It's the first time I am trying this project so it have never been working and I also just go the scale (confirmed to work in the mi fit app).

Error When I get off the scale

2022-01-03 23:32:55 - Starting Xiaomi mi Scale...
2022-01-03 23:32:55 - Loading Config From Add-On Options...
2022-01-03 23:32:55 - Config Loaded...
Traceback (most recent call last):
  File "/opt/miscale/Xiaomi_Scale.py", line 276, in <module>
    main()
  File "/opt/miscale/Xiaomi_Scale.py", line 242, in main
    discovery()
  File "/opt/miscale/Xiaomi_Scale.py", line 129, in discovery
    publish.single(
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/publish.py", line 227, in single
    multiple([msg], hostname, port, client_id, keepalive, will, auth, tls,
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/publish.py", line 163, in multiple
    client.connect(hostname, port, keepalive)
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 937, in connect
    return self.reconnect()
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 1071, in reconnect
    sock = self._create_socket_connection()
  File "/usr/local/lib/python3.8/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
    return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
  File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
socket.timeout: timed out

Mi Body Composition Scale 2
XMTZC05HM
HA core-2021.12.7 - Home Assistant OS 7.1
Raspberry Pi 3b
--

Why can it happen???

Thanks in advance!

4th person

Is there any chance to add 4th person?

Thank you for this awesome work.

Setup in Docker installation of Home Assistant

Hi, I'm new to Home Assistant and it's not clear to me at all how I would go about installing this.
I am using a Docker installation, so I do not have access to add-on store, but from what I learned it's possible to use add-ons by adding them to the docker-compose file. However, it seems like there are some implicit dependencies (like mqqt) in here. Could you provide an example of a minimal docker-compose file that would allow to run this add-on?

Feature request: Use release versions

Coult it be possible to keep all versions on Docker Hub? Currently, only the latest version is available. If previous versions were available, we would be able to:

  • Have stability, as there would not be risk of upgrading to a non backwards-compatible version.
  • Have traceability, which in conjuntion with Github releases/Git tags and even changelogs, it would be very powerful.
  • Go back to previous versions to avoid bugs introduced in new versions (I am experiencing #13) or for debugability purposes.

Thanks!

Make used Bluetooth Device configurable

The software picks hci0 as default bluetooth device to communicate with the scale. It would be great, if it would be configurable as docker environment variable, which hci device the software uses. This would make it possible to use the bluetooth device nearest to the scale or the device with the highest range.

work perfect!!!

i dont know how to send you massage but maybe you can build integration same for Xiaomi Mi Scale?

Better timestamp format

Is it possible to send the timestamp in the following format?
2020-09-07T10:46:40.867941+00:00

The current timestamp string is not useful in HA and the front-end is unable to treat this value as date.
Thank you.

Bluetooth device name does not contain the word "MIBCS"

Hello! I just installed and tested the connector with my scale, thank you so much, works flawlessly!
That being said, I wanted to mention that during the configuration I did not find any device with this command:

$ sudo hcitool lescan | grep -i MIBCS

After checking, I did see that the device name was MI SCALE2, so maybe that could be added to that grep command as well :)

Here's some data from my scale:

Product name: Mi Smart Scale 2
Bluetooth device name: MI SCALE2
Bluetooth address: C8:47:8C:BA:CB:XX
Model: XMTZC04HM
Firmware version: 1.0.0.12

Remove "network_mode=host" from Docker example

Is your feature request related to a problem? Please describe.
The docker-compose example contains "network_mode=host", which is not needed and it is bad practice to do this (less secure).

Describe the solution you'd like
Remove "network_mode=host" from example

Describe alternatives you've considered
N/A

Additional context
N/A

wrapper.sh is missing whole section on mqtt configuration

Describe the bug
wrapper.sh is missing whole section on mqtt configuration.

To Reproduce
compare contents of wrapper.sh with docker-compose

Expected behaviour
It should be equals

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop/Server (please complete the following information):

  • Python 3.9, venv

Not working on Raspberry Pi3

Getting this on fresh Raspberry Pi 3 install:

MQTT connection: Connection Accepted.
Traceback (most recent call last):
  File "/opt/miscale/Xiaomi_Scale.py", line 180, in <module>
    main()
  File "/opt/miscale/Xiaomi_Scale.py", line 173, in main
    scanner.scan(5)
  File "/usr/local/lib/python3.8/site-packages/bluepy/btle.py", line 852, in scan
    self.start(passive=passive)
  File "/usr/local/lib/python3.8/site-packages/bluepy/btle.py", line 797, in start
    self._mgmtCmd(self._cmd()+"end")
  File "/usr/local/lib/python3.8/site-packages/bluepy/btle.py", line 312, in _mgmtCmd
    raise BTLEManagementError("Failed to execute management command '%s'" % (cmd), rsp)
bluepy.btle.BTLEManagementError: Failed to execute management command 'scanend' (code: 11, error: Rejected)

Added fixes!

Hello!
Debian 12 fixes:

Running script directly on your host system:
..............................................
Install python requirements (pip3 install -r requirements.txt --break-system-packages) # added --break-system-packages

Xiaomi_Scale.py

#!/usr/bin/python

-- coding: utf-8 --

import asyncio
import binascii
import collections # added
collections.Iterable = collections.abc.Iterable # added
from bleak import BleakScanner
from collections import namedtuple

Container startup error

Traceback (most recent call last):
  File "/opt/miscale/Xiaomi_Scale.py", line 344, in <module>
    main()
  File "/opt/miscale/Xiaomi_Scale.py", line 312, in main
    if MQTT_DISCOVERY.lower() in ['true', '1', 'y', 'yes']:
AttributeError: 'bool' object has no attribute 'lower'

Doesn't run script

Hi,

The last update does not run the script.

~/xiaomi_mi_scale/src $ python3 Xiaomi_Scale.py File "Xiaomi_Scale.py", line 146 sys.stdout.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Publishing data to topic {MQTT_PREFIX + '/' + user + '/weight'}: {message}\n") ^ SyntaxError: invalid syntax

My environment:
raspberry pi 2
bluetooth stick

disconnected from mqtt

hello,

this may be related to #2 ... or maybe not
mqtt client sometimes disconnects from mqtt, and fails to publish the next payload.

I'm wondering if we really need to have to have a always connected client? I'd rather use https://pypi.org/project/paho-mqtt/#single to connect-publish-disconnect each time we receive a payload from the scale, it works like that in my setup.

What do you think? are you interested in a PR to change that?

thanks for your work!

ConnectionRefusedError: [Errno 111] Connection refused

Describe the bug
pi@goforit:~ $ bash /home/pi/scaleish/wrapper.sh


2021-11-10 00:46:37 - Starting Xiaomi mi Scale...
2021-11-10 00:46:37 - Loading Config From Options.json...
2021-11-10 00:46:37 - Config Loaded...
Traceback (most recent call last):
File "/home/pi/scaleish/Xiaomi_Scale.py", line 298, in
main()
File "/home/pi/scaleish/Xiaomi_Scale.py", line 264, in main
discovery()
File "/home/pi/scaleish/Xiaomi_Scale.py", line 156, in discovery
tls=MQTT_TLS
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/publish.py", line 241, in single
protocol, transport, proxy_args)
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/publish.py", line 176, in multiple
client.connect(hostname, port, keepalive)
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 914, in connect
return self.reconnect()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 1044, in reconnect
sock = self._create_socket_connection()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 3685, in _create_socket_connection
return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
File "/usr/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

Expected behaviour
Expected the scripts to run successfully.

Scale (please complete the following information):

  • Model: Xiaomi Smart Scale 2

Desktop/Server (please complete the following information):

  • Docker or manually ran after a Git Clone? Docker
  • Device used to run the Script/Container [e.g. Raspberry Pi, NUC] Raspberry Pi 4
  • Bluetooth device used [e.g. Built-in, USB Dongle] Built-in

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.