diff --git a/common/its_g5/decode.h b/common/its_g5/decode.h new file mode 100644 index 0000000..93dc646 --- /dev/null +++ b/common/its_g5/decode.h @@ -0,0 +1,154 @@ +#pragma once +// Header-level decoding of captured ITS-G5 frames: 802.11 + LLC/SNAP, GeoNetworking (EN 302 636-4-1) +// and BTP (EN 302 636-5-1). Gives the message type (from the BTP port) and the sender's position +// vector, which GeoNetworking carries in every packet. The message bodies (CAM, DENM, SPATEM, ...) +// are ASN.1 UPER and are not decoded here. + +#include +#include +#include + +namespace its_g5_decode { + +struct Info { + uint16_t port{0}; // BTP destination port, 0 = none + uint8_t station_type{0}; // ETSI station type from the GN address + bool secured{false}; // carried in an ETSI TS 103 097 signed packet (signature not verified) + double lat{0}, lon{0}; // degrees + float speed_kmh{0}; + float heading{0}; // degrees +}; + +inline const char *port_name(uint16_t port) { + switch (port) { + case 2001: return "CAM"; + case 2002: return "DENM"; + case 2003: return "MAPEM"; + case 2004: return "SPATEM"; + case 2005: return "SAEM"; + case 2006: return "IVIM"; + case 2007: return "SREM"; + case 2008: return "SSEM"; + case 2009: return "CPM"; + case 2010: return "EVCSN"; + case 2011: return "TRM"; + case 2013: return "RTCMEM"; + case 2018: return "VAM"; + default: return "other"; + } +} + +inline const char *station_name(uint8_t type) { + static const char *const NAMES[] = {"unknown", "pedestrian", "cyclist", "moped", + "motorcycle", "passengerCar", "bus", "lightTruck", + "heavyTruck", "trailer", "specialVehicle", "tram"}; + if (type < sizeof(NAMES) / sizeof(NAMES[0])) + return NAMES[type]; + return type == 15 ? "roadSideUnit" : "other"; +} + +inline uint16_t be16(const uint8_t *p) { return (p[0] << 8) | p[1]; } +inline int32_t be32(const uint8_t *p) { + return static_cast((uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3]); +} + +// Returns false for anything that is not a GeoNetworking packet it understands. +inline bool parse(const std::vector &frame, Info &out) { + const uint8_t *f = frame.data(); + const size_t n = frame.size(); + if (n < 24 || ((f[0] >> 2) & 3) != 2) // data frames only + return false; + size_t i = 24; + const bool qos = f[0] & 0x80; + if (qos) + i += 2; + if ((f[1] & 3) == 3) // ToDS + FromDS: fourth address + i += 6; + if (qos && (f[1] & 0x80)) // +HTC + i += 4; + + static const uint8_t SNAP_GN[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x47}; + if (i + 8 + 4 > n) + return false; + for (size_t k = 0; k < 8; k++) { + if (f[i + k] != SNAP_GN[k]) + return false; + } + i += 8; + + // GN basic header: version | next header, reserved, lifetime, remaining hop limit + const uint8_t basic_nh = f[i] & 0x0F; + i += 4; + if (basic_nh == 2) { + // ponytail: walks only the usual 1609.2 shape (signedData with an unsecuredData payload, no + // external hash); anything else is skipped. A real OER decoder is needed for the rest. + if (i + 7 > n || f[i] != 0x03 || f[i + 1] != 0x81 || !(f[i + 3] & 0x40) || f[i + 4] != 0x03 || + f[i + 5] != 0x80) + return false; + i += 6; + if (f[i] & 0x80) { + i += 1 + (f[i] & 0x7F); + } else { + i += 1; + } + out.secured = true; + } else if (basic_nh != 1) { + return false; + } + + // GN common header (8 bytes): next header | reserved, header type | subtype, ... + if (i + 8 > n) + return false; + const uint8_t common_nh = f[i] >> 4; + const uint8_t ht = f[i + 1] >> 4, hst = f[i + 1] & 0x0F; + i += 8; + + size_t pv, ext; // offset of the source position vector, length of the extended header + switch (ht) { + case 1: pv = i; ext = 24; break; // beacon + case 2: pv = i + 4; ext = 48; break; // GUC + case 3: case 4: pv = i + 4; ext = 44; break; // GAC, GBC + case 5: pv = hst == 0 ? i : i + 4; ext = 28; break; // SHB, TSB + default: return false; // location service, unknown + } + if (pv + 24 > n) + return false; + + // Long position vector: GN address (8), timestamp (4), lat, lon (1/10 µdeg), PAI | speed, heading + out.station_type = (f[pv] >> 2) & 0x1F; + out.lat = be32(f + pv + 12) / 1e7; + out.lon = be32(f + pv + 16) / 1e7; + int16_t speed = be16(f + pv + 20) & 0x7FFF; + if (speed & 0x4000) + speed -= 0x8000; // 15-bit signed, 0.01 m/s + out.speed_kmh = speed * 0.036f; + out.heading = be16(f + pv + 22) / 10.0f; + + if ((common_nh == 1 || common_nh == 2) && i + ext + 2 <= n) // BTP-A / BTP-B + out.port = be16(f + i + ext); + return true; +} + +struct Stats { + uint32_t cam{0}, denm{0}, spatem{0}, mapem{0}, other{0}; + Info last; +}; +inline Stats stats; + +// Parse, count and log one frame; returns false if it was not decoded. +inline bool handle(const std::vector &frame) { + Info info; + if (!parse(frame, info)) + return false; + switch (info.port) { + case 2001: stats.cam++; break; + case 2002: stats.denm++; break; + case 2004: stats.spatem++; break; + case 2003: stats.mapem++; break; + default: stats.other++; break; + } + stats.last = info; + return true; +} + +} // namespace its_g5_decode diff --git a/common/its_g5/decode_test.cpp b/common/its_g5/decode_test.cpp new file mode 100644 index 0000000..4631a88 --- /dev/null +++ b/common/its_g5/decode_test.cpp @@ -0,0 +1,31 @@ +// Self-check for decode.h: one signed SHB CAM frame from a passenger car. +// Build: g++ -std=c++20 decode_test.cpp -o /tmp/t && /tmp/t +#include "decode.h" +#include +#include +#include +using namespace its_g5_decode; +int main() { + std::vector f = {0x88, 0x00, 0, 0, 0xff,0xff,0xff,0xff,0xff,0xff, 1,2,3,4,5,6, 0xff,0xff,0xff,0xff,0xff,0xff, 0,0, // QoS data hdr + 0x00, 0x00, // QoS ctrl + 0xAA,0xAA,0x03,0,0,0,0x89,0x47, // SNAP GN + 0x12, 0x00, 0x1a, 0x01, // basic, NH=2 secured + 0x03, 0x81, 0x00, 0x40, 0x03, 0x80, 0x30, // 1609.2 signedData/unsecuredData len + 0x20, 0x50, 0x02, 0x80, 0x00, 0x30, 0x01, 0x00}; // common: NH=BTP-B, HT=5 HST=0 + uint8_t pv[24] = {5 << 2, 0, 1,2,3,4,5,6, 0,0,0,0, + 0x1C,0xB3,0x8A,0x40, // lat 481528384 -> 48.1528384 + 0x0A,0x34,0x5A,0x60, // lon 171203168 -> 17.1203168 + 0x05,0x6E, // 1390 * 0.01 m/s = 50.04 km/h + 0x04,0xD2}; // 123.4 deg + f.insert(f.end(), pv, pv + 24); + uint8_t media[4] = {0}; f.insert(f.end(), media, media + 4); + uint8_t btp[4] = {0x07, 0xD1, 0, 0}; f.insert(f.end(), btp, btp + 4); // port 2001 + Info i; + assert(parse(f, i)); + assert(i.secured && i.port == 2001 && i.station_type == 5); + assert(std::fabs(i.lat - 48.1528384) < 1e-7 && std::fabs(i.lon - 17.1203168) < 1e-7); + assert(std::fabs(i.speed_kmh - 50.04f) < 0.01f && std::fabs(i.heading - 123.4f) < 0.01f); + assert(handle(f) && stats.cam == 1); + f[30] = 0x48; assert(!parse(f, i)); // not GeoNetworking + std::puts("ok"); +} diff --git a/mcu-its-g5.yaml b/mcu-its-g5.yaml new file mode 100644 index 0000000..a995f60 --- /dev/null +++ b/mcu-its-g5.yaml @@ -0,0 +1,213 @@ +--- +# Hardware: Seeed Studio XIAO ESP32-C5 (host, its own radio in 802.11p for ITS-G5) +# + Seeed Studio XIAO ESP32-C6 (esp32_hosted co-processor, Wi-Fi uplink over SPI) +# Wi-Fi on the C6 needs esphome/esphome#22819 and hn/esphome-its-g5#3 (external components below) +# and the esp-hosted-mcu 3.1.0 co-processor firmware (examples/wifi/sta/cp, SPI) on the C6. +# Pinout: +# GPIO8 D8 -> esp32_hosted clk -> C6 D8 GPIO19 +# GPIO9 D9 <- esp32_hosted miso <- C6 D9 GPIO20 +# GPIO10 D10 -> esp32_hosted mosi -> C6 D10 GPIO18 +# GPIO7 D3 -> esp32_hosted cs -> C6 D3 GPIO21 +# GPIO1 D0 <- esp32_hosted handshake <- C6 D0 GPIO0 +# GPIO0 D1 <- esp32_hosted data_ready <- C6 D1 GPIO1 +# GPIO25 D2 -> esp32_hosted reset -> C6 D2 GPIO2 (CP firmware restarts itself on LOW) +# GND, 3V3 shared +substitutions: + device: its-g5 + name: ITS-G5 + area: DEV + comment: ITS-G5 receiver + # OpenTrafficMap node ID (MQTT topics its//...): the reference firmware uses the MAC as + # lowercase hex; replace it if opentrafficmap assigned a name (e.g. "node789") + node_id: "3844bebe8638" + +esphome: + name: mcu-${device} + friendly_name: ${name} + area: ${area} + comment: ${comment} + includes: + - common/its_g5/decode.h # its_g5_decode:: header decoding for the lambdas below + +esp32: + board: seeed_xiao_esp32c5 + framework: + type: esp-idf + +packages: + common: !include common/common.yaml + # ipv6_only off: eppp_link (pulled in by esp_wifi_remote) needs IPv4, fix belongs in esp-protocols + # ipv6_only: !include common/ipv6_only.yaml + +external_components: + # Wi-Fi on the esp32_hosted co-processor of a host with its own radio + - source: github://pr#22819 + components: [wifi] + # its_g5_receiver allowing wifi on the co-processor + - source: github://hn/esphome-its-g5@pull/3/head + components: [its_g5_receiver] + refresh: 1d + +esp32_hosted: + type: spi + variant: ESP32C6 + clk_pin: GPIO8 + miso_pin: GPIO9 + mosi_pin: GPIO10 + cs_pin: GPIO7 + handshake_pin: GPIO1 + data_ready_pin: GPIO0 + reset_pin: GPIO25 + +wifi: + use_coprocessor: true # Wi-Fi on the C6, the C5 radio is for 802.11p + # car: ESP joins the tablet's hotspot as a client + min_auth_mode: WPA2 + networks: + - id: !remove wifi_iot + - ssid: !secret wifi_ssid_0 + password: !secret wifi_password_0 + +# Raw 802.11 frames as UDP broadcasts; in Wireshark use the "UDP Listener" +# (udpdump) interface on port 18511 with payload "wlan". +udp: + id: its_udp + +# Raw frames to the OpenTrafficMap C-ITS server, as in hn's its-g5-opentrafficmap.yaml +mqtt: + id: mqtt_client + broker: cits1.opentrafficmap.org + port: 8883 # TLS is mandatory; publishing is anonymous + discovery: false + # *.opentrafficmap.org wildcard certificate, the hostname check fails with MbedTLS + skip_cert_cn_check: true + certificate_authority: | + -----BEGIN CERTIFICATE----- + MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw + TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh + cmNoIEdyb3VwMRUwEwYDVQQDEwx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XIpu+ILlaS/V9lZL + ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ + 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK + NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 + ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur + TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC + jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc + oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq + 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA + mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d + emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= + -----END CERTIFICATE----- + # Empty prefix: no entity states, no command topics (the broker is anonymous) and no log topic; + # only the OpenTrafficMap topics below + topic_prefix: null + log_topic: null + birth_message: + topic: its/${node_id}/status + payload: online + retain: true + will_message: + topic: its/${node_id}/status + payload: offline + retain: true + on_connect: + - delay: 3s + - lambda: |- + uint8_t mac[6]; + get_mac_address_raw(mac); + char info[160]; + int n = snprintf(info, sizeof(info), + "{\"emac\":\"%02x:%02x:%02x:%02x:%02x:%02x\",\"ver\":\"%s\",\"hwv\":\"esphome\"}", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], ESPHOME_VERSION); + id(mqtt_client).publish("its/${node_id}/info", info, n, 0, false); + +interval: + - interval: 60s + then: + - lambda: |- + char stats[48]; + int n = snprintf(stats, sizeof(stats), "{\"rbt\":%llu}", millis_64() / 1000ULL); + id(mqtt_client).publish("its/${node_id}/stats", stats, n, 0, false); + +its_g5_receiver: + id: g5 + channel: 5900 # G5CC + broadcast_only: true + on_packet: + - lambda: |- + id(mqtt_client).publish("its/${node_id}/packet", (const char *) x.data(), x.size(), 0, false); + - udp.write: + id: its_udp + data: !lambda return x; + - lambda: |- + if (!its_g5_decode::handle(x)) + return; + const auto &i = its_g5_decode::stats.last; + ESP_LOGD("its_g5", "%s from %s %.6f,%.6f %.0f km/h %.0f deg%s, rssi %.0f dBm", + its_g5_decode::port_name(i.port), its_g5_decode::station_name(i.station_type), + i.lat, i.lon, i.speed_kmh, i.heading, i.secured ? ", signed" : "", rssi); + +sensor: + - platform: its_g5_receiver + its_g5_receiver_id: g5 + bytes_received: + name: Bytes Received + packets_received: + name: Packets Received + packets_dropped: + name: Packets Dropped + - platform: template + name: CAM Received + state_class: total_increasing + accuracy_decimals: 0 + lambda: return its_g5_decode::stats.cam; + - platform: template + name: DENM Received + state_class: total_increasing + accuracy_decimals: 0 + lambda: return its_g5_decode::stats.denm; + - platform: template + name: SPATEM Received + state_class: total_increasing + accuracy_decimals: 0 + lambda: return its_g5_decode::stats.spatem; + - platform: template + name: MAPEM Received + state_class: total_increasing + accuracy_decimals: 0 + lambda: return its_g5_decode::stats.mapem; + +binary_sensor: + - platform: template + name: MQTT Connected + device_class: connectivity + entity_category: diagnostic + lambda: return id(mqtt_client).is_connected(); + +text_sensor: + - platform: template + name: Last Station + update_interval: 10s + lambda: |- + const auto &i = its_g5_decode::stats.last; + if (i.lat == 0 && i.lon == 0) + return {}; + char buf[96]; + snprintf(buf, sizeof(buf), "%s %s %.6f,%.6f %.0f km/h %.0f°", its_g5_decode::port_name(i.port), + its_g5_decode::station_name(i.station_type), i.lat, i.lon, i.speed_kmh, i.heading); + return std::string(buf); diff --git a/secrets.yaml.default b/secrets.yaml.default index f0e5bb9..a6cf90d 100644 --- a/secrets.yaml.default +++ b/secrets.yaml.default @@ -37,3 +37,5 @@ thread_tlv: "0E080000000000010000" # ANT+ network key (8 bytes hex), from thisisant.com ant_plus_network_key: "0000000000000000" +wifi_ssid_0: "ssid" +wifi_password_0: "password"