feature-requests icon indicating copy to clipboard operation
feature-requests copied to clipboard

Switchbot support - BLE

Open nemccarthy opened this issue 4 years ago • 83 comments

Describe the problem you have/What new integration you would like

It would be great to build a switch component which could be used to control SwitchBot devices over BLE.

https://www.switch-bot.com/

Please describe your use case for this integration and alternatives you've tried:

Switchbot devices seem to have a few connectivity issues with HomeAssistant and the RaspberryPi BLE transmission isn’t that powerful.

Having an ESPhome act as a BLE wifi bridge to home assistant would be great. The API for the switchbot seems pretty simple: https://github.com/OpenWonderLabs/python-host

Would be great start to doing BLE transmission to control other BLE output devices.

Additional context

nemccarthy avatar Oct 27 '19 13:10 nemccarthy

Just FYI, I would say this is unlikely to happen in the nearer future. ESPHome currently only handles reading BLE passive ADV packets. The device noted here requires BLE connections.

OttoWinter avatar Oct 28 '19 12:10 OttoWinter

What's the current state on this request? I would really love this component!

SchmDan avatar Jun 04 '20 19:06 SchmDan

I would also love this.

plantoschka avatar Jul 31 '20 11:07 plantoschka

This would be absolutely amazing. I am not sure if this is gonna be directly useful, but there are some nifty wrappers written for the SwitchBot API too. https://github.com/AS137430/switchbot https://github.com/combatistor/ESP32_BLE_Gateway

ajayjohn avatar Aug 22 '20 21:08 ajayjohn

I would like to add that someone has written the following: https://github.com/devWaves/SwitchBot-MQTT-BLE-ESP32

This includes CurtainBot support.

ronytomen avatar Mar 13 '21 13:03 ronytomen

Is any chance for Switchbot Curtain Support?

marithpl avatar Apr 29 '21 13:04 marithpl

Any updates on this? Anyway to use an esp32 with esphome to control switbot bot without an hub?

Thanks!

firstdominator avatar May 19 '21 00:05 firstdominator

I would like to add that someone has written the following: https://github.com/devWaves/SwitchBot-MQTT-BLE-ESP32

This includes CurtainBot support.

Did you managed to make it working with MQTT broker in home assistant?

firstdominator avatar May 19 '21 01:05 firstdominator

I would like to add that someone has written the following: https://github.com/devWaves/SwitchBot-MQTT-BLE-ESP32 This includes CurtainBot support.

Did you managed to make it working with MQTT broker in home assistant?

Yes I did. But next few days should be released version with MQTT Auto Discovery, so devices should automatically add to MQTT Integration.

marithpl avatar May 19 '21 06:05 marithpl

I would like to add that someone has written the following: https://github.com/devWaves/SwitchBot-MQTT-BLE-ESP32 This includes CurtainBot support.

Did you managed to make it working with MQTT broker in home assistant?

Yes I did. But next few days should be released version with MQTT Auto Discovery, so devices should automatically add to MQTT Integration.

Do you think it’s a possibility that the above can be made into an ESPHome integration?

mplacona avatar May 19 '21 07:05 mplacona

