🚨 Active Supply Chain Attack:node-ipc Package Compromised.Learn More β†’
Socket
Book a DemoSign in
Socket

@switchbot/openapi-cli

Package Overview
Dependencies
Maintainers
4
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@switchbot/openapi-cli

Command-line interface for SwitchBot API v1.1

Source
npmnpm
Version
1.3.2
Version published
Weekly downloads
862
186.38%
Maintainers
4
Weekly downloads
Β 
Created
Source

@switchbot/openapi-cli

npm version npm downloads license node CI

Command-line interface for the SwitchBot API v1.1. List devices, query live status, send control commands, run scenes, and manage webhooks β€” all from your terminal or shell scripts.

Who is this for?

Three entry points, same binary β€” pick the one that matches how you use it:

AudienceWhere to startWhat you get
Humanthis README (Quick start)Colored tables, helpful hints on errors, shell completion, switchbot doctor self-check.
ScriptOutput modes, Scripting examples--json, --format=tsv/yaml/id, --fields, stable exit codes, history replay, audit log.
Agentdocs/agent-guide.mdswitchbot mcp serve (stdio MCP server), schema export, plan run, destructive-command guard.

Under the hood every surface shares the same catalog, cache, and HMAC client β€” switching between them costs nothing.

Table of contents

Features

  • πŸ”Œ Complete API coverage β€” every /v1.1 endpoint (devices, scenes, webhooks)
  • πŸ“š Built-in catalog β€” offline reference for every device type's supported commands, parameter formats, and status fields (no API call needed)
  • 🎨 Dual output modes β€” colorized tables by default; --json passthrough for jq and scripting
  • πŸ” Secure credentials β€” HMAC-SHA256 signed requests; config file written with 0600; env-var override for CI
  • πŸ” Dry-run mode β€” preview every mutating request before it hits the API
  • πŸ§ͺ Fully tested β€” 592 Vitest tests, mocked axios, zero network in CI
  • ⚑ Shell completion β€” Bash / Zsh / Fish / PowerShell

Requirements

  • Node.js β‰₯ 18
  • A SwitchBot account with Developer Options enabled (see Credentials)

Installation

npm install -g @switchbot/openapi-cli

This adds the switchbot binary to your $PATH.

From source

git clone https://github.com/OpenWonderLabs/switchbot-openapi-cli.git
cd switchbot-openapi-cli
npm install
npm run build
npm link      # optional β€” expose `switchbot` globally

Verify:

switchbot --version
switchbot --help

Quick start

# 1. Save your credentials (one-time)
switchbot config set-token <token> <secret>

# 2. List every device on your account
switchbot devices list

# 3. Control a device
switchbot devices command <deviceId> turnOn

Credentials

The CLI reads credentials in this order (first match wins):

  • Environment variables β€” SWITCHBOT_TOKEN and SWITCHBOT_SECRET
  • Config file β€” ~/.switchbot/config.json (written by config set-token, mode 0600)

Obtain the token and secret from the SwitchBot mobile app: Profile β†’ Preferences β†’ Developer Options β†’ Get Token.

# One-time setup (writes ~/.switchbot/config.json)
switchbot config set-token <token> <secret>

# Or export environment variables (e.g. in CI)
export SWITCHBOT_TOKEN=...
export SWITCHBOT_SECRET=...

# Confirm which source is active and see the masked secret
switchbot config show

Global options

OptionDescription
--jsonPrint the raw JSON response instead of a formatted table
--format <fmt>Output format: tsv, yaml, jsonl, json, id
--fields <cols>Comma-separated column names to include (e.g. deviceId,type)
-v, --verboseLog HTTP request/response details to stderr
--dry-runPrint mutating requests (POST/PUT/DELETE) without sending them
--timeout <ms>HTTP request timeout in milliseconds (default: 30000)
--config <path>Override credential file location (default: ~/.switchbot/config.json)
--profile <name>Use a named credential profile (~/.switchbot/profiles/<name>.json)
--cache <dur>Set list and status cache TTL, e.g. 5m, 1h, off, auto (default)
--cache-list <dur>Set list-cache TTL independently (overrides --cache)
--cache-status <dur>Set status-cache TTL independently (default off; overrides --cache)
--no-cacheDisable all cache reads for this invocation
--retry-on-429 <n>Max 429 retry attempts (default: 3)
--no-retryDisable automatic 429 retries
--backoff <strategy>Retry backoff: exponential (default) or linear
--no-quotaDisable local request-quota tracking
--audit-log [path]Append mutating commands to a JSONL audit log (default path: ~/.switchbot/audit.log)
-V, --versionPrint the CLI version
-h, --helpShow help for any command or subcommand

