HomeHome AutomationSwitchBot just got better - SwitchBot API

SwitchBot just got better – SwitchBot API

Making it mine!

In case you missed it, SwitchBot is pretty cool. Call me strange, but there is something awesome in little, simple robots doing mundane tasks for you. I transformed one of SwitchBots (review) into a KettleBot. SwitchBot Curtain (review), or CurtainBot is, on the other hand, the best way to drag your curtains on the cheap without modifications. Everything SwitchBot just got better, thanks to SwitchBot API published on GitHub. I’m here to give you a headstart so you don’t feel lost.

Enjoy a discount of 20% using code 20NET in the SwitchBot store!

New in SwitchBot

The team behind the SwitchBot had been busy with app updates and the release of the SwitchBot API. The SwitchBot app has a new, more modern look and it’s easier to navigate thanks to new tabs. The functionality is still the same.

The SwitchBot API is a much more interesting update for me. Available on GitHub libraries are split between direct Bluetooth control and SwitchBot account API. There is also a Home Bridge integration if you are into HomeKit. Playing with Bluetooth stack is over my head if I’m honest, but I really appreciate the option. This way, you can interact with SwitchBot gadgets directly (without the need for a SwitchBot Hub).

REST API enables access to SwitchBot serves in a very easy way. To take advantage of this, you will need the SwitchBot hub. All devices registered with the SwitchBot account will be available via API.

Shop for Switchbot

Get Switchbot devices in the following stores:

How to use SwitchBot API

While HomeKit and Bluetooth integrations you have to figure out yourself, I will show you how to interact with SwitchBot API via REST and NodeRED. You will be able to download the flow as well so you don’t have to create anything from scratch! How good am I? Well, there is a support page in case you want to return the favour.

Thanks to SwitchBot API you can control your bots, curtains, IR devices and trigger scenes. Unfortunately, you won’t be able to capture SwitchBot Remote using this method (you can do so via Bluetooth API).

To get started, you will need an authentication token. Go to SwitchBot app Profile – Preferences and tap 10 times on App Version. It will generate the token for you. You will need this token to authenticate your requests. To make it easier, save the token as a global variable (and turn on persistent context) with global.set("SwitchBotAPI", "token"). All my flows will use that to authenticate sent requests.

Getting devices and scenes

SwitchBot API uses device ID in requests, so it makes sense to grab all of these for each device and scene, and then save them as flow variables. This way I don’t have to refer back and forth and my functions will retrieve the correct ID based on submitted names. The same principle applies to scenes created in the app.

The flow is fairly simple, compose the HTTP header with an authentication token and the list of devices will be sent back as JSON.

//devices
msg.headers = {Authorization: global.get("SwitchBotAPI")};
msg.url = "https://api.switch-bot.com/v1.0/devices";
return msg;

//scenes
msg.headers = {Authorization: global.get("SwitchBotAPI")};
msg.url = "https://api.switch-bot.com/v1.0/scenes";
return msg;

The list is iterated and saved to flow variables for devices and scenes for your convenience. If you add new devices, simply re-run the flow and you are up to date. The same goes if your devices are renamed.

//devices
var devices = msg.payload.body.deviceList
var deviceList = [];

for( var y in devices) {    
    let device = {"type": devices[y].deviceType,
                  "name": devices[y].deviceName,
                  "deviceID": devices[y].deviceId
                 };
    deviceList.push(device);
} 
flow.set("devices", deviceList);
return msg;

//scenes
var scenes = msg.payload.body
var sceneList = [];

for( var y in scenes) {    
    let scene = { "name": scenes[y].sceneName,
                  "sceneID": scenes[y].sceneId
                 };
    sceneList.push(scene);
} 
flow.set("scenes", sceneList);
return msg;

Now that we have a list of devices to play with, let’s get started. Before I manipulate any of them, I will show you how to get statuses.

Status

As before, the request has to be authenticated, but this time, the URL has to contain the deviceID. Flow is designed to work with names. Submit the name, and the correct ID will be added to the final URL and status retrieved as a JSON message.

var devices = flow.get("devices");
var device =  msg.payload; //enter name of the device or use msg.payload 

function FindDevice(name){
    let index = devices.find(o => o.name === name);
    let deviceID = index.deviceID;
    return deviceID
}

msg.headers = {"Authorization": global.get("SwitchBotAPI"),
               "ContentType": "application/json; charset=utf8"};
                
msg.url = "https://api.switch-bot.com/v1.0/devices/"+ FindDevice(device) +"/status"
return msg;

Just make sure to ignore the incoming payloads in the HTTP node and keep it set as GET request.

Depending on the queried device, the response will contain different data. The temperature sensor will respond with values for temperature and humidity, SwitchBots will share the state and CurtainBots will let you know about their position.

// SwitchBot
"body": {
		"deviceId": "XXXXXXXXXX",
		"deviceType": "Bot",
		"hubDeviceId": "XXXXXXXXXX",
		"power": "off"
	}

//CurtainBot
"body": {
		"deviceId": "XXXXXXXXXX",
		"deviceType": "Curtain",
		"hubDeviceId": "XXXXXXXXXX",
		"calibrate": true,
		"group": false,
		"moving": false,
		"slidePosition": 25
	}

//SwitchBot Sensor
"body": {
		"deviceId": "XXXXXXXXXX",
		"deviceType": "Meter",
		"hubDeviceId": "XXXXXXXXXX",
		"humidity": 43,
		"temperature": 19.9
	}

Unfortunately, the data from the luminosity sensor from CurtainBots isn’t available at the time of the writing. Perhaps this will change in the future.

Control

It’s time for the exciting part: the control. You already had a peek at how I’m going to tackle the control scheme. I already have a script that identifies the deviceID given the name of the device. This time around, we have to use POST request and add the content type to the header. To complete the control scheme, we have to submit the control JSON in the body of the request: {"command":"command","parameter":"default","commandType":"command"};.

All control schemes will have a similar pattern. Take a closer look at the GitHub page to look up control commands for specific devices.

SwitchBot control

SwitchBot require “command” set to turnOn/turnOff/toggle – so the command JSON would look like this: {"command":turnOn/turnOff/toggle,"parameter":"default","commandType":"command"} – to. To streamline the use, I will pass the command as the msg.payload. I assume that for the control scenario you want to hardcode the name in the script.

var devices = flow.get("devices");
var device =  "White B"; //enter name of the device 

function FindDevice(name){
    let index = devices.find(o => o.name === name);
    let deviceID = index.deviceID;
    return deviceID
}
var command = msg.payload;
msg.headers = {"Authorization": global.get("SwitchBotAPI"),
               "ContentType": "application/json; charset=utf8"};                
msg.url = "https://api.switch-bot.com/v1.0/devices/"+ FindDevice(device) +"/commands"
msg.payload = {"command":command,"parameter":"default","commandType":"command"};

return msg;

CurtainBot control

CurtainBot also uses turnOn/turnOff commands as well as setPosition. The last one needs specific “parameter” to be set (index,mode,position). To be fair, I’m not sure what the index refers to, but “0” works just fine.

Modes are 0 (Performance Mode), 1 (Silent Mode), ff (default mode) and position is expressed in % 0-100 where 100 is closed.

In my flow, if the topic is set to setPosition, then the script will execute the params given in the payload, otherwise, you can use turnOn/turnOff as with SwitchBot.

var devices = flow.get("devices");
var param = msg.topic;

if(param === undefined){
    param = "default";
}

var device =  "Curtain"; //enter name of the device or use msg.payload 

function FindDevice(name){
    let index = devices.find(o => o.name === name);    
    let deviceID = index.deviceID;
    return deviceID
}
var command = msg.payload;

msg.headers = {"Authorization": global.get("SwitchBotAPI"),
               "ContentType": "application/json; charset=utf8"};
                
msg.url = "https://api.switch-bot.com/v1.0/devices/"+ FindDevice(device) +"/commands"
msg.payload = {"command":command,"parameter":param,"commandType":"command"};

return msg;

IR control

The most complex commands are with IR devices. I’d strongly recommend using scenes instead for this, but if you are fixed on making the commands from scratch, you can compose it based on GitHub reference.

In this case, all params have to be set according to device specifications. The script allows this if msg.topic is set to custom.

var devices = flow.get("devices");

