diff --git a/Panel.qml b/Panel.qml index 54e84eb..dafd5c9 100644 --- a/Panel.qml +++ b/Panel.qml @@ -44,7 +44,7 @@ Panel { property var current: null property var daily: [] property var hourly: [] - property var stations: [] // [{id, name}] + property var stations: [] // [{id, name, device}] property string autoStationId: "" property string stationName: "" property string tokenState: "unknown" // unknown | ok | missing | invalid @@ -157,6 +157,7 @@ Panel { // Theme-coloured weather icons: warm sun, cool moon and rain. property color sunColor: "#e0a93b" property color moonColor: "#5b9bd5" + property color greenColor: "#8fb573" function glyphColor(icon) { var i = String(icon || "") if (i.indexOf("night") >= 0) return moonColor @@ -174,6 +175,8 @@ Panel { var b = /^\s*blue\s*=\s*"(#[0-9a-fA-F]{6})"/m.exec(text()) if (y) root.sunColor = y[1] if (b) root.moonColor = b[1] + var g = /^\s*green\s*=\s*"(#[0-9a-fA-F]{6})"/m.exec(text()) + if (g) root.greenColor = g[1] } } function ago(ms) { @@ -299,7 +302,11 @@ Panel { for (var i = 0; i < d.stations.length && list.length < 20; i++) { var s = d.stations[i] if (!s || !/^[0-9]{1,10}$/.test(String(s.station_id))) continue - list.push({ id: String(s.station_id), name: clean(s.name || s.public_name || ("Station " + s.station_id), 60) }) + var dev = "" + var ds = Array.isArray(s.devices) ? s.devices : [] + for (var j = 0; j < ds.length; j++) + if (ds[j] && ds[j].device_type === "ST" && /^[0-9]{1,10}$/.test(String(ds[j].device_id))) { dev = String(ds[j].device_id); break } + list.push({ id: String(s.station_id), name: clean(s.name || s.public_name || ("Station " + s.station_id), 60), device: dev }) } stations = list tokenState = "ok" @@ -349,6 +356,7 @@ Panel { fetchedAt = Date.now() statusText = "" errorDetail = "" + if (live) mergeLive(null) } function fail(detail) { @@ -358,6 +366,121 @@ Panel { property string _body: "" property string _sbody: "" + property string _lbody: "" + + // ---- live mode ---------------------------------------------------------- + // While the panel is open, the station's latest observation is polled every + // 15 s (QtWebSockets is not available in this shell, and the API rate-limits + // faster polling) and merged over the REST conditions. Closed: no polling. + // Real time: live.py (stdlib WebSocket client) streams rapid_wind (~3 s) and + // obs_st (~1 min); the REST poll slows to 60 s to fill rain, lightning, pressure. + property bool havePython: false + property int wsFails: 0 + property double wsAt: 0 + readonly property string pluginDir: Qt.resolvedUrl(".").toString().replace(/^file:\/\//, "").replace(/\/$/, "") + readonly property string deviceId: { + for (var i = 0; i < stations.length; i++) if (stations[i].id === stationId) return stations[i].device || "" + return "" + } + readonly property bool wsWanted: liveWanted && havePython && deviceId !== "" && wsFails < 4 + readonly property bool wsLive: wsWanted && wsAt > 0 && (nowMs - wsAt) < 20000 + property double liveAt: 0 + property double rapidAt: 0 + property double tick: Date.now() + readonly property string linkState: { + if (!liveWanted) return "off" + if (wsLive) return "live" + if (liveFails >= 2 || (liveAt === 0 && statusText !== "" && fetchedAt === 0)) return "offline" + if (wsWanted) return wsFails > 0 ? "retry" : "connecting" + return "poll" + } + readonly property color linkColor: linkState === "live" ? greenColor + : (linkState === "retry" || linkState === "connecting") ? sunColor + : linkState === "poll" ? moonColor : urgent + readonly property string linkLabel: linkState === "live" ? tr("link.live") + : linkState === "connecting" ? tr("link.connecting") : linkState === "retry" ? tr("link.retry") + : linkState === "poll" ? tr("link.poll") : tr("link.offline") + readonly property string linkSub: linkState === "live" && rapidAt > 0 ? Math.max(0, Math.round((tick - rapidAt) / 1000)) + "s" : "" + property int liveFails: 0 + property real windRot: 180 + readonly property bool liveWanted: opened && view === "weather" && tokenState === "ok" && stationId !== "" + readonly property bool live: wsLive || (liveWanted && liveAt > 0 && (nowMs - liveAt) < 45000) + + function cardinal(d) { + var n = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] + return n[Math.round(((d % 360) + 360) % 360 / 22.5) % 16] + } + function setWindRot(dir) { + var t = (num(dir) !== null ? dir : 0) + 180 + var delta = ((t - windRot) % 360 + 540) % 360 - 180 + windRot = windRot + delta + } + function applyWs(line) { + var m + try { m = JSON.parse(line) } catch (e) { return } + if (!m || !Array.isArray(m.ob) || !current) return + var o = m.ob, c = {} + for (var k in current) c[k] = current[k] + function put(key, v) { if (num(v) !== null) c[key] = v } + var w = metric ? 1 : 2.23694 + if (m.t === "rapid") { + rapidAt = Date.now() + if (num(o[1]) === null || num(o[2]) === null) return + c.wind_avg = o[1] * w + c.wind_direction = o[2]; c.wind_direction_cardinal = cardinal(o[2]) + } else if (m.t === "obs" && o.length >= 12) { + put("air_temperature", metric ? o[7] : o[7] * 9 / 5 + 32) + put("relative_humidity", o[8]); put("uv", o[10]); put("solar_radiation", o[11]) + put("wind_gust", num(o[3]) === null ? null : o[3] * w) + } else return + wsFails = 0 + wsAt = Date.now(); nowMs = wsAt + current = c + if (liveObs) liveObs = null // stale REST overlay must not undo newer values + } + function pollLive() { + if (!liveWanted || liveProc.running) return + liveProc.command = ["sh", "-c", curlScript, "sh", + apiBase + "observations/station/" + stationId + "?units_temp=c&units_wind=mps&units_pressure=mb&units_precip=mm&units_distance=km&"] + liveProc.running = true + } + function applyLive(text) { + var r = splitCode(text), d + if (r.code !== "200") { liveFails++; return } + try { d = JSON.parse(r.body) } catch (e) { liveFails++; return } + var o = d && Array.isArray(d.obs) && d.obs.length ? d.obs[0] : null + if (!o || num(o.timestamp) === null) { liveFails++; return } + liveFails = 0 + liveAt = Date.now() + nowMs = liveAt + mergeLive(o) + } + property var liveObs: null + function mergeLive(o) { + if (o) liveObs = o + o = liveObs + if (!o || !current) return + var c = {} + for (var k in current) c[k] = current[k] + function put(key, v) { if (num(v) !== null) c[key] = v } + put("air_temperature", metric ? o.air_temperature : o.air_temperature * 9 / 5 + 32) + put("relative_humidity", o.relative_humidity) + put("uv", o.uv) + put("solar_radiation", o.solar_radiation) + if (!wsLive) { + put("wind_avg", metric ? o.wind_avg : o.wind_avg * 2.23694) + put("wind_gust", metric ? o.wind_gust : o.wind_gust * 2.23694) + if (num(o.wind_direction) !== null) { c.wind_direction = o.wind_direction; c.wind_direction_cardinal = cardinal(o.wind_direction) } + } + var p = metric ? o.sea_level_pressure : o.sea_level_pressure / 33.8639 + put("sea_level_pressure", p) + put("station_pressure", metric ? o.station_pressure : o.station_pressure / 33.8639) + if (typeof o.pressure_trend === "string") c.pressure_trend = o.pressure_trend + put("precip_accum_local_day", metric ? o.precip_accum_local_day : o.precip_accum_local_day / 25.4) + put("lightning_strike_count_last_3hr", o.lightning_strike_count_last_3hr) + put("lightning_strike_last_distance", metric ? o.lightning_strike_last_distance : o.lightning_strike_last_distance * 0.621371) + current = c + } Process { id: fetchProc @@ -369,6 +492,33 @@ Panel { } } + Process { + id: pyCheck + command: ["sh", "-c", "command -v python3 >/dev/null"] + onExited: function(code) { root.havePython = code === 0 } + } + Process { + id: wsProc + command: ["python3", root.pluginDir + "/live.py", root.deviceId] + stdout: SplitParser { onRead: function(line) { root.applyWs(line) } } + onExited: function(code) { + root.wsAt = 0 + if (root.wsWanted && !wsBackoff.running) { root.wsFails++; wsBackoff.interval = Math.min(30000, 2000 * (1 << Math.min(root.wsFails, 4))); wsBackoff.restart() } + } + } + Timer { id: wsBackoff; repeat: false; onTriggered: root.syncWs() } + function syncWs() { wsProc.running = wsWanted && !wsBackoff.running } + onWsWantedChanged: { if (!wsWanted) wsBackoff.stop(); syncWs() } + onDeviceIdChanged: if (wsProc.running) { wsProc.running = false } + Process { + id: liveProc + stdout: StdioCollector { onStreamFinished: root._lbody = text } + onExited: function(code) { + if (code !== 0) { root.liveFails++; return } + root.applyLive(root._lbody) + } + } + Process { id: stationsProc stdout: StdioCollector { onStreamFinished: root._sbody = text } @@ -456,6 +606,22 @@ Panel { repeat: true onTriggered: root.refresh() } + Timer { + interval: root.liveFails > 0 ? Math.min(60000, 15000 * (1 << Math.min(root.liveFails, 2))) : (root.wsLive ? 60000 : 15000) + running: root.liveWanted + repeat: true + onTriggered: root.pollLive() + } + onLiveWantedChanged: { + if (liveWanted) pollLive() + else { liveAt = 0; liveFails = 0; liveObs = null; wsAt = 0; wsFails = 0 } + } + Timer { + interval: 1000 + running: root.liveWanted + repeat: true + onTriggered: root.tick = Date.now() + } Timer { interval: 30000 running: true @@ -463,7 +629,7 @@ Panel { onTriggered: root.nowMs = Date.now() } - Component.onCompleted: { aiCheck.running = true; refresh() } + Component.onCompleted: { aiCheck.running = true; pyCheck.running = true; refresh() } onSettingsChanged: { if (tokenState !== "missing" && tokenState !== "invalid") refresh() } onTokenStateChanged: if (tokenState === "ok") tailProc.running = true @@ -474,6 +640,7 @@ Panel { if (fetchedAt === 0 || nowMs - fetchedAt > 60000 || statusText !== "" || tokenState === "unknown") refresh() open() } + onCurrentChanged: if (current) setWindRot(current.wind_direction) function togglePanel() { opened ? close() : openPanel() } ShellIpc { @@ -550,7 +717,7 @@ Panel { centerOnBar: root.centredOnBar focusTarget: keyCatcher contentWidth: panel.fittedContentWidth(Style.space(420)) - contentHeight: panel.fittedContentHeight(column.implicitHeight, Style.space(900)) + contentHeight: panel.fittedContentHeight(column.implicitHeight, Style.space(1000)) PanelKeyCatcher { id: keyCatcher @@ -612,6 +779,57 @@ Panel { text: root.tr("error.load").arg(root.errorDetail) } + // ---- Header: station name | link status + Item { + visible: root.current !== null + width: parent.width + height: Style.space(18) + T { + anchors.left: parent.left + anchors.right: linkChip.left + anchors.rightMargin: Style.space(8) + anchors.verticalCenter: parent.verticalCenter + font.weight: Font.DemiBold + text: root.stationName !== "" ? root.stationName : (root.stationId !== "" ? root.tr("footer.station").arg(root.stationId) : " ") + } + Rectangle { + id: linkChip + opacity: root.linkState !== "off" ? 1 : 0 + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: Style.space(78); height: Style.space(18) + radius: height / 2 + color: Qt.rgba(root.linkColor.r, root.linkColor.g, root.linkColor.b, 0.18) + border.width: 1 + border.color: Qt.rgba(root.linkColor.r, root.linkColor.g, root.linkColor.b, 0.6) + Row { + anchors.centerIn: parent + spacing: Style.space(5) + Rectangle { + id: linkDot + anchors.verticalCenter: parent.verticalCenter + width: Style.space(6); height: width; radius: width / 2 + color: root.linkColor + SequentialAnimation on opacity { + running: root.linkState === "live" || root.linkState === "connecting" || root.linkState === "retry" + loops: Animation.Infinite + NumberAnimation { to: 0.25; duration: Style.duration(root.linkState === "live" ? 900 : 450) } + NumberAnimation { to: 1.0; duration: Style.duration(root.linkState === "live" ? 900 : 450) } + onRunningChanged: if (!running) linkDot.opacity = 1 + } + } + T { + anchors.verticalCenter: parent.verticalCenter + font.pixelSize: Style.font.caption + font.weight: Font.Bold + elide: Text.ElideNone + color: root.linkColor + text: root.linkLabel + } + } + } + } + // ---- Hero: temperature + feels like | condition icon + text RowLayout { visible: root.current !== null @@ -665,7 +883,7 @@ Panel { // ---- What's next Row { - visible: root.current !== null && root.nextLine !== "" + visible: root.current !== null width: parent.width spacing: Style.space(8) Rectangle { @@ -676,10 +894,10 @@ Panel { T { id: nextText width: parent.width - Style.space(10) - wrapMode: Text.WordWrap - elide: Text.ElideNone + wrapMode: Text.NoWrap + elide: Text.ElideRight font.weight: Font.Medium - text: root.nextLine + text: root.nextLine !== "" ? root.nextLine : " " } } @@ -704,6 +922,7 @@ Panel { property string detail: "" property color detailColor: root.dim property int level: -1 + property bool levelRow: false Layout.fillWidth: true Layout.preferredWidth: 1 Layout.alignment: Qt.AlignTop @@ -727,6 +946,7 @@ Panel { elide: Text.ElideNone font.pixelSize: tile.ring ? Style.font.icon : Style.font.iconLarge + 2 rotation: tile.iconRotation + Behavior on rotation { NumberAnimation { duration: Style.duration(600); easing.type: Easing.OutCubic } } } } ColumnLayout { @@ -739,7 +959,7 @@ Panel { T { width: Math.max(0, parent.width - tv.width - parent.spacing); text: tile.label } } Row { - visible: tile.level >= 0 + visible: tile.levelRow spacing: Style.space(2) Repeater { model: 5 @@ -747,16 +967,15 @@ Panel { required property int index width: Style.space(18); height: Style.space(5) radius: Style.cornerRadius - color: index < tile.level ? root.accent : Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.15) + color: index < Math.max(0, tile.level) ? root.accent : Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.15) } } } T { - visible: tile.detail !== "" Layout.fillWidth: true color: tile.detailColor font.pixelSize: Style.font.bodySmall - text: tile.detail + text: tile.detail !== "" ? tile.detail : " " } } } @@ -769,13 +988,15 @@ Panel { Tile { ring: true icon: "󰁝" - iconRotation: (root.num(tiles.c.wind_direction) !== null ? tiles.c.wind_direction : 0) + 180 + iconRotation: root.windRot value: (tiles.c.wind_direction_cardinal ? root.clean(tiles.c.wind_direction_cardinal, 4) + " " : "") + root.fmt(tiles.c.wind_avg, 0) label: root.wUnit - level: root.num(tiles.c.wind_avg) !== null ? root.windLevel(tiles.c.wind_avg) : -1 - detail: root.num(tiles.c.wind_gust) !== null && tiles.c.wind_gust > (tiles.c.wind_avg || 0) - ? root.tr("tile.gust").arg(root.fmt(tiles.c.wind_gust, 0)).arg(root.wUnit) : "" + levelRow: true + level: root.num(tiles.c.wind_avg) !== null ? root.windLevel(tiles.c.wind_avg) : 0 + detail: root.num(tiles.c.wind_gust) !== null + ? root.tr("tile.gust").arg(root.fmt(Math.max(tiles.c.wind_gust, tiles.c.wind_avg || 0), 0)).arg(root.wUnit) + : root.tr("tile.gust").arg("–").arg(root.wUnit) } Tile { ring: true @@ -798,7 +1019,6 @@ Panel { label: root.rUnit + " " + root.tr("tile.rain") } Tile { - visible: root.num(tiles.c.lightning_strike_count_last_3hr) !== null icon: "󱐋" value: root.fmt(tiles.c.lightning_strike_count_last_3hr, 0) label: root.tr("tile.lightning.strikes") @@ -825,17 +1045,26 @@ Panel { width: parent.width readonly property bool anyPrecipLine: true readonly property bool anyMarker: root.upcoming.some(function(h) { return root.sunEvent(h.time) !== "" }) - height: (anyMarker ? Style.font.caption * 1.5 : 0) + Style.font.bodySmall * 1.35 * 3 + Style.font.iconLarge * 1.4 + Style.font.body * 1.35 + height: Style.font.caption * 1.5 + Style.font.bodySmall * 1.35 * 3 + Style.font.iconLarge * 1.4 + Style.font.body * 1.35 orientation: ListView.Horizontal spacing: 0 clip: true boundsBehavior: Flickable.StopAtBounds model: root.upcoming + NumberAnimation { id: wheelAnim; target: hours; property: "contentX"; duration: Style.duration(160); easing.type: Easing.OutCubic } WheelHandler { acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad onWheel: function(ev) { - var d = ev.angleDelta.y !== 0 ? ev.angleDelta.y : ev.angleDelta.x - hours.contentX = Math.max(0, Math.min(hours.contentWidth - hours.width, hours.contentX - d)) + var touch = ev.pixelDelta.x !== 0 || ev.pixelDelta.y !== 0 + var d = touch ? (Math.abs(ev.pixelDelta.x) > Math.abs(ev.pixelDelta.y) ? ev.pixelDelta.x : ev.pixelDelta.y) + : (ev.angleDelta.y !== 0 ? ev.angleDelta.y : ev.angleDelta.x) + var max = Math.max(0, hours.contentWidth - hours.width) + var from = wheelAnim.running ? wheelAnim.to : hours.contentX + var to = Math.max(0, Math.min(max, from - d)) + wheelAnim.stop() + if (touch) hours.contentX = to + else { wheelAnim.from = hours.contentX; wheelAnim.to = to; wheelAnim.start() } + ev.accepted = true } } delegate: Column { @@ -844,7 +1073,7 @@ Panel { width: Style.space(56) spacing: Style.space(1) readonly property string sun: root.sunEvent(modelData.time) - T { visible: hours.anyMarker; width: parent.width; horizontalAlignment: Text.AlignHCenter + T { width: parent.width; horizontalAlignment: Text.AlignHCenter font.pixelSize: Style.font.caption; color: root.dim; elide: Text.ElideNone text: parent.sun === "rise" ? "󰖜 " + root.clockTime(root.sunTime(modelData.time, true), true, true) : (parent.sun === "set" ? "󰖛 " + root.clockTime(root.sunTime(modelData.time, false), true, true) : " ") } @@ -900,7 +1129,7 @@ Panel { font.pixelSize: Style.font.bodySmall color: (root.stale || root.failing) ? root.urgent : root.dim text: { - var s = root.stationName !== "" ? root.stationName : (root.stationId !== "" ? root.tr("footer.station").arg(root.stationId) : "") + var s = "" if (root.fetchedAt > 0) s += (s !== "" ? " · " : "") + root.tr("footer.updated").arg(root.ago(root.fetchedAt)) if (root.failing) s += " · " + root.errorDetail else if (root.stale) s += " · " + root.tr("footer.stale") diff --git a/README.md b/README.md index 3f633b4..117ce6d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,16 @@ Hyper-local weather in the Omarchy bar, from your own [Tempest](https://tempest.earth) personal weather station. The bar pill shows the station temperature; click it for current conditions (feels like, wind, -pressure, humidity, UV, rain, lightning), the next hours, and the week ahead. +pressure, humidity, UV, rain, lightning), the next hours (scroll the hourly +strip with the mouse wheel), and the week ahead. + +## Live mode + +While the panel is open it streams from WeatherFlow's WebSocket: wind about +every 3 seconds, full observations every minute. A status pill shows the +state: `LIVE`, `LINKING`, `RETRY`, `POLL 15s` or `OFFLINE`. Streaming stops +when the panel closes. If `python3` is missing, the panel falls back to +polling the REST API every 15 seconds.

TempestWX panel

@@ -63,6 +72,7 @@ rm -r ~/.config/tempestwx # optional: deletes your saved token ## Dependencies - `curl` +- `python3` (standard on Omarchy), for live mode - `xdg-open` (from `xdg-utils`), to open the token page in your browser - `omarchy-agent`, optional, only for the **Set up with AI** button @@ -70,11 +80,13 @@ No other packages. No sudo. ## Network and privacy -The plugin talks only to `https://swd.weatherflow.com` (the WeatherFlow -Tempest API), once every `refreshMinutes` minutes while the shell runs. Your -token is passed to `curl` over stdin, never on a command line, and never -leaves your machine except in those requests to WeatherFlow. It is not logged -or displayed. The plugin writes nothing besides `~/.config/tempestwx/token`. +The plugin talks only to WeatherFlow's Tempest service: `https://swd.weatherflow.com` +(REST) once every `refreshMinutes` minutes while the shell runs, and +`wss://ws.weatherflow.com` (WebSocket) only while the panel is open. Your +token is passed to `curl` over stdin, never on a command line, and to the +WebSocket by the live helper (`live.py`); it never leaves your machine except +in requests to WeatherFlow. It is not logged or displayed. The plugin writes +nothing besides `~/.config/tempestwx/token`. ## License diff --git a/i18n/en.json b/i18n/en.json index 4581a2c..099bd51 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -43,6 +43,12 @@ "section.week": "THIS WEEK", "footer.station": "Station %1", "footer.updated": "Updated %1", + "footer.live": "LIVE", + "link.live": "LIVE", + "link.connecting": "LINKING", + "link.retry": "RETRY", + "link.poll": "POLL 15s", + "link.offline": "OFFLINE", "footer.stale": "stale", "footer.failed": "refresh failed, showing last data", "footer.refresh": "Refresh", @@ -88,6 +94,6 @@ "settings.auto": "Automatic", "settings.display": "DISPLAY", "settings.data": "DATA", - "settings.disclose": "TempestWX contacts swd.weatherflow.com (HTTPS) every refresh interval while the shell runs, and once more when you open the panel if data is over a minute old. Only your token and station id are sent.", + "settings.disclose": "TempestWX contacts swd.weatherflow.com (HTTPS) every refresh interval while the shell runs, and once more when you open the panel if data is over a minute old. While the panel is open, it streams live readings from WeatherFlow (the latest observation, polled every 15 seconds). Only your token and station id are sent.", "footer.tz": "All times are in station local time (%1)" } \ No newline at end of file diff --git a/live.py b/live.py new file mode 100644 index 0000000..07456db --- /dev/null +++ b/live.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""TempestWX live helper: minimal stdlib WebSocket client for the WeatherFlow +Tempest stream. Usage: live.py . The token is read from +~/.config/tempestwx/token, never from argv. Prints one compact JSON line per +obs_st / rapid_wind message. Exit 0 on SIGTERM, 1 on failure.""" +import base64, json, os, re, signal, socket, ssl, struct, sys + +HOST = "ws.weatherflow.com" + +def die(code): + sys.exit(code) + +def main(): + if len(sys.argv) != 2 or not re.fullmatch(r"[0-9]{1,10}", sys.argv[1]): + die(2) + dev = int(sys.argv[1]) + try: + with open(os.path.expanduser("~/.config/tempestwx/token")) as f: + tok = f.readline().strip() + except OSError: + die(3) + if not re.fullmatch(r"[A-Za-z0-9._-]{8,200}", tok): + die(3) + signal.signal(signal.SIGTERM, lambda *a: die(0)) + raw = socket.create_connection((HOST, 443), timeout=15) + s = ssl.create_default_context().wrap_socket(raw, server_hostname=HOST) + key = base64.b64encode(os.urandom(16)).decode() + s.sendall(("GET /swd/data?token=%s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\n" + "Connection: Upgrade\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" + % (tok, HOST, key)).encode()) + buf = b"" + while b"\r\n\r\n" not in buf: + d = s.recv(4096) + if not d: + die(1) + buf += d + if len(buf) > 65536: + die(1) + head, buf = buf.split(b"\r\n\r\n", 1) + if b" 101 " not in head.split(b"\r\n")[0] + b" ": + die(1) + + def send(op, payload): + m = os.urandom(4) + n = len(payload) + h = bytes([0x80 | op]) + if n < 126: h += bytes([0x80 | n]) + elif n < 65536: h += bytes([0x80 | 126]) + struct.pack(">H", n) + else: h += bytes([0x80 | 127]) + struct.pack(">Q", n) + s.sendall(h + m + bytes(b ^ m[i % 4] for i, b in enumerate(payload))) + + def msg(o): + send(1, json.dumps(o).encode()) + msg({"type": "listen_start", "device_id": dev, "id": "twx-obs"}) + msg({"type": "listen_rapid_start", "device_id": dev, "id": "twx-rapid"}) + + s.settimeout(None) + frag = b"" + last = 0 + while True: + while len(buf) < 2: + buf += recv_more(s) + b1, b2 = buf[0], buf[1] + n = b2 & 0x7F + off = 2 + if n == 126: + while len(buf) < 4: buf += recv_more(s) + n = struct.unpack(">H", buf[2:4])[0]; off = 4 + elif n == 127: + while len(buf) < 10: buf += recv_more(s) + n = struct.unpack(">Q", buf[2:10])[0]; off = 10 + if n > 1 << 20: + die(1) + while len(buf) < off + n: + buf += recv_more(s) + payload, buf = buf[off:off + n], buf[off + n:] + op = b1 & 0x0F + if op == 8: + die(1) + if op == 9: + send(10, payload); continue + if op == 10: + continue + if op in (1, 0): + frag += payload + if not (b1 & 0x80): + continue + text, frag = frag, b"" + try: + d = json.loads(text.decode()) + except ValueError: + continue + t = d.get("type") + if t == "rapid_wind" and isinstance(d.get("ob"), list): + out = {"t": "rapid", "ob": d["ob"]} + elif t == "obs_st" and isinstance(d.get("obs"), list) and d["obs"]: + out = {"t": "obs", "ob": d["obs"][0]} + else: + continue + sys.stdout.write(json.dumps(out, separators=(",", ":")) + "\n") + sys.stdout.flush() + +def recv_more(s): + d = s.recv(65536) + if not d: + die(1) + return d + +try: + main() +except SystemExit: + raise +except Exception: + sys.exit(1) diff --git a/manifest.json b/manifest.json index c42dccb..affb496 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "io.github.swaits.tempestwx", "name": "TempestWX", - "version": "1.0.0", + "version": "1.1.0", "author": "Stephen Waits", "license": "MIT", "homepage": "https://github.com/swaits/omarchy-tempestwx", diff --git a/preview.png b/preview.png index e9af906..6eff6b2 100644 Binary files a/preview.png and b/preview.png differ