Every subcommand supports --help, and most include a parameter-format reference and examples.

switchbot --help
switchbot devices command --help

--dry-run

Intercepts every non-GET request: the CLI prints the URL/body it would have sent, then exits 0 without contacting the API. GET requests (list, status, query) are still executed so you can preview the state involved.

switchbot devices command ABC123 turnOn --dry-run
# [dry-run] Would POST https://api.switch-bot.com/v1.1/devices/ABC123/commands
# [dry-run] body: {"command":"turnOn","parameter":"default","commandType":"command"}

Commands

config β€” credential management

switchbot config set-token <token> <secret>   # Save to ~/.switchbot/config.json
switchbot config show                          # Print current source + masked secret

devices β€” list, status, control

# List all physical devices and IR remote devices
# Default columns (4): deviceId, deviceName, type, category
# Pass --wide for the full 10-column operator view
switchbot devices list
switchbot devices list --wide
switchbot devices list --json | jq '.deviceList[].deviceId'

# IR remotes: type = remoteType (e.g. "TV"), category = "ir"
# Physical: category = "physical"
switchbot devices list --format=tsv --fields=deviceId,type,category

# Filter by family / room (family & room info requires the 'src: OpenClaw'
# header, which this CLI sends on every request)
switchbot devices list --json | jq '.deviceList[] | select(.familyName == "Home")'
switchbot devices list --json | jq '[.deviceList[], .infraredRemoteList[]] | group_by(.familyName)'

# Query real-time status of a physical device
switchbot devices status <deviceId>
switchbot devices status <deviceId> --json

# Send a control command
switchbot devices command <deviceId> <cmd> [parameter] [--type command|customize]

# Describe a specific device (1 API call): metadata + supported commands + status fields
switchbot devices describe <deviceId>
switchbot devices describe <deviceId> --json

# Discover what's supported (offline reference, no API call)
switchbot devices types                 # List all device types + IR remote types
switchbot devices commands <type>       # Show commands, parameter formats, and status fields
switchbot devices commands Bot
switchbot devices commands "Smart Lock"
switchbot devices commands curtain      # Case-insensitive, substring match

Parameter formats

parameter is optional β€” omit it for commands like turnOn/turnOff (auto-defaults to "default"). Numeric-only and JSON-object parameters are auto-parsed; strings with colons / commas / semicolons pass through as-is.

For the exact commands and parameter formats a specific device supports, query the built-in catalog:

switchbot devices commands <type>       # e.g. Bot, Curtain, "Smart Lock", "Robot Vacuum Cleaner S10"

Generic parameter shapes (which one applies is decided by the device β€” see the catalog):

ShapeExample
(none)devices command <id> turnOn
<integer>devices command <id> setBrightness 75
<R:G:B>devices command <id> setColor "255:0:0"
<direction;angle>devices command <id> setPosition "up;60"
<a,b,c,…>devices command <id> setAll "26,1,3,on"
<json object>'{"action":"sweep","param":{"fanLevel":2,"times":1}}'
Custom IR buttondevices command <id> MyButton --type customize

For the complete per-device command reference, see the SwitchBot API docs.

scenes β€” run manual scenes

switchbot scenes list                 # Columns: sceneId, sceneName
switchbot scenes execute <sceneId>

webhook β€” receive device events over HTTP

# Register a receiver URL for events from ALL devices
switchbot webhook setup https://your.host/hook

# Query what is currently configured
switchbot webhook query
switchbot webhook query --details https://your.host/hook

# Enable / disable / re-submit the registered URL
switchbot webhook update https://your.host/hook --enable
switchbot webhook update https://your.host/hook --disable

# Remove the configuration
switchbot webhook delete https://your.host/hook

The CLI validates that <url> is an absolute http:// or https:// URL before calling the API. --enable and --disable are mutually exclusive.

completion β€” shell tab-completion

# Bash: load on every new shell
echo 'source <(switchbot completion bash)' >> ~/.bashrc

