ha-dashboard-create
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWorks with Python websocket-client, WebSocket API authentication, and Lovelace configuration.
基于Python websocket-client、WebSocket API认证和Lovelace配置实现。
Home Assistant Dashboard Creation
Home Assistant 仪表盘创建
Create and update Lovelace dashboards programmatically using the WebSocket API.
通过WebSocket API以程序化方式创建和更新Lovelace仪表盘。
CRITICAL: Dashboard URL Path Requirements
重要:仪表盘URL路径要求
Home Assistant requires dashboard URL paths to contain a hyphen:
- ✅ CORRECT: "climate-control", "mobile-app", "energy-monitor"
- ❌ WRONG: "climate", "mobile", "energy"
Rule: Always use kebab-case with at least one hyphen in the field.
url_pathHome Assistant要求仪表盘URL路径必须包含连字符:
- ✅ 正确示例:"climate-control", "mobile-app", "energy-monitor"
- ❌ 错误示例:"climate", "mobile", "energy"
规则: 字段必须始终使用至少包含一个连字符的kebab-case命名方式。
url_pathWhen to Use This Skill
何时使用本技能
Use this skill when you need to:
- Create Home Assistant dashboards programmatically via WebSocket API
- Automate dashboard creation and updates for multiple environments
- Build dashboard generators for dynamic card configurations
- Validate dashboard entities before deployment
- Manage dashboards as code with version control
- Programmatically update existing dashboard configurations
Do NOT use when:
- You can use the Home Assistant UI dashboard editor (simpler for manual changes)
- Building simple static dashboards (UI editor is more intuitive)
- You haven't created a long-lived access token for API authentication
在以下场景使用本技能:
- 通过WebSocket API程序化创建Home Assistant仪表盘
- 为多环境自动化创建和更新仪表盘
- 为动态卡片配置构建仪表盘生成器
- 部署前校验仪表盘实体
- 通过版本控制以代码形式管理仪表盘
- 程序化更新现有仪表盘配置
请勿在以下场景使用:
- 可使用Home Assistant UI仪表盘编辑器时(手动变更更简单)
- 构建简单静态仪表盘时(UI编辑器更直观)
- 未创建用于API认证的长期访问令牌时
Usage
使用步骤
- Connect to WebSocket: Authenticate with long-lived access token
- Check if exists: Query existing dashboards with
lovelace/dashboards/list - Create dashboard: Use with url_path containing hyphen
lovelace/dashboards/create - Save configuration: Update config with
lovelace/config/save - Verify: Check HA UI and system logs for errors
- 连接WebSocket:使用长期访问令牌进行认证
- 检查是否存在:使用查询现有仪表盘
lovelace/dashboards/list - 创建仪表盘:使用接口,且url_path需包含连字符
lovelace/dashboards/create - 保存配置:使用更新配置
lovelace/config/save - 验证:检查HA UI和系统日志是否存在错误
Quick Start
快速开始
python
import json
import websocket
HA_URL = "http://192.168.68.123:8123"
HA_TOKEN = os.environ["HA_LONG_LIVED_TOKEN"]
def create_dashboard(url_path: str, title: str, config: dict):
"""Create or update a dashboard.
Args:
url_path: Dashboard URL path (must contain hyphen, e.g., "climate-control")
title: Dashboard display title
config: Dashboard configuration dict
"""
# Validate url_path contains hyphen
if "-" not in url_path:
raise ValueError(f"url_path must contain hyphen: '{url_path}' -> '{url_path}-view'")
ws_url = HA_URL.replace("http://", "ws://") + "/api/websocket"
ws = websocket.create_connection(ws_url)
msg_id = 1
# 1. Receive auth_required
ws.recv()
# 2. Send auth
ws.send(json.dumps({"type": "auth", "access_token": HA_TOKEN}))
ws.recv() # auth_ok
# 3. Check if dashboard exists
ws.send(json.dumps({"id": msg_id, "type": "lovelace/dashboards/list"}))
msg_id += 1
response = json.loads(ws.recv())
exists = any(d["url_path"] == url_path for d in response.get("result", []))
# 4. Create if doesn't exist
if not exists:
ws.send(json.dumps({
"id": msg_id,
"type": "lovelace/dashboards/create",
"url_path": url_path, # Must contain hyphen!
"title": title,
"icon": "mdi:view-dashboard",
"show_in_sidebar": True,
}))
msg_id += 1
ws.recv()
# 5. Save configuration
ws.send(json.dumps({
"id": msg_id,
"type": "lovelace/config/save",
"url_path": url_path,
"config": config,
}))
ws.recv()
ws.close()python
import json
import websocket
HA_URL = "http://192.168.68.123:8123"
HA_TOKEN = os.environ["HA_LONG_LIVED_TOKEN"]
def create_dashboard(url_path: str, title: str, config: dict):
"""Create or update a dashboard.
Args:
url_path: Dashboard URL path (must contain hyphen, e.g., "climate-control")
title: Dashboard display title
config: Dashboard configuration dict
"""
# Validate url_path contains hyphen
if "-" not in url_path:
raise ValueError(f"url_path must contain hyphen: '{url_path}' -> '{url_path}-view'")
ws_url = HA_URL.replace("http://", "ws://") + "/api/websocket"
ws = websocket.create_connection(ws_url)
msg_id = 1
# 1. Receive auth_required
ws.recv()
# 2. Send auth
ws.send(json.dumps({"type": "auth", "access_token": HA_TOKEN}))
ws.recv() # auth_ok
# 3. Check if dashboard exists
ws.send(json.dumps({"id": msg_id, "type": "lovelace/dashboards/list"}))
msg_id += 1
response = json.loads(ws.recv())
exists = any(d["url_path"] == url_path for d in response.get("result", []))
# 4. Create if doesn't exist
if not exists:
ws.send(json.dumps({
"id": msg_id,
"type": "lovelace/dashboards/create",
"url_path": url_path, # Must contain hyphen!
"title": title,
"icon": "mdi:view-dashboard",
"show_in_sidebar": True,
}))
msg_id += 1
ws.recv()
# 5. Save configuration
ws.send(json.dumps({
"id": msg_id,
"type": "lovelace/config/save",
"url_path": url_path,
"config": config,
}))
ws.recv()
ws.close()WebSocket Message Types
WebSocket消息类型
| Type | Purpose |
|---|---|
| List all dashboards |
| Create new dashboard |
| Delete dashboard |
| Save dashboard config |
| Get dashboard config |
| Check for lovelace errors |
See references/card-types.md for dashboard configuration structure and common card types.
| Type | 用途 |
|---|---|
| 列出所有仪表盘 |
| 创建新仪表盘 |
| 删除仪表盘 |
| 保存仪表盘配置 |
| 获取仪表盘配置 |
| 检查Lovelace相关错误 |
如需了解仪表盘配置结构和常见卡片类型,请查看references/card-types.md。
Error Checking
错误排查
Validate Dashboard Configuration
校验仪表盘配置
python
undefinedpython
undefined1. Check system logs for lovelace errors
1. Check system logs for lovelace errors
ws.send(json.dumps({"id": 1, "type": "system_log/list"}))
logs = json.loads(ws.recv())
ws.send(json.dumps({"id": 1, "type": "system_log/list"}))
logs = json.loads(ws.recv())
Filter for 'lovelace' or 'frontend' errors
Filter for 'lovelace' or 'frontend' errors
2. Validate dashboard configuration
2. Validate dashboard configuration
ws.send(json.dumps({
"id": 2,
"type": "lovelace/config",
"url_path": "climate-control" # Must contain hyphen
}))
config = json.loads(ws.recv())
ws.send(json.dumps({
"id": 2,
"type": "lovelace/config",
"url_path": "climate-control" # Must contain hyphen
}))
config = json.loads(ws.recv())
3. Validate entity IDs exist
3. Validate entity IDs exist
ws.send(json.dumps({"id": 3, "type": "get_states"}))
states = json.loads(ws.recv())
entity_ids = [s["entity_id"] for s in states["result"]]
ws.send(json.dumps({"id": 3, "type": "get_states"}))
states = json.loads(ws.recv())
entity_ids = [s["entity_id"] for s in states["result"]]
4. Check if entities used in dashboard exist
4. Check if entities used in dashboard exist
for card in dashboard_config["views"][0]["cards"]:
if "entity" in card:
if card["entity"] not in entity_ids:
print(f"Warning: Entity {card['entity']} not found")
undefinedfor card in dashboard_config["views"][0]["cards"]:
if "entity" in card:
if card["entity"] not in entity_ids:
print(f"Warning: Entity {card['entity']} not found")
undefinedCommon Error Patterns
常见错误类型
- URL path missing hyphen: → Add hyphen:
"url_path": "climate""climate-control" - Entity doesn't exist: Check entity ID in Developer Tools → States
- Custom card not installed: Install via HACS first
- JavaScript errors: Check browser console (F12) for configuration errors
- URL路径缺少连字符:→ 添加连字符:
"url_path": "climate""climate-control" - 实体不存在:在开发者工具→状态中检查实体ID
- 自定义卡片未安装:先通过HACS安装
- JavaScript错误:查看浏览器控制台(F12)中的配置错误
Entity Validation
实体校验
Verify entity IDs exist before using them in dashboards.
See references/entity-patterns.md for entity validation functions and common entity patterns.
在仪表盘使用实体ID前,请先验证其是否存在。
如需了解实体校验函数和常见实体模式,请查看references/entity-patterns.md。
Supporting Files
配套文件
- scripts/create_dashboard.py - Complete working example with entity validation
- references/card-types.md - Dashboard configuration structure and card types
- references/entity-patterns.md - Entity validation and common patterns
- scripts/create_dashboard.py - 包含实体校验的完整可运行示例
- references/card-types.md - 仪表盘配置结构和卡片类型
- references/entity-patterns.md - 实体校验和常见模式
Workflow
工作流程
- Design dashboard - Plan views and card layout
- Validate entities - Check all entity IDs exist
- Connect to WebSocket - Authenticate with HA
- Check if exists - Query existing dashboards
- Create dashboard - Create if new (ensure url_path has hyphen!)
- Save configuration - Update dashboard config
- Verify - Check in HA UI and system logs for errors
- 设计仪表盘:规划视图和卡片布局
- 校验实体:检查所有实体ID是否存在
- 连接WebSocket:通过HA进行认证
- 检查是否存在:查询现有仪表盘
- 创建仪表盘:若为新仪表盘则创建(确保url_path包含连字符!)
- 保存配置:更新仪表盘配置
- 验证:在HA UI和系统日志中检查是否存在错误
URL Path Examples
URL路径示例
| Dashboard Type | Bad URL Path | Good URL Path |
|---|---|---|
| Climate monitoring | "climate" | "climate-control" |
| Mobile view | "mobile" | "mobile-app" |
| Energy tracking | "energy" | "energy-monitor" |
| Air quality | "air" | "air-quality" |
| Irrigation | "irrigation" | "irrigation-control" |
| 仪表盘类型 | 错误URL路径 | 正确URL路径 |
|---|---|---|
| 气候监控 | "climate" | "climate-control" |
| 移动端视图 | "mobile" | "mobile-app" |
| 能源追踪 | "energy" | "energy-monitor" |
| 空气质量 | "air" | "air-quality" |
| 灌溉控制 | "irrigation" | "irrigation-control" |
Troubleshooting
故障排除
Dashboard not appearing in sidebar
仪表盘未显示在侧边栏
- Check in dashboard creation
show_in_sidebar: True - Verify contains hyphen
url_path - Refresh browser (Ctrl+Shift+R)
- Check HA logs for errors
- 检查仪表盘创建时是否设置了
show_in_sidebar: True - 验证是否包含连字符
url_path - 刷新浏览器(Ctrl+Shift+R)
- 检查HA日志是否存在错误
Configuration not saving
配置未保存
- Verify WebSocket authentication succeeded
- Check matches existing dashboard
url_path - Validate JSON structure (no syntax errors)
- Check system logs via
system_log/list
- 验证WebSocket认证是否成功
- 检查是否与现有仪表盘匹配
url_path - 校验JSON结构(无语法错误)
- 通过检查系统日志
system_log/list
Entity not found errors
实体未找到错误
- Get all entities:
{"type": "get_states"} - Compare with entities used in dashboard
- Fix entity IDs or remove missing entities
- Ensure entity has proper for sensors
state_class
- 获取所有实体:
{"type": "get_states"} - 与仪表盘使用的实体进行对比
- 修正实体ID或移除不存在的实体
- 确保传感器实体拥有正确的
state_class