I do not plan to maintain this repository any longer. It was a starting point for myself to learn the API to implement a module for Bitfocus Companion. See https://github.com/bitfocus/companion-module-esphome-api
This library implements client for Esphome Native APi.
$ npm i esphome-native-api
const { Client } = require('esphome-native-api');
const client = new Client({
host: '<esp host or ip>',
port: 6053
});
client.on('deviceInfo', deviceInfo => {
console.log('Device info:', deviceInfo);
});
client.on('newEntity', entity => {
console.log('New entity:', entity);
// enable light
if (entity.name === 'Light') {
entity.setState(true);
}
});
const { Discovery } = require('esphome-native-api');
Discovery().then(results => {
console.log(results);
/*
[
{
mac: '240ac45eebd4',
host: 'esp32_binary_fan.local',
version: '1.16.1',
address: '192.168.0.144',
family: 'IPv4'
}
]
*/
});
const { Discovery } = require('esphome-native-api');
const discovery = new Discovery();
discovery.on('info', console.log);
/*
{
mac: '240ac45eebd4',
host: 'esp32_binary_fan.local',
version: '1.16.1',
address: '192.168.0.144',
family: 'IPv4'
}
*/
discovery.run();
const { Client } = require('esphome-native-api');
const client = new Client({
host: '<esp host or ip>',
port: 6053,
initializeSubscribeLogs: true
});
client.on('logs', ({ message }) => {
console.log(message);
});
const { Discovery } = require('esphome-native-api');
const discovery = new Discovery(options);
options
- optional
multicast
- optional. Default - true
. Use udp multicasting
interface
- optional. Explicitly specify a network interface. defaults to all
port
- optional. Default - 5353
. Set the udp port
ip
- optional. Default - 224.0.0.251
. Set the udp ip
ttl
- optional. Default - 255
. Set the multicast ttl
loopback
- optional. Default - true
. Receive your own packets
reuseAddr
- optional. Default - true
. Set the reuseAddr option when creating the socket (requires node >=0.11.13)
const { Discovery } = require('esphome-native-api');
Discovery(options).then(console.log)
options
- optional
timeout
- optional. Default - 5
. Time in seconds how long to wait for responses
*
- all options above
More frienly layer over the Connection
const { Client } = require('esphome-native-api');
const client = new Client({
clearSession = false,
initializeDeviceInfo = true,
initializeListEntities = true,
initializeSubscribeStates = true,
initializeSubscribeLogs = false,
port = 6053,
host,
clientInfo = 'esphomenativeapi',
password = '',
reconnect = true,
reconnectInterval = 30000,
pingInterval = 15000,
pingAttempts = 3
});
host
- (REQUIRED). Host or ip to connect to.port
- optional. Default -6053
. Port to connect to.password
- passsword. Default -''
. Password used to authorized the clientreconnect
- optional. Default -true
. indicates wheter reconnect automatically or notreconnectInterval
- optional. Default -30000
. Number. Amount of miliseconds to wait before new tryclearSession
- optional. Default -true
. Settrue
to forget any information after reconnectioninitializeDeviceInfo
- optional. Default -true
. Settrue
to retrieve device info after connection is establishedinitializeListEntities
- optional. Default -true
. Settrue
to retrieve list of device's entities after connection is establishedinitializeSubscribeStates
- optional. Default -true
.initializeSubscribeLogs
- optional. Default -false
.clientInfo
- string, name of client to be sent to esphome device. (Not necessary to send but nice for debugging issues)clientInfo
- string, name of client to be sent to esphome device. Usually needed only for tracking connection on esphome device. See ConnectionpingInterval
- optional. Default -15000
. Ping interval. Amount of miliseconds. See ConnectionpingAttempts
- optional. Default -3
. Number of failed ping attempts after witch connection is considered to be corrupted. See Connection
connect()
- starts clientdisconnect()
- srops clientconnected
- indicates if client is connected to esphome and autorizedinitialized
- indicates if client is connected and autorized and all initialization step are doneentities
- array of discovered entitiesconnection
- connection instance
connected
- emmited if client is connected to esphome and autorizeddisconnected
- emmited when connection is corruptedinitialized
- emmited if client is connected and autorized and all initialization step are donedeviceInfo
- emmited when deviceInfo is retrieved or updated. Activated withinitializeDeviceInfo
options passed toClient
's constructor.newEntity
- emmited when new entity is discovered. Activated withinitializeListEntities
options passed toClient
's constructor. First argument is instance of one of entities classlogs
- emmited when esphome send any logs. Activated withinitializeSubscribeLogs
options passed toClient
's constructor. First argument is object withlevel
,tag
,message
,send_failed
error
- emitted when any error occurs
Each entity class defines individual interaction with esphome components. All entities have
config
attrubute - entity configuration receved from esphomestate
event when new state is receivedstate
attributedestroyed
event which is called when corresponfing client is no longer connection to this entity(SeeclearSession
option) andtype
attribute equal to component typename
attribute equal to name of entity
Only base functionality
static commandService(connection, { key })
Params:key
- REQUIRED. key/id of entity
static commandService(connection, { key, mode, targetTemperature, targetTemperatureLow, targetTemperatureHigh, away, fanMode, swingMode })
- sends command to climate entity Params:key
- REQUIRED. key/id of entitymode
- optional. 0 - OFF, 1 - AUTO, 2 - COOL, 3 - HEAT, 4 - FAN_ONLY, 5 - DRY. SeesupportedModesList
attr in configtargetTemperature
- optional. floattargetTemperatureLow
- optional. floattargetTemperatureHigh
- optional. floatlegacyAway
- optional. Boolean. Deprecated: usepreset
with AWAYfanMode
- optional. 0 - ON, 1 - OFF, 2 - AUTO, 3 - LOW, 4 - MEDIUM, 5 - HIGH, 6 - MIDDLE, 7 - FOCUS, 8 - DIFFUSE. SeesupportedFanModesList
attr in configswingMode
- optional. 0 - OFF, 1 - BOTH, 2 - VERTICAL, 3 - HORIZONTAL. SeesupportedSwingModesList
attr in configcustomFanMode
- optional. string. SeesupportedCustomFanModesList
attr in configpreset
- optional. 0 - NONE, 1 - HOME, 2 - AWAY, 3 - BOOST, 4 - COMFORT, 5 - ECO, 6 - SLEEP, 7 - ACTIVITY. SeesupportedPresetsList
attr in configcustomPreset
- optional. string. SeesupportedCustomPresetsList
attr in config
static commandService(connection, { key, legacyCommand, position, tilt, stop })
- sends command to cover entity. Params:key
- REQUIRED. key/id of entitylegacyCommand
- optional. 0 - OPEN, 1 - CLOSE, 2 - STOP. Deprecated: useposition
position
- optional. float. 0.0 - CLOSED, 1.0 - OPEN. SeesupportsPosition
attr in configtilt
- optional. float. 0.0 - CLOSED, 1.0 - OPEN. SeesupportsTilt
attr in configstop
- optional. boolean
static commandService(connection, { key, state, speed, oscillating, direction, speedLevel })
- sends command to fan entity. Params:key
- REQUIRED. key/id of entitystate
- optional. booleanspeed
- optional. 0 - LOW, 1 - MEDIUM, 2 - HIGHoscillating
- optional. booleandirection
- optional. 0 - FORWARD, 1 - REVERSEspeedLevel
- optional. integer. SeesupportedSpeedCount
attr in config
static commandService(connection, { key, state, brightness, red, green, blue, colorMode, colorBrightness, white, colorTemperature, coldWhite, warmWhite, transitionLength, flashLength, effect })
- sends command to light entity. Params:key
- REQUIRED. key/id of entitystate
- optional. booleanbrightness
- optional. floatred
- optional. integer 0-255green
- optional. integer 0-255blue
- optional. integer 0-255colorMode
- optional. integer. SeesupportedColorModesList
attr in configcolorBrightness
- optional. floatwhite
- optional. integer 0-255colorTemperature
- optional. integercoldWhite
- optional. floatwarmWhite
- optional. floatflashLength
- optional. integereffect
- optional. string. effect from effects array in config list
static commandService(connection, { key, command }
- sends command to lock entity. Params:key
- REQUIRED. key/id of entitycommand
- REQUIRED. 0 - UNLOCK, 1 - LOCK, 2 - OPEN
static commandService(connection, { key, state })
- sends command to number entity. Params:key
- REQUIRED. key/id of entitystate
- REQUIRED. float. SeeminValue
,maxValue
, andstep
attrs in config
static commandService(connection, { key, state })
- sends command to select entity. Params:key
- REQUIRED. key/id of entitystate
- REQUIRED. string. SeeoptionsList
attr in config
Only base functionality
static commandService(connection, { key, state })
- sends command to switch entity. Params:key
- REQUIRED. key/id of entitystate
- REQUIRED. boolean
Only base functionality
const { Connection } = require('esphome-native-api');
const connection = new Connection({
port = 6053,
host,
clientInfo = 'esphomenativeapi',
password = '',
reconnect = true,
reconnectInterval = 30000,
pingInterval = 15000,
pingAttempts = 3
});
host
- (REQUIRED). Host or ip to connect to.port
- optional. Default -6053
. Port to connect to.password
- passsword. Default -''
. Password used to authorized the clientreconnect
- optional. Default -true
. indicates wheter reconnect automatically or notreconnectInterval
- optional. Default -30000
. Number. Amount of miliseconds to wait before new tryclientInfo
- string, name of client to be sent to esphome device. (Not necessary to send but nice for debugging issues)clientInfo
- string, name of client to be sent to esphome device. Usually needed only for tracking connection on esphome device.pingInterval
- optional. Default -15000
. Ping interval. Amount of miliseconds.pingAttempts
- optional. Default -3
. Number of failed ping attempts after witch connection is considered to be corrupted.
socketConnected
-true
if socket is connected but noconnected
-true
if client is introduced to esphome deviceauthorized
-true
if client is logged in esphome deviceconnecting
reconnecting
disconnecting
connect()
- do connection tryconnect()
- do connection trydisconnect()
- close connectionasync deviceInfoService()
- subsribes to entities state changes. Returns device info objectasync getTimeService()
- subsribes to entities state changes. Returns time objectasync listEntitiesService()
- subsribes to entities state changes. Returns entities listsubscribeStatesService()
- subsribes to entities state changessubscribeLogsService(level = 3, dumpConfig = false)
- subsribes to logs. Params:level
- logs level. 0 - NONE, 1 - ERROR, 2 - WARN, 3 - INFO, 4 - DEBUG, 5 - DEBUG, 6 - VERBOSE, 7 - VERY_VERBOSEdumpConfig
cameraImageService(single = true, stream = false)
- requests camera image. Params:single
stream
<entityType>CommandService(data)
- sends command to the specified entity. Seestatic commandService
in the Entity classesbuttonCommandService(data)
climateCommandService(data)
coverCommandService(data)
fanCommandService(data)
lightCommandService(data)
lockCommandService(data)
numberCommandService(data)
selectCommandService(data)
switchCommandService(data)
message.<type>
- when valid message from esphome device is received. First arg is message. The event is called beforemessage
event(more genetal analogue)message
- when valid message from esphome device is received. First arg is type, second is message.socketConnected
- emmited when socket is connectedsocketDisconnected
- emmited when socket is disconnectedconnected
- emmited if client is introduced to esphome devicedisconnected
- emmited if session is corruptredauthorized
- emmited if client is logged in esphome deviceunauthorized
- emmited if session is corruptreddata
- when any data is receivederror
- when any error is occuredunhandledData
- when data is received, but an error occured and we have unprocessed data
message.<type>
- when valid message from esphome device is received. First arg is message. The event is called beforemessage
event(more genetal analogue)message
- when valid message from esphome device is received. First arg is type, second is message.socketConnected
- emmited when socket is connectedsocketDisconnected
- emmited when socket is disconnectedconnected
- emmited if client is introduced to esphome devicedisconnected
- emmited if session is corruptredauthorized
- emmited if client is logged in esphome deviceunauthorized
- emmited if session is corruptreddata
- when any data is receivederror
- when any error is occuredunhandledData
- when data is received, but an error occured and we have unprocessed data