Electronics programming: We control a cheap air conditioner from the command line

Posted by


While one of the biggest consumer topics in the European Union and the US in recent years has been the right to repair, we DIYers, tinkerers and makers of all kinds are perhaps even more eager to right to the application interface – API.

If we decided the world, every smart box would be required to offer, in addition to connections to all kinds of smart home systems, a basic interface for developers who want to control the lighting, vacuum cleaner, refrigerator and stove in their own way.

It should be noted that even in 2022 this is a rather rare phenomenon and the world of commercial IoT remains relatively closed. A common argument for manufacturers is security, as they see APIs that they will not have full control of as just another vector of potential cyber attack. Unfortunately, the fact that their product was purchased by an adult and with their own personal responsibility for their actions is no longer of much interest to them.

Watch the video how we turn on the air conditioner from the command line:

Chinese Tuya mainly conquers cheap electronics

Ironically, the world of smart home electronics is mainly opened up by the controversial China and the IoT platforms of its manufacturers. One of them is Tuya, whose ecosystem reads today more than 8,400 manufacturers. The list includes thousands of unknown Asian brands, as well as the French Schneider Electric or Philips.

Click for larger image
Tuya Smart mobile application and control of cheap air conditioning from Sencor

Tuya has also penetrated into the world of cheap and traditionally widespread brands in Europe such as Sencor, and it also forms the core of cheap smart home electronics from Lidl.

Compatibility with European legislation in terms of data protection is ensured by several servers in the territory of the European Union. If you choose them, you don’t have to worry about your information leaking through, at least according to the manufacturer headquarters of the Communist Party of China.

Cloud management of smart boxes

However, we are DIY rather than a single mobile application Tuya Smart for Android and iOS, with which you can completely control the entire smart home, is interesting developer portal iot.tuya.com.

This is not only for manufacturers who would like to implement Tuyu in their electronics, but absolutely anyone can create an account here. For example, a do-it-yourselfer who then pairs terminal devices with his cloud project via a mobile app, obtains their access keys and can control them by himself.

Click for larger image
Device management in the developer console

Standard commands in JSON format are used for this, which can be used to describe practically anything from a smart kettle to a robotic vacuum cleaner, automatic blinds and air conditioning.

Last fall, Tuya also introduced a complete SDK for development in Python, which simplifies the integration of electronics even more and offers a service that we would usually look for in vain from Western competitors.

The tiny TinyTuya library for Python

And it is in Python that we will show Tuya in today’s article, instead of the official and messy SDK, however, we will use the TinyTuya community library, which, according to its name, makes it even simpler. It’s available on GitHub, where you’ll also find a bunch of examples, but you can also get it via the Python pip package installer.

TinyTuya allows you to control devices in the Tuya ecosystem either through cloud API – i.e. via the Internet from anywhere in the world – but it also offers access through local network and UDP. This is useful in cases where there will be no Internet connection available, but only LAN.

Smokers forced me to buy an air conditioner

I live on the fifth floor, all my windows face west, and to top it all off, several smokers nested in the house years ago, and in the hot summer they annoy the other residents by practically continuously emitting smoke. If you want to ventilate with us after sunset, you risk contaminating the entire apartment with nicotine smoke.

Click for larger image
Air temperature on my hot balcony for the last three months

To make matters worse, the layout of the house is not exactly the most suitable for the installation of a classic two-piece air conditioning unit, which would solve the cooling problem at least a little, so last year I went to the nearest hobby market and brought home a cheap 1kW mobile air conditioner with a trunk, for which I am in the panel he cut a ventilation shaft.

Any cheap device has Wi-Fi

Better pieces with high-quality hot air extraction can indeed cool a small apartment similarly to a smaller wall-mounted air conditioner, but at the cost of high noise and the creation of negative pressure in the room.

It’s just a compromise. On the other hand, Wi-Fi, mobile applications and connections to smart ecosystems from Amazon, Google and Apple are often not missing from around NOK 5,000. For classic wall air conditioners, on the other hand, this is still rather an exception.

