@7365admin1/core 3.117.1 → 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.
- package/CHANGELOG.md +12 -0
- package/dist/index.d.ts +494 -27
- package/dist/index.js +4256 -2909
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4112 -2813
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/test/e2e/harness.mjs +6 -0
- package/test/e2e/padbot-mqtt.e2e.test.mjs +419 -0
- package/test/notification-category.util.test.mjs +3 -2
- package/test/padbot-mqtt.test.mjs +399 -0
- package/test/padbot-real-data.test.mjs +1 -1
- package/test/padbot.test.mjs +2 -2
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@7365admin1/core",
|
|
3
3
|
"license": "MIT",
|
|
4
|
-
"version": "3.
|
|
4
|
+
"version": "3.118.0",
|
|
5
5
|
"author": "7365admin1",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist/index.mjs",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"build": "tsup src/index.ts --format cjs,esm --dts && shx cp -r src/public dist && shx cp -r src/utils/handlebars dist",
|
|
14
14
|
"release": "yarn run build && changeset publish",
|
|
15
15
|
"lint": "tsc",
|
|
16
|
-
"test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/services/ounitech.adapter.ts src/services/robot-cloud.service.ts src/services/robot-fleet.service.ts src/services/padbot.adapter.ts src/utils/padbot-sign.util.ts src/services/open-rmf.adapter.ts src/utils/robot-credentials.util.ts src/utils/rmf-building.util.ts src/utils/door-contract.util.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/site-owner-edit.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/notification-kind.util.ts src/utils/notification-email.util.ts src/models/notification.model.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts src/utils/customer-site-list.util.ts src/utils/org-search.util.ts src/utils/invite-origin.util.ts src/utils/member-role-assign.util.ts src/utils/cross-site-role.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
|
|
16
|
+
"test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/services/ounitech.adapter.ts src/services/robot-cloud.service.ts src/services/robot-fleet.service.ts src/services/padbot.adapter.ts src/utils/padbot-sign.util.ts src/utils/padbot-mqtt.util.ts src/services/open-rmf.adapter.ts src/utils/robot-credentials.util.ts src/utils/rmf-building.util.ts src/utils/door-contract.util.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/site-owner-edit.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/notification-kind.util.ts src/utils/notification-email.util.ts src/models/notification.model.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts src/utils/customer-site-list.util.ts src/utils/org-search.util.ts src/utils/invite-origin.util.ts src/utils/member-role-assign.util.ts src/utils/cross-site-role.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
|
|
17
17
|
"test:camera": "yarn test",
|
|
18
18
|
"test:e2e": "yarn build && node --test --test-concurrency=1 --test-timeout=600000 \"test/e2e/*.test.mjs\""
|
|
19
19
|
},
|
package/test/e2e/harness.mjs
CHANGED
|
@@ -960,6 +960,10 @@ function buildApp(nsu, core) {
|
|
|
960
960
|
robots.post("/:id([0-9a-fA-F]{24})/alerts/resolve", requireAuth, f.resolveAlerts);
|
|
961
961
|
robots.get("/:id([0-9a-fA-F]{24})/patrol-history", requireAuth, f.getPatrolHistory);
|
|
962
962
|
robots.get("/:id([0-9a-fA-F]{24})/patrol-history/:recordId", requireAuth, f.getPatrolVisits);
|
|
963
|
+
// PadBot live position stream (MQTT push + REST fallback) and manual control.
|
|
964
|
+
robots.get("/:id([0-9a-fA-F]{24})/track", requireAuth, f.trackRobot);
|
|
965
|
+
robots.post("/:id([0-9a-fA-F]{24})/drive", requireAuth, f.startDrive);
|
|
966
|
+
robots.post("/:id([0-9a-fA-F]{24})/drive/:session", requireAuth, f.driveSignal);
|
|
963
967
|
}
|
|
964
968
|
|
|
965
969
|
// mirrors iservice365-API-core/src/routes/attendance-settings.route.ts
|
|
@@ -1832,6 +1836,8 @@ export async function startHarness() {
|
|
|
1832
1836
|
redisDel,
|
|
1833
1837
|
mails: mail.messages,
|
|
1834
1838
|
pushes,
|
|
1839
|
+
base,
|
|
1840
|
+
nsu,
|
|
1835
1841
|
hashPassword: nsu.hashPassword,
|
|
1836
1842
|
stop,
|
|
1837
1843
|
};
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
// End-to-end: the PadBot live feed and manual control against a LOCAL mock
|
|
2
|
+
// MQTT broker over TLS (self-signed CA made for this run) and a local mock
|
|
3
|
+
// PadBot REST API. Nothing leaves the machine; no real PadBot is contacted.
|
|
4
|
+
//
|
|
5
|
+
// - TLS is verified: without our test CA the link never connects;
|
|
6
|
+
// - CONNECT carries the credential API's clientId / username / token; the
|
|
7
|
+
// client subscribes to exactly our robot's robotPubTopic (no wildcard,
|
|
8
|
+
// not the other robot on the account);
|
|
9
|
+
// - battery / position messages reach /state and the /track stream at once;
|
|
10
|
+
// a duplicated message id is ignored;
|
|
11
|
+
// - an MQTT alarm triggers the alarm read; ONE notice per occurrence to the
|
|
12
|
+
// site's staff with robot rights (not to others), across a restart;
|
|
13
|
+
// - a dropped link reconnects with fresh credentials;
|
|
14
|
+
// - manual control: off by default, blocked on e-stop, capped speed on the
|
|
15
|
+
// robot's robotSubTopic, STOP x3 when the heartbeat stops, audited;
|
|
16
|
+
// - no credential in any log line.
|
|
17
|
+
//
|
|
18
|
+
// Run with: yarn test:e2e
|
|
19
|
+
|
|
20
|
+
import { after, before, describe, it } from "node:test";
|
|
21
|
+
import assert from "node:assert/strict";
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { execFileSync } from "node:child_process";
|
|
24
|
+
import { mkdtempSync, readFileSync } from "node:fs";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import tls from "node:tls";
|
|
28
|
+
import { ObjectId } from "mongodb";
|
|
29
|
+
|
|
30
|
+
import { startHarness } from "./harness.mjs";
|
|
31
|
+
|
|
32
|
+
const PASSWORD = "Robot-Passw0rd!";
|
|
33
|
+
const MANAGER = "pbm-manager@e2e.example.com";
|
|
34
|
+
const GUARD = "pbm-guard@e2e.example.com";
|
|
35
|
+
const AK = "e2e-mqtt-access-key";
|
|
36
|
+
const SK = "e2e-mqtt-secret"; // mock only
|
|
37
|
+
const MQTT_USER = "Token|LTAI-e2e-user|post-cn-e2e";
|
|
38
|
+
const MQTT_TOKEN = "R|e2e-temporary-token-value";
|
|
39
|
+
const PUB = "robot-open/e2e/PS0001";
|
|
40
|
+
const SUB = "robot-topic/e2e/PS0001";
|
|
41
|
+
|
|
42
|
+
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
43
|
+
async function until(check, ms = 8000, step = 50) {
|
|
44
|
+
const end = Date.now() + ms;
|
|
45
|
+
for (;;) {
|
|
46
|
+
const v = await check();
|
|
47
|
+
if (v) return v;
|
|
48
|
+
if (Date.now() > end) throw new Error("timed out waiting");
|
|
49
|
+
await wait(step);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function makeCert() {
|
|
54
|
+
const dir = mkdtempSync(join(tmpdir(), "pbmqtt-"));
|
|
55
|
+
const key = join(dir, "key.pem");
|
|
56
|
+
const cert = join(dir, "cert.pem");
|
|
57
|
+
execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", cert, "-days", "2", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"], { stdio: "ignore" });
|
|
58
|
+
return { key: readFileSync(key), cert: readFileSync(cert) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A minimal MQTT 3.1.1 broker over TLS: CONNACK, SUBACK, PINGRESP, fan-out, and a record of everything. */
|
|
62
|
+
function startBroker(core, pem) {
|
|
63
|
+
const b = { connects: [], subscribes: [], published: [], sockets: new Set() };
|
|
64
|
+
const server = tls.createServer({ key: pem.key, cert: pem.cert, minVersion: "TLSv1.2" }, (s) => {
|
|
65
|
+
b.sockets.add(s);
|
|
66
|
+
s.subs = [];
|
|
67
|
+
const read = core.createMqttReader();
|
|
68
|
+
s.on("data", (chunk) => {
|
|
69
|
+
for (const p of read(chunk)) {
|
|
70
|
+
if (p.type === 1) {
|
|
71
|
+
const body = p.body;
|
|
72
|
+
let o = 10;
|
|
73
|
+
const str = () => {
|
|
74
|
+
const n = body.readUInt16BE(o);
|
|
75
|
+
const v = body.subarray(o + 2, o + 2 + n).toString();
|
|
76
|
+
o += 2 + n;
|
|
77
|
+
return v;
|
|
78
|
+
};
|
|
79
|
+
const flags = body[7];
|
|
80
|
+
const clientId = str();
|
|
81
|
+
const username = flags & 0x80 ? str() : null;
|
|
82
|
+
const password = flags & 0x40 ? str() : null;
|
|
83
|
+
b.connects.push({ clientId, username, password, keepAlive: body.readUInt16BE(8), level: body[6] });
|
|
84
|
+
s.write(Buffer.from([0x20, 2, 0, 0]));
|
|
85
|
+
} else if (p.type === 8) {
|
|
86
|
+
const pid = p.body.readUInt16BE(0);
|
|
87
|
+
let o = 2;
|
|
88
|
+
const topics = [];
|
|
89
|
+
while (o < p.body.length) {
|
|
90
|
+
const n = p.body.readUInt16BE(o);
|
|
91
|
+
topics.push({ topic: p.body.subarray(o + 2, o + 2 + n).toString(), qos: p.body[o + 2 + n] });
|
|
92
|
+
o += 3 + n;
|
|
93
|
+
}
|
|
94
|
+
s.subs.push(...topics.map((t) => t.topic));
|
|
95
|
+
b.subscribes.push(topics);
|
|
96
|
+
s.write(Buffer.from([0x90, 2 + topics.length, pid >> 8, pid & 255, ...topics.map(() => 0)]));
|
|
97
|
+
} else if (p.type === 3) {
|
|
98
|
+
const d = core.decodePublish(p);
|
|
99
|
+
const msg = JSON.parse(d.payload.toString());
|
|
100
|
+
b.published.push({ topic: d.topic, qos: d.qos, msg, inner: JSON.parse(msg.m), at: Date.now() });
|
|
101
|
+
} else if (p.type === 12) {
|
|
102
|
+
s.write(Buffer.from([0xd0, 0]));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
s.on("close", () => b.sockets.delete(s));
|
|
107
|
+
s.on("error", () => undefined);
|
|
108
|
+
});
|
|
109
|
+
server.on("tlsClientError", () => (b.tlsErrors = (b.tlsErrors ?? 0) + 1));
|
|
110
|
+
b.publish = (topic, obj) => {
|
|
111
|
+
for (const s of b.sockets) if (s.subs.includes(topic)) s.write(core.encodePublish(topic, JSON.stringify(obj)));
|
|
112
|
+
};
|
|
113
|
+
b.kick = () => {
|
|
114
|
+
for (const s of b.sockets) s.destroy();
|
|
115
|
+
};
|
|
116
|
+
return new Promise((r) => server.listen(0, "127.0.0.1", () => r(Object.assign(b, { server, port: server.address().port }))));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function startMockPadbot(brokerPort) {
|
|
120
|
+
const now = () => new Date().toISOString();
|
|
121
|
+
const state = {
|
|
122
|
+
estop: 0,
|
|
123
|
+
nav: { actionType: 0, actionState: 0 },
|
|
124
|
+
alarms: [],
|
|
125
|
+
credentialCalls: 0,
|
|
126
|
+
};
|
|
127
|
+
const data = {
|
|
128
|
+
"/api/v1/robots/list": () => [{ serialNumber: "PS0001", robotName: "Patrol 1", robotType: "PATROL", robotModel: "S2" }],
|
|
129
|
+
"/api/v1/robots/states/list": (b) =>
|
|
130
|
+
(b.serialNumbers ?? []).map((sn) => ({
|
|
131
|
+
serialNumber: sn,
|
|
132
|
+
states: [
|
|
133
|
+
{ stateType: "1000", data: { updatedAt: now() } },
|
|
134
|
+
{ stateType: "1001", data: { updatedAt: new Date(Date.now() - 600_000).toISOString(), batteryPercent: 90 } },
|
|
135
|
+
{ stateType: "1003", data: { updatedAt: now(), ...state.nav } },
|
|
136
|
+
{ stateType: "1006", data: { updatedAt: now(), emergencyStopState: state.estop, wheelLockState: 0 } },
|
|
137
|
+
{ stateType: "1007", data: { updatedAt: now(), mapId: "m1", floor: 3 } },
|
|
138
|
+
],
|
|
139
|
+
})),
|
|
140
|
+
"/api/v1/robots/location/get": () => ({ mapId: "m1", worldX: 1, worldY: 1, yaw: 0 }),
|
|
141
|
+
"/api/v1/robots/maps/list": () => [{ mapId: "m1", floor: 3, width: 200, height: 100, resolution: 0.05, originX: 0, originY: 0, targetPoints: [] }],
|
|
142
|
+
"/api/v1/robots/patrol/alarms/page": (b) => {
|
|
143
|
+
const items = state.alarms.filter((a) => (!b.startTime || a.occurredAt >= b.startTime) && (b.resolved === undefined || b.resolved === false));
|
|
144
|
+
return { items, totalItems: items.length, totalPages: items.length ? 1 : 0 };
|
|
145
|
+
},
|
|
146
|
+
"/api/v1/robots/mqtt/credentials": () => {
|
|
147
|
+
state.credentialCalls++;
|
|
148
|
+
return {
|
|
149
|
+
clientId: `GID_Robot_Open@@@e2e${state.credentialCalls}`,
|
|
150
|
+
username: MQTT_USER,
|
|
151
|
+
token: MQTT_TOKEN,
|
|
152
|
+
expiresAt: new Date(Date.now() + 3600_000).toISOString(),
|
|
153
|
+
port: brokerPort,
|
|
154
|
+
host: "localhost",
|
|
155
|
+
robotMqttInfoList: [
|
|
156
|
+
{ serialNumber: "PS0001", robotPubTopic: PUB, robotSubTopic: SUB },
|
|
157
|
+
{ serialNumber: "PS9999", robotPubTopic: "robot-open/e2e/PS9999", robotSubTopic: "robot-topic/e2e/PS9999" },
|
|
158
|
+
],
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
const server = createServer((req, res) => {
|
|
163
|
+
let raw = "";
|
|
164
|
+
req.on("data", (c) => (raw += c));
|
|
165
|
+
req.on("end", () => {
|
|
166
|
+
const hit = data[req.url];
|
|
167
|
+
res.writeHead(hit ? 200 : 404, { "Content-Type": "application/json" });
|
|
168
|
+
res.end(hit ? JSON.stringify({ code: 0, message: "success", data: hit(raw ? JSON.parse(raw) : {}) ?? null }) : "");
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
return new Promise((r) => server.listen(0, "127.0.0.1", () => r({ server, state, url: `http://127.0.0.1:${server.address().port}` })));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** First SSE event from /track matching `pick`. */
|
|
175
|
+
async function trackUntil(h, id, sid, pick, ms = 8000) {
|
|
176
|
+
const ctrl = new AbortController();
|
|
177
|
+
const res = await fetch(`${h.base}/robots/${id}/track`, { headers: { authorization: `Bearer ${sid}` }, signal: ctrl.signal });
|
|
178
|
+
const reader = res.body.getReader();
|
|
179
|
+
const dec = new TextDecoder();
|
|
180
|
+
let buf = "";
|
|
181
|
+
const timer = setTimeout(() => ctrl.abort(), ms);
|
|
182
|
+
try {
|
|
183
|
+
for (;;) {
|
|
184
|
+
const { done, value } = await reader.read();
|
|
185
|
+
if (done) return null;
|
|
186
|
+
buf += dec.decode(value, { stream: true });
|
|
187
|
+
const frames = buf.split("\n\n");
|
|
188
|
+
buf = frames.pop();
|
|
189
|
+
for (const f of frames) {
|
|
190
|
+
const line = f.split("\n").find((l) => l.startsWith("data:"));
|
|
191
|
+
if (!line) continue;
|
|
192
|
+
const ev = JSON.parse(line.slice(5));
|
|
193
|
+
if (pick(ev)) return ev;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
} catch {
|
|
197
|
+
return null;
|
|
198
|
+
} finally {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
ctrl.abort();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let pem = null;
|
|
205
|
+
try {
|
|
206
|
+
pem = makeCert();
|
|
207
|
+
} catch {
|
|
208
|
+
pem = null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
describe("PadBot live feed (MQTT over TLS) and manual control", { concurrency: 1, skip: pem ? false : "openssl not available" }, () => {
|
|
212
|
+
let h, broker, mock, feed;
|
|
213
|
+
const id = {};
|
|
214
|
+
let managerSid, guardSid;
|
|
215
|
+
const logs = [];
|
|
216
|
+
let restoreLog;
|
|
217
|
+
|
|
218
|
+
before(async () => {
|
|
219
|
+
h = await startHarness();
|
|
220
|
+
broker = await startBroker(h.core, pem);
|
|
221
|
+
mock = await startMockPadbot(broker.port);
|
|
222
|
+
process.env.PADBOT_API_BASE = mock.url;
|
|
223
|
+
h.core.clearPadbotCache();
|
|
224
|
+
const orig = h.nsu.logger.log.bind(h.nsu.logger);
|
|
225
|
+
h.nsu.logger.log = (entry) => {
|
|
226
|
+
logs.push(JSON.stringify(entry));
|
|
227
|
+
return orig(entry);
|
|
228
|
+
};
|
|
229
|
+
restoreLog = () => (h.nsu.logger.log = orig);
|
|
230
|
+
Object.assign(id, await seed(h));
|
|
231
|
+
managerSid = await h.login(MANAGER, PASSWORD);
|
|
232
|
+
guardSid = await h.login(GUARD, PASSWORD);
|
|
233
|
+
}, { timeout: 300000 });
|
|
234
|
+
|
|
235
|
+
after(async () => {
|
|
236
|
+
feed?.stop();
|
|
237
|
+
h?.core.endAllPadbotDrives?.();
|
|
238
|
+
restoreLog?.();
|
|
239
|
+
delete process.env.PADBOT_API_BASE;
|
|
240
|
+
delete process.env.PADBOT_MANUAL_DRIVE;
|
|
241
|
+
broker?.server.close();
|
|
242
|
+
mock?.server.close();
|
|
243
|
+
if (h) await h.stop();
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it("TLS is verified: without our test CA the client never gets as far as CONNECT", async () => {
|
|
247
|
+
const f = h.core.startPadbotLiveFeed({ firstSyncMs: 0, syncMs: 3600_000, rand: () => 0 });
|
|
248
|
+
await until(() => mock.state.credentialCalls >= 1);
|
|
249
|
+
await wait(1500);
|
|
250
|
+
assert.equal(broker.connects.length, 0, "an untrusted certificate is refused");
|
|
251
|
+
f.stop();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("connects with the credential API's clientId / username / token and subscribes to exactly our robot's topic", async () => {
|
|
255
|
+
feed = h.core.startPadbotLiveFeed({ firstSyncMs: 0, syncMs: 3600_000, rand: () => 0, tlsOptions: { ca: pem.cert } });
|
|
256
|
+
await until(() => broker.subscribes.length >= 1);
|
|
257
|
+
const c = broker.connects.at(-1);
|
|
258
|
+
assert.equal(c.level, 4);
|
|
259
|
+
assert.equal(c.username, MQTT_USER);
|
|
260
|
+
assert.equal(c.password, MQTT_TOKEN);
|
|
261
|
+
assert.match(c.clientId, /^GID_Robot_Open@@@e2e\d$/);
|
|
262
|
+
assert.deepEqual(broker.subscribes.at(-1), [{ topic: PUB, qos: 0 }], "one topic, ours, no wildcard");
|
|
263
|
+
assert.equal(h.core.padbotLinkUp(String(id.robot)), true);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("battery over MQTT beats the older REST reading; a repeated message id is ignored", async () => {
|
|
267
|
+
broker.publish(PUB, { id: "b1", t: "1103", ts: Date.now(), sn: "PS0001", m: '{"pt":55}' });
|
|
268
|
+
broker.publish(PUB, { id: "b1", t: "1103", ts: Date.now(), sn: "PS0001", m: '{"pt":11}' });
|
|
269
|
+
broker.publish(PUB, { id: "x1", t: "1103", ts: Date.now(), sn: "PS9999", m: '{"pt":1}' });
|
|
270
|
+
await wait(300);
|
|
271
|
+
const s = await h.api(`/robots/${id.robot}/state`, { sid: managerSid });
|
|
272
|
+
assert.equal(s.status, 200, JSON.stringify(s.body));
|
|
273
|
+
assert.equal(s.body.batteryPercent, 55);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("a position over MQTT reaches the /track stream at once (not the 1,1 REST reading)", async () => {
|
|
277
|
+
const got = trackUntil(h, id.robot, managerSid, (ev) => ev.type === "pose" && ev.pose.x === 5);
|
|
278
|
+
await wait(400);
|
|
279
|
+
const sentAt = Date.now();
|
|
280
|
+
broker.publish(PUB, { id: "p1", t: "1200", ts: Date.now(), sn: "PS0001", m: '{"mi":"m1","worldX":5,"worldY":2.5,"r":90}' });
|
|
281
|
+
const ev = await got;
|
|
282
|
+
assert.ok(ev, "pose event arrived");
|
|
283
|
+
assert.deepEqual(ev.planPosition, { x: 50, y: 50 });
|
|
284
|
+
assert.equal(Math.round((ev.pose.theta * 180) / Math.PI), 90);
|
|
285
|
+
assert.ok(Date.now() - sentAt < 2000, "pushed, not waiting for a poll");
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("an MQTT alarm triggers the alarm read: one notice to the site's robot staff, none to others, once per occurrence (also after a restart)", async () => {
|
|
289
|
+
mock.state.alarms.push({ alarmId: "a1", serialNumber: "PS0001", alarmType: "3", occurredAt: new Date().toISOString(), toPointName: "Lobby", visibleLightImageUrl: "https://img.mock/a1.png" });
|
|
290
|
+
broker.publish(PUB, { id: "al1", t: "1123", ts: Date.now(), sn: "PS0001", m: '{"bt":"3","tn":"Lobby","csu":"https://img.mock/a1.png"}' });
|
|
291
|
+
const rows = () => h.db.collection("notifications").find({ module: "robotAlert" }).toArray();
|
|
292
|
+
const got = await until(async () => ((await rows()).length ? rows() : null));
|
|
293
|
+
assert.equal(got.length, 1);
|
|
294
|
+
assert.equal(String(got[0].userId), String(id.manager));
|
|
295
|
+
assert.equal(got[0].title, "Smoke detected by Lobby patrol on L3");
|
|
296
|
+
assert.match(got[0].body, /near Lobby/);
|
|
297
|
+
assert.equal(got[0].params.id, String(id.robot));
|
|
298
|
+
assert.equal(got[0].params.imageUrl, "https://img.mock/a1.png");
|
|
299
|
+
const fault = await h.db.collection("robot-faults").findOne({ code: "ALARM-3", clearedAt: null });
|
|
300
|
+
assert.ok(fault, "an open robot-faults record");
|
|
301
|
+
|
|
302
|
+
assert.equal(await feed.pollAlarms(), 0, "the same alarm id is not processed twice");
|
|
303
|
+
feed.stop();
|
|
304
|
+
feed = h.core.startPadbotLiveFeed({ firstSyncMs: 0, syncMs: 3600_000, rand: () => 0, tlsOptions: { ca: pem.cert } });
|
|
305
|
+
await until(() => broker.subscribes.length >= 2);
|
|
306
|
+
await feed.pollAlarms();
|
|
307
|
+
assert.equal((await rows()).length, 1, "a restarted server does not announce it again (robot-faults decides)");
|
|
308
|
+
assert.equal((await h.db.collection("notifications").find({ userId: String(id.guard) }).toArray()).length + (await h.db.collection("notifications").find({ userId: id.guard }).toArray()).length, 0, "a guard without robot rights gets nothing");
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it("a dropped link reconnects with fresh credentials and re-subscribes", async () => {
|
|
312
|
+
const calls = mock.state.credentialCalls;
|
|
313
|
+
const subs = broker.subscribes.length;
|
|
314
|
+
broker.kick();
|
|
315
|
+
await until(() => broker.subscribes.length > subs, 10000);
|
|
316
|
+
assert.ok(mock.state.credentialCalls > calls, "new credentials fetched for the new connection");
|
|
317
|
+
assert.deepEqual(broker.subscribes.at(-1), [{ topic: PUB, qos: 0 }]);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("manual control is off by default", async () => {
|
|
321
|
+
delete process.env.PADBOT_MANUAL_DRIVE;
|
|
322
|
+
const r = await h.api(`/robots/${id.robot}/drive`, { method: "POST", sid: managerSid, body: { action: "start" } });
|
|
323
|
+
assert.equal(r.status, 400);
|
|
324
|
+
assert.match(r.body.message, /switched off/);
|
|
325
|
+
const s = await h.api(`/robots/${id.robot}/state`, { sid: managerSid });
|
|
326
|
+
assert.equal(s.body.capabilities.manualDrive, false);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("manual control refuses to start while the emergency stop is pressed", async () => {
|
|
330
|
+
process.env.PADBOT_MANUAL_DRIVE = "on";
|
|
331
|
+
mock.state.estop = 1;
|
|
332
|
+
const r = await h.api(`/robots/${id.robot}/drive`, { method: "POST", sid: managerSid, body: { action: "start" } });
|
|
333
|
+
assert.equal(r.status, 400);
|
|
334
|
+
assert.match(r.body.message, /emergency stop/);
|
|
335
|
+
mock.state.estop = 0;
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
it("manual control: capped move on robotSubTopic, then STOP x3 when the heartbeat stops; the next signal is told why; audited", async () => {
|
|
339
|
+
await until(() => h.core.padbotLinkUp(String(id.robot)), 10000);
|
|
340
|
+
const start = await h.api(`/robots/${id.robot}/drive`, { method: "POST", sid: managerSid, body: { action: "start" } });
|
|
341
|
+
assert.equal(start.status, 200, JSON.stringify(start.body));
|
|
342
|
+
assert.equal(start.body.limits.maxLinear, 0.3);
|
|
343
|
+
const session = start.body.session;
|
|
344
|
+
const mark = broker.published.length;
|
|
345
|
+
const mv = await h.api(`/robots/${id.robot}/drive/${session}`, { method: "POST", sid: managerSid, body: { seq: 1, action: "move", lv: 1, av: 0 } });
|
|
346
|
+
assert.equal(mv.status, 200, JSON.stringify(mv.body));
|
|
347
|
+
const move = await until(() => broker.published.slice(mark).find((p) => p.inner.a === "1001"));
|
|
348
|
+
assert.equal(move.topic, SUB, "published only to robotSubTopic");
|
|
349
|
+
assert.equal(move.msg.t, "1505");
|
|
350
|
+
assert.deepEqual(move.inner.m, { lv: 0.3, av: 0 }, "capped to 0.3 m/s");
|
|
351
|
+
// Heartbeat stops: STOP within ~300 ms, three times.
|
|
352
|
+
await until(() => broker.published.slice(mark).filter((p) => p.inner.a === "1000").length >= 3, 3000);
|
|
353
|
+
const stops = broker.published.slice(mark).filter((p) => p.inner.a === "1000");
|
|
354
|
+
assert.ok(stops[0].at - move.at < 1200, "stopped promptly after the heartbeat was lost");
|
|
355
|
+
const late = await h.api(`/robots/${id.robot}/drive/${session}`, { method: "POST", sid: managerSid, body: { seq: 2, action: "beat" } });
|
|
356
|
+
assert.equal(late.status, 410);
|
|
357
|
+
assert.match(late.body.message, /connection to your screen was lost/);
|
|
358
|
+
await wait(200);
|
|
359
|
+
const audit = await h.db.collection("console-audit").find({ action: "robot.commanded", target: String(id.robot) }).toArray();
|
|
360
|
+
const cmds = audit.map((a) => a.after?.command);
|
|
361
|
+
assert.ok(cmds.includes("manual-drive-start") && cmds.includes("manual-drive-end"));
|
|
362
|
+
assert.equal(audit.find((a) => a.after?.command === "manual-drive-end").after.reason, "heartbeat-lost");
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
it("manual control ends at once when the robot reports its emergency stop over MQTT", async () => {
|
|
366
|
+
const start = await h.api(`/robots/${id.robot}/drive`, { method: "POST", sid: managerSid, body: { action: "start" } });
|
|
367
|
+
assert.equal(start.status, 200, JSON.stringify(start.body));
|
|
368
|
+
const mark = broker.published.length;
|
|
369
|
+
broker.publish(PUB, { id: "es1", t: "1104", ts: Date.now(), sn: "PS0001", m: '{"es":1,"ws":0}' });
|
|
370
|
+
await until(() => broker.published.slice(mark).some((p) => p.inner.a === "1000"));
|
|
371
|
+
const r = await h.api(`/robots/${id.robot}/drive/${start.body.session}`, { method: "POST", sid: managerSid, body: { seq: 1, action: "beat" } });
|
|
372
|
+
assert.equal(r.status, 410);
|
|
373
|
+
assert.match(r.body.message, /emergency stop/);
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("no log line carries the MQTT username, token, AccessKey secret or the broker address", () => {
|
|
377
|
+
const text = logs.join("\n");
|
|
378
|
+
for (const secret of [MQTT_USER, MQTT_TOKEN, SK, `localhost:${broker.port}`, "LTAI-e2e-user"]) {
|
|
379
|
+
assert.ok(!text.includes(secret), `leaked: ${secret}`);
|
|
380
|
+
}
|
|
381
|
+
assert.ok(text.includes("[padbot-mqtt]"), "the feed did log (so the check means something)");
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
async function seed(h) {
|
|
386
|
+
const now = new Date().toISOString();
|
|
387
|
+
const org = new ObjectId();
|
|
388
|
+
const site = new ObjectId();
|
|
389
|
+
const mgrRole = new ObjectId();
|
|
390
|
+
const guardRole = new ObjectId();
|
|
391
|
+
await h.db.collection("organizations").insertOne({ _id: org, name: "PBM Org", email: "pbm@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now });
|
|
392
|
+
await h.db.collection("sites").insertOne({ _id: site, name: "PBM Site", org, orgId: org, status: "active" });
|
|
393
|
+
await h.db.collection("roles").insertMany([
|
|
394
|
+
{ _id: mgrRole, name: "Robot manager", org, permissions: ["robot-mgmt:see-robot-details", "robot-mgmt:update-robot"], status: "active" },
|
|
395
|
+
{ _id: guardRole, name: "Guard", org, permissions: ["visitor-mgmt:add-visitor"], status: "active" },
|
|
396
|
+
]);
|
|
397
|
+
const users = await h.db.collection("users").insertMany([MANAGER, GUARD].map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })));
|
|
398
|
+
const hashed = await h.hashPassword(PASSWORD);
|
|
399
|
+
await h.db.collection("users").updateMany({ email: { $in: [MANAGER, GUARD] } }, { $set: { password: hashed } });
|
|
400
|
+
const [manager, guard] = [users.insertedIds[0], users.insertedIds[1]];
|
|
401
|
+
await h.db.collection("members").insertMany([
|
|
402
|
+
{ user: manager, org, siteId: site, type: "organization", role: mgrRole, status: "active" },
|
|
403
|
+
{ user: guard, org, siteId: site, type: "organization", role: guardRole, status: "active" },
|
|
404
|
+
]);
|
|
405
|
+
const robot = new ObjectId();
|
|
406
|
+
await h.db.collection("robots").insertOne({
|
|
407
|
+
_id: robot,
|
|
408
|
+
name: "Lobby patrol",
|
|
409
|
+
type: "security",
|
|
410
|
+
brand: "padbot",
|
|
411
|
+
robotSn: "PS0001",
|
|
412
|
+
appKey: AK,
|
|
413
|
+
appToken: SK,
|
|
414
|
+
metadata: { orgId: org, siteId: site },
|
|
415
|
+
status: "active",
|
|
416
|
+
createdAt: now,
|
|
417
|
+
});
|
|
418
|
+
return { org, site, robot, manager, guard };
|
|
419
|
+
}
|
|
@@ -52,7 +52,7 @@ describe("notification categories", () => {
|
|
|
52
52
|
}
|
|
53
53
|
});
|
|
54
54
|
|
|
55
|
-
it("the
|
|
55
|
+
it("the safety categories are on by default and switchable", () => {
|
|
56
56
|
const safety = NOTIFICATION_CATEGORIES.filter((c) => c.safety);
|
|
57
57
|
|
|
58
58
|
assert.deepEqual(keys(safety), [
|
|
@@ -60,6 +60,7 @@ describe("notification categories", () => {
|
|
|
60
60
|
"emergencyContact",
|
|
61
61
|
"virtualPatrol",
|
|
62
62
|
"cameraFault",
|
|
63
|
+
"robotAlert",
|
|
63
64
|
]);
|
|
64
65
|
|
|
65
66
|
for (const category of safety) {
|
|
@@ -381,7 +382,7 @@ describe("marketplace order categories", () => {
|
|
|
381
382
|
|
|
382
383
|
const NEW_KEYS = ["marketplaceOrder", "marketplaceVendorOrder"];
|
|
383
384
|
// Categories added after this snapshot was taken; each is pinned by its own test.
|
|
384
|
-
const LATER_KEYS = ["inventory"];
|
|
385
|
+
const LATER_KEYS = ["inventory", "robotAlert"];
|
|
385
386
|
const withoutNew = (result) => keys(result).filter((k) => !NEW_KEYS.includes(k) && !LATER_KEYS.includes(k));
|
|
386
387
|
const onlyNew = (result) => keys(result).filter((k) => NEW_KEYS.includes(k));
|
|
387
388
|
|