@2colors/esphome-native-api

中文文档
1.3.7发布于 2026/11/04MITTypeScriptCommonJS近 30 天下载 4456

esphome 本地 api 客户端

中文使用文档
文档目录14 节
  1. 安装
  2. 概要
  3. 设备信息和列表实体
  4. 发现
  5. 日志
  6. 用户定义的服务(概要)
  7. 叙事
  8. 发现
  9. 客户端
  10. 客户方法和属性
  11. 客户事件
  12. 实体
  13. 用户定义的服务
  14. 连接

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 ip
  • ttl -可选的 默认 - 255设置多播 ttl
  • loopback -可选的 默认 - 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) - 怎么样? 要连接的主机或 ip
  • port -可选的 默认 - 6053要连接的端口
  • encryptionKey - 加密钥匙 默认 - ''。用于加密的预共享密钥。 这是32字节的基础64 编码字符串
  • password - 口供(过期)。 默认 - ''。用于授权客户端的密码,建议使用加密密钥
  • reconnect -可选的 默认 - true。表示 wheter 是否自动重联
  • reconnectInterval -可选的 默认 - 30000数字。 等待新尝试的微秒数
  • clearSession -可选的 默认 - true设置 true 在重新连接后忘记任何信息
  • initializeDeviceInfo -可选的 默认 - true设置 true 在连接建立后检索设备信息
  • initializeListEntities -可选的 默认 - true设置 true 在连接建立后检索设备实体列表
  • initializeSubscribeStates -可选的 默认 - true
  • initializeSubscribeLogs -可选的 默认 - false
  • initializeSubscribeBLEAdvertisements -可选的 默认 - false
  • clientInfo - 字符串, 发送到 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_failed
  • ble - 当Esphome寄出任何BLE广告时发出。 启用于 initializeSubscribeBLEAdvertisements 转到 Client建筑师 第一个参数是对象 address, (中文(简体) ), name, (中文(简体) ), rssi, (中文(简体) ), serviceUuidsList, (中文(简体) ), serviceDataList, (中文(简体) ), manufacturerDataList, (中文(简体) ), addressType
  • error - 任何出错时发射

实体

每个实体类定义了个人与esphome组件的交互. 所有实体都有

  • config attrubute - 从 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 -停止。 折旧:使用 position
    • position -可选的,漂浮的 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-255
    • green -可选的 整数 0-255
    • blue -可选的 整数 0-255
    • colorMode -可选的整数 见 supportedColorModesList 在配置中调用
    • colorBrightness -可选的 浮动
    • white -可选的 整数 0-255
    • colorTemperature -可选的 整数
    • 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 UNMUTE
    • volume -可选的 浮动
    • 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 将参数类型名称导出到协议中使用的数值 :

名称数值说明
Bool0 个单布尔
Int1个单整数
Float2个单个浮点
String3个单字符串
BoolArray页:1布尔数组
IntArray页:1整数矩阵
FloatArray6个浮点阵列
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 VERBOSE
    • dumpConfig
  • cameraImageService(single = true, stream = false) - 请求相机图像.
    • single
    • stream
  • 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 特性更多 拖动/ 10
  • async 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 - 收到数据时,但发生错误,我们没有处理数据

版本与发布记录

@2colors/esphome-native-api 共发布 24 个版本,首次发布于 2023/02/08;过去 12 个月发布了 2 个版本。

版本发布日期距今
1.3.7latest2026/11/042 天前
1.3.62026/02/248 个月前
1.3.52025/11/061 年前
1.3.42025/10/211 年前
1.3.32025/09/161.1 年前
1.3.22024/07/152 年前

关于 @2colors/esphome-native-api 的常见问题

@2colors/esphome-native-api 是什么?

esphome 本地 api 客户端

如何安装 @2colors/esphome-native-api?

在项目目录运行 npm install @2colors/esphome-native-api,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 esphome-discover,可以用 npx esphome-discover 直接运行。

@2colors/esphome-native-api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@2colors/esphome-native-api 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@2colors/esphome-native-api 可以商用吗?

@2colors/esphome-native-api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@2colors/esphome-native-api 的下载量有多少?

根据 npm 官方下载统计,@2colors/esphome-native-api 在 2026/10/05 – 2026/11/03 这 30 天内被下载 4,456 次,日均约 149 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@2colors/esphome-native-api 还在维护吗?

最新版本 1.3.7 发布于 2026/11/04(2 天前);至今共发布 24 个版本,其中过去 12 个月发布了 2 个;首次发布于 2023/02/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。