Click for larger image
A cheap mobile air conditioner for a few thousand with a trunk and Wi-Fi

But this is not a review of mobile air conditioners, so I will go straight to the essentials. The brain of the air conditioner is popular among do-it-yourselfers Wi-Fi chip from Espressif, that is, if I were to dismantle the unit, I can upload my own firmware to the microcontroller, for example from Arduino, or one of the community ones. For example ESPhome.

In my case, this is not necessary, because Sencor used firmware from Tuya, so I will connect to the air conditioner directly using its official API for developers.

I pair my project with the device using QR

So I installed the Tuya Smart app on my mobile and paired the air conditioner in it. After that, I created an account on the Tuya developer portal and set up new project in the Cloud section. Each such project has its own Access ID/Client ID, which is a unique identifier, a Access Secret/Client Secretwhich in turn is the access key.

Click for larger image
In Tuya IoT Platform, I created a new project in which I will manage my devices

I will need both values ​​later when accessing the device. But first I have to connect some to my project, which I will do in its administration and in the section Devices. Here I can find a list of all my toys in the Tuya ecosystem, the current status and also a button Add Device. The device is connected to the project via a QR code.

Click for larger image
I pair the new device with the project via a QR code, which I scan in the Tuya mobile application

Of course, I can also transfer the QR code to someone else and remotely manage their smart electronics from one developer desk.

Click for larger image
And it’s already there. I have rights to read and write to the device and also to manage it

Control instructions in JSON

The developer dashboard can do a lot. When I open the tab of one of the devices, I learn basic information, belonging to a specific geographic data center with which it communicates (my project should be the same), but there are also detailed time logs of all events and finally a bookmark Device Debugging.

Click for larger imageClick for larger image
Graphical and textual terminal for sending instructions in JSON

It is actually a kind of GUI/text terminal for sending JSON commands directly to the device through the cloud API.

So if I wanted my air conditioner turn onjust send the instruction in JSON:

{
    "code": "switch",
    "value": true
}

And if I wanted her turn onbut at the same time also set the mode to cooling, temperature to 18 °C and fan on highest speedI adjust the dose in this way:

[
  {
    "code": "switch",
    "value": false
  },
  {
    "code": "mode",
    "value": "cold"
  },
  {
    "code": "temp_set",
    "value": 18
  },
  {
    "code": "fan_speed_enum",
    "value": "high"
  },
]

Thanks to the structured JSON format, I can combine a number of sub-commands in one message.

We will connect with air conditioning through TinyTuya

Well, that would be enough on the web and hooray for Python. I installed the TinyTuya library on my home Raspberry Pi, which I SSH into from the free editor Visual Studio Code and he prepared the first example of a short code that just verifies the connection with the air conditioner through the cloud API and writes the configuration of the device again in JSON format.

Click for larger image
The text output at the bottom reveals that I have successfully connected to the AC and gotten its current state in JSON format

In order to do this, I will need those identification values ​​of my project (Access ID and Access Secret) and the Device ID, which I will find in the list of paired appliances on the website.

The whole code will look like this:

import tinytuya as tt

# Přístup pres Tuya Cloud (internet)
cloud = tt.Cloud(
    apiRegion = "eu", # Geografický region/datacentrum
    apiKey = "sk8uycg7aqood", # Access ID projektu
    apiSecret = "19b1d39c0a784a", # Access Secret
    apiDeviceID = "54766874e86" # Device ID
)

# Pole odpovídajících zařízení
spotrebice = cloud.getdevices()

# Projdu pole
for spotrebic in spotrebice:
    print(f"Název: {spotrebic['name']}")
    print(f"ID: {spotrebic['id']}")

    # Vypíšu surový obsak stavu zařízení v JSON
    stav = cloud.getstatus(spotrebic["id"])
    print(f"n{stav}")