Im not a dev :( But I wish to have it in ESPHome

marithpl avatar May 19 '21 07:05 marithpl

Any news on this ? Since esphome release 1.18.0 there is BLE client support. So this means that adding switchbot might be feasible.

Almost here guys!

firstdominator avatar May 28 '21 00:05 firstdominator

Another bump! I'm also trying to get switch bots and curtains going, I might try the MQTT route but it would be awesome if these were setup in espHome!

ry8s avatar Jun 14 '21 11:06 ry8s

Personal warning note upfront: I'm no expert in ESPhome/BLE and are not experienced in this work on getting stuff to work. Warning note from BLE client as part of ESPHome: maximum is three clients, the code is known to be memory intensive.

That being said, i've tried to connect to a switchbot from esphome. I've used the Android app BLE Scanner on my phone and held it near my switchbot curtain motor to discover the MAC-address of the Switchbot. This was fairly easy, I'm not aware of another method to gain this information. For what is worth, I have two switchbot motors for my curtains which open from the middle.

I've added the following code to my ESPHome:

esp32_ble_tracker:

ble_client:
  - mac_address: D2:9B:5D:XX:XX:XX
    id: switchbot_a

Below is the log output from ESPHome, it is the same for both switchbot curtain motors:

[10:56:47][D][ble_client:045]: Found device at MAC address [D2:9B:5D:xx:xx:xx]
[10:56:47][I][ble_client:083]: Attempting BLE connection to d2:9b:5d:xxxx:xx
[10:56:48][I][ble_client:159]: Service UUID: 0x1800
[10:56:48][I][ble_client:160]:   start_handle: 0x1  end_handle: 0x9
[10:56:48][I][ble_client:339]:  characteristic 0x2A00, handle 0x3, properties 0xa
[10:56:48][I][ble_client:339]:  characteristic 0x2A01, handle 0x5, properties 0x2
[10:56:48][I][ble_client:339]:  characteristic 0x2A04, handle 0x7, properties 0x2
[10:56:48][I][ble_client:339]:  characteristic 0x2AA6, handle 0x9, properties 0x2
[10:56:48][I][ble_client:159]: Service UUID: 0x1801
[10:56:48][I][ble_client:160]:   start_handle: 0xa  end_handle: 0xa
[10:56:48][I][ble_client:159]: Service UUID: CBA20D00224D11-E69F-B800-02A5-D5C51B
[10:56:48][I][ble_client:160]:   start_handle: 0xb  end_handle: 0xffff
[10:56:48][I][ble_client:339]:  characteristic CBA20002224D11-E69F-B800-02A5-D5C51B, handle 0xd, properties 0xc
[10:56:48][I][ble_client:339]:  characteristic CBA20003224D11-E69F-B800-02A5-D5C51B, handle 0xf, properties 0x10

I'm trying to cross reference information from the ESP32 BLE gateway code but I'm not really sure how to continue in adding the correct sensor information with the correct characteristics. If someone has more knowledge or ideas, please do share as I'm fine with future testing.

randysnel avatar Jul 14 '21 09:07 randysnel

Personal warning note upfront: I'm no expert in ESPhome/BLE and are not experienced in this work on getting stuff to work. Warning note from BLE client as part of ESPHome: maximum is three clients, the code is known to be memory intensive.

That being said, i've tried to connect to a switchbot from esphome. I've used the Android app BLE Scanner on my phone and held it near my switchbot curtain motor to discover the MAC-address of the Switchbot. This was fairly easy, I'm not aware of another method to gain this information. For what is worth, I have two switchbot motors for my curtains which open from the middle.

I've added the following code to my ESPHome:

esp32_ble_tracker:

ble_client:
  - mac_address: D2:9B:5D:XX:XX:XX
    id: switchbot_a

Below is the log output from ESPHome, it is the same for both switchbot curtain motors:

[10:56:47][D][ble_client:045]: Found device at MAC address [D2:9B:5D:xx:xx:xx]
[10:56:47][I][ble_client:083]: Attempting BLE connection to d2:9b:5d:xxxx:xx
[10:56:48][I][ble_client:159]: Service UUID: 0x1800
[10:56:48][I][ble_client:160]:   start_handle: 0x1  end_handle: 0x9
[10:56:48][I][ble_client:339]:  characteristic 0x2A00, handle 0x3, properties 0xa
[10:56:48][I][ble_client:339]:  characteristic 0x2A01, handle 0x5, properties 0x2
[10:56:48][I][ble_client:339]:  characteristic 0x2A04, handle 0x7, properties 0x2
[10:56:48][I][ble_client:339]:  characteristic 0x2AA6, handle 0x9, properties 0x2
[10:56:48][I][ble_client:159]: Service UUID: 0x1801
[10:56:48][I][ble_client:160]:   start_handle: 0xa  end_handle: 0xa
[10:56:48][I][ble_client:159]: Service UUID: CBA20D00224D11-E69F-B800-02A5-D5C51B
[10:56:48][I][ble_client:160]:   start_handle: 0xb  end_handle: 0xffff
[10:56:48][I][ble_client:339]:  characteristic CBA20002224D11-E69F-B800-02A5-D5C51B, handle 0xd, properties 0xc
[10:56:48][I][ble_client:339]:  characteristic CBA20003224D11-E69F-B800-02A5-D5C51B, handle 0xf, properties 0x10

I'm trying to cross reference information from the ESP32 BLE gateway code but I'm not really sure how to continue in adding the correct sensor information with the correct characteristics. If someone has more knowledge or ideas, please do share as I'm fine with future testing.

The Switchbot BT MAC address you can find in Switchbot App, so you don't have to scan network around you. The MAC address you can display by clicking tree dots in right top corner. image

marithpl avatar Jul 14 '21 09:07 marithpl

I tried quite a few things with the BLE_client function, however the Switchbot itself keeps disconnecting, possibly due to energy conservation reasons. I managed to read the battery with the code below, however due to the disconnects the sensor status in HA switches from the current percentage to 'unknown' until the ESP connects to the Switchbot again and requests the value again. That value is stored in the HA sensor for 1-3 seconds until it is overwritten to unknown again due to the disconnect cycle.

ble_client:
  - mac_address: D2:9B:5D:xx:xx:xx
    id: switchbot_a
    
sensor:
  - platform: ble_client
    ble_client_id: switchbot_a
    name: "Switchbot A battery"
    service_uuid: '1800'
    characteristic_uuid: '2A00'
    device_class: battery
    icon: 'mdi:battery'
    unit_of_measurement: '%'

Reading values of the Switchbot curtain motors is fun on its own of course, but from the code i found at this repository seems we need to write to a service to call an action on the Switchbot like close or open. See line 96-112 for specific calls and required format.

In the documentation of the BLE Client of ESPHome I can only observe a sensor function as a usable component, which can only read as far as i can tell. With further digging it seems that there more components which are not mentioned on the BLE_Client page itself:

  • BLE Client Switch available as well, but the only thing that can do is enable or disable a specific BLE Client as specified in the ESPHome code with mac address & id. This might be useful if you want to bypass the limit of 3 ble_clients concurrent connections limit.
  • BLE Signal strength sensor to measure the signal strength of a BLE device
  • Xiamoi BLE sensor which is specific for Xiaomi BLE sensors
  • BLE presence component to see if a BLE device is present.
  • BLE Scanner the scanner for devices nearby
  • BLE Tracker Hub creates a global hub so that you can track bluetooth low energy devices
  • BLE Beacon to create your own BLE beacon

Looking at the feature requests of ESPhome regarding BLE, I cannot observe a request for writing to BLE services for the BLE_client function. In this pull request I can observe that the work for writing to services is something that could be done in the future as an enhancement. The codebase/supporting libraries of ESPHome supports writing to services as I can observe from other platforms that can control a device through BLE and ESPHome.

Currently I cannot see a method to manage the Switchbot curtain motors from the ble_client function due to the missing write function. It seems a custom platform could be written to support the Switchbot functions more natively in ESPHome, however that is not something I am able to undertake.

randysnel avatar Jul 15 '21 08:07 randysnel

@randysnel I am looking into this as well! Unfortunately I don't have a SwitchBot Curtain yet, but I am looking to buy them for my new house in a two months. It should be doable to add this to ESPHome as well and have all functionality, I just wonder how the retries should be implemented since I read that the BT LE connection is not super reliable.

It seems that they broadcast the sensor data in the advertising service data;

https://github.com/OpenWonderLabs/node-switchbot/blob/6427e72e2d590864014635a732f4f0a65f598f00/lib/switchbot-advertising.js#L178-L201

Would that mean that the only issue is the 'write' functionality, which should be implemented in C++ most likely? I could have a look at that in the coming months, if no one has fixed it beforehand.

iMicknl avatar Jul 27 '21 23:07 iMicknl

Hi Everyone, I wrote the ESP32 MQTT code https://github.com/devWaves/SwitchBot-MQTT-BLE-ESP32

If people have questions I am also on the HA forums.

if people are working on an ESPHome switchbot integration that's awesome. Implementing all the features of my code may be tricky though, but I can provide info if needed

I am still new to HA and ESPHome. I'm no C++/arduino expert either. I can give you some info that I learned while experimenting with switchbots though...

  1. They require a connection to send commands. In my code I only keep the connection active for the duration of the command action, then I disconnect after

  2. Subscribing to BLE notifications of the device will return the response of the command sent to it. Possible values range from 1,5 = success, 3 = busy , 7,9 etc = error

  3. Getting the latest status/state/attributes of the device can be done via a passive BLE scan to get the advertising service data. This is information that is being constantly broadcasted by the device and does not require a "connection". The meter/temp sensor ONLY need a passive scan and no connection

  4. The only attributes to collect that required a temporary connection were for the bot (firmware, hold secs,num of timers). The curtain attributes can all be collected passively without a connection, same for meter

  5. You will need to implement retry logic. My code can retry on all of these issues: a) retry connection until success b) retry send until success c) retry if bot is busy until success d) retry if the bot or curtain doesnt send a response (no response may still trigger bot, so this you can turn off if needed). Curtain doesnt really matter if you resend the same command with no response

  6. if you want to do something like set the hold second value on the bot and then after call the press/on/off command, you can keep the connection active between commands, and then disconnect. This will make it action much faster

