Esphome 土生土长
此库执行客户端 Esphome 原住民协会。 。 。 .
此库重写 节点-红-接孔-接孔,原始图书馆 esphome-native-api (英语) @Nafaya)
安装
$ npm i @2colors/esphome-native-api
概要
设备信息和列表实体
const { Client } = require('@2colors/esphome-native-api');
const client = new Client({
host: '<esp host or ip>',
port: 6053,
// encryptionKey: '', // Use encryption key
// password: '', // Insert password if you have any (Deprecated)
});
client.connect();
client.on('deviceInfo', deviceInfo => {
console.log('Device info:', deviceInfo);
});
client.on('newEntity', entity => {
console.log('New entity:', entity);
// enable light
if (entity.type === 'Light') {
entity.setState(true);
}
// show state
entity.on('state', (state) => console.log(state));
});
client.on('error', (error) => console.log(error));
发现
const { Discovery } = require('@2colors/esphome-native-api');
Discovery().then(results => {
console.log(results);
/*
[
{
port: 6053,
network: 'wifi',
board: 'esp01_1m',
platform: 'ESP8266',
mac: 'c82b965b4153',
version: '2023.11.4',
host: 'bathroom-light.local',
address: '192.168.0.119'
}
]
*/
});
const { Discovery } = require('@2colors/esphome-native-api');
const discovery = new Discovery();
discovery.on('info', console.log);
/*
{
port: 6053,
network: 'wifi',
board: 'esp01_1m',
platform: 'ESP8266',
mac: 'c82b965b4153',
version: '2023.11.4',
host: 'bathroom-light.local',
address: '192.168.0.119'
}
*/
discovery.run();
日志
const { Client } = require('@2colors/esphome-native-api');
const client = new Client({
host: '<esp host or ip>',
port: 6053,
initializeSubscribeLogs: true
});
client.on('logs', ({ message }) => {
console.log(message);
});
用户定义的服务(概要)
用户定义的服务 让一个ESPHome设备曝光自定义的可调用功能.
使用 listEntitiesService() 发现它们 executeServiceService() 以援引它们.
const { Connection, ServiceArgType } = require('@2colors/esphome-native-api');
const connection = new Connection({
host: '<esp host or ip>',
port: 6053,
});
connection.connect();
connection.on('authorized', async () => {
// Discover all entities, including user-defined services
const entities = await connection.listEntitiesService();
const services = entities
.filter(e => e.component === 'Services')
.map(e => e.entity);
console.log('User-defined services:', services);
/*
[
{
name: 'my_service',
key: 1234567890,
argsList: [
{ name: 'brightness', type: 1 }, // ServiceArgType.Int
{ name: 'message', type: 3 } // ServiceArgType.String
]
}
]
*/
// Call a user-defined service by key with typed arguments
connection.executeServiceService({
key: services[0].key,
args: [
{ type: ServiceArgType.Int, value: 100 },
{ type: ServiceArgType.String, value: 'hello' },
],
});
});
叙事
发现
快点! Improman, 如果您想要在 Windows 上使用, 必须禁用/ 取消安装 Bonjour( 苹果) ! !
const { Discovery } = require('@2colors/esphome-native-api');
const discovery = new Discovery(options);
options- 可选multicast-可选的 默认 -true。使用 UP 多播interface-可选的 明确指定网络接口. 默认为全部port-可选的 默认 -5353设置 UP 端口ip-可选的 默认 -224.0.0.251设置 UP ipttl-可选的 默认 -255设置多播 ttlloopback-可选的 默认 -true。接收自己的包reuseAddr-可选的 默认 -true。在创建套接字时设置再使用添加器选项(需要 {0.11.13})bind-可选的 (单位:千美元)interface读取 更多
const { Discovery } = require('@2colors/esphome-native-api');
Discovery(options).then(console.log)
options- 可选timeout-可选的 默认 -5时间(秒) 等待答复的时间*- 以上所有选项
客户端
更亲切的一层 连接
const { Client } = require('@2colors/esphome-native-api');
const client = new Client({
clearSession = false,
initializeDeviceInfo = true,
initializeListEntities = true,
initializeSubscribeStates = true,
initializeSubscribeLogs = false,
initializeSubscribeBLEAdvertisements = false,
port = 6053,
host,
clientInfo = 'esphomenativeapi',
encryptionKey = '',
password = '', // Deprecated
reconnect = true,
reconnectInterval = 30000,
pingInterval = 15000,
pingAttempts = 3
});
host- (REQUIRED) - 怎么样? 要连接的主机或 ipport-可选的 默认 -6053要连接的端口encryptionKey- 加密钥匙 默认 -''。用于加密的预共享密钥。 这是32字节的基础64 编码字符串password- 口供(过期)。 默认 -''。用于授权客户端的密码,建议使用加密密钥reconnect-可选的 默认 -true。表示 wheter 是否自动重联reconnectInterval-可选的 默认 -30000数字。 等待新尝试的微秒数clearSession-可选的 默认 -true设置true在重新连接后忘记任何信息initializeDeviceInfo-可选的 默认 -true设置true在连接建立后检索设备信息initializeListEntities-可选的 默认 -true设置true在连接建立后检索设备实体列表initializeSubscribeStates-可选的 默认 -trueinitializeSubscribeLogs-可选的 默认 -falseinitializeSubscribeBLEAdvertisements-可选的 默认 -falseclientInfo- 字符串, 发送到 esphome 设备的客户端名称 。 (没有必要发送,但很好的调试问题)clientInfo- 字符串, 发送到 esphome 设备的客户端名称 。 通常只需要用于esphome设备上的跟踪连接. 见 连接pingInterval-可选的 默认 -15000. 平间. 微秒数。 见 连接pingAttempts-可选的 默认 -3. 巫术联系被认为被腐蚀后失败的接力尝试数量. 见 连接
客户方法和属性
connect()- 启动客户端disconnect()- srops客户端connected- 显示客户端是否连接到esphome和自闭initialized- 说明客户端是否连接和自动化,所有初始化步骤是否完成entities- 已发现的阵列 实体connection- 连接实例
客户事件
connected- 如果客户端连接到esphome和自主化,则发出disconnected- 当连接被破坏时发出initialized- 如果客户端连接和自动化,并完成所有初始化步骤,则发出deviceInfo- 当设备Info被检索或更新时发出。 启用于initializeDeviceInfo转到Client建筑师.newEntity- 发现新实体时发出。 启用于initializeListEntities转到Client建筑师 第一个论点是: 实体 类logs- 当Esphome寄出任何日志时发出。 启用于initializeSubscribeLogs转到Client建筑师 第一个参数是对象level, (中文(简体) ),tag, (中文(简体) ),message, (中文(简体) ),send_failedble- 当Esphome寄出任何BLE广告时发出。 启用于initializeSubscribeBLEAdvertisements转到Client建筑师 第一个参数是对象address, (中文(简体) ),name, (中文(简体) ),rssi, (中文(简体) ),serviceUuidsList, (中文(简体) ),serviceDataList, (中文(简体) ),manufacturerDataList, (中文(简体) ),addressTypeerror- 任何出错时发射
实体
每个实体类定义了个人与esphome组件的交互. 所有实体都有
configattrubute - 从 esphome 重置实体配置state收到新状态时的事件state属性destroyed当 Corresponfifing 客户端不再连接到此实体时, 将调用的事件 () 见clearSession备选案文)和type属性等于组件类型name属性等于实体名称
二进制传感器
只有基础功能
按钮
static commandService(connection, { key })key- 要求。 实体的钥匙/代号
相机
气候
static commandService(connection, { key, mode, targetTemperature, targetTemperatureLow, targetTemperatureHigh, away, fanMode, swingMode })- 向气候实体发出指令key- 要求。 实体的钥匙/代号mode-可选的 0 -关闭,1-AUTO,2-COOL,3-HEAT,4-FAN ONLY,5-干燥。 见supportedModesList在配置中调用targetTemperature-可选的 浮动targetTemperatureLow-可选的 浮动targetTemperatureHigh-可选的 浮动legacyAway-可选的 布尔. 折旧:使用preset与离开fanMode-可选的 0 - On, 1 - Off, 2 - AUTO, 3 - Low, 4 - MEDIUM, 5 - High, 6 - Middle, 7 - FOCUS, 8 - DIFFUSE, 9 - QUIET. 见supportedFanModesList在配置中调用swingMode-可选的 0 -关闭, 1 -两个, 2 -虚拟, 3 见supportedSwingModesList在配置中调用customFanMode-可选的弦 见supportedCustomFanModesList在配置中调用preset-可选的 0 -没有,1 - 家,2 - 离开,3 - 博斯特,4 - 舒适,5 - 经合组织,6 - 睡,7 - 活动。 见supportedPresetsList在配置中调用customPreset-可选的弦 见supportedCustomPresetsList在配置中调用
覆盖
static commandService(connection, { key, legacyCommand, position, tilt, stop })- 发送命令覆盖实体.key- 要求。 实体的钥匙/代号legacyCommand-可选的 0 -打开,1 -关闭,2 -停止。 折旧:使用positionposition-可选的,漂浮的 0.0 - 关闭,1.0 - 打开. 见supportsPosition在配置中调用tilt-可选的,漂浮的 0.0 - 关闭,1.0 - 打开. 见supportsTilt在配置中调用stop-可选的 布尔
风扇
static commandService(connection, { key, state, speed, oscillating, direction, speedLevel })- 向粉丝实体发出命令.key- 要求。 实体的钥匙/代号state-可选的 布尔speed-可选的 0 - 低音, 1 - 中音, 2 - 高音oscillating-可选的 布尔direction-可选的 0 - 前锋 1 - 重复speedLevel-可选的整数 见supportedSpeedLevels在配置中调用
光线
static commandService(connection, { key, state, brightness, red, green, blue, colorMode, colorBrightness, white, colorTemperature, coldWhite, warmWhite, transitionLength, flashLength, effect })- 向轻实体发出指令.key- 要求。 实体的钥匙/代号state-可选的 布尔brightness-可选的 浮动red-可选的 整数 0-255green-可选的 整数 0-255blue-可选的 整数 0-255colorMode-可选的整数 见supportedColorModesList在配置中调用colorBrightness-可选的 浮动white-可选的 整数 0-255colorTemperature-可选的 整数coldWhite-可选的 浮动warmWhite-可选的 浮动flashLength-可选的 整数effect-可选的 绳子。 配置列表中效果阵列的效果
锁定
static commandService(connection, { key, command, code }- 向锁定实体发出命令.key- 要求。 实体的钥匙/代号command- 需要钱。 0 - 无洛克,1-洛克,2-开放code-可选的弦 见requiresCode在配置中调用
媒体显示器
static commandService(connection, { key, command, volume, mediaUrl }- 向媒体玩家实体发出命令.key- 要求。 实体的钥匙/代号command- 需要钱。 0-MEDIA PLAYER COMMAND PLAYE, 1-MEDIA PLAYER COMMAND PAUSE, 2-MEDIA PLAYER COMMAND STOP, 3-MEDIA PLAYER COMMAND MUTE, 4-MEDIA PLAYER COMMAND UNMUTEvolume-可选的 浮动mediaUrl-可选的 字符串
数目
static commandService(connection, { key, state })- 向数字实体发出命令.key- 要求。 实体的钥匙/代号state- 需要,飘来飘去 见minValue, (中文(简体) ),maxValue,以及step在配置中访问
选择
static commandService(connection, { key, state })- 向选定的实体发送命令.key- 要求。 实体的钥匙/代号state- 需要帮助 弦 见optionsList在配置中调用
传感器
只有基础功能
警报
static commandService(connection, { key, state, tone, duration, volume })- 向警报器发出指令.key- 要求。 实体的钥匙/代号state- 要求,布尔tone-可选的弦 见tonesList在配置中调用duration-可选的整数 见supportsDuration在配置中调用volume-可选的整数 见supportsVolume在配置中调用
切换
static commandService(connection, { key, state })- 发送命令切换实体.key- 要求。 实体的钥匙/代号state- 要求,布尔
文本传感器
只有基础功能
文本
static commandService(connection, { key, state })- 向文本实体发送命令.key- 要求。 实体的钥匙/代号state- 需要帮助 弦 见minLength, (中文(简体) ),maxLength在配置中访问
用户定义的服务
用户定义的服务 是ESPHome设备的YAML配置中声明的自定义可调用函数。 当你打电话时会自动发现它们 listEntitiesService() 并被援引 executeServiceService()。 。 。 .
服务ArgType
这个 ServiceArgType 将参数类型名称导出到协议中使用的数值 :
| 名称 | 数值 | 说明 |
|---|---|---|
Bool | 0 个 | 单布尔 |
Int | 1个 | 单整数 |
Float | 2个 | 单个浮点 |
String | 3个 | 单字符串 |
BoolArray | 页:1 | 布尔数组 |
IntArray | 页:1 | 整数矩阵 |
FloatArray | 6个 | 浮点阵列 |
StringArray | 第7条 | 字符串组合 |
const { ServiceArgType } = require('@2colors/esphome-native-api');
发现服务 listEntitiesService()
与正规实体一起恢复服务。 过滤器由 component === 'Services' 只获取服务定义 :
const entities = await connection.listEntitiesService();
const services = entities
.filter(e => e.component === 'Services')
.map(e => e.entity);
/*
[
{
name: 'my_service',
key: 1234567890,
argsList: [
{ name: 'brightness', type: 1 }, // ServiceArgType.Int
{ name: 'enable', type: 0 } // ServiceArgType.Bool
]
}
]
*/
每个服务条目有:
name- 绳子 ESPHome YAML 中声明的服务名称key- 号码。 用于引用服务的独特密钥argsList- 数组{ name: string, type: ServiceArgType }参数描述符
执行服务 executeServiceService(data)
connection.executeServiceService({ key, args })
key- 需要,号码。 服务key从发现回复中args-可选的 矩阵{ type: ServiceArgType, value }对象,按argsList
const { Connection, ServiceArgType } = require('@2colors/esphome-native-api');
connection.executeServiceService({
key: 1234567890,
args: [
{ type: ServiceArgType.Int, value: 100 },
{ type: ServiceArgType.Bool, value: true },
{ type: ServiceArgType.String, value: 'hello' },
],
});
倾听服务定义
在服务定义使用连接事件到达时,您也可以对此作出反应:
connection.on('message.ListEntitiesServicesResponse', (service) => {
console.log('Service discovered:', service.name, 'key:', service.key);
});
连接
const { Connection } = require('@2colors/esphome-native-api');
const connection = new Connection({
port = 6053,
host,
clientInfo = 'esphomenativeapi',
encryptionKey = '',
password = '', // Deprecated
reconnect = true,
reconnectInterval = 30000,
pingInterval = 15000,
pingAttempts = 3
});
host- (REQUIRED) - 怎么样? 要连接的主机或 ip .port-可选的 默认 -6053。要连接的端口.encryptionKey- 加密钥匙 默认 -''。用于加密的预共享密钥。 这是32字节的基础64 编码字符串password- 口供(过期)。 默认 -''。用于授权客户端的密码,建议使用加密密钥reconnect-可选的 默认 -true。表示 wheter 是否自动重联reconnectInterval-可选的 默认 -30000数字。 等待新尝试的微秒数clientInfo- 字符串, 发送到 esphome 设备的客户端名称 。 (没有必要发送,但很好的调试问题)clientInfo- 字符串, 发送到 esphome 设备的客户端名称 。 通常只需要用于esphome设备上的跟踪连接.pingInterval-可选的 默认 -15000. 平间. 微秒数.pingAttempts-可选的 默认 -3. 巫术联系被认为被腐蚀后失败的接力尝试数量.
方法和属性
connected- 说吧true如果客户端被引入 esphome 设备authorized- 说吧true如果客户端登录在 esphome 设备中connect()- 尝试连接disconnect()- 密切连接async deviceInfoService()- 实体的子更改。 返回设备信息对象async getTimeService()- 实体的子更改。 返回时间对象async listEntitiesService()- 实体的子更改。 回返实体名单subscribeStatesService()- 实体的子更改subscribeLogsService(level = 5, dumpConfig = false)- 分层到日志.level- 记录水平。 0 - 无, 1 - 错误, 2 - 危险, 3 - INFO, 4 - DEBUG, 5 - DEBUG, 6 - VERBOSE, 7 - very VERBOSEdumpConfig
cameraImageService(single = true, stream = false)- 请求相机图像.singlestream
subscribeBluetoothAdvertisementService()- 蓝牙广告状态变化的子图unsubscribeBluetoothAdvertisementService()- 蓝牙广告状态的更改async connectBluetoothDeviceService(address = int, addressType = int, useCache = boolean)- 连接到可连接的BLE设备async disconnectBluetoothDeviceService(address = int)- 断开可连接的BLE设备async listBluetoothGATTServicesService(address = int)- 必须连接到BLE设备,BLE 列出关贸总协定服务async readBluetoothGATTCharacteristicService(address = int, handle)- 必须连接到BLE设备,BLE列表 关贸总协定特征服务async writeBluetoothGATTCharacteristicService(address = int, handle, someUint8Array, response = false)- 必须连接到 BLE 设备, BLE 写 GATT 特性更多 拖动/ 10async notifyBluetoothGATTCharacteristicService(address = int, handle)- 必须与BLE设备相接,BLE通知关贸总协定的特点async readBluetoothGATTDescriptorService(address = int, handle)- 必须连接到BLE设备,BLE列表 GATT描述器async writeBluetoothGATTDescriptorService(address = int, handle, someUint8Array)- 必须连接到BLE设备,BLE编写关贸总协定说明<entityType>CommandService(data)- 向指定的实体发出命令。 见static commandService实体类别buttonCommandService(data)climateCommandService(data)coverCommandService(data)fanCommandService(data)lightCommandService(data)lockCommandService(data)numberCommandService(data)textCommandService(data)selectCommandService(data)sirenCommandService(data)switchCommandService(data)mediaplayerCommandService(data)
executeServiceService({ key, args })- 执行 用户定义的服务。见 用户定义的服务 详细情况.key- 需要,号码。 从listEntitiesService()args-可选的 矩阵{ type: ServiceArgType, value }对象
连接事件
message.<type>- 收到esphome设备的有效消息时。 初标为通. 之前就叫这个message事件( 更多基因模拟)reconnect- 如果客户端重新连接到 esphome 设备, 则发出message- 收到esphome设备的有效消息时。 第一个参数是类型,第二个是消息.connected- 如果引入客户端到 esphome 设备, 即发出disconnected- 如果会话被损坏就发出authorized- 如果客户端登录到 esphome 设备中, 则发出unauthorized- 如果会话被损坏就发出data- 收到任何数据后error- 当出现错误时unhandledData- 收到数据时,但发生错误,我们没有处理数据