It works! Information about my air conditioner will soon appear in the terminal. I’m using a cloud API, so it might take a few seconds, because the connection goes through a server somewhere in a European data center.

On the other hand, this way I can connect to the air conditioner from anywhere, even if my smart home will be behind the router’s NAT and the operator’s infrastructure – even without a public and fixed home IP address.

We send commands in JSON to the air conditioner

But passively reading the status is boring. So I’ll take the initiative and modify the script above for messaging. When I add the terminal parameter turn onthe air conditioning will start, so what if turn offstops analogously.

Click for larger image
Turning the air conditioner on and off from the command line using a Python script

As we said above, messages are sent to the device in JSON format and the TinyTuya library has a method for this sendcommand(Deviceid, JSON). The modified code could therefore look like this:

import tinytuya as tt
import sys

# ID naší klimatizace v systému Tuya Cloud
klimatizaceId = "54766874e86"

# Instrukce pro zapnutí
zapni = {
    "commands":[
        {
            "code": "switch",
            "value": True
        }
    ]
}

# Instrukce pro vypnutí
vypni = {
    "commands":[
        {
            "code": "switch",
            "value": False
        }
    ]
}

# Přístup Tuya Cloud (internet)
cloud = tt.Cloud(
    apiRegion = "eu", # Geografický region/datacentrum
    apiKey = "sk8uycg7aqood", # Access ID projektu
    apiSecret = "19b1d39c0a784a", # Access Secret
    apiDeviceID = klimatizaceId # Device ID
)

# Pole odpovídajících zařízení
spotrebice = cloud.getdevices()

# Projdu pole
for spotrebic in spotrebice:
    print(f"ID: {spotrebic['id']}")

    # Vypíšu surový obsak stavu zařízení v JSON
    stav = cloud.getstatus(spotrebic["id"])
    print(f"n{stav}")

print("")

# Pokud jsem použil parametr zapni, zapnu klimatizaci
if "zapni" in sys.argv:
    print("*** ZAPÍNÁM KLIMATIZACI ***")
    odpoved = cloud.sendcommand(klimatizaceId, zapni)
    print(f"Odpověď: {odpoved}")

# Pokud jsem použil parametr vypni, vypnu klimatizaci
elif "vypni" in sys.argv:
    print("*** VYPÍNÁM KLIMATIZACI ***")
    odpoved = cloud.sendcommand(klimatizaceId, vypni)
    print(f"Odpověď: {odpoved}")

We start and turn off the air conditioner from the command line

If our Python script was called controlled.pyto start the air conditioner just call the command:

python3 ovladani.py zapni

And to turn it off:

python3 ovladani.py vypni

Just to be sure, for Python newbies, the command above corresponds to my configuration of the Python interpreter. On your computer, the launcher may not be named python3, but simply python, regardless of its version.

And if you don’t want the cloud, you can use LAN and UDP

In the same way, I could give the air conditioner another, and even a combined command, which will change the fan speed, the target temperature and other parameters.

And since a bunch of other types of electronics run on the Tuya platform, I can control lighting, smart sockets and other appliances using an identical protocol in an analogous way. I just choose adequate instructions in JSON.

Click for larger image
Control in a LAN without the need for the Internet differs mainly in the simpler numerical format of the instructions in JSON and the key for local connection with the appliance

And if I wanted to cut off the entire Tuya Cloud, in TinyTuya I can finally work with the aforementioned access via LAN and UDP without the need for the Internet. This step requires an additional level of authorization and a different JSON command format. You can learn how to do it directly on the GitHub of the TinyTuya library.

The democratization of integration is essential

What to write in conclusion? It is sad that Western manufacturers do not offer a similar development service, and the owner of the appliance cannot get inside the box on his own axis. Hopefully the situation will improve over time and the ecosystems will open up in a similar way to Tuya.

This is necessary for the next level of democratization of the IoT in the future – that is, the democratization of its integration.



Source link

Leave a Reply

Your email address will not be published.