var device =  "Curtain"; //enter name of the device or use msg.payload 
msg.payload = {"command":command,"parameter":"default","commandType":"customize"};

if(msg.topic !== "custom"){    
    msg.payload = {"command":command,"parameter":"default","commandType":"customize"};    
}

function FindDevice(name){
    let index = devices.find(o => o.name === name);    
    let deviceID = index.deviceID;
    return deviceID
}
var command = msg.payload;
msg.headers = {"Authorization": global.get("SwitchBotAPI"),
               "ContentType": "application/json; charset=utf8"};                
msg.url = "https://api.switch-bot.com/v1.0/devices/"+ FindDevice(device) +"/commands"
return msg;

Executing scenes

As I already have a list of scenes available in NodeRED, executing these is very simple. SwitchBot API uses SceneID to trigger it and I already have a way of matching the name of the scene to the ID.

var devices = flow.get("devices");
var device =  msg.payload; //enter name of the device or use msg.payload 

function FindDevice(name){
    let index = devices.find(o => o.name === name);
    let deviceID = index.deviceID;
    return deviceID
}

msg.headers = {"Authorization": global.get("SwitchBotAPI"),
               "ContentType": "application/json; charset=utf8"};                
msg.url = "https://api.switch-bot.com/v1.0/devices/"+ FindDevice(device) +"/status"
return msg;

My NodeRED flow contains examples of executing commands for SwitchBot, CurtainBot and Scenes. So feel free to download it and modify that to your needs.

Shop for Switchbot

Get Switchbot devices in the following stores:

Final thoughts

I’m pleased to see SwitchBot opening API and offering local ways of controlling SwitchBot devices. It’s a move in a good direction and welcomed by any DIY enthusiast out there. For now, I’ll stick with SwitchBot API, but perhaps with time, I will give the local Bluetooth controls a go as well. I will keep you all posted. If you have any comments or questions leave it in this Reddit thread.

Project Download

Download project files here. Bear in mind that Patreon supporters have early access to project files and videos.

PayPal

Nothing says "Thank you" better than keeping my coffee jar topped up!

Patreon

Support me on Patreon and get an early access to tutorial files and videos.

image/svg+xml

Bitcoin (BTC)

Use this QR to keep me caffeinated with BTC: 1FwFqqh71mUTENcRe9q4s9AWFgoc8BA9ZU

Smart Ideas with

Automate your space in with these ecosystems and integrate it with other automation services

client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image

Learn NodeRED

NodeRED for beginners: 1. Why do you need a NodeRED server?

0
To server or not to server? That's a very silly question!

Best Automation Projects

Tuya SDK for beginners: Intro to Tuya Cloud API

0
Working with Tuya Cloud API. A guide to Cloud automation for beginners, get started with REST!

NEST your old thermostat under $5

0
Nest-ing up your older thermostat under $5

Nora – Google Assistant in NodeRED

0
Integrate Google Assistant with NodeRED thanks to Nora - NodeRED home automation

Sonoff Zigbee Bridge – review

0
Sonoff line up will soon include Sonoff Zigbee Bridge and more Zigbee sensors - here is the first look

DIY Smart Washing Machine – for about 15 bucks!

0
Learn how to add washing machine notifications to your Google Home on the cheap

Smart Home

We’ve seen this before: SwitchBot K10+ PRO

0
This is an odd one. Building on the success of SwitchBot K10+ they released SwitchBot K10+ PRO - but is the experience actually better?

Is this the smart panel we have waited for?

0
ITEAD has released a new smart panel: Sonoff NSPanel Pro 120 - have they learned the lesson from the terrible launch of the original Pro? Let's see what's new.

Aqara FP1E detects motionless humans

0
This isn't exactly a new device, it's an interaction of the original Aqara presence sensor. Aqara FP1E brings Matter, ZigBee and new triggers to your smart home

SwitchBot S10: cleaning re-imagined!

0
SwitchBot S10 promises unattended vacuuming and mopping so you can focus on things you love and care for. Does it deliver?

Sonoff for households and gardens

0
ITEAD released two ZigBee devices to manage water in your household and gardens. Now you can monitor the flow and dispense water with Sonoff SWV and prevent water damage using the Sonoff Water Leak sensor with a twist.