# Zsh
echo 'source <(switchbot completion zsh)' >> ~/.zshrc

# Fish
switchbot completion fish > ~/.config/fish/completions/switchbot.fish

# PowerShell (profile)
switchbot completion powershell >> $PROFILE

Supported shells: bash, zsh, fish, powershell (pwsh is accepted as an alias).

batch β€” run multiple commands

# Run a sequence of commands from a JSON/YAML file
switchbot batch run commands.json
switchbot batch run commands.yaml --dry-run

# Validate a plan file without executing it
switchbot batch validate commands.json

A batch file is a JSON array of { deviceId, command, parameter?, commandType? } objects.

watch β€” poll device status

# Poll a device's status every 30 s until Ctrl-C
switchbot watch <deviceId>
switchbot watch <deviceId> --interval 10s --json

Output is a stream of JSON status objects (with --json) or a refreshed table.

mcp β€” Model Context Protocol server

# Start the stdio MCP server (connect via Claude, Cursor, etc.)
switchbot mcp serve

Exposes 7 MCP tools: list_devices, describe_device, get_device_status, send_command, list_scenes, run_scene, search_catalog. See docs/agent-guide.md for the full tool reference and safety rules (destructive-command guard).

cache β€” inspect and clear local cache

# Show cache status (paths, age, entry counts)
switchbot cache show

# Clear everything
switchbot cache clear

# Clear only the device-list cache or only the status cache
switchbot cache clear --key list
switchbot cache clear --key status
  • Default β€” ANSI-colored tables for list/status, key-value tables for details.
  • --json β€” raw API payload passthrough. Output is the exact JSON the SwitchBot API returned, ideal for jq and scripting. Errors are also JSON on stderr: { "error": { "code", "kind", "message", "hint?" } }.
  • --format=json β€” projected row view. Same JSON structure but built from the CLI's column model (--fields applies). Use this when you only want specific fields.
  • --format=tsv|yaml|jsonl|id β€” tabular text formats; --fields filters columns.
# Raw API payload (--json)
switchbot devices list --json | jq '.deviceList[] | {id: .deviceId, name: .deviceName}'

# Projected rows with field filter (--format)
switchbot devices list --format tsv --fields deviceId,deviceName,type,cloud
switchbot devices list --format id      # one deviceId per line
switchbot devices status <id> --format yaml

Cache

The CLI maintains two local disk caches under ~/.switchbot/:

FileContentsDefault TTL
devices.jsonDevice metadata (id, name, type, category, hub, room…)1 hour
status.jsonPer-device status bodiesoff (0)

The device-list cache powers offline validation (command name checks, destructive-command guard) and the MCP server's send_command tool. It is refreshed automatically on every devices list call.

Cache control flags

# Turn off all cache reads for one invocation
switchbot devices list --no-cache

# Set both list and status TTL to 5 minutes
switchbot devices status <id> --cache 5m

# Set TTLs independently
switchbot devices status <id> --cache-list 2h --cache-status 30s

# Disable only the list cache (keep status cache at its current TTL)
switchbot devices list --cache-list 0

Cache management commands

# Show paths, age, and entry counts
switchbot cache show

# Clear all cached data
switchbot cache clear

# Scope the clear to one store
switchbot cache clear --key list
switchbot cache clear --key status

Status-cache GC

status.json entries are automatically evicted after 24 hours (or 10Γ— the configured status TTL, whichever is longer), so the file cannot grow without bound even when the status cache is left enabled long-term.

Exit codes & error codes

CodeMeaning
0Success (including --dry-run intercept)
1Runtime error β€” API error, network failure, missing credentials
2Usage error β€” bad flag, missing/invalid argument, unknown subcommand, unknown device type, invalid URL, conflicting flags

Typical errors bubble up in the form Error: <message> on stderr. The SwitchBot-specific error codes that get mapped to readable English messages:

CodeMeaning
151Device type error
152Device not found
160Command not supported by this device
161Device offline (BLE devices need a Hub)
171Hub offline
190Device internal error / server busy
401Authentication failed (check token/secret)
429Request rate too high (10,000 req/day cap)

Environment variables

VariableDescription
SWITCHBOT_TOKENAPI token β€” takes priority over the config file
SWITCHBOT_SECRETAPI secret β€” takes priority over the config file
NO_COLORDisable ANSI colors in all output (automatically respected)

Scripting examples

