ha-dashboard-create

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Works 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
url_path
field.
Home Assistant要求仪表盘URL路径必须包含连字符:
  • ✅ 正确示例:"climate-control", "mobile-app", "energy-monitor"
  • ❌ 错误示例:"climate", "mobile", "energy"
规则:
url_path
字段必须始终使用至少包含一个连字符的kebab-case命名方式。

When 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

使用步骤

  1. Connect to WebSocket: Authenticate with long-lived access token
  2. Check if exists: Query existing dashboards with
    lovelace/dashboards/list
  3. Create dashboard: Use
    lovelace/dashboards/create
    with url_path containing hyphen
  4. Save configuration: Update config with
    lovelace/config/save
  5. Verify: Check HA UI and system logs for errors
  1. 连接WebSocket:使用长期访问令牌进行认证
  2. 检查是否存在:使用
    lovelace/dashboards/list
    查询现有仪表盘
  3. 创建仪表盘:使用
    lovelace/dashboards/create
    接口,且url_path需包含连字符
  4. 保存配置:使用
    lovelace/config/save
    更新配置
  5. 验证:检查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消息类型

TypePurpose
lovelace/dashboards/list
List all dashboards
lovelace/dashboards/create
Create new dashboard
lovelace/dashboards/delete
Delete dashboard
lovelace/config/save
Save dashboard config
lovelace/config
Get dashboard config
system_log/list
Check for lovelace errors
See references/card-types.md for dashboard configuration structure and common card types.
Type用途
lovelace/dashboards/list
列出所有仪表盘
lovelace/dashboards/create
创建新仪表盘
lovelace/dashboards/delete
删除仪表盘
lovelace/config/save
保存仪表盘配置
lovelace/config
获取仪表盘配置
system_log/list
检查Lovelace相关错误
如需了解仪表盘配置结构和常见卡片类型,请查看references/card-types.md

Error Checking

错误排查

Validate Dashboard Configuration

校验仪表盘配置

python
undefined
python
undefined

1. 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")
undefined
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")
undefined

Common Error Patterns

常见错误类型

  1. URL path missing hyphen:
    "url_path": "climate"
    → Add hyphen:
    "climate-control"
  2. Entity doesn't exist: Check entity ID in Developer Tools → States
  3. Custom card not installed: Install via HACS first
  4. JavaScript errors: Check browser console (F12) for configuration errors
  1. URL路径缺少连字符
    "url_path": "climate"
    → 添加连字符:
    "climate-control"
  2. 实体不存在:在开发者工具→状态中检查实体ID
  3. 自定义卡片未安装:先通过HACS安装
  4. 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

工作流程

  1. Design dashboard - Plan views and card layout
  2. Validate entities - Check all entity IDs exist
  3. Connect to WebSocket - Authenticate with HA
  4. Check if exists - Query existing dashboards
  5. Create dashboard - Create if new (ensure url_path has hyphen!)
  6. Save configuration - Update dashboard config
  7. Verify - Check in HA UI and system logs for errors
  1. 设计仪表盘:规划视图和卡片布局
  2. 校验实体:检查所有实体ID是否存在
  3. 连接WebSocket:通过HA进行认证
  4. 检查是否存在:查询现有仪表盘
  5. 创建仪表盘:若为新仪表盘则创建(确保url_path包含连字符!)
  6. 保存配置:更新仪表盘配置
  7. 验证:在HA UI和系统日志中检查是否存在错误

URL Path Examples

URL路径示例

Dashboard TypeBad URL PathGood 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

仪表盘未显示在侧边栏

  1. Check
    show_in_sidebar: True
    in dashboard creation
  2. Verify
    url_path
    contains hyphen
  3. Refresh browser (Ctrl+Shift+R)
  4. Check HA logs for errors
  1. 检查仪表盘创建时是否设置了
    show_in_sidebar: True
  2. 验证
    url_path
    是否包含连字符
  3. 刷新浏览器(Ctrl+Shift+R)
  4. 检查HA日志是否存在错误

Configuration not saving

配置未保存

  1. Verify WebSocket authentication succeeded
  2. Check
    url_path
    matches existing dashboard
  3. Validate JSON structure (no syntax errors)
  4. Check system logs via
    system_log/list
  1. 验证WebSocket认证是否成功
  2. 检查
    url_path
    是否与现有仪表盘匹配
  3. 校验JSON结构(无语法错误)
  4. 通过
    system_log/list
    检查系统日志

Entity not found errors

实体未找到错误

  1. Get all entities:
    {"type": "get_states"}
  2. Compare with entities used in dashboard
  3. Fix entity IDs or remove missing entities
  4. Ensure entity has proper
    state_class
    for sensors
  1. 获取所有实体:
    {"type": "get_states"}
  2. 与仪表盘使用的实体进行对比
  3. 修正实体ID或移除不存在的实体
  4. 确保传感器实体拥有正确的
    state_class

Official Documentation

官方文档