CurMttr :: Act I :: How to remotely switch lights via Terminal using MiJia Smart Socket4.0 — Curious Matter
We have a bunch of accelerometers connected to a Raspberry Pi. An audience is going to interact with the sensors and once a certain event occurred we have to remotely switch a neon sign and/or luminescent lamps (powered by wall sockets) on and off.
Probably, the easiest way to do that is to buy MiJia Smart Sockets and hack them to be able to control them from the Terminal on Raspberry Pi.
So I have bought a socket:
Make sure to get a standard version, not a Zigbee, because it has to work without Xiaomi Multifunctional Gateway.
Then I downloaded Hi Home app and added a new device, it was fairly easy, except for one minor issue, the app struggled to find it until I have changed a server location to Mainland China. The socket worked perfectly, but we do not want to control it using a phone, we want to be able to switch it via Terminal.
After some research, I found a handy library https://github.com/aholstenson/miio, which allows us to control Mi Home devices that implement the miIO protocol, including Mi Smart Socket.
I installed the library and was able to discover the device (Woohoo!!):
Great, I have got an IP address and other data, but … it was not that clear how to actually toggle power because to do that we have to know actual commands which the device understands. To get them I had to capture packets wich Mi Home app sends to the device and parse them.
So I have downloaded BlueStacks to run an Android app on the desktop and Wireshark to capture data sent by the app. Then we have to run BlueStacks, install Mi Home, add a new device (using Chinese server), start capturing packets in Wireshark, switch the device on and off via Mi Home app, stop packet capturing and apply filter “udp.dstport == 54321”:
Now you can see the communication between the app and our socket. The next step is to find out the exact commands the app sends to the device. To do that we have to export our Wireshark capture as a JSON file:
Now it is time to parse the JSON file to extract the actual commands, for that, we should run this in the Terminal:
miio protocol json-dump path/to/file.json --token tokenAsHex
As you can see, the methods and parameters we need are:
This way, the respective Terminal commands will be:
miio protocol call 192.168.1.158 set_power '["on"]'
miio protocol call 192.168.1.158 set_power '["off"]'
And voilà! It works!