@7365admin1/core 3.122.4 → 3.122.6

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/dist/index.mjs CHANGED
@@ -64666,6 +64666,64 @@ function padbotMode(states, now = Date.now()) {
64666
64666
  const base = phase || (charging ? "Charging" : patrolling ? "Patrolling" : work.workState === 1 ? "Working on a task" : "Standing by");
64667
64667
  return { online: true, mode, statusName: `${base}${networkText(states["1107"])}` };
64668
64668
  }
64669
+ var MOVING_COMMANDS = /* @__PURE__ */ new Set(["full", "area", "patrol-resume", "return", "navigate", "go-to-point"]);
64670
+ function padbotCommandBlock(states, kind, now = Date.now()) {
64671
+ if (!MOVING_COMMANDS.has(kind))
64672
+ return null;
64673
+ if (!states || !padbotMode(states, now).online)
64674
+ return "The robot is not reporting to PadBot, so it cannot take a command. Check it is switched on and connected.";
64675
+ if (states["1006"]?.emergencyStopState === 1)
64676
+ return "The robot's emergency stop button is pressed. Release the red button on the robot, then try again.";
64677
+ const battery = num(states["1001"]?.batteryPercent);
64678
+ if (kind !== "return" && battery !== null && battery < 10)
64679
+ return `The battery is at ${battery}%. PadBot robots do not start jobs under 10%; send it to charge first.`;
64680
+ if (kind === "return" && [1, 2].includes(states["1002"]?.chargingState))
64681
+ return "The robot is already on its charger.";
64682
+ return null;
64683
+ }
64684
+ function padbotReadiness(states, now = Date.now()) {
64685
+ const st = states ?? {};
64686
+ const nav = st["1003"] ?? {};
64687
+ const es = st["1006"] ?? {};
64688
+ const charging = st["1002"]?.chargingState;
64689
+ const notes = [];
64690
+ if (es.wheelLockState === 1)
64691
+ notes.push("PadBot reports the wheel motor lock ON (1006 wheelLockState 1). PadBot's v4.0 document does not say whether this stops navigation - asked PadBot.");
64692
+ if (charging === 2)
64693
+ notes.push("Charging state 2 is not in PadBot's v4.0 document (only 0 and 1) - asked PadBot what it means.");
64694
+ return {
64695
+ online: padbotMode(st, now).online,
64696
+ heartbeatAt: st["1000"]?.updatedAt ?? null,
64697
+ emergencyStopPressed: es.emergencyStopState === 1,
64698
+ wheelLockState: es.wheelLockState ?? null,
64699
+ batteryPercent: num(st["1001"]?.batteryPercent),
64700
+ chargingState: charging ?? null,
64701
+ map: { id: st["1007"]?.mapId ?? null, name: st["1007"]?.mapDisplayName ?? null, floor: st["1007"]?.floor ?? null },
64702
+ navigation: { actionType: nav.actionType ?? null, actionState: nav.actionState ?? null, message: nav.message ?? null, updatedAt: nav.updatedAt ?? null },
64703
+ work: { workState: st["1010"]?.workState ?? null, taskType: st["1010"]?.taskType ?? null, updatedAt: st["1010"]?.updatedAt ?? null },
64704
+ blocker: padbotCommandBlock(st, "go-to-point", now),
64705
+ notes
64706
+ };
64707
+ }
64708
+ function padbotReactionPoint(states) {
64709
+ const st = states ?? {};
64710
+ const nav = st["1003"] ?? {};
64711
+ return {
64712
+ action: Number(nav.actionType) || 0,
64713
+ state: Number(nav.actionState) || 0,
64714
+ target: nav.finalTargetPointName ?? nav.nextTargetPointName ?? null,
64715
+ message: nav.message ?? null,
64716
+ work: Number(st["1010"]?.workState) || 0,
64717
+ charging: st["1002"]?.chargingState ?? null,
64718
+ estop: st["1006"]?.emergencyStopState ?? null,
64719
+ wheelLock: st["1006"]?.wheelLockState ?? null
64720
+ };
64721
+ }
64722
+ function padbotFailureText(p) {
64723
+ if (p.state !== 6)
64724
+ return null;
64725
+ return `Could not reach ${p.target || "its destination"}${p.message ? ` (${p.message})` : ""}`;
64726
+ }
64669
64727
  function networkText(net) {
64670
64728
  const say = (label2, v) => v < 0 ? ` \xB7 ${label2} ${v} dBm` : ` \xB7 ${label2} signal ${v}`;
64671
64729
  const wifi = num(net?.wifi?.signalStrength);
@@ -64755,6 +64813,9 @@ function padbotPatrolPlan(paths, maps, states = {}) {
64755
64813
  const routeMapId = (p) => {
64756
64814
  if (typeof p?.mapId === "string" && p.mapId)
64757
64815
  return p.mapId;
64816
+ const pointMaps = new Set((Array.isArray(p?.points) ? p.points : []).map((pt) => pt?.mapId).filter((id) => typeof id === "string" && id));
64817
+ if (pointMaps.size === 1)
64818
+ return [...pointMaps][0];
64758
64819
  const names = Array.isArray(p?.points) && p.points.length ? p.points.map((pt) => pt?.targetPointName) : Array.isArray(p?.pointNames) ? p.pointNames : [];
64759
64820
  if (!names.length)
64760
64821
  return p?.mapId;
@@ -64789,7 +64850,10 @@ function padbotPatrolPlan(paths, maps, states = {}) {
64789
64850
  const r = candidates[0];
64790
64851
  r.currentCheckpoint = r.checkpoints.findIndex((c) => c.name === next);
64791
64852
  }
64792
- routes.sort((a, b) => Number(b.currentCheckpoint !== null) - Number(a.currentCheckpoint !== null) || Number(b._default) - Number(a._default));
64853
+ const here = (r) => Number(!!currentMap && r.mapId === currentMap);
64854
+ routes.sort(
64855
+ (a, b) => Number(b.currentCheckpoint !== null) - Number(a.currentCheckpoint !== null) || here(b) - here(a) || Number(b._default) - Number(a._default)
64856
+ );
64793
64857
  for (const r of routes)
64794
64858
  delete r._default;
64795
64859
  return { routes, schedule: [], scheduleShared: false };
@@ -64827,7 +64891,7 @@ function createPadbotClient(credentials, options = {}) {
64827
64891
  const baseUrl = (options.baseUrl ?? padbotBaseUrl()).replace(/\/+$/, "");
64828
64892
  const doFetch = options.fetch ?? ((url2, init) => fetch(url2, init));
64829
64893
  const timeoutMs = options.timeoutMs ?? 8e3;
64830
- async function call(path5, body = {}) {
64894
+ async function call(path5, body = {}, meta) {
64831
64895
  const req = padbotSignedRequest({ path: path5, body, accessKeyId: credentials.appid, accessKeySecret: credentials.secret, now: options.now });
64832
64896
  let res;
64833
64897
  try {
@@ -64847,6 +64911,10 @@ function createPadbotClient(credentials, options = {}) {
64847
64911
  } catch {
64848
64912
  throw new AppError24("PadBot's cloud sent an answer that is not JSON.", 502);
64849
64913
  }
64914
+ if (meta) {
64915
+ meta.message = typeof json?.message === "string" ? json.message.slice(0, 200) : "";
64916
+ meta.requestId = typeof json?.requestId === "string" ? json.requestId.slice(0, 64) : "";
64917
+ }
64850
64918
  if (json?.code !== 0) {
64851
64919
  const e = new BadRequestError135(padbotErrorText(Number(json?.code)));
64852
64920
  e.vendorCode = Number(json?.code);
@@ -64923,6 +64991,7 @@ function clearPadbotCache() {
64923
64991
  cache2.clear();
64924
64992
  live.clear();
64925
64993
  commandLog.clear();
64994
+ lastFailure.clear();
64926
64995
  }
64927
64996
  function forgetPadbotMaps(appid, robotSn) {
64928
64997
  for (const key of cache2.keys())
@@ -64949,6 +65018,8 @@ function logCommand(accountKey, robotSn, entry) {
64949
65018
  commandLog.set(k, [entry, ...commandLog.get(k) ?? []].slice(0, 10));
64950
65019
  }
64951
65020
  var padbotCommandLog = (accountKey, robotSn) => commandLog.get(`${accountKey}:${robotSn}`) ?? [];
65021
+ var lastFailure = /* @__PURE__ */ new Map();
65022
+ var PADBOT_FAILURE_SHOW_MS = 3 * 6e4;
64952
65023
  async function readPadbotStates(credentials, robotSn, stateTypes) {
64953
65024
  const list = await createPadbotClient(credentials).call(PADBOT_PATHS.states, { serialNumbers: [robotSn], stateTypes });
64954
65025
  const entry = (list ?? []).find((e) => e?.serialNumber === robotSn);
@@ -64974,6 +65045,11 @@ async function listPadbotAlarmsSince(credentials, serials, startTime) {
64974
65045
  }
64975
65046
  function createPadbotAdapter(credentials, options = {}) {
64976
65047
  const { call, raw } = createPadbotClient(credentials, options);
65048
+ const watch = options.watch === void 0 ? { everyMs: 2e3, forMs: 3e4 } : options.watch;
65049
+ const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve) => {
65050
+ const t = setTimeout(resolve, ms2);
65051
+ t?.unref?.();
65052
+ }));
64977
65053
  const now = options.now ?? Date.now;
64978
65054
  const ns = `${credentials.appid}@${options.baseUrl ?? padbotBaseUrl()}`;
64979
65055
  const account = padbotAccountKey(credentials);
@@ -64995,13 +65071,15 @@ function createPadbotAdapter(credentials, options = {}) {
64995
65071
  const heard = padbotLive(account, robotSn);
64996
65072
  const restBatteryAt = ms(st["1001"]?.updatedAt);
64997
65073
  const battery = heard?.batteryPercent !== void 0 && (!Number.isFinite(restBatteryAt) || (heard.batteryAt ?? 0) > restBatteryAt) ? heard.batteryPercent : num(st["1001"]?.batteryPercent);
65074
+ const failed = lastFailure.get(`${account}:${robotSn}`);
65075
+ const showFailure = online && failed && now() - failed.at < PADBOT_FAILURE_SHOW_MS && /^(Standing by|Charging)/.test(statusName);
64998
65076
  const robot = {
64999
65077
  robotSn,
65000
65078
  name: info?.robotName,
65001
65079
  model: info?.robotModel ? `PadBot ${info.robotModel}` : void 0,
65002
65080
  online,
65003
65081
  mode,
65004
- statusName,
65082
+ statusName: showFailure ? `${failed.text} \xB7 ${statusName}` : statusName,
65005
65083
  batteryPercent: battery,
65006
65084
  floorNo: Number.isInteger(floor) ? floor : null,
65007
65085
  floorKnown: Number.isInteger(floor),
@@ -65057,13 +65135,89 @@ function createPadbotAdapter(credentials, options = {}) {
65057
65135
  const n = command?.options?.cleanTimes;
65058
65136
  return Number.isInteger(n) && n >= 1 ? Math.min(n, 99) : 1;
65059
65137
  };
65138
+ async function whereIs(robotSn) {
65139
+ const [st, all, loc] = await Promise.all([
65140
+ states(robotSn),
65141
+ maps(robotSn).catch(() => []),
65142
+ call(PADBOT_PATHS.location, { serialNumber: robotSn }).catch(() => null)
65143
+ ]);
65144
+ const ids2 = [loc?.mapId, st?.["1007"]?.mapId];
65145
+ const map = padbotCurrentMap(all, ids2, st?.["1007"]?.floor);
65146
+ const mapId = map?.mapId ?? ids2.find((id) => typeof id === "string" && id) ?? null;
65147
+ return { st: st ?? {}, all: all ?? [], mapId };
65148
+ }
65149
+ const mapName = (all, id) => {
65150
+ const m = all.find((x) => x?.mapId === id);
65151
+ return String(m?.mapDisplayName || m?.mapName || "another");
65152
+ };
65153
+ async function checkedRoute(robotSn, routeId) {
65154
+ const [paths, where] = await Promise.all([call(PADBOT_PATHS.patrolRoutes, { serialNumber: robotSn }).then(asList), whereIs(robotSn)]);
65155
+ const rawRoute = routeId ? paths.find((p) => p?.pathId === routeId) : paths.find((p) => p?.isDefault);
65156
+ if (!rawRoute) {
65157
+ if (routeId)
65158
+ throw new BadRequestError135(padbotErrorText(2002));
65159
+ return null;
65160
+ }
65161
+ const plan = padbotPatrolPlan(paths, where.all, { ...where.st, "1007": { ...where.st["1007"] ?? {}, mapId: where.mapId } });
65162
+ const route = plan.routes.find((r) => r.id === String(rawRoute.pathId));
65163
+ const routeMap = route?.mapId;
65164
+ if (routeMap && where.mapId && !padbotCanReachMap(where.all, where.mapId, routeMap)) {
65165
+ throw new BadRequestError135(
65166
+ `"${rawRoute.pathName || "That route"}" is on the ${mapName(where.all, routeMap)} map, but the robot is on ${mapName(where.all, where.mapId)}. Pick a route on the robot's map.`
65167
+ );
65168
+ }
65169
+ return String(rawRoute.pathId);
65170
+ }
65171
+ async function watchReaction(robotSn, entry, sentAt) {
65172
+ if (!watch)
65173
+ return;
65174
+ const r = entry.reaction = { watching: true, points: [], failure: null, moved: false };
65175
+ let last = "";
65176
+ try {
65177
+ for (let waited = 0; waited < watch.forMs; ) {
65178
+ await sleep3(watch.everyMs);
65179
+ waited += watch.everyMs;
65180
+ const st = await states(robotSn).catch(() => null);
65181
+ if (!st)
65182
+ continue;
65183
+ const p = padbotReactionPoint(st);
65184
+ const key = JSON.stringify(p);
65185
+ if (key !== last && r.points.length < 20)
65186
+ r.points.push({ ...p, afterSeconds: Math.round((now() - sentAt) / 1e3) });
65187
+ last = key;
65188
+ if (p.state >= 1 && p.state <= 4)
65189
+ r.moved = true;
65190
+ const failure = padbotFailureText(p);
65191
+ if (failure) {
65192
+ r.failure = failure;
65193
+ lastFailure.set(`${account}:${robotSn}`, { at: now(), text: failure });
65194
+ break;
65195
+ }
65196
+ if (p.state === 5)
65197
+ break;
65198
+ }
65199
+ } finally {
65200
+ r.watching = false;
65201
+ }
65202
+ }
65060
65203
  async function sendCommand2(robotSn, command) {
65061
65204
  const sn = { serialNumber: robotSn };
65205
+ if (MOVING_COMMANDS.has(command.kind)) {
65206
+ const block = padbotCommandBlock(await states(robotSn), command.kind, now());
65207
+ if (block)
65208
+ throw new BadRequestError135(block);
65209
+ lastFailure.delete(`${account}:${robotSn}`);
65210
+ }
65062
65211
  const call2 = async (path5, body) => {
65063
65212
  const at2 = new Date(now()).toISOString();
65213
+ const meta = {};
65064
65214
  try {
65065
- await callRaw(path5, body);
65066
- logCommand(account, robotSn, { at: at2, command: command.kind, path: path5, body, ok: true });
65215
+ await callRaw(path5, body, meta);
65216
+ const entry = { at: at2, command: command.kind, path: path5, body, ok: true, vendorCode: 0, vendorMessage: meta.message, requestId: meta.requestId };
65217
+ logCommand(account, robotSn, entry);
65218
+ if (MOVING_COMMANDS.has(command.kind))
65219
+ void watchReaction(robotSn, entry, now()).catch(() => {
65220
+ });
65067
65221
  } catch (e) {
65068
65222
  logCommand(account, robotSn, {
65069
65223
  at: at2,
@@ -65078,14 +65232,18 @@ function createPadbotAdapter(credentials, options = {}) {
65078
65232
  }
65079
65233
  };
65080
65234
  switch (command.kind) {
65081
- case "full":
65082
- await call2(PADBOT_PATHS.patrolStart, { ...sn, patrolCount: rounds(command) });
65235
+ case "full": {
65236
+ const pathId = await checkedRoute(robotSn, null);
65237
+ await call2(PADBOT_PATHS.patrolStart, { ...sn, ...pathId ? { pathId } : {}, patrolCount: rounds(command) });
65083
65238
  return;
65084
- case "area":
65239
+ }
65240
+ case "area": {
65085
65241
  if (command.areas.length !== 1)
65086
65242
  throw new BadRequestError135("Choose one patrol route to start.");
65087
- await call2(PADBOT_PATHS.patrolStart, { ...sn, pathId: command.areas[0], patrolCount: rounds(command) });
65243
+ const pathId = await checkedRoute(robotSn, command.areas[0]);
65244
+ await call2(PADBOT_PATHS.patrolStart, { ...sn, pathId, patrolCount: rounds(command) });
65088
65245
  return;
65246
+ }
65089
65247
  case "patrol-resume":
65090
65248
  await call2(PADBOT_PATHS.patrolResume, sn);
65091
65249
  return;
@@ -65104,8 +65262,8 @@ function createPadbotAdapter(credentials, options = {}) {
65104
65262
  await call2(PADBOT_PATHS.relocate, { ...sn, worldX: command.x, worldY: command.y });
65105
65263
  return;
65106
65264
  case "go-to-point": {
65107
- const [st, all] = await Promise.all([states(robotSn), maps(robotSn).catch(() => [])]);
65108
- if (!padbotCanReachMap(all, st?.["1007"]?.mapId, command.mapId))
65265
+ const where = await whereIs(robotSn);
65266
+ if (!padbotCanReachMap(where.all, where.mapId, command.mapId))
65109
65267
  throw new BadRequestError135(PADBOT_OTHER_MAP_TEXT);
65110
65268
  await call2(PADBOT_PATHS.navigateTarget, { ...sn, mapId: command.mapId, targetPointId: command.targetPointId });
65111
65269
  return;
@@ -65156,6 +65314,8 @@ function createPadbotAdapter(credentials, options = {}) {
65156
65314
  steps.push({ step, path: path5, body, httpStatus: r.httpStatus, code: r.code, message: r.message, ms: r.ms, data: r.code === 0 ? shape(r.data) : r.data });
65157
65315
  };
65158
65316
  await run("states (4.2)", PADBOT_PATHS.states, { serialNumbers: [robotSn] });
65317
+ const stEntry = (Array.isArray(steps[0]?.data) ? steps[0].data : []).find((e) => e?.serialNumber === robotSn);
65318
+ const ready = padbotReadiness(stEntry ? statesByType(stEntry) : null, now());
65159
65319
  await run("location (4.3)", PADBOT_PATHS.location, sn);
65160
65320
  await run("maps (5.1)", PADBOT_PATHS.maps, sn, (d) => Array.isArray(d) ? d.slice(0, 100).map(mapSummary) : d);
65161
65321
  await run("patrol routes (6.1)", PADBOT_PATHS.patrolRoutes, sn, (d) => Array.isArray(d) ? d.slice(0, 50) : d);
@@ -65163,6 +65323,7 @@ function createPadbotAdapter(credentials, options = {}) {
65163
65323
  await run("patrol records (6.7)", PADBOT_PATHS.records, { serialNumbers: [robotSn], pageNumber: 1, pageSize: 3 });
65164
65324
  const replies = padbotCommandLog(account, robotSn);
65165
65325
  steps.push({ step: "recent commands (this server)", path: "", body: null, httpStatus: 200, code: 0, message: replies.length ? `${replies.length} kept` : "none since this server started", ms: 0, data: replies });
65326
+ steps.push({ step: "can it move now? (from 4.2)", path: "", body: null, httpStatus: 200, code: 0, message: ready.blocker ?? (ready.notes.length ? "No documented blocker; see notes" : "No blocker"), ms: 0, data: ready });
65166
65327
  return steps;
65167
65328
  },
65168
65329
  async getPatrolRoutes(robotSn) {
@@ -104740,6 +104901,7 @@ export {
104740
104901
  PADBOT_BRAND_DEFINITION,
104741
104902
  PADBOT_CAPABILITIES,
104742
104903
  PADBOT_DISPLAY_NAME,
104904
+ PADBOT_FAILURE_SHOW_MS,
104743
104905
  PADBOT_LIVE_POSE_MS,
104744
104906
  PADBOT_MAKER_APP_ONLY,
104745
104907
  PADBOT_MODELS,
@@ -105086,12 +105248,14 @@ export {
105086
105248
  padbotCanReachMap,
105087
105249
  padbotChargingPoint,
105088
105250
  padbotCheckpointVisit,
105251
+ padbotCommandBlock,
105089
105252
  padbotCommandLog,
105090
105253
  padbotCurrentMap,
105091
105254
  padbotDriveBlock,
105092
105255
  padbotDriveLimits,
105093
105256
  padbotDriveSignal,
105094
105257
  padbotErrorText,
105258
+ padbotFailureText,
105095
105259
  padbotLinkUp,
105096
105260
  padbotLive,
105097
105261
  padbotManualDriveEnabled,
@@ -105100,6 +105264,8 @@ export {
105100
105264
  padbotPatrolPlan,
105101
105265
  padbotPatrolRecord,
105102
105266
  padbotPlanShare,
105267
+ padbotReactionPoint,
105268
+ padbotReadiness,
105103
105269
  padbotSignature,
105104
105270
  padbotSignedRequest,
105105
105271
  parseCameraChannel,