# Turn off every Bot device
switchbot devices list --json \
  | jq -r '.deviceList[] | select(.deviceType == "Bot") | .deviceId' \
  | while read id; do switchbot devices command "$id" turnOff; done

# Dump each scene as `<id> <name>`
switchbot scenes list --json | jq -r '.[] | "\(.sceneId) \(.sceneName)"'

Development

git clone https://github.com/OpenWonderLabs/switchbot-openapi-cli.git
cd switchbot-openapi-cli
npm install

npm run dev -- <args>       # Run from TypeScript sources via tsx
npm run build               # Compile to dist/
npm test                    # Run the Vitest suite (592 tests)
npm run test:watch          # Watch mode
npm run test:coverage       # Coverage report (v8, HTML + text)

Project layout

src/
β”œβ”€β”€ index.ts              # Commander entry; mounts all subcommands; global flags
β”œβ”€β”€ auth.ts               # HMAC-SHA256 signature (token + t + nonce β†’ sign)
β”œβ”€β”€ config.ts             # Credential load/save; env > file priority; --config override
β”œβ”€β”€ api/client.ts         # axios instance + request/response interceptors;
β”‚                         # --verbose / --dry-run / --timeout wiring
β”œβ”€β”€ devices/
β”‚   β”œβ”€β”€ catalog.ts        # Static device catalog (commands, params, status fields)
β”‚   └── cache.ts          # Disk + in-memory cache for device list and status
β”œβ”€β”€ lib/
β”‚   └── devices.ts        # Shared logic: listDevices, describeDevice, isDestructiveCommand
β”œβ”€β”€ commands/
β”‚   β”œβ”€β”€ config.ts
β”‚   β”œβ”€β”€ devices.ts
β”‚   β”œβ”€β”€ scenes.ts
β”‚   β”œβ”€β”€ webhook.ts
β”‚   β”œβ”€β”€ batch.ts          # `switchbot batch run/validate`
β”‚   β”œβ”€β”€ watch.ts          # `switchbot watch <deviceId>`
β”‚   β”œβ”€β”€ mcp.ts            # `switchbot mcp serve` (MCP stdio server)
β”‚   β”œβ”€β”€ cache.ts          # `switchbot cache show/clear`
β”‚   β”œβ”€β”€ history.ts        # `switchbot history [replay]`
β”‚   β”œβ”€β”€ events.ts         # `switchbot events`
β”‚   β”œβ”€β”€ quota.ts          # `switchbot quota`
β”‚   β”œβ”€β”€ explain.ts        # `switchbot explain <deviceId>`
β”‚   β”œβ”€β”€ plan.ts           # `switchbot plan run <file>`
β”‚   β”œβ”€β”€ doctor.ts         # `switchbot doctor`
β”‚   β”œβ”€β”€ schema.ts         # `switchbot schema export`
β”‚   β”œβ”€β”€ catalog.ts        # `switchbot catalog search`
β”‚   └── completion.ts     # `switchbot completion bash|zsh|fish|powershell`
└── utils/
    β”œβ”€β”€ flags.ts          # Global flag readers (isVerbose / isDryRun / getCacheMode / …)
    β”œβ”€β”€ output.ts         # printTable / printKeyValue / printJson / handleError / buildErrorPayload
    β”œβ”€β”€ format.ts         # renderRows / filterFields / output-format dispatch
    β”œβ”€β”€ audit.ts          # JSONL audit log writer
    └── quota.ts          # Local daily-quota counter
tests/                    # Vitest suite (592 tests, mocked axios, no network)

Release flow

Releases are cut on tag push and published to npm by GitHub Actions:

npm version patch        # bump version + create git tag
git push --follow-tags

Then on GitHub β†’ Releases β†’ Draft a new release β†’ select tag β†’ Publish. The publish.yml workflow runs tests, verifies the tag matches package.json, and publishes @switchbot/openapi-cli to npm with provenance.

Contributing

Bug reports, feature requests, and PRs are welcome.

  • Fork the repo and create a topic branch.
  • Keep changes small and focused; add or update Vitest cases for any behavior change.
  • Run npm test and npm run build locally β€” both must pass.
  • Open a pull request against main. CI runs on Node 18/20/22; all three must stay green.

License

MIT Β© chenliuyun

References

Keywords

switchbot

FAQs

Package last updated on 19 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts