Compare commits

...
10 Commits
Author SHA1 Message Date
eiggerandClaude Opus 5 9e55c585f9 feat(door): add door_event event entity for pass-through timestamps
Validate YAML Configs / Validate YAML Schema (push) Failing after 11m0s
door_status stays at the same value on every pass, so HA never moves
last_changed and the logbook cannot show when the door was actually used.
An event entity's state is the timestamp of the last occurrence, so a repeated
event_type still updates it, and it is not restored across HA restarts — no
stale "entering" coming back after a reboot.

Both entities are derived from the same advertisement: door_status for the
current state, door_event for when it happened. heartbeat: 60s lets the same
event_type fire again after 60s, which is once per pass in practice.

Also teach scripts/validate.py the event platform, mirroring the app's
ConfigValidator rules: event_types required (error), map values missing from
event_types, absent decode.map, numeric metadata, and a publish rule whose
on_change_only suppresses repeats (warnings). The inherited publish rule
(sensor > device > defaults) is now threaded down to sensor validation.

Requires HassBle 1.5.0 or newer — event_types is a new key and older versions
parse config.yaml in strict mode.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 22:40:52 +09:00
eigger 9b937c8840 Update config.yaml to comment out advertise section
Commented out the advertise section and modified the state mapping for authentication.
2026-09-06 17:33:23 +09:00
eiggerandCursor d2e399afc2 feat(parking): set APT SmartKey advertise local_name
parking_beacon requests include Complete Local Name. Requires HassBle 1.4.1.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 08:11:17 +09:00
eiggerandCursor c596db47bf feat(parking): persist request counter and 0x41/0x40 payload phases
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 15:55:50 +09:00
eigger e4851696eb feat: add location request advertise and button to parking_beacon 2026-08-30 19:06:57 +09:00
eigger b4fc6f799f feat(advertise): add BLE advertising TX schema, templates, and validation
- Update scripts/validate.py with advertise block and control action validation
- Update templates.yaml with mytown_parking_beacon advertising TX template
- Add commented parking beacon TX/RX example to config.yaml
- Document advertise schema, counter_mode, counter_start, and control actions in README.md / README.ko.md
2026-08-28 21:55:05 +09:00
eigger 5659408d8d fix(mytown): update parking_location decode length to 3 in mytown template 2026-08-28 17:24:24 +09:00
eigger 9658db3bcc ci: add YAML schema and validation checks for config and templates 2026-08-27 20:18:14 +09:00
eigger 25088f660e fix(template): use uint8 and unsigned map keys for mytown parking floor 2026-08-27 20:16:16 +09:00
eigger 042630b7df feat: add MyTown parking beacon template (format 0x06) 2026-08-27 20:12:07 +09:00
6 changed files with 946 additions and 11 deletions

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
name: Validate YAML Configs
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
validate:
name: Validate YAML Schema
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install Dependencies
run: pip install pyyaml
- name: Validate config.yaml and templates.yaml
run: python scripts/validate.py
+55 -4
View File
@@ -140,7 +140,7 @@ defaults:
on_change_only: true
min_interval: 5s
sensors: [...]
controls: [...] # gatt_notify / obd만 사용 가능
controls: [...] # gatt_notify / obd / advertisement(action 전용)
```
| 필드 | 타입 | 필수 | 설명 |
@@ -205,6 +205,56 @@ defaults:
| `mac` (기본) | 고유 MAC 주소마다 별도의 HA 엔티티 세트를 생성합니다. 엔티티 unique_id: `{device_id}_{MAC}_temperature` 등. 앱의 Sensors 탭에서 MAC을 바인딩하면 기기가 스캔되기 전에 엔티티를 미리 생성할 수 있습니다. |
| `shared` | 모든 매칭 광고 기기가 하나의 HA 엔티티를 공유합니다. 마지막으로 수신된 패킷이 상태를 덮어씁니다. 주차 비콘, 클리커 등에 유용합니다. |
### advertise — BLE 광고 송신 (TX)
지하주차장 위치 요청 비콘처럼 앱에서 스마트폰의 BLE 광고를 송신하여 주변 비콘을 깨우고 응답을 유도하는 기능입니다.
```yaml
- id: mytown_parking
name: "마이타운 주차위치"
source: advertisement
instance_mode: shared
match:
manufacturer_id: 861 # 0x035D — kaml 파싱을 위해 10진수(decimal) 사용 권장
manufacturer_hex_prefix: "06" # 06 응답 포맷 매칭
manufacturer_min_length: 18
advertise:
manufacturer_id: 861
payload: "05CB34447B91F8C69BBE41157C70BB631C40{counter:02X}"
counter_mode: reset # reset(기본) | persist
counter_start: 0 # reset 모드 시작값, persist 모드 초기 시드값 (0~255)
mode: balanced # low_power (~1s) | balanced (~250ms) | low_latency (~100ms)
tx_power: high # ultra_low | low | medium | high
timeout: 15s # 이 시간 지나면 자동 송신 중단
repeat_interval: 1s # (선택) 이 주기로 payload 갱신 = counter 증가
stop_on_response: true # match 조건에 부합하는 광고 수신 시 즉시 송신 중단
connectable: false
scannable: true
controls:
- key: request_location
type: button
name: "주차위치 요청"
action: advertise # command 대신 앱 내부 광고 송신 동작 실행
icon: mdi:car-search
```
| 필드 | 필수 | 기본값 | 설명 |
|------|------|--------|------|
| `manufacturer_id` | ✅ | | BLE Company Identifier (10진수). 예: 861 (=0x035D). |
| `payload` | ✅ | | Manufacturer Data payload hex (Company ID 제외). `{counter}`(10진수) 또는 `{counter:02X}`(2자리 hex) 토큰 사용 가능. 레거시 광고 24바이트 제한. |
| `counter_mode` | | `reset` | 카운터 모드: `reset` (누를 때마다 `counter_start`부터 시작, 버스트 내에서만 증가) \| `persist` (앱 재시작 후에도 이전 값에서 이어짐). |
| `counter_start` | | `0` | 카운터 시작값 (0~255). `reset` 모드 시 매 요청 시작값, `persist` 모드 시 최초 영속 전 초기 시드값. |
| `mode` | | `balanced` | 광고 주기: `low_power` (~1s) \| `balanced` (~250ms) \| `low_latency` (~100ms). |
| `tx_power` | | `high` | 송신 출력: `ultra_low` \| `low` \| `medium` \| `high`. |
| `timeout` | | `15s` | 광고 송신 최대 지속 시간 (지나면 자동 중단). |
| `repeat_interval` | | `null` | 지정 시 해당 주기마다 counter를 증가시키며 payload 갱신 (생략 시 1회 세팅 후 대기). |
| `stop_on_response` | | `true` | 이 기기의 `match` 조건을 만족하는 응답 패킷 수신 시 즉시 광고 송신 중단. |
| `connectable` | | `false` | BLE 연결 가능 여부. |
| `scannable` | | `true` | Scannable 광고 여부. |
| `include_device_name` | | `false` | 기기 이름 포함 여부 (31바이트 예산 절약을 위해 기본 false 권장). |
> **알림:** `advertise` 블록이 설정된 기기는 HA에 `{id}_advertising` 진단 바이너리 센서(`binary_sensor`)가 자동으로 생성되어 현재 광고 송신 진행 여부(`on`/`off`)를 보고합니다.
---
## source: gatt_notify — GATT 연결
@@ -359,7 +409,7 @@ obd:
```yaml
sensors:
- key: temperature # 필수 — 기기 내 고유 키
platform: sensor # sensor | binary_sensor | text_sensor
platform: sensor # sensor | binary_sensor | text_sensor | event
device_class: temperature # HA device_class (선택)
unit: "°C"
state_class: measurement # measurement | total | total_increasing
@@ -439,7 +489,7 @@ decode:
| `int32` | 4 | 부호 있는 32비트 정수. |
| `float32` | 4 | IEEE 754 단정밀도 부동소수점. |
| `timestamp` | 4 | 각 바이트를 월/일/시/분으로 해석. ISO 8601 문자열 반환. |
| `string` | N | 바이트를 ASCII로 디코딩. `platform: text_sensor`와 함께 사용. |
| `string` | N | 바이트를 ASCII로 디코딩. `length: 0` 지정 시 잔여 바이트 전체를 가변 길이로 읽고 공백/null을 자동 트림합니다. `platform: text_sensor`와 함께 사용. |
---
@@ -492,7 +542,8 @@ controls:
| `name` | string | ❌ | HA 표시 이름. 생략 시 key에서 자동 생성. |
| `icon` | string | ❌ | MDI 아이콘. |
| `entity_category` | string | ❌ | `config` 또는 `diagnostic`. |
| `command` | object | ✅ | 명령 맵. type에 따라 키가 다릅니다 (위 예제 참조). |
| `command` | object | ❌* | 명령 맵. type에 따라 키가 다릅니다 (위 예제 참조). `action`이 없을 때 필수. |
| `action` | enum | ❌* | 앱 내부 동작 트리거 (`advertise` \| `stop_advertise`). `action` 사용 시 `command` 생략 가능. |
| `options` | list | select만 | `select` 타입 옵션 목록. |
| `min` | float | number만 | `number` 타입 최솟값. |
| `max` | float | number만 | `number` 타입 최댓값. |
+4 -3
View File
@@ -140,7 +140,7 @@ Every entry in `devices` must have a `source` field that selects the data path.
on_change_only: true
min_interval: 5s
sensors: [...]
controls: [...] # gatt_notify / obd only
controls: [...] # gatt_notify / obd / advertisement(action only)
```
| Field | Type | Required | Description |
@@ -360,7 +360,7 @@ Each item in the `sensors` list defines one HA entity.
```yaml
sensors:
- key: temperature # Required — unique key within the device
platform: sensor # sensor | binary_sensor | text_sensor
platform: sensor # sensor | binary_sensor | text_sensor | event
device_class: temperature # HA device_class (optional)
unit: "°C"
state_class: measurement # measurement | total | total_increasing
@@ -493,7 +493,8 @@ controls:
| `name` | string | ❌ | Display name in HA. Auto-generated from key if omitted. |
| `icon` | string | ❌ | MDI icon string. |
| `entity_category` | string | ❌ | `config` or `diagnostic`. |
| `command` | object | ✅ | Command map. Keys depend on type (see examples above). |
| `command` | object | ❌* | Command map. Keys depend on type (see examples above). Required when `action` is omitted. |
| `action` | enum | ❌* | Internal app action trigger (`advertise` \| `stop_advertise`). Omit `command` when `action` is specified. |
| `options` | list | select only | Options list for `select` type. |
| `min` | float | number only | Minimum value for `number` type. |
| `max` | float | number only | Maximum value for `number` type. |
+97 -2
View File
@@ -50,8 +50,60 @@ devices:
# source_field: manufacturer_data
# decode: { offset: 23, length: 1, type: uint8 }
# 지하주차장 위치 요청 비콘 (BLE 광고 송신 및 수신 예제)
# UUID는 본인의 패킷 캡처에서 추출한 고유값으로 교체하세요.
#- id: mytown_parking
# name: "마이타운 주차위치"
# source: advertisement
# instance_mode: shared # 기둥 MAC이 매번 달라도 엔티티 1벌 유지
# match:
# manufacturer_id: 861 # 0x035D — kaml 파싱을 위해 10진수(decimal) 사용 권장
# manufacturer_hex_prefix: "06" # 06 응답 포맷 (본인 16B UUID 접두사)
# manufacturer_min_length: 18
# advertise:
# manufacturer_id: 861
# payload: "05<본인_16BYTE_UUID_HEX>40{counter:02X}"
# counter_mode: reset # reset(기본) | persist
# counter_start: 0 # reset 모드 시작값 (기본 0)
# mode: balanced # low_power | balanced | low_latency
# tx_power: high # ultra_low | low | medium | high
# timeout: 15s # 이 시간 지나면 자동 송신 중단
# repeat_interval: 1s # (선택) 이 주기로 payload 갱신 = counter 증가
# stop_on_response: true # 06 응답 수신 시 즉시 송신 중단
# controls:
# - key: request_location
# type: button
# name: "주차위치 요청"
# action: advertise # command 대신 앱 내부 광고 송신 동작 실행
# icon: mdi:car-search
# sensors:
# - key: parking_floor
# platform: text_sensor
# icon: mdi:layers-outline
# source_field: manufacturer_data
# decode:
# offset: 17
# length: 1
# type: uint8
# map:
# "251": "B5"
# "252": "B4"
# "253": "B3"
# "254": "B2"
# "255": "B1"
# "0": "LB"
# "1": "1F"
# "2": "2F"
# "3": "3F"
# - key: parking_location
# platform: text_sensor
# icon: mdi:map-marker-outline
# source_field: manufacturer_data
# decode: { offset: 18, length: 0, type: string }
# Parking beacon — instance_mode: shared → MAC 무관, manufacturer 0x035D 광고가 하나의 엔티티 공유
# payload 14바이트: [0]=04(응답타입), [1..6]=KeyMAC, [7..10]=월·일·시·분, [11]=층(256-raw), [12..13]=구역코드
# 요청 6바이트: [0]=02 [1]=05 [2]=00 [3]=battery [4]=state [5]=counter
# 응답 14바이트: [0]=04(응답타입), [1..6]=KeyMAC, [7..10]=월·일·시·분, [11]=층(256-raw), [12..13]=구역코드
# 04xx: 주차위치 응답 비콘, 07xx: SmartKey 인증(22B 암호화), 02xx: 출입 이벤트(6B) — prefix "04" 로 응답만 매칭
- id: parking_beacon
name: "Parking Beacon"
@@ -60,6 +112,29 @@ devices:
match:
manufacturer_id: 861 # 0x035D
manufacturer_hex_prefix: "04" # 응답 비콘만 매칭 (07=SmartKey 인증, 02=출입 이벤트 제외)
manufacturer_min_length: 14 # 최소 14바이트
#advertise:
# manufacturer_id: 861 # 0x035D
# # 02 05 00 | battery 100% | {state} | {counter} — 카운터는 버튼마다 +1, 버스트 중 고정
# payload: "02050064{state:02X}{counter:02X}"
# counter_mode: persist # 요청마다 누적. 0xFF 다음은 0
# counter_start: 0
# mode: low_latency # ~100ms → press 200ms 동안 약 1~2패킷
# tx_power: high
# timeout: 4s # 페이즈 합(3.2s)보다 약간 큰 상한
# local_name: "APT SmartKey" # Complete Local Name. 송신 중 이 이름으로 바꾸고, 종료·재시작 때 초기값으로 되돌림
# payload_phases:
# - state: 65 # 0x41 버튼 누름 + ACK 대기
# duration: 200ms
# - state: 64 # 0x40 홀드 + ACK 대기
# duration: 3s
# stop_on_response: true
#controls:
# - key: request_location
# type: button
# name: "주차위치 요청"
# action: advertise
# icon: mdi:car-search
sensors:
- key: parking_time
device_class: timestamp
@@ -105,9 +180,29 @@ devices:
type: uint8
map:
"65": "entering" # 0x41 인증 시작
"1": "entering" # 0x01 인증 완료 (entering과 동일 → 전환 노이즈 제거)
"1": "entered" # 0x01 인증 완료 (entering과 동일 → 전환 노이즈 제거)
"64": "exiting" # 0x40
"0": "idle" # 0x00
# 통과 "시각"을 남기는 이벤트 엔티티 — 상태값이 마지막 발생 시각이라 같은 event_type이
# 반복돼도 매번 갱신되고, HA 재시작 때 복원되지 않아 묵은 값이 되살아나지 않는다.
# door_status(현재 상태)와 병행: 같은 광고에서 두 엔티티를 뽑는다.
- key: door_event
platform: event
event_types: [entering, entered, exiting, idle]
icon: mdi:door-open
source_field: manufacturer_data
length: 6
publish:
heartbeat: 60s # 같은 event_type이어도 60초 지났으면 재발화 = 통과마다 1회
decode:
offset: 4
length: 1
type: uint8
map:
"65": "entering"
"1": "entered"
"64": "exiting"
"0": "idle"
# ──────────────────────────────────────────────────────────────
# Path C: OBD (ELM327) over BLE
+680
View File
@@ -0,0 +1,680 @@
#!/usr/bin/env python3
"""
HassBle YAML Configuration and Template Validator
Validates config.yaml and templates.yaml against the HassBle Android schema and ConfigValidator rules.
"""
import os
import re
import sys
from typing import Any, Dict, List, Optional, Set, Tuple
import yaml
VALID_SOURCES = {"advertisement", "gatt_notify", "obd"}
VALID_INSTANCE_MODES = {"mac", "shared"}
VALID_SOURCE_FIELDS = {"service_data", "manufacturer_data", "raw"}
VALID_PLATFORMS = {"sensor", "binary_sensor", "text_sensor", "event"}
VALID_DATA_TYPES = {
"int8", "uint8", "int16", "uint16", "int32", "uint32",
"float32", "timestamp", "string"
}
VALID_ENDIANS = {"big", "little"}
VALID_CONTROL_TYPES = {"switch", "number", "select", "button"}
VALID_CONTROL_ACTIONS = {"advertise", "stop_advertise"}
VALID_ADVERTISE_MODES = {"low_power", "balanced", "low_latency"}
VALID_ADVERTISE_TX_POWERS = {"ultra_low", "low", "medium", "high"}
VALID_ADVERTISE_COUNTER_MODES = {"reset", "persist"}
VALID_STATE_CLASSES = {"measurement", "measurement_angle", "total", "total_increasing"}
NUMERIC_DEVICE_CLASSES = {
"battery", "carbon_dioxide", "carbon_monoxide", "current", "distance",
"duration", "energy", "frequency", "gas", "humidity", "illuminance",
"moisture", "monetary", "nitrogen_dioxide", "nitrogen_monoxide",
"nitrous_oxide", "ozone", "pm1", "pm10", "pm25", "power", "power_factor",
"precipitation", "precipitation_intensity", "pressure", "reactive_energy",
"reactive_power", "signal_strength", "sound_pressure", "speed",
"sulphur_dioxide", "temperature", "volatile_organic_compounds",
"volatile_organic_compounds_parts", "voltage", "volume", "volume_flow_rate",
"volume_storage", "water", "weight", "wind_speed",
}
KNOWN_DEVICE_KEYS = {
"id", "name", "source", "match", "instance_mode", "gatt", "obd",
"advertise", "sensors", "controls", "publish"
}
KNOWN_MATCH_KEYS = {
"mac", "service_data_uuid", "manufacturer_id", "manufacturer_hex_prefix",
"manufacturer_min_length", "name_prefix"
}
KNOWN_GATT_KEYS = {
"mac", "service_uuid", "notify_char_uuid", "write_char_uuid", "auto_connect"
}
KNOWN_OBD_KEYS = {
"mac", "service_uuid", "tx_char_uuid", "rx_char_uuid", "tx_delay",
"init_commands", "default_commands", "auto_connect"
}
KNOWN_ADVERTISE_KEYS = {
"manufacturer_id", "payload", "counter_mode", "counter_start", "mode",
"tx_power", "timeout", "repeat_interval", "payload_phases", "stop_on_response",
"connectable", "scannable", "include_device_name", "local_name"
}
KNOWN_ADVERTISE_PHASE_KEYS = {
"state", "duration", "payload"
}
KNOWN_SENSOR_KEYS = {
"key", "name", "platform", "event_types", "device_class", "unit", "state_class", "icon",
"entity_category", "accuracy_decimals", "source_field", "length",
"min_length", "decode", "preset", "mode", "pid", "formula",
"update_interval", "pre_commands", "publish"
}
KNOWN_DECODE_KEYS = {
"offset", "length", "type", "endian", "bitmask", "scale",
"offset_value", "map"
}
KNOWN_CONTROL_KEYS = {
"key", "type", "name", "icon", "entity_category", "action", "command",
"options", "min", "max", "step"
}
KNOWN_PUBLISH_KEYS = {
"on_change_only", "min_interval", "heartbeat", "deadband"
}
class ValidationResult:
def __init__(self, filename: str):
self.filename = filename
self.errors: List[str] = []
self.warnings: List[str] = []
def error(self, path: str, msg: str):
self.errors.append(f"[{self.filename}] ERROR at '{path}': {msg}")
def warning(self, path: str, msg: str):
self.warnings.append(f"[{self.filename}] WARNING at '{path}': {msg}")
@property
def has_errors(self) -> bool:
return len(self.errors) > 0
def check_unknown_keys(data: Dict[str, Any], known_keys: Set[str], path: str, res: ValidationResult):
if not isinstance(data, dict):
return
for k in data.keys():
if k not in known_keys:
res.error(f"{path}.{k}", f"Unknown property '{k}'. Allowed keys: {sorted(list(known_keys))}")
def validate_publish(publish: Any, path: str, res: ValidationResult):
if not isinstance(publish, dict):
res.error(path, "publish must be an object (map)")
return
check_unknown_keys(publish, KNOWN_PUBLISH_KEYS, path, res)
if "on_change_only" in publish and not isinstance(publish["on_change_only"], bool):
res.error(f"{path}.on_change_only", "Must be a boolean (true/false)")
for dur_field in ["min_interval", "heartbeat"]:
if dur_field in publish:
val = publish[dur_field]
if not isinstance(val, str) or not re.match(r"^\d+(ms|s|m|h)$", str(val).strip()):
res.error(f"{path}.{dur_field}", f"Invalid duration '{val}'. Example: 500ms, 10s, 5m")
if "deadband" in publish and not isinstance(publish["deadband"], (int, float)):
res.error(f"{path}.deadband", "deadband must be a number")
def validate_decode(decode: Any, path: str, res: ValidationResult):
if not isinstance(decode, dict):
res.error(path, "decode must be an object")
return
check_unknown_keys(decode, KNOWN_DECODE_KEYS, path, res)
if "offset" in decode and not isinstance(decode["offset"], int):
res.error(f"{path}.offset", "offset must be an integer")
if "length" in decode and not isinstance(decode["length"], int):
res.error(f"{path}.length", "length must be an integer")
dtype = str(decode.get("type", "uint8")).lower()
if dtype not in VALID_DATA_TYPES:
res.error(f"{path}.type", f"Invalid data type '{decode.get('type')}'. Must be one of {sorted(list(VALID_DATA_TYPES))}")
if "endian" in decode:
endian = str(decode["endian"]).lower()
if endian not in VALID_ENDIANS:
res.error(f"{path}.endian", f"Invalid endian '{decode['endian']}'. Must be 'big' or 'little'")
if "scale" in decode and not isinstance(decode["scale"], (int, float)):
res.error(f"{path}.scale", "scale must be a number")
if "offset_value" in decode and not isinstance(decode["offset_value"], (int, float)):
res.error(f"{path}.offset_value", "offset_value must be a number")
if "map" in decode:
if not isinstance(decode["map"], dict):
res.error(f"{path}.map", "map must be a dictionary (key: value)")
def validate_sensor(sensor: Any, device_source: str, path: str, res: ValidationResult,
inherited_publish: Optional[Dict[str, Any]] = None):
if not isinstance(sensor, dict):
res.error(path, "Sensor must be an object")
return
check_unknown_keys(sensor, KNOWN_SENSOR_KEYS, path, res)
key = sensor.get("key")
if not key or not isinstance(key, str):
res.error(f"{path}.key", "Missing or invalid sensor 'key'")
return
platform = sensor.get("platform", "sensor")
if platform not in VALID_PLATFORMS:
res.error(f"{path}.platform", f"Invalid platform '{platform}'. Must be one of {sorted(list(VALID_PLATFORMS))}")
is_text = platform == "text_sensor"
is_event = platform == "event"
unit = sensor.get("unit")
state_class = sensor.get("state_class")
if isinstance(state_class, str) and state_class.lower() == "none":
state_class = None
device_class = sensor.get("device_class")
accuracy_decimals = sensor.get("accuracy_decimals")
if is_event:
event_types = sensor.get("event_types")
if not isinstance(event_types, list) or not event_types:
res.error(f"{path}.event_types",
"platform=event requires a non-empty 'event_types' list — HA rejects the declaration without it")
event_types = []
decode_map = (sensor.get("decode") or {}).get("map")
if isinstance(decode_map, dict):
undeclared = sorted({str(v) for v in decode_map.values()} - {str(t) for t in event_types})
if undeclared:
res.warning(f"{path}.event_types",
f"decode.map value(s) {undeclared} missing from event_types — HA drops those events")
elif sensor.get("decode") is not None:
res.warning(f"{path}.decode",
"platform=event without decode.map — the raw decoded value becomes the event_type and will be dropped")
if unit is not None or state_class is not None or accuracy_decimals is not None:
res.warning(f"{path}.unit", "unit/state_class/accuracy_decimals are ignored for event")
if device_class in NUMERIC_DEVICE_CLASSES:
res.warning(f"{path}.device_class",
f"device_class='{device_class}' is numeric but platform is event — HA event supports doorbell/button/motion")
publish = sensor.get("publish", inherited_publish) or {}
heartbeat = publish.get("heartbeat") if isinstance(publish, dict) else None
on_change_only = publish.get("on_change_only", True) if isinstance(publish, dict) else True
if on_change_only and not (isinstance(heartbeat, str) and _DURATION_RE.match(heartbeat.strip())):
res.warning(f"{path}.publish",
"on_change_only suppresses repeats of the same event_type — "
"set publish.heartbeat (or on_change_only: false) to fire on every occurrence")
elif is_text:
if unit is not None:
res.warning(f"{path}.unit", f"unit='{unit}' is ignored for text_sensor")
if state_class is not None:
res.warning(f"{path}.state_class", f"state_class='{state_class}' is ignored for text_sensor")
if accuracy_decimals is not None:
res.warning(f"{path}.accuracy_decimals", "accuracy_decimals is ignored for text_sensor")
if device_class in NUMERIC_DEVICE_CLASSES:
res.warning(f"{path}.device_class", f"device_class='{device_class}' expects numeric value but platform is text_sensor")
else:
if state_class is not None and state_class not in VALID_STATE_CLASSES:
res.error(f"{path}.state_class", f"Invalid state_class '{state_class}'. Must be one of {sorted(list(VALID_STATE_CLASSES))}")
if unit is not None and state_class is None:
res.warning(f"{path}.state_class", f"unit='{unit}' set but state_class is missing")
if state_class is not None and unit is None:
res.warning(f"{path}.unit", f"state_class='{state_class}' set but unit is missing")
if device_class == "timestamp" and accuracy_decimals is not None:
res.warning(f"{path}.accuracy_decimals", "accuracy_decimals is meaningless for timestamp")
if "source_field" in sensor:
sf = str(sensor["source_field"]).lower()
if sf not in VALID_SOURCE_FIELDS:
res.error(f"{path}.source_field", f"Invalid source_field '{sensor['source_field']}'. Must be one of {sorted(list(VALID_SOURCE_FIELDS))}")
decode = sensor.get("decode")
if decode:
validate_decode(decode, f"{path}.decode", res)
d_offset = decode.get("offset", 0)
d_len = decode.get("length", 1)
required = d_offset + d_len
min_len = sensor.get("min_length")
exact_len = sensor.get("length")
if min_len is not None and required > min_len:
res.error(f"{path}.decode", f"decode(offset={d_offset} + length={d_len}={required}) exceeds min_length={min_len}")
if exact_len is not None and required > exact_len:
res.error(f"{path}.decode", f"decode(offset={d_offset} + length={d_len}={required}) exceeds length={exact_len}")
if device_source == "obd":
if sensor.get("pid") is None and sensor.get("preset") is None:
res.error(f"{path}", "OBD sensor requires 'pid' or 'preset'")
elif device_source in {"advertisement", "gatt_notify"}:
if decode is None and platform != "binary_sensor":
res.warning(f"{path}.decode", "No decode config — sensor will never produce a value")
if "publish" in sensor:
validate_publish(sensor["publish"], f"{path}.publish", res)
_PAYLOAD_TOKEN_RE = re.compile(r"\{(counter|state)(?::[^}]+)?\}")
_DURATION_RE = re.compile(r"^\d+(ms|s|m|h)$")
def _payload_has_state_token(payload: str) -> bool:
return any(m.group(1) == "state" for m in _PAYLOAD_TOKEN_RE.finditer(payload))
def validate_advertise_payload(payload: str) -> Optional[str]:
def subst(m: re.Match) -> str:
token = m.group(0)
if ":02X" in token or ":02x" in token:
return "00"
return "0"
clean = _PAYLOAD_TOKEN_RE.sub(subst, payload)
if not re.match(r"^[0-9A-Fa-f]*$", clean):
return f"payload contains invalid hex characters: '{payload}'"
if len(clean) % 2 != 0:
return f"payload length ({len(clean)}) must be even"
byte_len = len(clean) // 2
if byte_len > 24:
return f"payload size ({byte_len} bytes) exceeds 24 bytes legacy advertisement limit"
return None
def _payload_byte_len(payload: str) -> Optional[int]:
def subst(m: re.Match) -> str:
token = m.group(0)
if ":02X" in token or ":02x" in token:
return "00"
return "0"
clean = _PAYLOAD_TOKEN_RE.sub(subst, payload)
if not re.match(r"^[0-9A-Fa-f]*$", clean) or len(clean) % 2 != 0:
return None
return len(clean) // 2
def _legacy_adv_size(payload_bytes: int, local_name: str) -> int:
return 3 + 4 + payload_bytes + 2 + len(local_name.encode("utf-8"))
def validate_advertise(adv: Any, device: dict, path: str, res: ValidationResult):
if not isinstance(adv, dict):
res.error(path, "advertise must be an object")
return
check_unknown_keys(adv, KNOWN_ADVERTISE_KEYS, path, res)
if device.get("source") != "advertisement":
res.error(path, "'advertise' is only supported for source: advertisement")
if "manufacturer_id" not in adv:
res.error(f"{path}.manufacturer_id", "Missing required 'manufacturer_id'")
elif not isinstance(adv["manufacturer_id"], int):
res.error(f"{path}.manufacturer_id", f"manufacturer_id must be a decimal integer (got '{adv['manufacturer_id']}')")
if "payload" not in adv:
res.error(f"{path}.payload", "Missing required 'payload'")
elif not isinstance(adv["payload"], str):
res.error(f"{path}.payload", "payload must be a string")
else:
err = validate_advertise_payload(adv["payload"])
if err:
res.error(f"{path}.payload", err)
if "counter_mode" in adv:
cm = str(adv["counter_mode"]).lower()
if cm not in VALID_ADVERTISE_COUNTER_MODES:
res.error(f"{path}.counter_mode", f"Invalid counter_mode '{adv['counter_mode']}'. Must be one of {sorted(list(VALID_ADVERTISE_COUNTER_MODES))}")
if "counter_start" in adv:
cs = adv["counter_start"]
if not isinstance(cs, int) or cs < 0 or cs > 255:
res.error(f"{path}.counter_start", f"counter_start must be between 0 and 255 (got '{cs}')")
if "mode" in adv:
m = str(adv["mode"]).lower()
if m not in VALID_ADVERTISE_MODES:
res.error(f"{path}.mode", f"Invalid mode '{adv['mode']}'. Must be one of {sorted(list(VALID_ADVERTISE_MODES))}")
if "tx_power" in adv:
tp = str(adv["tx_power"]).lower()
if tp not in VALID_ADVERTISE_TX_POWERS:
res.error(f"{path}.tx_power", f"Invalid tx_power '{adv['tx_power']}'. Must be one of {sorted(list(VALID_ADVERTISE_TX_POWERS))}")
for dur_field in ["timeout", "repeat_interval"]:
if dur_field in adv:
val = adv[dur_field]
if val is not None and (not isinstance(val, str) or not _DURATION_RE.match(str(val).strip())):
res.error(f"{path}.{dur_field}", f"Invalid duration '{val}'. Example: 500ms, 15s, 1m")
phases = adv.get("payload_phases", [])
if phases:
if not isinstance(phases, list):
res.error(f"{path}.payload_phases", "payload_phases must be a list")
else:
if adv.get("repeat_interval"):
res.warning(f"{path}.repeat_interval", "repeat_interval is ignored when payload_phases is set — counter stays fixed across phases")
for i, phase in enumerate(phases):
ppath = f"{path}.payload_phases[{i}]"
if not isinstance(phase, dict):
res.error(ppath, "payload_phases item must be an object")
continue
check_unknown_keys(phase, KNOWN_ADVERTISE_PHASE_KEYS, ppath, res)
duration = phase.get("duration")
if not isinstance(duration, str) or not _DURATION_RE.match(duration.strip()):
res.error(f"{ppath}.duration", f"Invalid duration '{duration}'. Example: 200ms, 3s")
state = phase.get("state")
if state is not None and (not isinstance(state, int) or state < 0 or state > 255):
res.error(f"{ppath}.state", f"state must be between 0 and 255 (got '{state}')")
template = phase["payload"] if isinstance(phase.get("payload"), str) and phase["payload"].strip() else adv.get("payload", "")
if isinstance(template, str):
if _payload_has_state_token(template) and state is None:
res.error(f"{ppath}.state", "payload_phases item has a {state} token but no state value")
err = validate_advertise_payload(template)
if err:
res.error(ppath, err)
payload = adv.get("payload")
if isinstance(payload, str) and _payload_has_state_token(payload) and not phases:
res.error(f"{path}.payload", "payload contains {state} but advertise.payload_phases is empty")
for bool_field in ["stop_on_response", "connectable", "scannable", "include_device_name"]:
if bool_field in adv and not isinstance(adv[bool_field], bool):
res.error(f"{path}.{bool_field}", f"{bool_field} must be a boolean (true/false)")
if adv.get("include_device_name") is True and not (isinstance(adv.get("local_name"), str) and adv["local_name"].strip()):
res.warning(f"{path}.include_device_name", "include_device_name: true includes device name in advertising data, which may exceed the 31-byte legacy BLE limit")
local_name = adv.get("local_name")
if local_name is not None:
if not isinstance(local_name, str):
res.error(f"{path}.local_name", "local_name must be a string")
else:
name = local_name.strip()
if not name:
res.warning(f"{path}.local_name", "local_name is empty after trim — ignored")
else:
name_bytes = len(name.encode("utf-8"))
if name_bytes > 248:
res.error(f"{path}.local_name", f"local_name UTF-8 size ({name_bytes} bytes) exceeds Bluetooth name limit (248)")
templates = [adv.get("payload", "")]
if isinstance(phases, list) and phases:
templates = []
for phase in phases:
if not isinstance(phase, dict):
continue
override = phase.get("payload")
if isinstance(override, str) and override.strip():
templates.append(override)
else:
templates.append(adv.get("payload", ""))
for i, template in enumerate(templates):
if not isinstance(template, str):
continue
blen = _payload_byte_len(template)
if blen is None:
continue
total = _legacy_adv_size(blen, name)
if total > 31:
loc = f"{path}.local_name" if not phases else f"{path}.payload_phases[{i}]"
res.error(loc, f"local_name '{name}' plus payload would be {total} bytes, exceeding the 31-byte legacy BLE limit")
res.warning(f"{path}.local_name", "local_name resets the phone Bluetooth name after advertising (and again on next app start if the process was killed)")
if device.get("instance_mode") == "mac" and not device.get("match", {}).get("mac"):
res.warning(path, "advertise with instance_mode: mac creates one button per discovered MAC — use instance_mode: shared")
controls = device.get("controls", [])
if isinstance(controls, list) and not any(isinstance(c, dict) and c.get("action") == "advertise" for c in controls):
res.warning(path, "'advertise' block has no control with action: advertise — it can only be triggered from the app")
def validate_control(control: Any, device_source: str, gatt: Optional[dict], obd: Optional[dict], path: str, res: ValidationResult):
if not isinstance(control, dict):
res.error(path, "Control must be an object")
return
check_unknown_keys(control, KNOWN_CONTROL_KEYS, path, res)
key = control.get("key")
if not key or not isinstance(key, str):
res.error(f"{path}.key", "Missing or invalid control 'key'")
return
ctype_str = str(control.get("type", ""))
if ctype_str not in VALID_CONTROL_TYPES:
res.error(f"{path}.type", f"Invalid control type '{ctype_str}'. Must be one of {sorted(list(VALID_CONTROL_TYPES))}")
return
action = control.get("action")
if action is not None:
if action not in VALID_CONTROL_ACTIONS:
res.error(f"{path}.action", f"Invalid action '{action}'. Must be one of {sorted(list(VALID_CONTROL_ACTIONS))}")
# When action is specified, command is optional
if "command" not in control:
return
if device_source == "gatt_notify":
if not gatt or not gatt.get("write_char_uuid"):
res.error(f"{path}", "Control requires write_char_uuid in gatt config")
elif device_source == "obd":
if not obd or not obd.get("tx_char_uuid"):
res.error(f"{path}", "Control requires tx_char_uuid in obd config")
if "command" not in control:
res.error(f"{path}", "Control requires 'command' or 'action'")
return
cmd_raw = control.get("command", {})
if not isinstance(cmd_raw, dict):
res.error(f"{path}.command", "command must be a map of {state: hex_string}")
return
# Normalize YAML boolean keys (e.g. on -> True, off -> False in YAML 1.1)
cmd = {}
for k, v in cmd_raw.items():
if k is True:
cmd["on"] = v
elif k is False:
cmd["off"] = v
else:
cmd[str(k)] = v
if ctype_str == "switch":
for k in ["on", "off"]:
if k not in cmd:
res.error(f"{path}.command", f"Switch control missing command key '{k}'")
elif ctype_str == "button":
if "press" not in cmd:
res.error(f"{path}.command", "Button control missing command key 'press'")
elif ctype_str == "number":
if "template" not in cmd:
res.error(f"{path}.command", "Number control missing command key 'template'")
elif ctype_str == "select":
options = control.get("options", [])
if not isinstance(options, list) or not options:
res.error(f"{path}.options", "Select control requires a non-empty 'options' list")
else:
for opt in options:
if opt not in cmd:
res.error(f"{path}.command", f"Select control missing command key for option '{opt}'")
def validate_device(device: Any, path: str, res: ValidationResult,
defaults_publish: Optional[Dict[str, Any]] = None):
if not isinstance(device, dict):
res.error(path, "Device must be an object")
return
check_unknown_keys(device, KNOWN_DEVICE_KEYS, path, res)
dev_id = device.get("id")
if not dev_id or not isinstance(dev_id, str):
res.error(f"{path}.id", "Device missing required 'id'")
dev_name = device.get("name")
if not dev_name or not isinstance(dev_name, str):
res.error(f"{path}.name", "Device missing required 'name'")
source = str(device.get("source", ""))
if source not in VALID_SOURCES:
res.error(f"{path}.source", f"Invalid source '{source}'. Must be one of {sorted(list(VALID_SOURCES))}")
return
instance_mode = device.get("instance_mode", "mac")
if instance_mode not in VALID_INSTANCE_MODES:
res.error(f"{path}.instance_mode", f"Invalid instance_mode '{instance_mode}'. Must be one of {sorted(list(VALID_INSTANCE_MODES))}")
match = device.get("match")
if match:
if not isinstance(match, dict):
res.error(f"{path}.match", "match must be an object")
else:
check_unknown_keys(match, KNOWN_MATCH_KEYS, f"{path}.match", res)
if "manufacturer_id" in match:
m_id = match["manufacturer_id"]
if not isinstance(m_id, int):
res.error(f"{path}.match.manufacturer_id", f"manufacturer_id must be a decimal integer (got '{m_id}')")
gatt = device.get("gatt")
if gatt:
if not isinstance(gatt, dict):
res.error(f"{path}.gatt", "gatt must be an object")
else:
check_unknown_keys(gatt, KNOWN_GATT_KEYS, f"{path}.gatt", res)
if source == "gatt_notify":
if not gatt.get("service_uuid"):
res.error(f"{path}.gatt.service_uuid", "Missing required 'service_uuid'")
if not gatt.get("notify_char_uuid"):
res.error(f"{path}.gatt.notify_char_uuid", "Missing required 'notify_char_uuid'")
obd = device.get("obd")
if obd:
if not isinstance(obd, dict):
res.error(f"{path}.obd", "obd must be an object")
else:
check_unknown_keys(obd, KNOWN_OBD_KEYS, f"{path}.obd", res)
if "advertise" in device:
validate_advertise(device["advertise"], device, f"{path}.advertise", res)
sensors = device.get("sensors", [])
if not isinstance(sensors, list):
res.error(f"{path}.sensors", "sensors must be a list")
else:
for idx, s in enumerate(sensors):
validate_sensor(s, source, f"{path}.sensors[{idx}]", res,
device.get("publish", defaults_publish))
controls = device.get("controls", [])
if not isinstance(controls, list):
res.error(f"{path}.controls", "controls must be a list")
else:
for idx, c in enumerate(controls):
validate_control(c, source, gatt, obd, f"{path}.controls[{idx}]", res)
if "publish" in device:
validate_publish(device["publish"], f"{path}.publish", res)
def validate_config_file(filepath: str) -> ValidationResult:
res = ValidationResult(os.path.basename(filepath))
if not os.path.exists(filepath):
res.error("", f"File '{filepath}' does not exist")
return res
try:
with open(filepath, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception as e:
res.error("", f"YAML syntax error: {e}")
return res
if not isinstance(data, dict):
res.error("", "Root must be a YAML mapping")
return res
version = data.get("version")
if version != 1:
res.warning("version", f"Schema version is {version}, expected 1")
defaults_publish: Optional[Dict[str, Any]] = None
if "defaults" in data:
defaults = data["defaults"]
if not isinstance(defaults, dict):
res.error("defaults", "defaults must be an object")
elif "publish" in defaults:
validate_publish(defaults["publish"], "defaults.publish", res)
if isinstance(defaults["publish"], dict):
defaults_publish = defaults["publish"]
devices = data.get("devices", [])
if not isinstance(devices, list):
res.error("devices", "devices must be a list")
else:
for idx, dev in enumerate(devices):
validate_device(dev, f"devices[{idx}]", res, defaults_publish)
return res
def validate_templates_file(filepath: str) -> ValidationResult:
res = ValidationResult(os.path.basename(filepath))
if not os.path.exists(filepath):
res.error("", f"File '{filepath}' does not exist")
return res
try:
with open(filepath, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception as e:
res.error("", f"YAML syntax error: {e}")
return res
if not isinstance(data, dict):
res.error("", "Root must be a YAML mapping")
return res
templates = data.get("templates")
if not isinstance(templates, list):
res.error("templates", "templates must be a list")
return res
for idx, t in enumerate(templates):
path = f"templates[{idx}]"
if not isinstance(t, dict):
res.error(path, "Template item must be an object")
continue
for key in ["id", "name"]:
if not t.get(key) or not isinstance(t[key], str):
res.error(f"{path}.{key}", f"Missing or invalid template '{key}'")
device = t.get("device")
if not device:
res.error(f"{path}.device", "Missing 'device' configuration in template")
else:
validate_device(device, f"{path}.device", res)
return res
def main():
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_file = os.path.join(repo_root, "config.yaml")
templates_file = os.path.join(repo_root, "templates.yaml")
results = [
validate_config_file(config_file),
validate_templates_file(templates_file),
]
total_errors = 0
total_warnings = 0
for r in results:
for w in r.warnings:
print(f"⚠️ {w}")
total_warnings += 1
for e in r.errors:
print(f"❌ {e}")
total_errors += 1
if total_errors == 0:
print(f"✅ All YAML configurations valid ({total_warnings} warnings, 0 errors).")
sys.exit(0)
else:
print(f"\n💥 Validation failed with {total_errors} errors and {total_warnings} warnings.")
sys.exit(1)
if __name__ == "__main__":
main()
+83 -2
View File
@@ -38,14 +38,38 @@ templates:
- id: parking_beacon
name: "Parking Beacon"
description: "Shared parking beacon (manufacturer 861 / 0x035D)"
description: "공용 주차 위치 비콘 (제조사 861 / 0x035D, 02 요청 광고 송신 + 04 응답 수신)"
device:
id: parking_beacon
name: "Parking Beacon"
source: advertisement
instance_mode: shared
match:
manufacturer_id: 861
manufacturer_id: 861 # 0x035D
manufacturer_hex_prefix: "04" # 04 응답 포맷 (특정 스마트키만 필터링 시 04 + 6B MAC HEX 입력)
manufacturer_min_length: 14 # 포맷(1B) + 스마트키 MAC(6B) + 시간(4B) + 층(1B) + 구역(2B) = 14바이트
advertise:
manufacturer_id: 861 # 0x035D
# 02 05 00 | battery 100% | {state} | {counter} — 카운터는 버튼마다 +1, 버스트 중 고정
payload: "02050064{state:02X}{counter:02X}"
counter_mode: persist # 요청마다 누적. 0xFF 다음은 0
counter_start: 0
mode: low_latency # ~100ms → press 200ms 동안 약 1~2패킷
tx_power: high
timeout: 4s # 페이즈 합(3.2s)보다 약간 큰 상한
local_name: "APT SmartKey" # Complete Local Name. 송신 중 이 이름으로 바꾸고, 종료·재시작 때 초기값으로 되돌림
payload_phases:
- state: 65 # 0x41 버튼 누름 + ACK 대기
duration: 200ms
- state: 64 # 0x40 홀드 + ACK 대기
duration: 3s
stop_on_response: true
controls:
- key: request_location
type: button
name: "주차위치 요청"
action: advertise
icon: mdi:car-search
sensors:
- key: parking_time
device_class: timestamp
@@ -66,6 +90,63 @@ templates:
length: 14
decode: { offset: 12, length: 2, type: string }
- id: mytown_parking_beacon
name: "마이타운 주차 비콘 (MyTown Parking)"
description: "마이타운 주차 위치 비콘 (제조사 861 / 0x035D, 05 요청 광고 송신 + 06 응답 수신)"
device:
id: mytown_parking
name: "마이타운 주차위치"
source: advertisement
instance_mode: shared
match:
manufacturer_id: 861 # 0x035D
manufacturer_hex_prefix: "06" # 06 응답 포맷 (특정 세대만 필터링 시 06 + 16B 수신 UUID HEX 입력)
manufacturer_min_length: 18 # 포맷(1B) + 세대 UUID(16B) + 층(1B) = 최소 18바이트
advertise:
manufacturer_id: 861 # 0x035D
payload: "05CB34447B91F8C69BBE41157C70BB631C40{counter:02X}" # 05 + 16B UUID + 40 + counter
counter_mode: reset # reset(기본) | persist
counter_start: 0
mode: balanced
tx_power: high
timeout: 15s
repeat_interval: 1s
stop_on_response: true
controls:
- key: request_location
type: button
name: "주차위치 요청"
action: advertise
icon: mdi:car-search
sensors:
# 주차 층수: 1B uint8 (254=0xFE: B2, 255=0xFF: B1, 0=0x00: LB, 1=0x01: 1F, 2=0x02: 2F 등)
- key: parking_floor
platform: text_sensor
icon: mdi:layers-outline
source_field: manufacturer_data
decode:
offset: 17
length: 1
type: uint8
map:
"251": "B5"
"252": "B4"
"253": "B3"
"254": "B2"
"255": "B1"
"0": "LB"
"1": "1F"
"2": "2F"
"3": "3F"
"4": "4F"
"5": "5F"
# 주차 구역: ASCII 텍스트 (예: 42 33 31 -> "B31", 41 2D 30 31 -> "A-01", length: 0으로 가변 길이 자동 트림)
- key: parking_location
platform: text_sensor
icon: mdi:map-marker-outline
source_field: manufacturer_data
decode: { offset: 18, length: 0, type: string }
- id: obd_standard
name: "OBD-II (standard PIDs)"
description: "RPM, speed, coolant, fuel — bind ELM327 adapter in app"