Wednesday, April 29, 2026

SwitchBot API × Raspberry Pi 5: Automated Room AC Control [2026 Edition]

This article is for engineers who want to automatically control their air conditioner based on room temperature using SwitchBot Hub 2. Using a Python script and cron on a Raspberry Pi 5, I'll show you how to build a system that automatically turns the AC on and off based on room temperature.

3 approaches compared

There are three ways to accomplish the same thing. This article covers the Raspberry Pi + Python + cron approach.

(1) Raspberry Pi
+ cron
(this article)
(2) SwitchBot
Automation
(3) IFTTT
Integration
Extra hardwareRaspberry Pi requiredNoneNone
SetupPython code
+ cron config
App only
(easiest)
IFTTT account
+ applet config
TriggersUnlimited
(Python handles anything)
Temperature, time,
presence detection, etc.
Strength in GPS,
weather, other services
CostPi electricity only
(~1–2 W)
FreeFree plan limited
to 2 applets
Logic complexityHysteresis, logging,
extensions — fully free
AND/OR basicsSimple IF→THEN
rules only
Cloud dependencySwitchBot API onlySwitchBot
cloud only
IFTTT +
SwitchBot cloud

If you just want to use the app, see the SwitchBot Automation article. For GPS triggers or external service integration, see the IFTTT article (series list at the bottom).

What you can do with this

  • Call the SwitchBot API v1.1 from Python to control devices
  • Fetch room temperature every 5 minutes on a Raspberry Pi 5 and control the AC with conditional logic
  • Add hysteresis to temperature control to prevent rapid on/off cycling

What you need

Architecture overview

The Raspberry Pi itself does not need an IR module. The Pi only sends HTTPS commands to the SwitchBot API — the actual IR transmission is handled by the SwitchBot Hub 2.

Raspberry Pi 5

HTTPS (SwitchBot API v1.1)
SwitchBot Hub 2

Infrared
Air Conditioner

Prerequisite (1): register your AC in the SwitchBot app

To control the AC via Hub 2, you first need to teach the app your AC's IR codes.

  1. SwitchBot app → tap "+" in the top right of the home screen → "Add Infrared Remote"
  2. Select "Air Conditioner" → choose your brand (use a preset if available)
  3. If your brand isn't listed, use "Learning Remote" to capture the signal from your physical remote
  4. Verify you can turn the AC on and off from the app

This registers the AC as a "virtual IR remote" in the SwitchBot cloud. This step is required no matter which of the three approaches you use.

Prerequisite (2): get your SwitchBot API token

Tap the app version display 10 times in the SwitchBot app to unlock the developer options.

  1. SwitchBot app → Profile → Settings
  2. Tap "App Version" 10 times
  3. "Developer Options" → "Get Token"
  4. Copy the Token and Client Secret to a safe place
export SWITCHBOT_TOKEN="{your_token}"
export SWITCHBOT_SECRET="{your_secret}"

List your devices

Air conditioners live in infraredRemoteList, not deviceList. Check both.

import hashlib, hmac, base64, time, uuid, requests, os

TOKEN  = os.environ["SWITCHBOT_TOKEN"]
SECRET = os.environ["SWITCHBOT_SECRET"]

def get_headers():
    t   = str(round(time.time() * 1000))
    n   = str(uuid.uuid4())
    msg = TOKEN + t + n
    sig = base64.b64encode(
        hmac.new(SECRET.encode(), msg.encode(), hashlib.sha256).digest()
    ).decode()
    return {
        "Authorization": TOKEN,
        "t": t, "nonce": n, "sign": sig,
        "Content-Type": "application/json",
    }

r = requests.get("https://api.switch-bot.com/v1.1/devices", headers=get_headers())
body = r.json()["body"]

print("--- Physical devices (Hub 2, etc.) ---")
for d in body["deviceList"]:
    print(d["deviceId"], d["deviceName"], d["deviceType"])

print("--- Infrared remotes (AC, etc.) ---")
for d in body["infraredRemoteList"]:
    print(d["deviceId"], d["deviceName"], d["remoteType"])

Example output:

--- Physical devices ---
{hub_device_id}  Living Room Hub 2        Hub 2

--- Infrared remotes ---
{ac_device_id}   Living Room AC   Air Conditioner

Getting the room temperature

def get_temperature(device_id):
    url = f"https://api.switch-bot.com/v1.1/devices/{device_id}/status"
    r = requests.get(url, headers=get_headers())
    body = r.json()["body"]
    return body["temperature"], body["humidity"]

temp, hum = get_temperature("{hub_device_id}")  # Hub 2 device ID
print(f"Room temp: {temp}°C  Humidity: {hum}%")

Controlling the air conditioner

def control_ac(device_id, command):
    url = f"https://api.switch-bot.com/v1.1/devices/{device_id}/commands"
    payload = {
        "command": command,       # "turnOn" or "turnOff"
        "parameter": "default",
        "commandType": "command",
    }
    r = requests.post(url, headers=get_headers(), json=payload)
    return r.json()["statusCode"]

AC_ID    = "{ac_device_id}"    # from infraredRemoteList
HUB_ID   = "{hub_device_id}"   # from deviceList
ON_TEMP  = 28
OFF_TEMP = 25

temp, _ = get_temperature(HUB_ID)
if temp >= ON_TEMP:
    control_ac(AC_ID, "turnOn")
    print(f"{temp}°C → AC ON")
elif temp <= OFF_TEMP:
    control_ac(AC_ID, "turnOff")
    print(f"{temp}°C → AC OFF")

The gap between ON_TEMP and OFF_TEMP (hysteresis) prevents the AC from continuously cycling on and off whenever the temperature hovers near 28°C.

Running it automatically with cron

$ crontab -e

# Check room temperature every 5 minutes
*/5 * * * * /usr/bin/python3 /home/pi/ac_control.py >> /home/pi/ac_control.log 2>&1

Note: The steps and code in this article were verified as of April 2026, but library or hardware version changes may cause them to stop working as written. If something doesn't work, please let me know in the comments.

Wrap-up

With SwitchBot Hub 2, the Raspberry Pi needs no IR module — just Python API calls are enough to automatically control your AC. The big win over the SwitchBot app is the freedom to implement logic that the app can't handle: hysteresis, logging, time-of-day restrictions, and whatever else you can code.

If this article was helpful, I'd love it if you shared it on X (Twitter).

App by the author of this blog

I made an iOS reading management app called My Bookstore. Simple bookshelf management — give it a try.

View on App Store →

References

Series articles

Note: This article is part of an automated blog update experiment using Claude Code.

No comments:

Post a Comment