iHost Open API

1. Start to Use

1.1 Preparation

Step 1. Please make sure the gateway is powered on and works properly.

The BLUE indicator is a normal network connection.

The RED indicator is an abnormal network connection.

Step 2. Make sure the gateway and the PC are connected to the same LAN. Then enter the URL http://ihost.local on your browser.

Notice:

If you have several gateways, you can get the corresponding IP address to access the specified gateway in the below two ways.

  1. Log in to your wireless router and check the IP address of the gateway in DHCP.
  2. iHost supports local discovery via mDNS.

1.2 Get started

  • Call the [Access Token] interface, and get an error response, prompting to click <Done>. Note that after pressing, the interface access is valid for no more than 5 minutes.

// Request
curl --location --request GET 'http://<ip address>/open-api/v1/rest/bridge/access_token' --header 'Content-Type: application/json'
// Response
{
  "error": 401,
  "data": {},
  "message": "link button not pressed" 
}
  • Click <Done> and call the [Access Token] interface again. The response is successful, and the token is obtained.
// Request
curl --location --request GET 'http://<ip address>/open-api/v1/rest/bridge/access_token' --header 'Content-Type: application/json'
// Response
{
  "error": 0,
  "data": {
    "token": "376310da-7adf-4521-b18c-5e0752cfff8d"
  },
  "message": "success"
}

  • Verify token. Call the [Get Device List] interface. The response is successful, and the device list is obtained.
// Request
curl --location --request GET 'http://<ip address>/open-api/v1/rest/devices' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer 376310da-7adf-4521-b18c-5e0752cfff8d'
// Response
{
  "error": 0,
  "data": {
    "device_list":  [
      {
        "serial_number": "ABCDEFGHIJK",
        "name": "device name",
        "manufacturer": "manufacturer name",
        "model": "model name",
        "firmware_version": "1.1.0",
        "display_category": "switch",
        "capabilities": [
          {
            "capability": "power",
            "permission": "readWrite"
          }
        ],
        "protocol": "zigbee",
        "state": {
          "power": {
            "powerState": "on"
          }
        },
        "tags": {
          "key": "value"
        },
        "online": true
      }
    ]
  }
  "message": "success"
}
  • Get iHost access token method: After calling the [Access Token] interface, the iHost Web console page global pop-up box prompts the user to confirm the acquisition of the interface call credentials.
  • Note: If you open more than one iHost web console page, the confirmation pop-up box will appear on multiple web console pages together, and the pop-up box of other web console pages will be closed after clicking the confirmation on one of the web console pages.

2. Core Concept

2.1 Development Interface Address

The gateway Web API interface has two access methods (based on IP or domain name), usually the root path is /open-api/v1/rest/< specific function module >

// IP access
http://<IP address>/open-api/v1/rest/bridge

// Domain name access
http://<domain address>/open-api/v1/rest/bridge

2.2 Device Display Category & Capabilities

  • Device display category (DisplayCategory). Device display category is used to identify (device) specific categories, such as switch, plug, light, etc. This information will determine the UI display effect of the device in the gateway.
  • Device Capability. Device capability is used to describe the specific sub-functions of the device. Such as power control, brightness control, color temperature control, etc. A single device can support 1 or more capabilities.
    • Ability name. Identify a specific capability. For example power, brightness.
    • Ability permission. Identify whether the capability supports reading or writing.
      • Read-only (read). Obtain the status value or configuration information related to this capability. For example, the states of power are on (open) and off (closed).
      • Write-only (write). Update the status value or configuration information related to the capability. For example, the power status can be changed to off through the interface.
      • Read&Write (readWrite). This capability supports both reading and writing.
// Device capabilities description
{
  "capabilities": [
    // Power control
    {
      "capability": "power",
      "permission": "readWrite"
    },
    // Brightness adjustment
    {
      "capability": "brightness",
      "permission": "readWrite"
} ] } // Obtain the status state structure returned by the device list interface { "state":{ "[capability]": { "[capabilityState]":[value] } } } { "state": { "power": { "powerState": "on" }, "brightness": { "brightness": 100 } } } // Modify device state - power off { "state": { "power": { "powerState": "off" } } }

3.Web API

Type of Data

TypeDescription
stringString data type. UTF8 encoded.
numberNumber data type. double-precision 64-bit binary format IEEE 754
intIntegral data type.
objectObject data type. JSON-compliant object
string[]Array of string
int[]Array of integral
object[]Array of object
boolBoolean
dateTime string. String in ISO (ISO 8601 Extended Format) format: YYYY-MM-DDTHH:mm:ss.sssZ. The time zone is always UTC (Coordinated Universal Time), identified by a suffix “Z”.

Generic Response Results

Attribute

Type

Optional

Description

error

int

N

Error code:0: Success400:Parameter error401:Authentication failed500:Server exception

data

object

N

Response data body

message

string

N

Response description:When error is equal to 0, the content is successWhen error is not equal to 0, it is a non-empty string, and the content is an error description.

Response Example:

{
  "error": 0,
  "data": {
    "token": "376310da-7adf-4521-b18c-5e0752cfff8d"
  },
  "message": "success"
}

{
  "error": 400,
  "data": {},
  "message": "invalid parameters"
}

Resource List

Type

Description

Supported sound

– alert1 (Alarm Sound 1)
– alert2 (Alarm Sound 2)
– alert3 (Alarm Sound 3)
– alert4 (Alarm Sound 4)
– alert5 (Alarm Sound 5)
– doorbell1 (Doorbell Sound 1)
– doorbell2 (Doorbell Sound 2)
– doorbell3 (Doorbell Sound 3)
– doorbell4 (Doorbell Sound 4)
– doorbell5 (Doorbell Sound 5)
– alarm1 (Alarm Sound 1)
– alarm2 (Alarm Sound 2)
– alarm3 (Alarm Sound 3)
– alarm4 (Alarm Sound 4)
– alarm5 (Alarm Sound 5)

Supported deep

– bootComplete (System startup completed)
– networkConnected (Network connected)
– networkDisconnected (Network disconnected)
– systemShutdown (System shutdown)
-deviceDiscovered (Discover device)
– system Armed (System armed enable)
– system Disarmed (System armed disable)
– factoryReset (Reset device)

3.1 The Gateway Function

a. Access Token

Allow users to access token. iHost Version ≥ 1.2.0
●  Notice: The token will be cleared after device reset.
●  Notice: After obtaining the token, you need to press the button again to successfully obtain a new token.

  • URL:/open-api/v1/rest/bridge/access_token
  • Method:GET
  • Header
    • Content-Type: application/json

Request Parameters: 

iHost Version< 1.3.0

None

iHost Version ≥ 1.3.0

Attribute

Type

Optional

Description

app_name

string

Y

Application name description.

Successful data response:

Attribute

Type

Optional

Description

token

string

N

The interface access token. It’s valid for a long time, please save it

Condition: User trigger the < command key > and access this interface within the valid time.

Status Code: 200 OK

Response Example:
{
"error": 0,
"data": {
"token": "376310da-7adf-4521-b18c-5e0752cfff8d"
},
"message": "success"
}
Failure data response:empty Object

Conditions:The user has not triggered the < command key >, or the valid time has expired.

Status Code:  200 OK

Response Example:
{
  "error": 401,
  "data": {},
  "message": "link button not pressed"
}

b. Get the State of Gateway

iHost Version ≥ 1.2.0

Allow authorized users to obtain the status of gateway through this interface

  • URL:/open-api/v1/rest/bridge/runtime
  • Method:GET
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request Parameters: none

Successful data response:

Attribute

Type

Optional

Description

ram_used

int

N

ram usage percent.[0-100]

cpu_used

int

N

cpu usage percentage. [0-100]

power_up_time

date

N

The last power-on time

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {
    "ram_used": 40,
    "cpu_used": 30,
    "power_up_time": "2022-10-12T02:58:09.989Z"
  },
  "message": "success"
}

c. Set the Gateway

iHost Version ≥ 1.2.0

Allow authorized users to set the gateway through this interface

  • URL:/open-api/v1/rest/bridge/config
  • Method:PUT
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters:

Attribute

Type

Optional

Description

volume

int

Y

System volume. [0-100]

Successful data response:empty Object {}

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}

d. Get the Gateway info

iHost Version ≥ 1.3.0

Allow authorized users to get the gateway info through this interface

  • URL:/open-api/v1/rest/bridge
  • Method:GET
  • Header
    • Content-Type: application/json

Request parameters:

AttributeTypeOptionalDescription
ipstringNip address
macstringNmac address
domain iHost≥1.5.1stringYGateway service domain
fw_version iHost≥1.9.1stringNFirmware version
name iHost≥1.10.1stringNDevice name

Successful data response:empty Object {}

{
  "error": 0,
  "data": {
    "ip": "192.168.31.25",
    "mac": "00:0A:02:0B:03:0C"
  },
  "message": "success"
}

3.2 Hardware Function

a. Restart Gateway

iHost Version ≥ 1.2.0

Allow authorized user to restart the gateway through this interface

  • URL:/open-api/v1/rest/hardware/reboot
  • Method:POST
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters: None

Successful data response: empty Object {}

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}

b. Speaker Control

iHost Version ≥ 1.2.0

Allow authorized users to control the speaker through this interface

  • URL:/open-api/v1/rest/hardware/speaker
  • Method:POST
  • Header
    • Content-Type: application/json
    • Authorization: Bearer <token>

Request parameters: 

Attribute

Type

Optional

Description

type

string

N

Optional parameters: 1.play_sound (play the sound) 2.play_beep (play the beep)

sound

SoundObject

Y (N if type is play_sound.)

The sound.

beep

BeepObject

Y (N if type is play_beep.)

The beep

SoundObject Object

Attribute

Type

Optional

Description

name

string

N

The sound name. The supported values can be checked in [Resource List – Supported sound]

volume

int

N

The sound volume. [0-100]

countdown

int

N

The duration for the speaker to play the sound, and it will stop playing automatically after the time is up. Unit: second. [0,1799]

BeepObject Object

Attribute

Type

Optional

Description

name

string

N

The deep name. The supported values can be checked in [Resource List – Supported deep]

volume

int

N

The deep volume. [0-100]

Successful data response: empty Object {}

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}

3.3 Device Management Function

a. Supported Device Type

Device Type

Value

iHost Version

Plug

plug

≥ 1.2.0

Switch

switch

≥ 1.2.0

Light

light

≥ 1.2.0

Curtain

curtain

≥ 1.2.0

Door/Window Sensor

contactSensor

≥ 1.2.0

Motion sensor

motionSensor

≥ 1.2.0

Temperature sensor

temperatureSensor

≥ 1.2.0

Humidity sensor

humiditySensor

≥ 1.2.0

Temperature and humidity sensor

temperatureAndHumiditySensor

≥ 1.2.0

Water leak detector

waterLeakDetector

≥ 1.2.0

Smoke detector

smokeDetector

≥ 1.2.0

Wireless button

button

≥ 1.2.0

Camera

camera

≥ 1.2.0

General sensor

sensor

b. Supported Device Capabilities

NameDescriptionCapability&Permission ExampleAttribute(Status)Protocol(Status inquiry&Control command)
power

Power control

iHost Version ≥ 1.2.0