cheers

devWaves avatar Jul 31 '21 18:07 devWaves

Any update with cover and ble_client ?

ppanagiotis avatar Aug 17 '21 14:08 ppanagiotis

bump

cdrom1028 avatar Nov 01 '21 16:11 cdrom1028

In a first time, it could be great to have meters support as they only use BLE advertising. I still not really understand how to develop with ESPHome so not able to add it as a native component, but I found a website where only the code has been understandable for me :slightly_smiling_face: but so useful: https://xoops.hypweb.net/modules/UsersWiki/person/nao-pon/blog/2021-03-17

I use it with success. A code example:

esphome:
  name: "Meters Hub"
  platform: ESP32
  # Reste has to be adapted for your ESP
  board: esp32dev
  platformio_options: 
    platform: espressif32
    board: az-delivery-devkit-v4
    board_build.mcu: esp32
    board_build.f_cpu: 240000000L

logger:
  baud_rate: 0   # disable logging via UART, help to avoid numerous crash with ESP_LOGD
  level: NONE

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_key
  ap:
    password: !secret ap_key

captive_portal:

# API Home Assistant
api:
  password: !secret api_pass

ota:
  password: !secret ota_pass

sensor:
  - platform: template
    name: "Hygrometer"
    id: hygrometer
    unit_of_measurement: '%'
    accuracy_decimals: 0
    device_class: humidity
    icon: "mdi:water-percent"
  - platform: template
    name: "Thermometer"
    id: thermometer
    unit_of_measurement: '°C'
    device_class: temperature
    accuracy_decimals: 1
    icon: "mdi:thermometer"
  - platform: template
    name: "RSSI"
    id: rssi_meter
    unit_of_measurement: 'dB'
    device_class: signal_strength
    accuracy_decimals: 0
    icon: "mdi:bluetooth"
  - platform: template
    name: "Battery"
    id: battery_meter
    unit_of_measurement: '%'
    device_class: battery
    accuracy_decimals: 0
    icon: "mdi:battery"
