Package: pyMagicSwitchbot
pyMagicSwitchbotThis is a Python library that allows the integration ofMagic Switchbotdevices in open source projects like home automation.Product descriptionTheMagic Switchbot devicewas apparently a clone of theSwitchbotmanufactured by the Chinese companyShenzhen Interear Intelligent Technology Co., Ltd. Nowadays, the device seems to be discontinued and cannot be bought at any place.If we open the device (which is easy just lifting a lid), we can see it is based upon a low power and high performanceCC2541SOC chip, manufactured by Texas Instruments. It is compatible with BLE (Bluetooth Low Energy) 4.0.This is the board overview we see when opening the lid:The device has an internal 360mAh LiPo battery that can be recharged via its MicroUSB connector and according to the manufacturer its charge can last up to 2 or 3 months.The device has 2 different working modes:Switch.
In this mode, you canturn onorturn offa device. For this mode to work, the manufacturer provides an extension "hook" that can be attached to the physical switch you want to activate, so that when youturn offit effectivelypullsthe hook. You can watch a video tutorialin this link.Push button.In this mode, the device simplypushesthe object to which it is attached for a second and then retracts to its original position every time you activate it.Device API and protocolThe device uses apropietaryBLE protocol that I documented based on information provided by the manufacturer and some reverse engineering of the bluetooth logs and the originalAndroid App. Unfortunately, the app is no longer present at Google Play.The documentation is publishedhere.ReferencesThe latest version of this library is based onbleak, so theoretically it should work on Linux, Windows or Mac, although I've only tested it on Linux.The code is strongly influenced bypySwitchbotlibrary byDaniel Hjelseth Høyer (Danielhiversen). My original idea was to modify this library and make it work for both devices families, but the internal working mode is quite different and most of the code was going to be different, so I decided to start a new project but using some of his good techniques and code.Important NoteIMPORTANT: hcitool and python are not allowed to access bluetooth stack in Linux unless the user is root.
To solve it (insecure), you must run these commands if you don' t have the privileges:sudoapt-getinstalllibcap2-bin
sudosetcap'cap_net_raw,cap_net_admin+eip'$(readlink-f$(whichpython3))sudosetcap'cap_net_raw+ep'$(readlink-f$(whichhcitool))Using the libraryYou need Python 3.10 or newer to use the library, and it is published to PyPi. So to use it just fetch it:pipinstallpymagicswitchbotFrom your program just import the library or only the main class:importmagicswitchbot--OR--frommagicswitchbotimportMagicSwitchbotConstructorThe library uses a main class calledMagicSwitchbot. The constructor gets the device's MAC address as a parameter:MagicSwitchbot(device, password=None, interface=0, scan_timeout=5, retry_count=3)Parameters:device: BLEDevice (Required)
A bluetooth device discovered from thebleaklibrary.password: string (Optional)
Password or PIN set on the device.interface: int (Optional)
Order of the bluetooth client interface to use. It will be prefixed by 'hci'. Default is 0 (hci0)scan_timeout: int (Optional)Max timeout when looking for devices. Default: 5 secondsretry_count: int (Optional)
Number of retries if the connection does not succeed. Default: 3 times.MethodsIn addition to the constructor, the main class has the following public methods:async turn_on() ‑> boolUse the device to switch something on.Returns bool: Returns True if the command was sent succesfully.async turn_off() ‑> boolUse the device to switch something off.Returns bool: Returns True if the command was sent succesfully.async push() ‑> boolUse the device just to push a button.Returns bool: Returns True if the command was sent succesfully.async get_battery() ‑> intGets the device's battery levelReturns int: Level of the device's battery, from 0 to 100async get_basic_info() ‑> dictGets device's basic informationReturns a dictionary with the following items regarding the device:battery: level of the device's battery.firmware: version of the device's firmware.chip_typedevice_typepassword_enabled: True if the device has a PIN number set, False otherwiseExample codeThe following example shows how to use the library in your Python program:# Test program (tests/testAsync.py)'''Testing MagicSwitchBot devices libraryIMPORTANT: hcitool and python is not allowed to access bluetooth stack unless the user is rootTo solve it (unsecure):sudo apt-get install libcap2-binsudo setcap 'cap_net_raw,cap_net_admin+eip' $(readlink -f $(which python3))sudo setcap 'cap_net_raw+ep' $(readlink -f $(which hcitool))'''importsyssys.path.append("..")frommagicswitchbotimportMagicSwitchbotimportlogging,asynciofrombleakimportBleakScannerMAC="00:11:22:33:44:55"PASSWORD=Noneasyncdefmain():try:logging.basicConfig(level=logging.INFO)print(f"Connecting to MagicSwitchbot device at{MAC}...")ble_device=awaitBleakScanner.find_device_by_address(MAC,timeout=20)# await explore_device(ble_device)ifnotble_device:print(f"Couldn't find a BLE device with address{MAC}")else:device=MagicSwitchbot(ble_device)print("Device information:")print(awaitdevice.get_basic_info())res=awaitdevice.get_battery()ifres:print(f"Connected to MagicSwitchbot device at{MAC}with{res}% of battery remaining")print("Turning on...")ok=awaitdevice.turn_on()ifok:print("Command executed successfully")print("Turning off...")ok=awaitdevice.turn_off()ifok:print("Command executed successfully")print("Pushing...")ifawaitdevice.push():print("Command executed successfully")else:print("Error sending command")else:print("Error sending command")else:print("Error sending command")exceptExceptionase:print(e)finally:print("Testing finished")asyncio.run(main())