[ { “capability”: “power”, “permission”: “readWrite” }]{ “powerState”: “on”, //The field powerState indicates the power on/off state, which is required. string type, ”on“ means on, ”off“ means off, ”toggle“ means reverse.}Turn on:{ “powerState”: “on”}Turn off:{ “powerState”: “off”}
toggle

Toggle control

iHost Version ≥ 1.2.0

[  // Single toggle example { “capability”: “toggle”, “permission”: “readWrite”, “name”: “1” }, // Multiple toggle example[ { “capability”: “toggle”, “permission”: “readWrite”, “name”: “1” }, { “capability”: “toggle”, “permission”: “readWrite”, “name”: “2” }]{ “toggleState”: “on”, // The field “toggleState” indicates the toggle state of the {name} attribute of {device_id}. Required. String type. “on” means open, “off” means close, “toggle” means reverse.}toggle format is special{ [capability] :{ [toggle-name]:{ [toggleState]:[value] } }}toggle 1 on, toggle 2 off{ “toggle”: { “1”: { “toggleState”: “on” },  “2”: { “toggleState”: “off” } }}
brightness

Brightness Control

iHost Version ≥ 1.2.0

[ { “capability”: “brightness”, “permission”: “readWrite” }]{ “brightness”: 100, // The field “brightness” indicates the percentage of brightness. Int type. An integer with a value range of 0~100.}0 is the darkest and 100 is the brightest. Set the brightness to 80%. { “brightness”: { “brightness”: 80, }}
color-temperature

Color temperature control

iHost Version ≥ 1.2.0

[ { “capability”: “color-temperature”, “permission”: “readWrite” }]{ “colorTemperature”: 100, // 字段 “colorTemperature” Indicates the percentage of color temperature. Int type. An integer with a value range of 0~100. 0 means warm light, 50 means neutral light, and 100 means cold light.}Set the Color temperature to 80%. { “color-temperature”: { “colorTemperature”: 50 }}
color-rgb

Color control

iHost Version ≥ 1.2.0

[ { “capability”: “color-rgb”, “permission”: “readWrite” }]{ “red”: 255, // The field “red” represents red in the RGB color space. Required. Int type. An integer with a value range of 0~255. “green”: 0, // The field “green” represents green in the RGB color space. Required. Int type. An integer with a value range of 0~255. “blue”: 255, // The field “blue” represents blue in the RGB color space. Required. Int type. An integer with a value range of 0~255.}Set the color.{ “color-rgb”: { “red”: 255,  “green”: 0,  “blue”: 255,  }}
percentage

Percentage control

iHost Version ≥ 1.2.0

[ { “capability”: “percentage”, “permission”: “readWrite” }]{ “percentage”: 100, // The field “percentage” represents a percentage of a certain degree, and the field percentageDelta can be selected as one of the two. int type. An integer with a value range of 0~100.}Set to 40%{ “percentage”: { “percentage”: 40 }}
motor-control

Motor control

iHost Version ≥ 1.2.0

[ { “capability”: “motor-control”, “permission”: “readWrite” }]{ “motorControl”: “stop”, // The field “motor-control“ indicates the open or close state of the motor。 Required. String type. Optional values, “open” (open), “close” (close), “stop” (stop), “lock” (lock).}Turn on the motor{ “motor-control”: { “motorControl”: “open” }}
motor-reverse

Motor reverse

iHost Version ≥ 1.2.0

[ { “capability”: “motor-reverse”, “permission”: “readWrite” }]{ “motorReverse”: true, // The field “motor-reverse” indicates the forward and reverse setting of the motor. Required. boolean type. true means forward rotation, false means reverse rotation.}Set the motor reverse{ “motor-reverse”: { “motorReverse”: false }}
startup

Power on state (Power Supply)

iHost Version ≥ 1.2.0

[ { “capability”: “startup”, “permission”: “readWrite” }]{ “startup”: “on” // String type. Required. Optional values, “on” (power on) ,“stay“ (stay power on),”off“ (power off)}Set the power on state to always stay on when powered on{ “startup”: { “startup”: “on” }}
startup

Toggle power on state (can use with toggle)

iHost Version ≥ 1.2.0

[ { “capability”: “startup”, “permission”: “readWrite”, “components”: [ //Components that support power on retention. If the device with the toggle sub-channel needs to support power on retention, this field is mandatory. In particular, the toggle capability supports separate power-on retention settings. For details, see the update protocol of toggle. // toggle 1 power on state { “capability”: “toggle”, // String type. Required. Represents the name of the component capability that supports power-on retention. Only “power” and “toggle” are supported. “name”: “1”, // The field “name” indicates the attribute name that can be toggled. Required. String type. Only uppercase and lowercase letters and numbers are allowed. Taking the multi-channel switch as an example, it should be the channel number, that is, 1, 2, 3, 4 } ]  }]{ “startup”: “on” // String type. Required. Optional values, “on” (power on) ,“stay“ (stay power on),”off“ (power off)}When channel 1 power on, the power state is always on{ “toggle”: { “1”: { “startup”: “on” } }}
camera-stream

Camera stream

iHost Version ≥ 1.2.0

{ “capability”: “camera-stream”, // The field “capability” indicates the name of the specific function. Rrequired. String type. camera-stream indicates the video streaming capability of the camera. “permission”: “read”, // The field “permission” indicates the use of specific functions. Required. String type. Optional values: “read” (readable), “write” (writable), “readWrite” (readable and writable)。 “configuration”: { “streamUrl”: “rtsp://<username>:<password>@<hostname>:<port>/streaming/channel01”, //stream url. String type. Required. } }/{ “camera-stream”: { “configuration”: { “streamUrl”: “rtsp://<username>:<password>@<hostname>:<port>/streaming/channel01”, // stream url. String type. Required. } }}
motor-clb

Motor calibration detection

iHost Version ≥ 1.2.0

[ { “capability”: “motor-clb”, “permission”: “read” }]{ “motorClb”: “calibration”, // The field “motor-clb” indicates that the motor has been calibrated Required. String type, normal means normal mode (calibrated), calibration means it is being calibrated.}The motor is being calibrated.{ “motor-clb”: { “motorClb”: “calibration” }}
detect

State detection

iHost Version ≥ 1.2.0

[ { “capability”: “detect”, “permission”: “read” }]{ “detected”: true, // The field “detected” indicates the current detection result. Required. Boolean type, true indicates that the condition is detected, false indicates that the condition is not detected.}The current state is the result detected.{ “detect”: { “detected”: true }}
humidity

Humidity detection

iHost Version ≥ 1.2.0

[ { “capability”: “humidity”, “permission”: “read”, “configuration”: { // Configuration items, optional “range”: { // Percentage range configuration. Optional. Default range [0-100].  “min”: 0, // Minimum value, int type. Required. Range 0-100, must be less than max.  “max”: 100 // Maximum value, int type. Required. Range 0-100, must be greater than min.  } } }]{ “humidity”: 50, // The field “humidity” indicates the current relative humidity (percentage). Required. Int type. An integer with a value range of 0~100.}Current humidity is 20{ “humidity”: { “humidity”: 20 }}
temperature

Temperature detection

iHost Version ≥ 1.2.0

[ { “capability”: “temperature”, “permission”: “read”, “configuration”: { // Configuration items, optional “range”: { // Temperature range configuration. Optional. “min”: -40, // Minimum value, int type. Required. “max”: 80 //Maximum value, int type. Required. } } }]{ “temperature”: 26.5, // The field “temperature” indicates the current temperature. Required. Number type. The unit is Celsius.}Current temperature is 20 Celsius{“temperature”: {“temperature”: 20}}
battery

Remaining battery detection

iHost Version ≥ 1.2.0

[{ “capability”: “battery”, “permission”: “read” }]{ “battery”: 95, // The field “battery” indicates the percentage of remaining battery power. Required. Int type. An integer with a value range of -1~100. -1 means that the battery level is unknown.}Current remaining power is 40.{ “battery”: { “battery”: 40 }}
press

Press detection

iHost Version ≥ 1.2.0

[ { “capability”: “press”, “permission”: “read” }]{ “press”: “singlePress”, // The field “press” indicates the method of pressing the button. Required. String type. ptional values: “singlePress” (single-click/single short press), “doublePress” (double-click/two consecutive short presses), “longPress” (long press).}A single click was detected{ “press”: { “press”: “singlePress” }}
rssi

Wireless signal strength detection

iHost Version ≥ 1.2.0

[ { “capability”: “rssi”, “permission”: “read” }]{ “rssi”: -65, // The field “rssi” indicates the wireless signal strength (received signal strength indication). Required. int type. The unit is dBm, and the optional value is a negative integer.}{ “rssi”: {“rssi”: -65 }}
configurationFunction configuration[ { “capability”: “configuration”, “permission”: “readWrite” }]{ “deviceConfiguration”: { // Device-related function configuration “defaultReportResolution”: 300, // Default resolution for reading moisture saturation data. Int type. Required. Unit second.  “maxReportResolution”: 86400, // Maximum resolution for reading moisture saturation data. Required. Unit second.  “minReportResolution”: 60 // Minimum and minimum resolution for reading moisture saturation data. Required. Unit second.  }}{ “configuration”: { // Capability-related configuration, optional.  “deviceConfiguration”: { “report”: { // Report configuration. Required.  “defaultResolution”: 300, // Default resolution for reading moisture saturation data. Int type, mandatory, unit second.  “maxResolution”: 86400, // Maximum resolution for reading moisture saturation data, required, unit seconds.  “minResolution”: 60 // The minimum and minimum resolution for reading moisture saturation data. Required, unit seconds.  } } }}
systemSystem functions[ { “capability”: “system”, “permission”: “write” }]{ “restart”: true, // Restart device command. Boolean type. Required. The value is true only.}{ “system”: { // Capability-related configuration. Optional. “restart”: true }}
moistureMoisture detection[ { “capability”: “moisture”, “permission”: “read” }]{ “moisture”: 55.5, // The field “moisture” represents the percent moisture saturation. Number type, required. The value range is 0~100. From completely dry to fully saturated (saturation from 0% to 100%).}/ Report the current moisture saturation{ “moisture”: { “moisture”: 55.5 }}
barometric-pressureBarometric pressure detection[ { “capability”: “barometric-pressure”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //Air pressure range. Optional. Default range [540-1100] “min”: 540, // Minimum value, int type. Required. Range greater than or equal to 0, Must be less than max.  “max”: 1100 // Maximum value, int type, mandatory, range greater than 0, must be greater than min.  } } }]{ “barometricPressure”: 50, // Air pressure value, int type. Required. Unit hPa.}// Report the current barometric pressure{ “barometric-pressure”: { “barometricPressure”: 5000 }}
wind-speedWind speed detection[ { “capability”: “wind-speed”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { // Wind speed range. Optional. Default range [0-50] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “windSpeed”: 5000, //Wind speed value, number type. Required. Unit m/s (meter per second)}// Report the current wind speed{ “wind-speed”: { “windSpeed”: 50 }}
wind-directionWind direction detection[ { “capability”: “wind-direction”, “permission”: “read” }]{ “windDirection”: 10 // Wind direction. Int type. Required. The units are degrees. Range 0~360 degrees (clockwise).}// Report the current wind direction{ “wind-direction”: { “windDirection”: 10 //Wind direction. Int type. Required. The units are degrees. Range 0~360 degrees (clockwise). }}
rainfallRainfall detection[ { “capability”: “rainfall”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //Rainfall, optional, default range [0-450] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “rainfall”:11.11, // Rainfall value. Number type. Required.Unit mm/s (millimeters per hour).}// Report current precipitation{ “rainfall”: { “rainfall”: 50 }}
illuminationillumination detection[ { “capability”: “illumination”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //Illumination lux range. Optional. Default range [0,160000] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “illumination”: 11, // Illumination value. Int type. Required. Unit lux (lux)}// Report the current illuminance{ “illumination”: { “illumination”: { “value”: 5000, // Illumination value, int type. Required. Default range [0,160000]. “unit”: “lux” //Illumination value. Int type. Required. Unit lux (lux) } }}
ultraviolet-indexUV Index detection[ { “capability”: “ultraviolet-index”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //UV index range. Optional, default range [0-16] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “ultravioletIndex”: 11.1 // UV index. Number type. Required.}// Report current UV index{ “ultraviolet-index”: { “ultravioletIndex”: 5 }}
co2co2 detection[ { “capability”: “co2”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //ppm range, default range [400-10000] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “co2”: 111, // co2 concentration. Int type. Required. Unit ppm}// Report current co2 concentration{ “co2”: { “co2”: 500 }}
electrical-conductivityElectrical conductivity detection[ { “capability”: “electrical-conductivity”, “permission”: “read”, “configuration”: { // Capability configuration. Optional.  “range”: { //electrical conductivity range, default range [0-23] “min”: 0, // minimum value. Number type. Mandatory, range greater than or equal to 0, Must be less than max.  “max”: 50 // Maximum value, number type, mandatory, range greater than 0, must be greater than min.  } } }]{ “electricalConductivity”: 11.11 // electrical conductivity. Number type. Required. Unit dS/m。}// Report current electrical conductivity{ “electrical-conductivity”: { “electricalConductivity”: 11.11 // electrical conductivity. Number type. Required. Unit dS/m }}

electric-power

Power detection

iHost Version ≥ 1.6.0

[

{

“capability”: “electric-power”,

“permission”: “read”

}

}

]

{
“electric-power”: 50, // The electric-power field represents the current power value, the unit is 0.01W, the value range is greater than or equal to 0, required. int type.
“reactivePower”: 50, // The field reactivePower represents the current reactive power value, the unit is 0.01W, the value range is greater than or equal to 0, optional. int type.
“activePower”: 50, // The field activePower represents the current active power value, the unit is 0.01W, the value range is greater than or equal to 0, optional. int type.
“apparentPower”: 50, // The field apparentPower represents the current apparent power value, the unit is 0.01W, the value range is greater than or equal to 0, optional. int type.
}
}

{

“electric-power”: {

“electric-power”: 50,

“reactivePower”: 50,

“activePower”: 50,

“apparentPower”: 50,

}

}

modeMode control[
{
“capability”: “mode”,
“permission”: “readWrite”,
“name”: “fanLevel” // Mode name, used to identify specific mode functions, string type, required. Please refer to [Supported Preset Modes] for optional parameters. For example, fanLevel identifies the fan gear mode and can adjust the specific mode value.
“configuration”: { // Configuration items, optional
“supportedValues”: [ // Optional mode values. Optional. For the default value, please refer to [Supported Default Modes]. Custom mode values can be passed in through this parameter, and if configured, all will be overwritten.
“low”, “medium”, “high”, “normal”
]
}
}
]
{
“modeValue”: “low” // Mode value, String type, required. Please refer to [Supported Preset Modes] for optional parameters.
}
The current fan speed mode of the device is “Low” mode
{
“mode”: {
“fanLevel”: {
“modeValue”: “low”
}
}
}

thermostat-mode-detect

Thermostat  mode detection

There are two detection types:
1. Temperature detection (temperature)
2. Humidity detection

Detection options:
1. Minimum value detection: lowerSetpoint
2. Highest value detection: upperSetpoint

Supported modes:
1. supportedModes

[
{
“capability”: “thermostat-mode-detect”, // Temperature control mode detection
“permission”: “readWrite”,
“name”: “humidity”, // Temperature control detection type, String type, required. Optional parameters, humidity (humidity detection), temperature (temperature detection)
“configuration”: { // required
“supported”: [ // Supported detection setting conditions, required.
{
“name”: “lowerSetpoint”, // The detection value should remain above the set value. There must be at least one lowerSetpoint and upperSetpoint.
“value”: { // Detection range, optional. If there are preset conditions, write them.
“value”: 68.0, // Temperature or humidity value, required.
“scale”: “f” // Temperature unit, required when name=temperature. c (Celsius), f (Fahrenheit)
}
},
{
“name”: “upperSetpoint”, // The detection value should remain below the set value. There must be at least one lowerSetpoint and upperSetpoint.
“value”: { // Detection range, optional. If there are preset conditions, write them.
“value”: 68.0, // Temperature or humidity value, required.
“scale”: “f” // Temperature unit, required when name=temperature. c (Celsius), f (Fahrenheit)
}
}
],
“supportedModes”: [ // Supported modes, optional.
“COMFORT”, “COLD” //Supported mode id, optional parameters, COMFORT (comfort mode), COLD (cold mode), HOT (hot), DRY (dry), WET (humid)
]
}
}
]
{
“mode”: “COMFORT”, // Supported mode id, optional parameters, COMFORT (comfort mode), COLD (cold mode), HOT (hot), DRY (dry), WET (humid)
}

Format:
{
[capability] :{
[mode name]: {
mode:[value]
}
}
}

Example:
{
“thermostat-mode-detect “: {
“humidity”: {
“mode”: “COMFORT”
}
}
}

illumination-levelIllumination Level

[

{

“capability”: “illumination-level”,

“permission”: “read”

}

]

{
“level”: “brighter”, // Brightness level, String type, required. Optional parameters, “brighter” (brighter), “darker” (darker)
}

{

“illumination-level”: {

“level”: “brighter”

}

}

multi-press

Multiple wireless buttons[
{
“capability”: “multi-press”,
“permission”: “read”,
“name”: “1”, // The field name represents the attribute name of multi-press and is required. String type, only allowed to contain uppercase and lowercase letters and numbers. Taking a multi-channel switch as an example, the channels should be numbered, i.e. 1, 2, 3, 4.
]
{
“press”: “singlePress”, // The field press indicates the way the button is pressed, required. String type, standard optional values are “singlePress” (single click/single short press), “doublePress” (double click/two consecutive short presses), and “longPress” (long press).
}

{

[capability] :{

[multi-press-name]:{

press:[value]

}

}

}

Example:

{

“multi-press”: {

“1”: {

“press”: “singlePress”

},

“2”: {

“press”: “doublePress”

}

}

}

thermostat-target-setpoint
Thermosta Target Setpoint[
{
“capability”: “thermostat-target-setpoint”,
“permission”: “readWrite”,
“name”: “temperature”, // component name, String type, “temperature” represents the target temperature of the temperature control device
“configuration”: {
“temperature”: { // Temperature configuration item, default range [0,100]
“min”: 4, // Minimum value, number type, required, must be less than max
“max”: 35, // Maximum value, number type, required, must be greater than min
“increment”: 0.5, // Temperature adjustment step, optional, the unit is the same as scale.
“scale”: “c” // Temperature unit, optional, default is “c”. c (Celsius), f (Fahrenheit)
}
}
},
{
“capability”: “thermostat-target-setpoint”,
“permission”: “readWrite”,
“name”: “manual-mode”, // component name, String type, “manual-mode” represents the target temperature in manual mode of the temperature control device
“configuration”: {
“temperature”: {
“min”: 4,
“max”: 35,
“increment”: 0.5, // Temperature adjustment step size, the unit is the same as scale. required.
“scale”: “c” // Temperature unit, required. c (Celsius), f (Fahrenheit)
},
“mappingMode”: “MANUAL” // Mapping mode: thermostat-mode.MANUAL
}
},
{
“capability”: “thermostat-target-setpoint”,
“permission”: “read”,
“name”: “auto-mode”, // Component name, String type, “auto-mode” represents the target temperature in the automatic mode of the temperature control device
“configuration”: {
“temperature”: { // Temperature configuration item
“min”: 4,
“max”: 35,
“increment”: 0.5, // Temperature adjustment step size, the unit is the same as scale. required.
“scale”: “c” // Temperature unit, required. c (Celsius), f (Fahrenheit)
},
“mappingMode”: “AUTO”, // Mapping mode: thermostat-mode.AUTO
“weeklySchedule”: { // Schedule configuration items
“maxEntryPerDay”: 2 // Maximum number of segments per day
“Monday”: [{
“startTimeInMinutes”: 440, //Start time, expressed in minutes, type int. Such as 7:20 = 7 * 60 + 20 = 440
“upperSetpoint”: 36.5, // The maximum value of the target temperature, number type. There must be at least one lowerSetpoint and upperSetpoint.
“lowerSetpoint”: 20, //The lowest value of the target temperature, number type. There must be at least one lowerSetpoint and upperSetpoint.
}, {
“startTimeInMinutes”: 900, //Start time, expressed in minutes, int type. For example, 15:00 = 15 * 60 = 900
“upperSetpoint”: 26.5, // The maximum value of the target temperature, number type. There must be at least one lowerSetpoint and upperSetpoint.
“lowerSetpoint”: 21, //The lowest value of the target temperature, number type. There must be at least one lowerSetpoint and upperSetpoint.
}],
“Tuesday”: […],
“Wednesday”: […],
“Thursday”: […],
“Friday”: […],
“Saturday”: […],
“Sunday”: […],
}
}
},
{
“capability”: “thermostat-target-setpoint”,
“permission”: “readWrite”,
“name”: “eco-mode”, // Component name, String type, “eco-mode” represents the target temperature in the energy-saving mode of the temperature control device
“configuration”: {
“temperature”: {
“min”: 4,
“max”: 35,
“increment”: 0.5, // Temperature adjustment step size, the unit is the same as scale. required.
“scale”: “c” // Temperature unit, required. c (Celsius), f (Fahrenheit)
},
“mappingMode”: “ECO” // Mapping mode: thermostat-mode.ECO
}
}
]
{
“targetSetpoint”: 30, // Target temperature, number type, unit is the same as scale, see configuration.temperature for the range
}

{

“thermostat-target-setpoint”: {

“temperature”: {

“targetSetpoint”: 30

}

}

}

{

“thermostat-target-setpoint”: {

“manual-mode”: {

“targetSetpoint”: 30

},

“auto-mode”: {

“targetSetpoint”: 30

}

}

}

thermostat
Thermostat Feature

[
{
“capability”: “thermostat”,
“permission”: “read”,
“name”: “adaptive-recovery-status” // Temperature control adaptive status
},

{
“capability”: “thermostat”,
“permission”: “readWrite”,
“name”: “thermostat-mode”,
“configuration”: { // required
“supportedModes”: [ // Built-in modes
“MANUAL”,
“AUTO”,
“ECO”
]
}
},
]

{
“targetSetpoint”: 30, // Target temperature, number type, unit is the same as scale, see configuration.temperature for the range
}
{
“adaptiveRecoveryStatus”: “HEATING”, // Temperature control adaptive status, String type, optional values: “HEATING” (heating), “INACTIVE” (inactive)
}
{
“thermostatMode”: “MANUAL”, // Temperature control operating mode, String type, see configuration.supportedModes for optional values.
}

{

“thermostat”: {

“adaptive-recovery-status”: {

“adaptiveRecoveryStatus”: “HEATING”

}

}

}

{

“thermostat”: {

“thermostat-mode”: {

“thermostatMode”: “MANUAL”

}

}

}

faultFault Notification Capability

[

{

“capability”: “fault”,

“permission”: “read”

}

]

{
“fault”: “reasonCode1”, // Fault error code, String type, customized.
}

{

“fault”: {

“fault”: “reasonCode1”

}

}

Supported Preset Modes

Mode Name

Option

fanLevel (Fan Level)

“low”

“medium”

“high” 

thermostatMode (Thermostat Mode)

“auto”

“manual”

airConditionerMode (AirConditioner Mode)

“cool” 

“heat” 

“auto” 

“fan” 

“dry” 

fanMode (Fan Mode)

“normal” 

“sleep” 

“child” 

horizontalAngle (Horizontal Angle)

“30” 

“60” 

“90” 

“120” 

“180” 

“360” 

verticalAngle (Vertical Angle)

“30” 

“60” 

“90” 

“120” 

“180” 

“360” 

c. Tags Description

  • The special key toggle is used to set the name of the toggle subcomponent.
{
    "toggle": {
        '1': 'Chanel1',
        '2': 'Chanel2',
        '3': 'Chanel3',
        '4': 'Chanel4',
    },
}
  • The special key temperature_unit is used to set the temperature unit.
{
    "temperature_unit":'c' // c-Celsius; f-Fahrenheit
}

d. Special Error Code and Description

Error Code

Description

iHost Version

110000

The sub-device/group corresponding to the id does not exist

≥1.2.0

110001

The gateway is in the state of discovering zigbee devices

≥1.2.0

110002

Devices in a group do not have a common capability

≥1.2.0

110003

Incorrect number of devices

≥1.2.0

110004

Incorrect number of groups

≥1.2.0

110005

Device Offline

≥1.2.0

110006

Failed to update device status

≥1.2.0

110007

Failed to update group status

≥1.2.0

110008

The maximum number of groups has been reached. Create up to 50 groups

≥1.2.0

110009

The IP address of the camera device is incorrect

≥1.2.0

110010

Camera Device Access Authorization Error

≥1.2.0

110011

Camera device stream address error

≥1.2.0

110012

Camera device video encoding is not supported

≥1.2.0

110013

Device already exists

≥1.2.0

110014

Camera does not support offline operation

≥1.2.0

110015

The account password is inconsistent with the account password in the RTSP stream address

≥1.2.0

110016

The gateway is in the state of discovering onvif cameras

≥1.2.0

110017

Exceeded the maximum number of cameras added

≥1.2.0

110018

The path of the ESP camera is wrong

≥1.2.0

110019

Failed to access the service address of the third-party device

≥1.3.1

e. Search for Sub-device

iHost Version ≥ 1.2.0
Allow authorized users to enable or disable gateway search for sub-devices through this interface

  • 💡Note: Only supports searching for Zigbee sub-devices now.
  • 💡Note: Zigbee sub-devices will be added automatically after searching. Do not need to use the “Manually Add Sub-devices” interface
  • URL:/open-api/v1/rest/devices/discovery
  • Method: PUT
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters:

Attribute

Type

Optional

Description

enable

boolean

N

true (Start paring); false (Pause pairing)

type

string

N

Searching Type: Zigbee

Successful data response: empty Object {}

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}

f. Manually Add the Sub-device

iHost Version ≥ 1.2.0

Allow authorized users to add a single sub-device through this interface.

  • Note: Only RTSP Camera and ESP32 Camera are supported now
  • URL:/open-api/v1/rest/devices
  • Method:POST
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters:

AttributeTypeOptionalDescription
namestringNSub-device name
display_categorystringNDevice Type. Only support camera。
capabilitiesCapabilityObject[]NCapability list. When display_category = camera, capabilities only include camera-stream capabilities.
protocolstringNDevice protocol. RTSP; ESP32-CAM
manufacturerstringNManufacturer.
modelstringNDevice model
firmware_versionstringNDevice firmware version

CapabilityObject Object

Attribute

Type

Optional

Description

capability

string

N

Capability name. Only support “camera-stream”

permission

string

N

Device permission. Only support read.

configuration

CameraStreamConfigurationObject

Y

Camera stream configuration.

CameraStreamConfigurationObject Object

Attribute

Type

Optional

Description

stream_url

string

N

Stream url,<schema>://<hostname>:<port>/<username>:<password>@<service_path>,e.g.: rtsp://admin:123456@192.168.10.115:554/streaming/channel01

 

schema optional:

· rtsp

· http (For ESP32-Camera)

Note: Some cameras don’t have account numbers and passwords, so you can leave the username and password blank. |

Successful data response:

Attribute

Type

Optional

Description

serial_number

string

N

Device unique serial number

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {
    "serial_number": "serial_number"
  },
  "message": "success"
}

Failure data response: empty Object

Condition
1. Camera stream address access error (format error, authorization failure, network exception, etc.)
2. Device already exists
3.If a single device fails to add, returns all devices fail to add.

Status Code: 200 OK
Error code
● 110009 Camera IP address error
● 110010 Camera access authorization error
● 110011 Camera stream address error
● 110012 The Camera video encoding does not support
● 110013 Device already exists

Response Example:
{
"error": 110009,
"data": {},
"message": "camera ip access failed"
}

g. Get List of Sub-devices

iHost Version ≥ 1.2.0

Allow authorized users to obtain the list of gateway sub-device through this interface.

  • URL:/open-api/v1/rest/devices
  • Method: GET
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters: none

Successful data response:

Attribute

Type

Optional

Description

device_list

ResponseDeviceObject[]

N

Device list

ResponseDeviceObject Object

Attribute

Type

Optional

Description

serial_number

string

N

Device unique serial number

third_serial_number

string

“N” when a third-party device is connected, otherwise “Y”

Third-party device unique serial number

service_address

string

“N” when a third-party device is connected, otherwise “Y”

Third-party service address

name

string

N

Device name, if it is not renamed, will be displayed by the front end according to the default display rules.

manufacturer

string

N

Manufacturer

model

string

N

Device model

firmware_version

string

N

Firmware version. Can be an empty string.

hostname

string

Y

Device hostname

mac_address

string

Y

Device mac address

app_name

iHost Version ≥ 1.3.0

string

Y

The name of the application to which it belongs. If the app_name is filled in when obtaining the open interface certificate, then all subsequent devices connected through the certificate will be written into this field.

display_category

string

N

Device category

capabilities

CapabilityObject[]

N

Device capabilities

protocol

string

“N” when a third-party device is connected, otherwise “Y”

Device protocol: zigbee, onvif, rtsp, esp32-cam

state

object

Y

Device state object. For state examples of different capabilities, please check 【Support Device Capabilities】

tags

object

Y

JSON format key-value, custom device information. The function is as follows:- Used to store device channels- Used to store temperature units- Custom information for other third-party devices

online

boolean

N

Online status: True for onlineFalse is offline

subnet

boolean

Y

Whether it is in the same subnet as the gateway

CapabilityObject Object

💡Note: Please check the Examples of Supported Device Capabilities for [Supported Device Capabilities].

Attribute

Type

Optional

Description

capability

string

N

Ability name. For details, check [Supported Device Capabilities]

permission

string

N

Capability permission. Possible values are “read” (readable), “write” (writable), “readWrite” (readable and writable).

configuration

object

Y

Capability configuration information. Currently camera-stream is used, check [Supported Device Capabilities]

name

string

Y

The name field in toggle. The sub-channel number used to identify multi-channel devices. For example, if name is 1, it means channel 1.

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data":{
    "device_list":  [
      {
        "serial_number": "ABCDEFGHIJK",
        "name": "My Device",
        "manufacturer": "SONOFF",
        "model": "BASICZBR3",
        "firmware_version": "1.1.0",
        "display_category": "switch",
        "capabilities": [
          {
            "capability": "power",
            "permission": "readWrite"
          },
          {
            "capability": "rssi",
            "permission": "read"
          }
        ],
        "protocol": "zigbee",
        "state": {
          "power": {
            "powerState": "on"
          }
        },
        "tags": {
          "key": "value"
        },
        "online": true
      }
    ],
  }
  "message": "success"
}

h. Update Specified Device Information or State

iHost Version ≥ 1.2.0

Allow authorized users to modify the basic information of sub-device and issue control commands through this interface.

  • URL:/open-api/v1/rest/devices/{serial_number}
  • Method:PUT
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request parameters:

Attribute

Type

Optional

Description

name

string

Y

Device name

tags

object

Y

JSON format key-value, custom device information.

state

object

Y

Device state object. For state examples of different capabilities, please check [Support Device Capabilities]

configuration

object

Y

Capability configuration information, currently only the camera_stream capability supports modification.

Successful data response:

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Error Code:

  • 110000 The sub-device/group corresponding to the id does not exist
  • 110006 Failed to update device status
Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}
import axios from 'axios';
const serial_number = 'serial_number';
const access_token = 'access_token';
(async function main() {
    // turn on device
    await axios({
        url: `http://ihost.local/open-api/v1/rest/devices/${serial_number}`,
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${access_token}`
        },
        data: {
            state: {
                power: {
                    powerState: 'on'
                }
            }
        }
    });
})()

i. Delete Sub-device

iHost Version ≥ 1.2.0

Allow authorized users to delete sub-devices through this interface.

  • URL:/open-api/v1/rest/devices/{serial_number}
  • Method:DELETE
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request Parameters: none

Successful data response:

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:
{
  "error": 0,
  "data": {},
  "message": "success"
}

4. Third-party Device Access

4.1 Access Instruction

Device Access

Third-party gateway Access

Access steps

  1. Determine the classification of the device in the gateway. The detail please check the [Supported Device Type].
  2. Determine the capabilities that the device can access. The detail please check the [Supported Device Capabilities].
  3. Request the [Discovery Request] interface to add the device to the gateway.
    1. Attention: You need to provide the service address for receiving the instructions issued by the gateway, which is used to receive the device control instructions issued by the gateway.
  4. If the status of the third-party device changes, you need to call the [Device States Change Report] interface to send the latest status back to the gateway.
  5. After adding, the third-party device will appear in the Device List, with most of the functions of the gateway (other non-third-party devices). The common open interfaces related to the device can be used normally.
  • Select the appropriate device category. The classification will affect the final display result of the UI after the device is connected to the gateway.
  • Choose the right device capability. The capability list will determine the status of the device state protocol.

Program Process

a. Device Access
b. Third-party Gateway Access

4.2 Access Example

Switch, Plug

Sync third-party devices

Request Example
// Request
URL:/open-api/v1/rest/thirdparty/event
Method:POST
Header:
  Content-Type: application/json
  Autorization: Bearer  <token>
Body:
{
  "event": {
    "header": {
      "name": "DiscoveryRequest",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "endpoints": [
        {
          "third_serial_number": "third_serial_number_1",
          "name": "my plug",
          "display_category": "plug",
          "capabilities": [
            {
              "capability": "power",
              "permission" "readWrite"
            }
          ],
          "state": {
            "power": {
              "powerState": "on"
            }
          },
          "tags": {
            "key": "value"
          },
          "manufacturer": "manufacturer name",
          "model": "model name",
          "firmware_version": "firmware version",
          "service_address": "http://192.168.31.14/webhook"
        }
      ]
    }
  }
}
Response Example
{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "endpoints": [
      {
        "third_serial_number": "third_serial_number",
        "serial_number": "serial number"
      }
    ]
  }
}

Report device status

Request Example
URL:/open-api/v1/rest/thirdparty/event
Method:POST
Header:
  Content-Type: application/json
  Autorization: Bearer  <token>
Body:
{
  "event": {
    "header": {
      "name": "DeviceStatesChangeReport",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number"
    },
    "payload": {
       "state": {
        "power": {
          "powerState": "on"
        }
      }
    }
  }
}
Response Example
{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}

Report offline/online

Request Example
{
  "event": {
    "header": {
      "name": "DeviceStatesChangeReport",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number"
    },
    "payload": {
       "online": true
    }
  }
}
Response Example
{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}

Receive the instructions about the gateway control device

Request Example
URL:<service address>
Method:POST
Header:
  Content-Type: application/json
B
{
  "directive": {
    "header": {
      "name": "UpdateDeviceStates",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "third_serial_number": "third_serial_number",
      "serial_number": "serial_number"
    },
    "payload": {
       "state": : {
         "power": {
           "powerState": "on"
         }
       }
    }
  }
}
Response Example
{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}

Query device

Request Example
URL:/open-api/v1/rest/devices
Method:GET
Header:
  Content-Type: application/json
  Autorization: Bearer  <token>
Body: 无
Response Example
{
  "error": 0,
  "data": {
    "device_list": [
      {
        "serial_number": "serial number",
        "third_serial_number": "third_serial_number",
        "name": "my plug",
        "manufacturer": "manufacturer name",
        "model": "model name",
        "firmware_version": "firmware version",
        "display_category": "plug",
        "capabilities": [
          {
            "capability": "power",
            "permission": "readWrite"
          }
        ],
        "state": {
          "power": {
            "powerState": "on"
          }
        },
        "tags": {
          "key": "value"
        },
        "online": true
      }
    ]
  },
  "message": "success"
}

4.3 Web API

Third-Party Request Gateway Interface

Request Format

Allow authorized users to send event requests to the gateway through this interface.

  • URL:/open-api/v1/rest/thirdparty/event
  • Method:POST
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Request Parameters:

Attribute

Type

Optional

Description

event

EventObject

N

Request event object structure information

EventObject Object

Attribute

Type

Optional

Description

header

HeaderObject

N

Request header structure information

endpoint

EndpointObject

Y

Request endpoint structure informationNote: This field is empty when sync a new device list.

payload

PayloadObject

N

Request payload structure information

HeaderObject Object

Attribute

Type

Optional

Description

name

string

N

Request name. optional parameter: DiscoveryRequest: Sync new devices DeviceStatesChangeReport: Device status update report DeviceOnlineChangeReport: Device online status report

message_id

string

N

Request message ID, UUID_V4

version

string

N

Request protocol version number. Currently fixed at 1

EndpointObject Object

Attribute

Type

Optional

Description

serial_number

string

N

Device unique serial number

third_serial_number

string

N

Third-party device unique serial number

tags

object

Y

JSON format key-value, custom device information. [Device Management Function] – [Tags Description]

PayloadObject Object:

According to the different header.name have different request structure.

Response Format

Status Code: 200 OK

Response parameters:

Attribute

Type

Optional

Description

header

HeaderObject

N

Response header structure information

payload

PayloadObject

N

Response payload structure information

HeaderObject Object

Attribute

Type

Optional

Description

name

string

N

Response header name. optional parameters:Response: Successful response ErrorResponse: Error response

message_id

string

N

Response header message ID, UUID_V4. Pass in the request message header.message_id here*If the request input parameter lacks message_id, this field will be an empty string when responding.

version

string

N

– Request protocol version number. Currently fixed at 1.

Successful response–PayloadObject Object:

Depending on the request type, the response structure is different. For details, please refer to the specific request instruction document.

Failure response–PayloadObject Object:

Attribute

Type

Optional

Description

type

string

N

Error Type: INVALID_PARAMETERS: Parameter error INTERNAL_ERROR :Service internal error

description

string

N

Error description

DiscoveryRequest Sync a new device list

iHost Version ≥ 1.2.0

  • Note:After the device is synchronized to the gateway, it is online by default, that is, online=true. Subsequent online changes are completely dependent on synchronization with the third party through the DeviceOnlineChangeReport interface.

Request parameters:

EndpointObject Object

None

PayloadObject Object:

Attribute

Type

Optional

Description

endpoints

EndpointObject[]

N

Device List

EndpointObject Object:

Attribute

Type

Optional

Description

third_serial_number

string

N

Third-party device unique serial number

name

string

N

Device name

display_category

string

N

Device Category. See the [Supported Device Type] for details. *Three-party devices don’t support adding cameras now.

capabilities

CapabilityObject[]

N

Capabilities list

state

object

N

Initial state information

manufacturer

string

N

Manufacturer

model

string

N

Device model

tags

object

Y

JSON format key-value, custom device information:Be used to store device channelsBe used to store temperature unitsOther third-party custom data

firmware_version

string

N

Firmware version

service_address

string

N

Service address. Such as http://192.168.31.14/service_address

Example of Request :

{
  "event": {
    "header": {
      "name": "DiscoveryRequest",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "endpoints": [
        {
          "third_serial_number": "third_serial_number_1",
          "name": "my plug",
          "display_category": "plug",
          "capabilities": [
            {
              "capability": "power",
              "permission" "readWrite"
            }
          ],
          "state": {
            "power": {
              "powerState": "on"
            }
          },
          "tags": {
            "key": "value"
          },
          "manufacturer": "manufacturer name",
          "model": "model name",
          "firmware_version": "firmware version",
          "service_address": "http://192.168.31.14/service_address"
        }
      ]
    }
  }
}

Response parameters:

PayloadObject Object:

Attribute

Type

Optional

Description

endpoints

EndpointObject[]

N

Device list

EndpointObject Object:

Attribute

Type

Optional

Description

serial_number

string

N

Device unique serial number

third_serial_number

string

N

Third-party device unique serial number

Example of a correct response: 

{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "endpoints": [
      {
        "serial_number": "serial number",
        "third_serial_number": "third_serial_number"
      }
    ]
  }
}

Example of an error response:

{
  "header": {
    "name": "ErrorResponse",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "type": "INVALID_PARAMETERS",
    "description": "webhook cannot be empty"
  }
}

DeviceStatesChangeReport Device status update report

iHost Version ≥ 1.2.0

  • Note: Repeated status reports may falsely trigger associated scene.

Request parameters:

PayloadObject Object:

Attribute

Type

Optional

Description

state

object

N

Devicce state, See [Supported device cabilities] for detail

Example of Request :

{
  "event": {
    "header": {
      "name": "DeviceStatesChangeReport",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number"
    },
    "payload": {
       "state": {
        "power": {
          "powerState": "on"
        }
      }
    }
  }
}

Response parameters:

PayloadObject Object: Empty Object

Example of a successful response:

  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}
DeviceOnlineChangeReport Device online status report

iHost Version ≥ 1.2.0

  • Note: Repeated status reports may falsely trigger associated scene.

Request parameters:

PayloadObject Object:

Attribute

Type

Optional

Description

online

boolean

N

Device online status true: Online false: Offline

Example of Request :

{
  "event": {
    "header": {
      "name": "DeviceStatesChangeReport",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number"
    },
    "payload": {
       "online": true
    }
  }
}

Response parameters:

PayloadObject Object: Empty Object

Example of a successful response:

{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}

Gateway sends the instruction interface through the device service address

  • Note:
  1. The three parties need to respond to the gateway’s request within 3s. Otherwise, the gateway will judge the command processing timeout.
  2. If the third-party service is offline, the gateway will set the device to an offline state, and the third-party service needs to report the device state (DeviceStatesChangeReport) or the online state (DeviceOnlineChangeReport) before returning to the online state. iHost Version ≥ 3.1
Request format

Gateway sends instructions to the third-party through the device service address interface.

  • URL:<service address>
  • Method:POST
  • Header
    • Content-Type: application/json

Request parameters:

Attribute

Type

Optional

Description

directive

DirectiveObject

N

Directive object structure information

DirectiveObject Object

Attribute

Type

Optional

Description

header

HeaderObject

N

Request header structure information

endpoint

EndpointObject

N

Request endpoint structure information

payload

PayloadObject

N

Request payload structure information

HeaderObject Object

Attribute

Type

Optional

Description

name

string

N

Request name. Optional parameters:UpdateDeviceStates: Update device states

message_id

string

N

Request message ID, UUID_V4

version

string

N

Request protocol version number. Currently fixed at 1.

EndpointObject Object

Attribute

Type

Optional

Description

serial_number

string

N

Device unique serial number

third_serial_number

string

N

Third-party device unique serial number

tags

object

N

JSON format key-value, custom device information. [Device Management Function] – [Tags Description]

Example of Request :

{
  "directive": {
    "header": {
      "name": "UpdateDeviceStates",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number",
      "third_serial_number": "third_serial_number",
      "tags": {}
    },
    "payload": {
      "state": {
        "power": {
          "powerState": "on"
        }
      }
    }
  }
}
Response format

HTTP Status Code: 200 OK

HTTP Response Attribute:

Attribute

Type

Optional

Description

event

EventObject

N

Response event structure information

EventObject Object

Attribute

Type

Optional

Description

header

HeaderObject

N

Request header structure information

payload

PayloadObject

N

Request payload structure information

HeaderObject Object

Attribute

Type

Optional

Description

name

string

N

Response header name. Optional parameter: UpdateDeviceStatesResponse: Update device states response ErrorResponse: Error response

message_id

string

N

Response header message ID, UUID_V4. Pass in the request message header.message_id here

version

string

N

Request protocol version number. Currently fixed at 1.

Successful response–PayloadObject Object:

Depending on the request type, the response structure is different. For details, please refer to the specific request instruction document.

Failure response–PayloadObject Object:

Attribute

Type

Optional

Description

type

string

N

Error type:- ENDPOINT_UNREACHABLE: Device is unreachable or offline- ENDPOINT_LOW_POWER: Device is in a low battery state and cannot be controlled- INVALID_DIRECTIVE: Command issued by the gateway is abnormal- NO_SUCH_ENDPOINT: Device doesn’t exist- NOT_SUPPORTED_IN_CURRENT_MODE: Current mode is not supported- INTERNAL_ERROR: Service internal error

Conditions: The request parameters are legal.

Status Code: 200 OK

Response parameters:

Successful response
{
  "event": {
    "header": {
      "name": "UpdateDeviceStatesResponse",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {}
  }
}
Failure response
{
  "event": {
    "header": {
      "name": "ErrorResponse",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "type": "ENDPOINT_UNREACHABLE"
    }
  }
}
UpdateDeviceStates

iHost Version ≥ 1.2.0

Request parameters:

PayloadObject Object:

Attribute

Type

Optional

Description

state

object

N

Devicce state, See [Supported device cabilities] for detail.

Example of Request :

  "directive": {
    "header": {
      "name": "UpdateDeviceStates",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "endpoint": {
      "serial_number": "serial_number"
    },
    "payload": {
       "state": : {
         "power": {
           "powerState": "on"
         }
       }
    }
  }
}

Response parameters:

PayloadObject Object:empty Object

Example of Successful Response

{
  "header": {
    "name": "Response",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {}
}

Get Debug Logs Interface

iHost Version ≥ 1.2.0

Allow authorized users to obtain device debugging logs through this interface.

  • Failed to sync new device list, no log will be logged. If the synchronization is successful, a log (event_log) record will be generated for each serial_number
  • Gateway log storage limit is as follows.
  1. event_log: Third-party report request log. A single device only saves the latest 3000 logs.
  2. directive_log: Gateway sends request logs. A single device only saves the latest 3000 logs.
  • You can download the interface access logs within the selected time range through this interface. The file name is {start timestamp}{end timestamp}{device serial number}.json

The content format is:

[
  {
    "message_id": "message_id", //Message ID
    "ip": "", // Remote IP. Required.
    "req": { // Request record.
        "method": "GET", //  Request method. Required.
        "url": "", // Request url. Required.
        "body": "", // Request body, json string.Required. An empty string is allowed.
        "header": "" , // Request header, json string. Required.
    },
    "res": { // Response record.
            "status_code": 200, // Status code. Required.
        "body": "" , // Response body, json string.Required. An empty string is allowed.
        "header": "" , // Response header, json string. Required.}
       }
    }
]
  • URL:/open-api/v1/rest/thirdparty/debug-log/{serial_number}
  • Method:GET
  • Header
    • Content-Type: application/json
    • Autorization: Bearer <token>

Response parameters:

Attribute

Type

Optional

Description

type

string

N

Log type:event_log: Third-party report request logdirective_log: The directive log sent by the gateway

from_index

int

Y

Start sequence number. Default is 0. An integer in the range [0,3000].

start_time

date

Y

Start timestamp, query specific time. If empty, default is 1 minute ago.

end_time

date

Y

End timestamp, query specific time. If iempty, default is current time.

limit

int

Y

The limit messages to be pulled, the range is an integer of [1,50]. If empty, default is 50.

order

string

Y

Sort by time range,DESC: Descending orderASC: Ascending orderDefault is DESC

Successful Response

Status Code: 200 OK

Response header

  • Content-Type: application/octet-stream
  • Content-Disposition: attachment; filename={Start timestamp}{End timestamp}{device serial number}.json

Abnormal response

Status Code:

  • 400 Parameter error
  • 500 Gateway service exception

5. Server-sent events

MDN EventSource interface description:https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

5.1 Instruction

The gateway supports pushing messages to the client using SSE (Server-sent events). The client can monitor SSE messages after obtaining the access credentials and can parse the content of the push messages according to the development interface event notification protocol after receiving the messages pushed by the gateway. It should be noted that the gateway currently uses the HTTP1.1 protocol, so SSE on the browser side there will be a maximum of no more than 6 connections limit (Specific instructions can be found in the MDN EventSource interface description.)

5.2 Common Format

  • URL:/open-api/v1/sse/bridge
  • Method:GET

Request parameters:

 Name

 Type

 Optional

 Description

access_token

 string

N

Access Token

Note:

When requesting an SSE connection, the gateway will check the access_token, and it will return an authentication failure error if it is invalid. { “error”: 401, “data”: {}, “message”: “invalid access_token”}

<Module Name>#<Version>#<Message Type>

For example:

Module Name: device

Version: v1,v2,v3

Message Type: addDevice

Example:

const evtSource = new EventSource("http://ihost.local/open-api/v1/sse/bridge?access_token=xxxxxx");
evtSource.addEventListener('device#v1#addDevice',function (event) {
  try {
    const data = JSON.parse(event.data);
    console.log('data', data);
  } catch (error) {
    console.error(`parse error`,error);
  }
}

5.3 Device Module

a. Add Device Event

iHost Version ≥ 1.3.0

Module Name:device

Version:v1

Message Type:addDevice

event.data parameters:

 Name Type Optional Description
payloadResponseDeviceObjectObject – Interface the same with the Get Device ListNdevice information

Example:

// event.data
{
  "payload": {
    "serial_number": "ABCDEFGHIJK",
    "third_serial_number": "third_serial_number",
    "name": "My device",
    "manufacturer": "SONOFF",
    "model": "BASICZBR3",
    "firmware_version": "1.1.0",
    "display_category": "switch",
    "capabilities": [
      {
        "capability": "power",
        "permission": "readWrite"
      },
      {
        "capability": "rssi",
        "permission": "read"
      }
    ],
    "protocol": "zigbee",
    "state": {
      "power": {
        "powerState": "on"
      }
    },
    "tags": {
      "key": "value"
    },
    "online": true
  }
}

b. Update Device State Event

iHost Version ≥ 1.3.0

Module Name:device

Version:v1

Message Type:updateDeviceState

event.data parameters:

 Name

 Type

 Optional

 Description

endpoint

EndpointObject

N

Device Information

payload

object。 Structure the same as the device state

N

Device Status Data

EndpointObject Object:

Parameter

Type

Optional

Description

serial_number

string

N

 Device unique Serial Number

third_serial_number

string

Y

The unique serial number of the third-party device. For devices connected through open interfaces, this field is required.

Example

// event.data
{
  "endpoint": {
    "serial_number": "serial_number",
    "third_serial_number": "third_serial_number"
  },
  "payload": {
    "power": {
      "powerState": "on"
    },
    "brightness": {
      "brightness": 100
    }
  }
}

c. Update Device Info Event

iHost Version ≥ 1.3.0

Module Name:device

Version:v1

Message Type:updateDeviceInfo

event.data parameters:

 Name

 Type

 Optional

 Description

endpoint

EndpointObject

N

Device Information

payload

DeviceChangeObject

N

Device Change Data

EndpointObject Object:

Attribute

Type

Optional

Description

serial_number

string

N

 Device unique Serial Number

third_serial_number

string

Y

The unique serial number of the third-party device. For devices connected through open interfaces, this field is required.

DeviceChangeObject Object

 Name

 Type

 Optional

 Description

name

string

N

Device Name

Example

// event.data
{
"endpoint": {
"serial_number": "serial_number",
"third_serial_number": "third_serial_number"
},
"payload": {
"name": "device name"
}
}

d. Delete Device Event

iHost Version ≥ 1.3.0

Module Name:device

Version:v1

Message Type:deleteDevice

event.data parameters:

 Name

 Type

 Optional

 Description

endpoint

EndpointObject

N

Device Information

EndpointObject Object:

Attribute

Type

Optional

Description

serial_number

string

N

 Device unique Serial Number

third_serial_number

string

Y

The unique serial number of the third-party device. For devices connected through open interfaces, this field is required.

Example

// event.data
{
"endpoint": {
"serial_number": "serial_number",
"third_serial_number": "third_serial_number"
}
}

e. Update Device Online Event

iHost Version ≥ 1.3.0

Module Name:device

Version:v1

Message Type:updateDeviceOnline

event.data parameters:

 Name

 Type

 Optional

 Description

endpoint

EndpointObject

N

Device Information

payload

DeviceChangeObject

N

Device Change Data

EndpointObject Object:

Attribute

Type

Optional

Description

serial_number

string

N

 Device unique Serial Number

third_serial_number

string

Y

The unique serial number of the third-party device. For devices connected through open interfaces, this field is required.

DeviceChangeObject Object

 Name

 Type

 Optional

 Description

online

boolean

N

Device Online Status

Example

// event.data
{
  "endpoint": {
    "serial_number": "serial_number",
    "third_serial_number": "third_serial_number"
  },
  "payload": {
    "online": false
  }
}

6. TTS (Text-to-Speech) Engine Function

6.1 Instruction

Key Role

  • TTS Service Provider: The TTS service engine service provider is responsible for registering the TTS engine on the gateway and providing TTS services

  • Gateway Server:iHost

  • Gateway Open API Client

6.1.1 Registering TTS Engine Service

  1. 【TTS Service Provider】Call the interface to register the TTS engine on the gateway.

  2. 【Gateway Server】After successful registration, the gateway will store the basic information of the TTS engine (including the service address server_address, and subsequent communication between the gateway and the TTS Service Provider will be carried out through the server_address address), and allocate the TTS engine service ID within the gateway.

6.1.2 Get the List of Synthesized Audio

  1. 【Gateway Open API Client】Call the interface to obtain the list of registered TTS engine service. You can obtain the current list of registered TTS engines (including the ID of the TTS engine allocated by the gateway).

  2. 【Gateway Open API Client】Call the interface to obtain the list of a specified TTS engine audio. The gateway will issue a synchronous audio list instruction to the specified TTS Service Provider and return the result.

6.1.3 Speech Synthesis by Specifying a Speech Engine

  1. 【Gateway Open API Client】Call the interface to obtain the list of registered TTS engine service. You can obtain the current list of registered TTS engines (including the ID of the TTS engine allocated by the gateway).

  2. 【Gateway Open API Client】Call the interface to obtain the list of a specified TTS engine audio. The gateway will issue a synchronous audio list instruction to the specified TTS Service Provider and return the result.

6.1.4 Synthesize Audio and Play TTS Speech.

  1. 【Gateway Open API Client】Call the interface to obtain the list of registered TTS engine service. You can obtain the current list of registered TTS engines (including the ID of the TTS engine allocated by the gateway).

  2. 【Gateway Open API Client】Call the interface to obtain the list of a specified TTS engine audio. The gateway will issue a synchronous audio list instruction to the specified TTS Service Provider and return the result. (including the TTS audio file address)

  3. 【Gateway Open API Client】Record the TTS audio file address from the result returned in the previous step, call the play audio file interface, and play it through the gateway.

6.2 TTS Engine Module

6.2.1 Gateway Open Capability

a. Get the list of registered TTS engine services
  • URL/open-api/v1/rest/tts/engines

  • MethodGET

  • Header

    • Content-Type: application/json

    • Authorization: Bearer <token> 

Request parameters: none

Correct data response:

AttributeTypeOptionalDescription
enginesEngineObject []N

List of registered TTS engines

EngineObject Structure

AttributeAttributeAttributeAttribute
idstringNEngine ID assigned by gateway
namestringNName of TS engine service

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:

{
"error": 0,
"data": {
"engines": [
{
"id": "engine id",
"name": "engine name"
}
]
},
"message": "success"
}
b. Get list of specified TTS engine audio
  • URL/open-api/v1/rest/tts/engine/{id}/audio-list

  • MethodGET

  • Header

    • Content-Type: application/json

    • Authorization: Bearer <token>

Request parameters: none

Correct data response:

AttributeAttributeAttributeAttribute
audio_listAudioObject []NAudio list

AudioObject Structure

Attribute

Attribute

Attribute

Attribute

url

string

N

Audio file URL, for example:

https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3

label

string

Y

Audio file label

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Error Code:

  • 190000 The engine is running abnormally

Response Example:

{
  "error": 0,
  "data": {
    "audio_list": [
      {
        "url": "tts audio address", // for example: https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3
        "label": "tts audio label"
      }
    ]
  },
  "message": "success"
}
c .Perform speech synthesis using the specified TTS engine
    • URL/open-api/v1/rest/tts/engine/{id}/synthesize

    • MethodPOST

    • Header

      • Content-Type: application/json

      • Authorization: Bearer <token>

Request Parameters:

AttributeAttributeAttributeAttribute
textstringNText used to synthesize the audio
labelstringYAudio file label
languagestringYTransparent field. Optional language code for the synthesis speech request. The specific list of supported language codes is provided by the TTS speech engine service provider. Note that the TTS engine service needs to support default language for speech synthesis, which means that if the language is not passed, the default language of the engine will be used for synthesis.
optionsobjectYTransparent field. It is used to pass the configuration parameters required for synthesis to the TTS speech engine service.

Correct data response:

AttributeAttributeAttributeAttribute
audioAudioObjectNAudio list

AudioObject Structure

Attribute

Attribute

Attribute

Attribute

url

string

N

Audio file URL, for example:

https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3

label

string

Y

Audio file label

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Error Code:

  • 190000 The engine is running abnormally

Response Example:

{
  "error": 0,
  "data": {
    "audio": {
        "url": "tts audio address" // for example, https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3
        "label": "tts audio label"
    }
  },
  "message": "success"
}

6.2.2 Communication Between Gateway and TTS Service

a. Registering TTS engine service

Send request to gateway by TTS Service Provider

  • URL/open-api/v1/rest/thirdparty/event

  • MethodPOST

  • Header

    • Content-Type: application/json

    • Authorization: Bearer <token>

Request Parameters:

AttributeAttributeAttributeAttribute
eventEventObjectNRequest Event Object structure Information

EventObject Object

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Request name. Optional parameter.

  • RegisterTTSEngine

message_id

string

N

Request message ID, UUID_V4

version

string

N

Request protocol version number. Currently fixed at 1

PayloadObject Object

AttributeAttributeAttributeAttribute
service_addressstringNService Address. For example, http://<domain name or ip address>/<path>
namestringNService name

Request Example:

{
  "event": {
    "header": {
      "name": "RegisterTTSEngine",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
        "service_address": "service_address",
        "name": "tts service name"
    }
  }
}

Correct response parameters:

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Response header name. Optional parameter:

  • Response (Successful response)
  • ErrorResponse (Error response)

message_id

string

N

Response header message ID, UUID_V4. Incoming request message here: header.message_id

version

string

N

Request protocol version number. Currently fixed at 1

PayloadObject Object

AttributeAttributeAttributeAttribute
engine_idstringNEngine ID assigned by gateway

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:

Correct Response Example::

{
    "header": {
      "name": "Response",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "engine_id": "engine id"
    }
  }

Abnormal response parameters:

Attribute

Attribute

Attribute

Attribute

type

string

N

Error Type

  • INVALID_PARAMETERS (Parameters error)
  • AUTH_FAILURE (Authentication failure)
  • INTERNAL_ERROR (Service internal error)

description

string

N

Error description

Error Response Example::

{
  "header": {
    "name": "ErrorResponse",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "type": "INVALID_PARAMETERS",
    "description": "service_address cannot be empty" 
  }
}
b. Synchronize audio list command

Send command to the TTS Service Provider by gateway.

  • URL<service address>

  • MethodPOST

  • Header

    • Content-Type: application/json

Request Parameters:

AttributeAttributeAttributeAttribute
directiveDirectiveObjectNInstruction object structure information

DirectiveObject Object

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Request name. Optional parameter:

  • SyncTTSAudioList

message_id

string

N

Request message ID, UUID_V4

version

string

N

Request protocol version number. Currently fixed at 1

Request Example:

{
  "directive": {
    "header": {
      "name": "SyncTTSAudioList",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {}
  }
}

Correct response parameters:

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Response header name. Optional parameter:

  • Response (Successful response)
  • ErrorResponse (Error response)

message_id

string

N

Response header message ID, UUID_V4. Incoming request message here: header.message_id

version

string

N

Request protocol version number. Currently fixed at 1

PayloadObject Object:

AttributeAttributeAttributeAttribute
audio_listAudioObject []NTTS Audio list

AudioObject Structure

Attribute

Attribute

Attribute

Attribute

url

string

N

Audio file URL, for example:

https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3

label

string

Y

Audio file label

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:

Correct Response Example::
{
    "header": {
      "name": "Response",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "audio_list": [
        {
            "url": "tts audio url",
            "label": "tts audio label"
        }
      ]
    }
}

Abnormal response parameters:

Attribute

Attribute

Attribute

Attribute

type

string

N

Error Type

  • INVALID_PARAMETERS (Parameters error)
  • AUTH_FAILURE (Authentication failure)
  • INTERNAL_ERROR (Service internal error)

description

string

N

Error description

Error Response Example::
{
  "header": {
    "name": "ErrorResponse",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "type": "INVALID_PARAMETERS",
    "description": "service_address cannot be empty" 
  }
}
c. Speech synthesis command

Send request to gateway by TTS Service Provider

  • URL<service address>

  • MethodPOST

  • Header

    • Content-Type: application/json

Request Parameters:

Attribute

Attribute

Attribute

Attribute

directive

DirectiveObject

N

Instruction object structure information

DirectiveObject Object

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Request name. Optional parameter:

  • SynthesizeSpeech

message_id

string

N

Request message ID: UUID_V4

version

string

N

Request protocol version number. Currently fixed at 1

PayloadObject Object

AttributeAttributeAttributeAttribute
textstringNText used to synthesize the audio
labelstringYAudio file label
languagestringYTransparent field. Optional language code for the synthesis speech request. The specific list of supported language codes is provided by the TTS speech engine service provider. Note that the TTS engine service needs to support default language for speech synthesis, which means that if the language is not passed, the default language of the engine will be used for synthesis.
optionsobjectYTransparent field. It is used to pass the configuration parameters required for synthesis to the TTS speech engine service.

Request Example:

{
    "directive": {
        "header": {
            "name": "SynthesizeSpeech",
            "message_id": "Unique identifier, preferably a version 4 UUID",
            "version": "1"
        },
        "payload": {
            "text": "Input text to synthesize.",
            "label": "tts audio label"
        }
    }
}

Correct response parameters:

AttributeAttributeAttributeAttribute
headerHeaderObjectNRequest header structure information
payloadPayloadObjectNRequest payload structure information

HeaderObject Object

Attribute

Attribute

Attribute

Attribute

name

string

N

Response header name. Optional parameter:

  • Response (Successful response)
  • ErrorResponse (Error response)

message_id

string

N

Response header message ID, UUID_V4. Incoming request message here: header.message_id

version

string

N

Request protocol version number. Currently fixed at 1

PayloadObject Object

AttributeAttributeAttributeAttribute
audioAudioObjectNTTS Audio

AudioObject Structure

Attribute

Attribute

Attribute

Attribute

url

string

N

Audio file URL, for example:

https://dl.espressif.cn/dl/audio/gs-16b-2c-44100hz.mp3

label

string

Y

Audio file label

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:

Correct Response Example::

{
    "header": {
      "name": "Response",
      "message_id": "Unique identifier, preferably a version 4 UUID",
      "version": "1"
    },
    "payload": {
      "audio": {
        "url": "tts audio url",
        "label": "tts audio label"
      }
    }
}

Abnormal response parameters:

Attribute
Attribute
Attribute
Attribute
type
string
N
Error Type
INVALID_PARAMETERS (Parameters error)
AUTH_FAILURE (Authentication failure)
INTERNAL_ERROR (Service internal error)
description
string
N
Error description

 

Error Response Example::

{
  "header": {
    "name": "ErrorResponse",
    "message_id": "Unique identifier, preferably a version 4 UUID",
    "version": "1"
  },
  "payload": {
    "type": "INVALID_PARAMETERS",
    "description": "service_address cannot be empty" 
  }
}

7. Multimedia Module

7.1 Play Audio File

  • URL/open-api/v1/rest/media/audio-player

  • MethodPOST

  • Header

    • Content-Type: application/json

    • Authorization: Bearer <token>

Request Parameters:

Attribute

Attribute

Attribute

Attribute

audio_url

string

N

Audio URL address

Correct data response:

Conditions: The request parameters are legal, and the user identity verification is passed.

Status Code: 200 OK

Response Example:

{
  "error": 0,
  "data": {},
  "message": "success"
}

Pin It on Pinterest