esp32_ble_tracker:
  on_ble_advertise:
    - mac_address: xx:xx:xx:xx:xx:xx # MAC address in lowercase
      then:
        - lambda: |-
            for (auto data : x.get_service_datas()) {
                if(data.data.size() == 6) {
                  float temperature = (float)(data.data[4] & 0b01111111) + ((float)(data.data[3] & 0b00001111) / 10);
                  if (!(data.data[4] & 0b10000000)) {
                    temperature = -temperature;
                  }
                  int8_t humidity= data.data[5] & 0b01111111;
                  int8_t battery = data.data[2] & 0b01111111;
                  int8_t rssi=x.get_rssi();
                  id(hygrometer).publish_state(humidity);
                  id(thermometer).publish_state(temperature);
                  id(rssi_meter).publish_state(rssi);
                  id(battery_meter).publish_state(battery);
                }
            }

Things could be better with a native ESPHome component, maybe.

Nardol avatar Nov 24 '21 15:11 Nardol

I just received my Switchbut Curtain U-Rail 2 (and a 1) and I will try to port the ESP32 mqtt code to an ESPHome component, however I could use some help.

Would there be someone willing to tackle this with me? In my experience it moves way faster forward if it isn't just a side project that I tackle alone. 😄

iMicknl avatar Dec 04 '21 15:12 iMicknl

@iMicknl i want to help you!

Stephan296 avatar Dec 10 '21 10:12 Stephan296

@Stephan296 can you ping me on Discord? (iMick #1903). I am quite busy, but would love to work on this when I have some time. (currently waiting for my curtains to be delivered actually...)

iMicknl avatar Dec 10 '21 13:12 iMicknl

Linking https://github.com/esphome/esphome/pull/2776 since it was mentioned there might be some code functionality for this.

nmajin avatar Jan 04 '22 01:01 nmajin

@iMicknl did you ever get any further with this? I'd love to see this integrated somehow

jeroenterheerdt avatar Mar 30 '22 22:03 jeroenterheerdt

@iMicknl did you ever get any further with this? I'd love to see this integrated somehow

Not really... I have to admit that my SwitchBots are currently not mounted to the rails at all, had some other priorities lately.

However, I would be interested to see if we can tackle this together with some devs. Happy to contribute. @jeroenterheerdt

iMicknl avatar Mar 30 '22 22:03 iMicknl

Hi,

I'm not familiar with ESPHome's code base, but I do have a pair of switchbot curtains mounted and working so I'd be happy to help, if I can do anything. Guess I'll start reading these.

Ulrar avatar Apr 21 '22 13:04 Ulrar

This is almost what we want. If the connection problem resolved we can have switchbot (bots / covers) at esphome :dancers:

ppanagiotis avatar Apr 24 '22 20:04 ppanagiotis

What are you calling cover, the switchbot curtains ? That's great news. I wonder if these connections issues are why I've been having random delays in commands using switchbot mqtt ble esp32

Ulrar avatar Apr 24 '22 20:04 Ulrar