@7365admin1/core 3.117.0 → 3.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,399 @@
1
+ // PadBot MQTT (API v4.0 §7-§8): the codec, every documented robot message,
2
+ // credential refresh timing, backoff, de-duplication, the manual-drive limits
3
+ // and safety checks, and the drive watchdog's stop on every loss path.
4
+
5
+ import assert from "node:assert/strict";
6
+ import { mock, test } from "node:test";
7
+
8
+ import {
9
+ DISCONNECT,
10
+ MQTT,
11
+ PINGREQ,
12
+ clampChassis,
13
+ connackCode,
14
+ createDriveWatchdog,
15
+ createMessageDeduper,
16
+ createMqttReader,
17
+ decodePublish,
18
+ encodeConnect,
19
+ encodePublish,
20
+ encodeSubscribe,
21
+ headParams,
22
+ motionMessage,
23
+ mqttBackoffMs,
24
+ mqttRefreshDelayMs,
25
+ padbotAlarmPollEnabled,
26
+ padbotDriveBlock,
27
+ padbotDriveLimits,
28
+ padbotManualDriveEnabled,
29
+ padbotMqttEnabled,
30
+ parsePadbotMessage,
31
+ safeTopic,
32
+ subackOk,
33
+ } from "./.build/utils/padbot-mqtt.util.mjs";
34
+ import { floorWord, robotFaultText } from "./.build/utils/robot-fault.util.mjs";
35
+ import { parseRobotCommand } from "./.build/utils/robot-cloud.util.mjs";
36
+ import { commandSupported } from "./.build/utils/robot-adapter.util.mjs";
37
+ import {
38
+ PADBOT_CAPABILITIES,
39
+ PADBOT_PATHS,
40
+ clearPadbotCache,
41
+ createPadbotAdapter,
42
+ padbotAccountKey,
43
+ padbotAlarmFault,
44
+ padbotCommandLog,
45
+ recordPadbotLive,
46
+ } from "./.build/services/padbot.adapter.mjs";
47
+
48
+ /* ---------------------------------------------------------------- codec */
49
+
50
+ test("CONNECT: MQTT 3.1.1, clean session, username + password flags, keep-alive, fields in order", () => {
51
+ const b = encodeConnect({ clientId: "GID@@@c1", username: "Token|u", password: "R|t", keepAliveS: 60 });
52
+ assert.equal(b[0], 0x10);
53
+ const [p] = createMqttReader()(b);
54
+ assert.equal(p.type, MQTT.CONNECT);
55
+ assert.equal(p.body.subarray(0, 6).toString("latin1"), "\u0000\u0004MQTT");
56
+ assert.equal(p.body[6], 4, "protocol level 4 = 3.1.1");
57
+ assert.equal(p.body[7], 0xc2, "username + password + clean session");
58
+ assert.equal(p.body.readUInt16BE(8), 60);
59
+ const rest = p.body.subarray(10);
60
+ const read = (buf, off) => [buf.subarray(off + 2, off + 2 + buf.readUInt16BE(off)).toString(), off + 2 + buf.readUInt16BE(off)];
61
+ let [cid, o] = read(rest, 0);
62
+ let [user, o2] = read(rest, o);
63
+ let [pass] = read(rest, o2);
64
+ assert.deepEqual([cid, user, pass], ["GID@@@c1", "Token|u", "R|t"]);
65
+ });
66
+
67
+ test("SUBSCRIBE / PUBLISH round trip; PING / DISCONNECT bytes; reader reassembles split chunks", () => {
68
+ const sub = encodeSubscribe(7, ["robot-open/a/b"], 0);
69
+ assert.equal(sub[0], 0x82, "SUBSCRIBE has reserved flags 0010");
70
+ const pub = encodePublish("robot-open/a/b", '{"t":"1103"}', 1, 9);
71
+ const reader = createMqttReader();
72
+ const bytes = Buffer.concat([pub, PINGREQ]);
73
+ const first = reader(bytes.subarray(0, 5));
74
+ assert.equal(first.length, 0, "half a packet waits");
75
+ const rest = reader(bytes.subarray(5));
76
+ assert.deepEqual(rest.map((p) => p.type), [MQTT.PUBLISH, MQTT.PINGREQ]);
77
+ const d = decodePublish(rest[0]);
78
+ assert.deepEqual([d.topic, d.payload.toString(), d.qos, d.packetId], ["robot-open/a/b", '{"t":"1103"}', 1, 9]);
79
+ assert.deepEqual([...DISCONNECT], [0xe0, 0]);
80
+ // A long payload uses a multi-byte remaining length.
81
+ const big = encodePublish("t", "x".repeat(300));
82
+ const [bp] = createMqttReader()(big);
83
+ assert.equal(decodePublish(bp).payload.length, 300);
84
+ });
85
+
86
+ test("reader: oversized or malformed packets throw (the link is dropped - bounded memory)", () => {
87
+ assert.throws(() => createMqttReader(100)(encodePublish("t", "x".repeat(200))), /too large/);
88
+ assert.throws(() => createMqttReader()(Buffer.from([0x30, 0xff, 0xff, 0xff, 0xff, 0x01])), /malformed/);
89
+ });
90
+
91
+ test("CONNACK / SUBACK decoding; topics: never a wildcard", () => {
92
+ assert.equal(connackCode({ body: Buffer.from([0, 0]) }), 0);
93
+ assert.equal(connackCode({ body: Buffer.from([0, 5]) }), 5);
94
+ assert.equal(subackOk({ body: Buffer.from([0, 1, 0]) }), true);
95
+ assert.equal(subackOk({ body: Buffer.from([0, 1, 0x80]) }), false);
96
+ assert.equal(safeTopic("robot-open/x/y"), true);
97
+ for (const bad of ["robot-open/#", "robot-open/+/y", "", null, "a".repeat(600)]) assert.equal(safeTopic(bad), false, String(bad));
98
+ });
99
+
100
+ /* --------------------------------------------------------- §7 messages */
101
+
102
+ // The doc's own examples, verbatim.
103
+ const DOC = {
104
+ battery: { id: "3e1f1a4e89d242b7b93e588a699f4901", t: "1103", ts: 1785312000123, sn: "PW1001", m: '{"pt":68}' },
105
+ estop: { id: "3e1f1a4e89d242b7b93e588a699f4902", t: "1104", ts: 1785312001123, sn: "PW1001", m: '{"es":1,"ws":0}' },
106
+ mapUpdate: { id: "3e1f1a4e89d242b7b93e588a699f4903", t: "27", ts: 1785312002123, sn: "PW1001" },
107
+ position: { id: "3e1f1a4e89d242b7b93e588a699f4904", t: "1200", ts: 1785312003123, sn: "PW1001", m: '{"mi":"map_001","worldX":100.0,"worldY":100.1,"r":180}' },
108
+ mapSwitch: { id: "3e1f1a4e89d242b7b93e588a699f4912", t: "1202", ts: 1785312005124, sn: "PW1001", m: '{"mi":"m001"}' },
109
+ alarm: { id: "3e1f1a4e89d242b7b93e588a699f4909", t: "1123", ts: 1785312008123, sn: "PW1001", m: '{"bt":"1","csu":"https://img/v.png","tpu":"https://img/t.png","te":65,"mi":"map_001","di":"001","dn":"Target Point 1","ti":"002","tn":"Target Point 2","x":100.3,"y":200.2,"r":180}' },
110
+ arrival: { id: "3e1f1a4e89d242b7b93e588a699f4910", t: "1124", ts: 1785312009095, sn: "PW1001", m: '{"csu":"https://img/v.png","tpu":"https://img/t.png","di":"001","dn":"Target Point 1","ti":"002","tn":"Target Point 2","x":100.4,"y":200.6,"r":180}' },
111
+ };
112
+ const parse = (o) => parsePadbotMessage(Buffer.from(JSON.stringify(o)));
113
+
114
+ test("§7.1.3 battery, §7.1.4 e-stop / wheel lock", () => {
115
+ assert.deepEqual(parse(DOC.battery), { key: DOC.battery.id, sn: "PW1001", ts: DOC.battery.ts, event: { kind: "battery", batteryPercent: 68 } });
116
+ assert.deepEqual(parse(DOC.estop).event, { kind: "estop", emergencyStop: true, wheelLock: false });
117
+ });
118
+
119
+ test("§7.2.1 map updated, §7.2.2 position, §7.2.3 map switched", () => {
120
+ assert.deepEqual(parse(DOC.mapUpdate).event, { kind: "map-updated" });
121
+ assert.deepEqual(parse(DOC.position).event, { kind: "position", mapId: "map_001", x: 100, y: 100.1, yawDeg: 180 });
122
+ assert.deepEqual(parse(DOC.mapSwitch).event, { kind: "map-switch", mapId: "m001" });
123
+ });
124
+
125
+ test("§7.3.1 alarm, §7.3.2 patrol arrival: photos, points, pose", () => {
126
+ assert.deepEqual(parse(DOC.alarm).event, {
127
+ kind: "alarm", alarmType: "1", imageUrl: "https://img/v.png", thermalImageUrl: "https://img/t.png", temperatureC: 65, mapId: "map_001",
128
+ from: { id: "001", name: "Target Point 1" }, to: { id: "002", name: "Target Point 2" }, x: 100.3, y: 200.2, yawDeg: 180,
129
+ });
130
+ assert.deepEqual(parse(DOC.arrival).event, {
131
+ kind: "arrival", imageUrl: "https://img/v.png", thermalImageUrl: "https://img/t.png",
132
+ from: { id: "001", name: "Target Point 1" }, to: { id: "002", name: "Target Point 2" }, x: 100.4, y: 200.6, yawDeg: 180,
133
+ });
134
+ });
135
+
136
+ test("messages: m as an object is accepted; unknown type, bad JSON, no serial, bad battery = ignored; non-http photo dropped", () => {
137
+ assert.deepEqual(parse({ ...DOC.battery, m: { pt: 50 } }).event, { kind: "battery", batteryPercent: 50 });
138
+ assert.equal(parse({ ...DOC.battery, t: "9999" }), null);
139
+ assert.equal(parsePadbotMessage("{not json"), null);
140
+ assert.equal(parse({ ...DOC.battery, sn: "" }), null);
141
+ assert.equal(parse({ ...DOC.battery, m: '{"pt":140}' }), null);
142
+ assert.equal(parse({ ...DOC.battery, m: "{bad" }), null);
143
+ assert.equal(parse({ ...DOC.alarm, m: '{"bt":"3","csu":"javascript:alert(1)"}' }).event.imageUrl, null);
144
+ // No id -> a stable key from type + serial + time.
145
+ const { id, ...noId } = DOC.battery;
146
+ assert.equal(parse(noId).key, "1103:PW1001:1785312000123");
147
+ });
148
+
149
+ /* ------------------------------------------------ timing and dedupe */
150
+
151
+ test("credential refresh: 5 min before expiry; a fifth of short lives; never < 30 s or > 12 h; bad date 15 min", () => {
152
+ const now = Date.parse("2026-09-26T08:00:00Z");
153
+ const at = (min) => new Date(now + min * 60_000).toISOString();
154
+ assert.equal(mqttRefreshDelayMs(at(60), now), 55 * 60_000);
155
+ assert.equal(mqttRefreshDelayMs(at(10), now), 8 * 60_000);
156
+ assert.equal(mqttRefreshDelayMs(at(0.2), now), 30_000);
157
+ assert.equal(mqttRefreshDelayMs(at(-5), now), 30_000, "already expired: soon, not a spin");
158
+ assert.equal(mqttRefreshDelayMs(at(48 * 60), now), 12 * 3600_000);
159
+ assert.equal(mqttRefreshDelayMs("not a date", now), 15 * 60_000);
160
+ });
161
+
162
+ test("backoff: doubles from 2 s to a 5 min cap, with jitter in the upper half", () => {
163
+ assert.equal(mqttBackoffMs(0, () => 0), 1000);
164
+ assert.equal(mqttBackoffMs(0, () => 1), 2000);
165
+ assert.equal(mqttBackoffMs(3, () => 0), 8000);
166
+ assert.equal(mqttBackoffMs(50, () => 1), 300000);
167
+ assert.equal(mqttBackoffMs(50, () => 0), 150000);
168
+ });
169
+
170
+ test("dedupe: a message id is handled once; memory is bounded", () => {
171
+ const dup = createMessageDeduper(3);
172
+ assert.equal(dup("a"), false);
173
+ assert.equal(dup("a"), true);
174
+ dup("b"); dup("c"); dup("d");
175
+ assert.equal(dup("a"), false, "oldest forgotten past the bound");
176
+ });
177
+
178
+ test("flags: MQTT and alarm poll default on; manual drive default OFF (only the word on)", () => {
179
+ assert.equal(padbotMqttEnabled({}), true);
180
+ assert.equal(padbotMqttEnabled({ PADBOT_MQTT: "off" }), false);
181
+ assert.equal(padbotAlarmPollEnabled({}), true);
182
+ assert.equal(padbotAlarmPollEnabled({ PADBOT_ALARM_POLL: "OFF" }), false);
183
+ assert.equal(padbotManualDriveEnabled({}), false);
184
+ assert.equal(padbotManualDriveEnabled({ PADBOT_MANUAL_DRIVE: "true" }), false);
185
+ assert.equal(padbotManualDriveEnabled({ PADBOT_MANUAL_DRIVE: " On " }), true);
186
+ const env = process.env.PADBOT_MANUAL_DRIVE;
187
+ delete process.env.PADBOT_MANUAL_DRIVE;
188
+ assert.equal(PADBOT_CAPABILITIES.manualDrive, false, "the capability follows the flag");
189
+ process.env.PADBOT_MANUAL_DRIVE = "on";
190
+ assert.equal({ ...PADBOT_CAPABILITIES }.manualDrive, true);
191
+ if (env === undefined) delete process.env.PADBOT_MANUAL_DRIVE;
192
+ else process.env.PADBOT_MANUAL_DRIVE = env;
193
+ });
194
+
195
+ /* ------------------------------------------------- drive: limits + block */
196
+
197
+ test("drive limits: 0.3 m/s / 30 deg/s by default; env may raise to at most 0.5; head within the S2's range", () => {
198
+ const d = padbotDriveLimits({});
199
+ assert.deepEqual([d.maxLinear, d.maxAngular, d.heartbeatTimeoutMs, d.commandMaxMs], [0.3, 30, 300, 2000]);
200
+ assert.equal(padbotDriveLimits({ PADBOT_DRIVE_MAX_SPEED: "0.88" }).maxLinear, 0.5);
201
+ assert.equal(padbotDriveLimits({ PADBOT_DRIVE_MAX_SPEED: "0.01" }).maxLinear, 0.05);
202
+ assert.equal(padbotDriveLimits({ PADBOT_DRIVE_MAX_SPEED: "junk" }).maxLinear, 0.3);
203
+ assert.deepEqual(clampChassis(1, -90, d), { lv: 0.3, av: -30 });
204
+ assert.deepEqual(clampChassis("x", NaN, d), { lv: 0, av: 0 });
205
+ assert.deepEqual(headParams("pan", 120, d), { d: 2, a: 90, av: 30 });
206
+ assert.deepEqual(headParams("tilt", -40, d), { d: 1, a: -15, av: 30 });
207
+ });
208
+
209
+ test("drive block: offline, e-stop, wheel lock, lift, access door, docking, busy - and safe", () => {
210
+ const now = Date.parse("2026-09-26T08:00:00Z");
211
+ const hb = { updatedAt: new Date(now - 1000).toISOString() };
212
+ const st = (extra) => ({ "1000": hb, ...extra });
213
+ assert.match(padbotDriveBlock(null, now), /not reporting/);
214
+ assert.match(padbotDriveBlock({ "1000": { updatedAt: new Date(now - 600_000).toISOString() } }, now), /not reporting/);
215
+ assert.match(padbotDriveBlock(st({ "1006": { emergencyStopState: 1 } }), now), /emergency stop/);
216
+ assert.match(padbotDriveBlock(st({ "1006": { wheelLockState: 1 } }), now), /wheels are locked/);
217
+ for (const t of [1, 2, 3, 4, 5]) assert.match(padbotDriveBlock(st({ "1003": { actionType: t, actionState: 2 } }), now), /lift/);
218
+ for (const t of [8, 9, 10]) assert.match(padbotDriveBlock(st({ "1003": { actionType: t, actionState: 2 } }), now), /access door/);
219
+ assert.match(padbotDriveBlock(st({ "1003": { actionType: 12, actionState: 2 } }), now), /docking/);
220
+ assert.match(padbotDriveBlock(st({ "1003": { actionType: 11, actionState: 2 } }), now), /Press Cancel first/);
221
+ assert.equal(padbotDriveBlock(st({ "1003": { actionType: 11, actionState: 5 }, "1006": { emergencyStopState: 0, wheelLockState: 0 } }), now), null);
222
+ });
223
+
224
+ test("§8.1 message shape: t 1505, m = JSON string {a, m}", () => {
225
+ const m = JSON.parse(motionMessage("1001", { lv: 0.3, av: 30 }, { id: "abc", ts: 5 }));
226
+ assert.deepEqual(m, { id: "abc", t: "1505", ts: 5, m: '{"a":"1001","m":{"lv":0.3,"av":30}}' });
227
+ });
228
+
229
+ /* ------------------------------------------------------- drive watchdog */
230
+
231
+ function rig(publishOk = () => true) {
232
+ const sent = [];
233
+ const ends = [];
234
+ let n = 0;
235
+ const w = createDriveWatchdog({
236
+ limits: padbotDriveLimits({}),
237
+ newId: () => `m${++n}`,
238
+ now: () => 0,
239
+ publish: (msg) => {
240
+ const inner = JSON.parse(JSON.parse(msg).m);
241
+ sent.push(inner.a === "1001" ? `move ${inner.m.lv}/${inner.m.av}` : inner.a === "1000" ? "STOP" : inner.a);
242
+ return publishOk(inner);
243
+ },
244
+ onEnd: (r) => ends.push(r),
245
+ });
246
+ return { w, sent, ends };
247
+ }
248
+
249
+ test("watchdog: heartbeat lost (no beat for 300 ms) -> STOP x3 and the session ends", (t) => {
250
+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
251
+ const { w, sent, ends } = rig();
252
+ w.move(1, 0);
253
+ assert.deepEqual(sent, ["move 0.3/0"], "capped to 0.3 m/s");
254
+ t.mock.timers.tick(250);
255
+ w.beat();
256
+ t.mock.timers.tick(250);
257
+ assert.deepEqual(ends, [], "beats keep it alive");
258
+ t.mock.timers.tick(60);
259
+ assert.deepEqual(ends, ["heartbeat-lost"]);
260
+ t.mock.timers.tick(300);
261
+ assert.equal(sent.filter((s) => s === "STOP").length, 3, "STOP sent three times");
262
+ assert.equal(w.ended, true);
263
+ assert.equal(w.move(0.2, 0), false, "an ended session forwards nothing");
264
+ });
265
+
266
+ test("watchdog: a move lasts at most 2 s unless re-sent; chassis repeats every 500 ms meanwhile", (t) => {
267
+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
268
+ const { w, sent, ends } = rig();
269
+ w.move(0.2, 10);
270
+ for (let i = 0; i < 20; i++) {
271
+ t.mock.timers.tick(100);
272
+ w.beat();
273
+ }
274
+ assert.equal(sent.filter((s) => s === "move 0.2/10").length, 4, "initial + repeats at 500/1000/1500 ms");
275
+ assert.ok(sent.includes("STOP"), "stopped at 2 s");
276
+ assert.equal(w.moving, false);
277
+ assert.deepEqual(ends, [], "the session stays open (heartbeats kept coming)");
278
+ const before = sent.length;
279
+ t.mock.timers.tick(100);
280
+ w.beat();
281
+ t.mock.timers.tick(1000);
282
+ w.beat();
283
+ assert.ok(!sent.slice(before).some((s) => s.startsWith("move")), "no motion after the expiry");
284
+ w.end("closed");
285
+ });
286
+
287
+ test("watchdog: release = STOP; a newer move cancels the pending STOP repeats; zero move = STOP", (t) => {
288
+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
289
+ const { w, sent } = rig();
290
+ w.move(0.3, 0);
291
+ w.stop();
292
+ t.mock.timers.tick(50);
293
+ w.move(0, 30);
294
+ t.mock.timers.tick(250);
295
+ w.beat();
296
+ assert.deepEqual(sent, ["move 0.3/0", "STOP", "move 0/30"], "the +100 / +250 ms STOPs were cancelled by the new press");
297
+ w.move(0, 0);
298
+ assert.equal(sent.at(-1), "STOP");
299
+ w.end("closed");
300
+ });
301
+
302
+ test("watchdog: end (tab hidden / closed) = STOP; a failed publish ends the session as link-lost; 10 min cap", (t) => {
303
+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
304
+ const a = rig();
305
+ a.w.move(0.3, 0);
306
+ a.w.end("closed");
307
+ assert.deepEqual(a.ends, ["closed"]);
308
+ assert.equal(a.sent.at(-1), "STOP");
309
+
310
+ const b = rig((inner) => inner.a !== "1001");
311
+ b.w.move(0.3, 0);
312
+ assert.deepEqual(b.ends, ["link-lost"]);
313
+
314
+ const c = rig();
315
+ for (let i = 0; i < 6000; i++) {
316
+ c.w.beat();
317
+ t.mock.timers.tick(100);
318
+ }
319
+ assert.deepEqual(c.ends, ["time-limit"]);
320
+ assert.equal(c.sent.at(-1), "STOP");
321
+ });
322
+
323
+ test("watchdog: head moves stay inside the heartbeat-guarded session", (t) => {
324
+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
325
+ const { w, sent } = rig();
326
+ w.head("pan", 200);
327
+ w.head("reset");
328
+ w.head("stop");
329
+ assert.deepEqual(sent, ["1005", "1006", "1004"]);
330
+ w.end("closed");
331
+ });
332
+
333
+ /* ------------------------------------------- commands, alerts, texts */
334
+
335
+ test("go-to-point: parsed strictly; needs navigateToPoint; PadBot sends §5.7 with the map and point ids; reply kept for Diagnose", async () => {
336
+ assert.deepEqual(parseRobotCommand({ kind: "go-to-point", mapId: "m1", targetPointId: "t2" }), { ok: true, command: { kind: "go-to-point", mapId: "m1", targetPointId: "t2" } });
337
+ assert.equal(parseRobotCommand({ kind: "go-to-point", mapId: "m1" }).ok, false);
338
+ assert.equal(parseRobotCommand({ kind: "go-to-point", mapId: "m1", targetPointId: "t2", x: 1 }).ok, false);
339
+ assert.equal(parseRobotCommand({ kind: "go-to-point", mapId: "m 1", targetPointId: "t2" }).ok, false);
340
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "go-to-point"), true);
341
+
342
+ clearPadbotCache();
343
+ const creds = { appid: "ak", secret: "sk-never" };
344
+ const calls = [];
345
+ const fetch = async (url, init) => {
346
+ const path = new URL(url).pathname;
347
+ calls.push({ path, body: JSON.parse(init.body) });
348
+ const code = path === PADBOT_PATHS.stop ? 1009 : 0;
349
+ return { status: 200, text: async () => JSON.stringify({ code, message: code ? "robot busy" : "success", data: null }) };
350
+ };
351
+ const a = createPadbotAdapter(creds, { baseUrl: "https://pb.test", fetch });
352
+ await a.sendCommand("PS1", { kind: "go-to-point", mapId: "m1", targetPointId: "t2" });
353
+ assert.deepEqual(calls.at(-1), { path: "/api/v1/robots/actions/navigate-to-target", body: { serialNumber: "PS1", mapId: "m1", targetPointId: "t2" } });
354
+ await assert.rejects(a.sendCommand("PS1", { kind: "cancel" }), (e) => e.vendorCode === 1009 && e.vendorMessage === "robot busy");
355
+ const log = padbotCommandLog(padbotAccountKey(creds), "PS1");
356
+ assert.equal(log.length, 2);
357
+ assert.deepEqual([log[0].command, log[0].ok, log[0].vendorCode], ["cancel", false, 1009]);
358
+ assert.deepEqual([log[1].command, log[1].ok], ["go-to-point", true]);
359
+ assert.ok(!JSON.stringify(log).includes("sk-never"));
360
+ });
361
+
362
+ test("MQTT live store: a newer battery and a fresh position replace the REST read", async () => {
363
+ clearPadbotCache();
364
+ const creds = { appid: "ak2", secret: "sk2" };
365
+ const now = Date.parse("2026-09-26T08:00:00Z");
366
+ const old = new Date(now - 600_000).toISOString();
367
+ const calls = [];
368
+ const fetch = async (url, init) => {
369
+ const path = new URL(url).pathname;
370
+ calls.push(path);
371
+ const data = {
372
+ [PADBOT_PATHS.states]: [{ serialNumber: "PS1", states: [{ stateType: "1000", data: { updatedAt: new Date(now).toISOString() } }, { stateType: "1001", data: { updatedAt: old, batteryPercent: 90 } }] }],
373
+ [PADBOT_PATHS.robots]: [],
374
+ [PADBOT_PATHS.maps]: [{ mapId: "m1", width: 200, height: 100, resolution: 0.05, originX: 0, originY: 0 }],
375
+ [PADBOT_PATHS.alarms]: { items: [] },
376
+ }[path];
377
+ return { status: 200, text: async () => JSON.stringify({ code: 0, data: data ?? null }) };
378
+ };
379
+ recordPadbotLive(padbotAccountKey(creds), "PS1", { batteryPercent: 55, batteryAt: now - 1000, pose: { mapId: "m1", x: 5, y: 2.5, yawDeg: 90, at: now - 2000 } });
380
+ const r = await createPadbotAdapter(creds, { baseUrl: "https://pb.test", fetch, now: () => now }).getRobot("PS1");
381
+ assert.equal(r.batteryPercent, 55);
382
+ assert.deepEqual(r.planPosition, { x: 50, y: 50 });
383
+ assert.ok(!calls.includes(PADBOT_PATHS.location), "no REST location read while the MQTT pose is fresh");
384
+ });
385
+
386
+ test("alarm fault carries the robot's photos; notice titles are plain words with the floor", () => {
387
+ const f = padbotAlarmFault({ alarmType: "3", occurredAt: "2026-09-26T07:00:00.000Z", toPointName: "Lobby", visibleLightImageUrl: "https://i/v.png", thermalImageUrl: "ftp://x" });
388
+ assert.equal(f.imageUrl, "https://i/v.png");
389
+ assert.equal(f.thermalImageUrl, null);
390
+ assert.deepEqual(robotFaultText("HERO-OTH-SECURITY", { code: "ALARM-3", message: f.message, floorNo: 3 }), {
391
+ title: "Smoke detected by HERO-OTH-SECURITY on L3",
392
+ body: "HERO-OTH-SECURITY reports: smoke detected near Lobby on L3. Open the robot for the photo and live view.",
393
+ });
394
+ assert.equal(robotFaultText("R1", { code: "ALARM-1", message: "Person detected" }).title, "Person detected by R1");
395
+ assert.equal(robotFaultText("R1", { code: "E-STOP", message: "x", floorNo: -1 }).title, "Emergency stop pressed on R1");
396
+ assert.equal(robotFaultText("R1", { code: "E-STOP", message: "x", floorNo: -1 }).body, "R1 on B1 cannot move until its emergency stop button is released.");
397
+ assert.deepEqual([floorWord(1), floorWord(0), floorWord(-2)], ["L1", "G", "B2"]);
398
+ assert.equal(robotFaultText("R1", { code: "BRUSH", message: "Brush stuck" }).title, "Robot fault");
399
+ });
@@ -139,7 +139,7 @@ test("diagnose: PadBot's raw answers per read (code, message, data); maps summar
139
139
  [PADBOT_PATHS.records]: () => ({ items: [], totalItems: 0 }),
140
140
  });
