diff --git a/README.ko.md b/README.ko.md index c60d697..bf270bf 100644 --- a/README.ko.md +++ b/README.ko.md @@ -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 연결 @@ -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` 타입 최댓값. | diff --git a/README.md b/README.md index 36fbb59..da3ca3a 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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. | diff --git a/config.yaml b/config.yaml index d8974af..0401346 100644 --- a/config.yaml +++ b/config.yaml @@ -50,6 +50,57 @@ 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]=구역코드 # 04xx: 주차위치 응답 비콘, 07xx: SmartKey 인증(22B 암호화), 02xx: 출입 이벤트(6B) — prefix "04" 로 응답만 매칭 diff --git a/scripts/validate.py b/scripts/validate.py index a8d9a51..c683247 100644 --- a/scripts/validate.py +++ b/scripts/validate.py @@ -20,6 +20,10 @@ VALID_DATA_TYPES = { } 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", @@ -35,7 +39,7 @@ NUMERIC_DEVICE_CLASSES = { KNOWN_DEVICE_KEYS = { "id", "name", "source", "match", "instance_mode", "gatt", "obd", - "sensors", "controls", "publish" + "advertise", "sensors", "controls", "publish" } KNOWN_MATCH_KEYS = { "mac", "service_data_uuid", "manufacturer_id", "manufacturer_hex_prefix", @@ -48,6 +52,11 @@ 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", "stop_on_response", + "connectable", "scannable", "include_device_name" +} KNOWN_SENSOR_KEYS = { "key", "name", "platform", "device_class", "unit", "state_class", "icon", "entity_category", "accuracy_decimals", "source_field", "length", @@ -59,7 +68,7 @@ KNOWN_DECODE_KEYS = { "offset_value", "map" } KNOWN_CONTROL_KEYS = { - "key", "type", "name", "icon", "entity_category", "command", + "key", "type", "name", "icon", "entity_category", "action", "command", "options", "min", "max", "step" } KNOWN_PUBLISH_KEYS = { @@ -207,6 +216,82 @@ def validate_sensor(sensor: Any, device_source: str, path: str, res: ValidationR validate_publish(sensor["publish"], f"{path}.publish", res) +def validate_advertise_payload(payload: str) -> Optional[str]: + clean = payload.replace("{counter}", "0").replace("{counter:02X}", "00").replace("{counter:02x}", "00") + 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 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 re.match(r"^\d+(ms|s|m|h)$", str(val).strip())): + res.error(f"{path}.{dur_field}", f"Invalid duration '{val}'. Example: 500ms, 15s, 1m") + + 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: + 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") + + 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") @@ -223,6 +308,14 @@ def validate_control(control: Any, device_source: str, gatt: Optional[dict], obd 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") @@ -230,6 +323,10 @@ def validate_control(control: Any, device_source: str, gatt: Optional[dict], 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}") @@ -317,6 +414,9 @@ def validate_device(device: Any, path: str, res: ValidationResult): 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") diff --git a/templates.yaml b/templates.yaml index bcdff24..9c4b33c 100644 --- a/templates.yaml +++ b/templates.yaml @@ -68,7 +68,7 @@ templates: - id: mytown_parking_beacon name: "마이타운 주차 비콘 (MyTown Parking)" - description: "마이타운 주차 위치 비콘 (제조사 861 / 0x035D, 포맷 0x06)" + description: "마이타운 주차 위치 비콘 (제조사 861 / 0x035D, 05 요청 광고 송신 + 06 응답 수신)" device: id: mytown_parking name: "마이타운 주차위치" @@ -78,6 +78,22 @@ templates: 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 @@ -100,12 +116,12 @@ templates: "3": "3F" "4": "4F" "5": "5F" - # 주차 구역: ASCII 텍스트 (예: 42 33 31 -> "B31", 41 2D 30 31 -> "A-01", 단지 포맷에 맞춰 length 조정) + # 주차 구역: 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: 3, type: string } + decode: { offset: 18, length: 0, type: string } - id: obd_standard name: "OBD-II (standard PIDs)"