141
141
  const steps = await createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: () => NOW }).diagnose("PS8517");
142
- assert.deepEqual(steps.map((s) => s.step), ["states (4.2)", "location (4.3)", "maps (5.1)", "patrol routes (6.1)", "alarms (6.4)", "patrol records (6.7)"]);
142
+ assert.deepEqual(steps.map((s) => s.step), ["states (4.2)", "location (4.3)", "maps (5.1)", "patrol routes (6.1)", "alarms (6.4)", "patrol records (6.7)", "recent commands (this server)"]);
143
143
  const loc = steps[1];
144
144
  assert.equal(loc.code, 1008);
145
145
  assert.equal(loc.message, "Failed to retrieve data");
@@ -271,8 +271,8 @@ test("alarm -> fault: one code per type, plain words, since = when it happened,
271
271
  }
272
272
  assert.equal(padbotAlarmFault(null), null);
273
273
  assert.equal(padbotAlarmFault({ alarmType: "99" }).message, "Alarm type 99");
274
- assert.equal(robotFaultText("PB-1", { code: "ALARM-3", message: "Smoke detected near Lobby" }).title, "Robot alert");
275
- assert.equal(robotFaultText("PB-1", { code: "E-STOP", message: "x" }).title, "Robot fault");
274
+ assert.equal(robotFaultText("PB-1", { code: "ALARM-3", message: "Smoke detected near Lobby" }).title, "Smoke detected by PB-1");
275
+ assert.equal(robotFaultText("PB-1", { code: "E-STOP", message: "x" }).title, "Emergency stop pressed on PB-1");
276
276
  });
277
277
 
278
278
  test("alarm dedupe: the same alarm on every read opens once; a new occurrence re-opens; resolved clears", () => {
@@ -282,13 +282,13 @@ test("alarm dedupe: the same alarm on every read opens once; a new occurrence re
282
282
  assert.equal(first.open.length, 1);
283
283
  const rec = { _id: "r1", code: f.code, since: new Date(f.since) };
284
284
  const again = planFaultChanges([rec], { ok: true, online: true, fault: padbotAlarmFault(alarm) });
285
- assert.deepEqual(again, { open: [], clear: [] });
285
+ assert.deepEqual(again, { open: [], clear: [], refresh: [] });
286
286
  const later = padbotAlarmFault({ alarmType: "3", occurredAt: "2026-07-25T09:04:17.010Z" });
287
287
  const second = planFaultChanges([rec], { ok: true, online: true, fault: later });
288
288
  assert.deepEqual(second.clear, ["r1"]);
289
289
  assert.equal(second.open.length, 1);
290
290
  const resolved = planFaultChanges([rec], { ok: true, online: true, fault: null });
291
- assert.deepEqual(resolved, { open: [], clear: ["r1"] });
291
+ assert.deepEqual(resolved, { open: [], clear: ["r1"], refresh: [] });
292
292
  });
293
293
 
294
294
  /* ------------------------------------------------------ patrol */
@@ -50,14 +50,14 @@ const rec = (code, since = 1000, _id = code) => ({ _id, code, since: new Date(si
50
50
 
51
51
  test("plan: a new fault opens; the same fault on every read changes nothing", () => {
52
52
  const fault = { code: "JAM", message: "Brush jammed", since: 1000 };
53
- assert.deepEqual(planFaultChanges([], { ok: true, online: true, fault }), { open: [fault], clear: [] });
54
- assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault }), { open: [], clear: [] });
53
+ assert.deepEqual(planFaultChanges([], { ok: true, online: true, fault }), { open: [fault], clear: [], refresh: [] });
54
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault }), { open: [], clear: [], refresh: [] });
55
55
  // a brand that cannot say when it started: the open record stands
56
- assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: { code: "JAM" } }), { open: [], clear: [] });
56
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: { code: "JAM" } }), { open: [], clear: [], refresh: [] });
57
57
  });
58
58
 
59
59
  test("plan: a fault that goes away is cleared; coming back later is a new occurrence", () => {
60
- assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: null }), { open: [], clear: ["JAM"] });
60
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: null }), { open: [], clear: ["JAM"], refresh: [] });
61
61
  const again = planFaultChanges([rec("JAM", 1000)], { ok: true, online: true, fault: { code: "JAM", message: "m", since: 90000 } });
62
62
  assert.deepEqual(again.clear, ["JAM"]);
63
63
  assert.equal(again.open[0].code, "JAM");
@@ -74,7 +74,7 @@ test("plan: offline / not reporting is an OFFLINE record; a failed read cannot c
74
74
  const back = planFaultChanges([rec(OFFLINE_FAULT_CODE), rec("JAM")], { ok: true, online: true, fault: null });
75
75
  assert.deepEqual(back.clear.sort(), ["JAM", OFFLINE_FAULT_CODE].sort());
76
76
  // still offline: nothing new
77
- assert.deepEqual(planFaultChanges([rec(OFFLINE_FAULT_CODE)], { ok: true, online: false }), { open: [], clear: [] });
77
+ assert.deepEqual(planFaultChanges([rec(OFFLINE_FAULT_CODE)], { ok: true, online: false }), { open: [], clear: [], refresh: [] });
78
78
  // going offline does NOT clear the robot's own fault (it would re-notify on return)
79
79
  const wentOff = planFaultChanges([rec("JAM")], { ok: true, online: false, fault: null });
80
80
  assert.deepEqual(wentOff.clear, []);
@@ -117,3 +117,24 @@ test("bounded: never more than the limit in flight, one failure does not stop th
117
117
  await assert.rejects(withTimeout(new Promise(() => {}), 20, "slow"), /slow after 20 ms/);
118
118
  assert.equal(await withTimeout(Promise.resolve(7), 20), 7);
119
119
  });
120
+
121
+ test("plan: a still-open OFFLINE record takes the LATEST failed read's reason, without re-opening", () => {
122
+ // HERO-OTH: the record opened with "ROBOT_CLOUD_BASE_URL is not configured"
123
+ // and kept saying so after the base URL was fixed and the robot failed for a
124
+ // different reason.
125
+ const stale = { ...rec(OFFLINE_FAULT_CODE), message: "Not reporting: Robot cloud: ROBOT_CLOUD_BASE_URL is not configured." };
126
+ const plan = planFaultChanges([stale], { ok: false, error: "Ounitech rejected the robot list (sign-in) (sign error)." });
127
+ assert.deepEqual(plan.open, [], "no second record, so no second alert and the same since");
128
+ assert.deepEqual(plan.clear, []);
129
+ assert.deepEqual(plan.refresh, [
130
+ { id: OFFLINE_FAULT_CODE, message: "Not reporting: Ounitech rejected the robot list (sign-in) (sign error)." },
131
+ ]);
132
+
133
+ // Same reason: nothing to rewrite. A record read without its message: nothing either.
134
+ const same = { ...stale, message: plan.refresh[0].message };
135
+ assert.deepEqual(planFaultChanges([same], { ok: false, error: "Ounitech rejected the robot list (sign-in) (sign error)." }).refresh, []);
136
+ assert.deepEqual(planFaultChanges([rec(OFFLINE_FAULT_CODE)], { ok: false, error: "x" }).refresh, []);
137
+ // A machine fault's message is the robot's own and is never rewritten here.
138
+ const jam = { ...rec("JAM"), message: "old" };
139
+ assert.deepEqual(planFaultChanges([jam], { ok: true, online: true, fault: { code: "JAM", message: "new", since: 1000 } }).refresh, []);
140
+ });
@@ -287,3 +287,37 @@ test("diagnose: an unknown brand is named, not thrown", async () => {
287
287
  const d = await fleetFor("ok").diagnose(robotRow({ brand: "nobody" }));
288
288
  assert.equal(d.failedStep, "brand");
289
289
  });
290
+
291
+ /* ------------------------------------------- base URL with the env unset */
292
+
293
+ import { execFileSync } from "node:child_process";
294
+
295
+ test("with OUNITECH_API_BASE and ROBOT_CLOUD_BASE_URL unset (or blank), the Ounitech host is the default and nothing throws", () => {
296
+ const script = `
297
+ const { ROBOT_CLOUD_BASE_URL } = await import("./test/.build/config.mjs");
298
+ const { useRobotCloudService } = await import("./test/.build/services/robot-cloud.service.mjs");
299
+ useRobotCloudService({ appid: "a", secret: "s" }); // threw "not configured" when the base was empty
300
+ console.log(ROBOT_CLOUD_BASE_URL);`;
301
+ for (const extra of [{}, { OUNITECH_API_BASE: "", ROBOT_CLOUD_BASE_URL: "" }]) {
302
+ const env = { ...process.env, ...extra };
303
+ if (!("OUNITECH_API_BASE" in extra)) {
304
+ delete env.OUNITECH_API_BASE;
305
+ delete env.ROBOT_CLOUD_BASE_URL;
306
+ }
307
+ const out = execFileSync(process.execPath, ["--input-type=module", "-e", script], { env, encoding: "utf8" }).trim();
308
+ assert.equal(out.split("\n").pop(), "https://app.frankfurt.robotcloud.top", JSON.stringify(extra));
309
+ }
310
+ });
311
+
312
+ test("a missing base URL (only reachable by passing an empty one) is a handled 502, never a 500", () => {
313
+ let e;
314
+ try {
315
+ useRobotCloudService(CREDS, { baseUrl: "" });
316
+ } catch (err) {
317
+ e = err;
318
+ }
319
+ assert.ok(e instanceof RobotCloudError);
320
+ const answer = apiAnswer(e);
321
+ assert.equal(answer.status, 502);
322
+ assert.match(answer.body.message, /not configured/);
323
+ });