@7365admin1/layer-common 4.24.0 → 4.25.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 CHANGED
@@ -1,5 +1,27 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a227cdf: Robot screens: brand picker, live positions, and cleaning by area
8
+
9
+ The Add Robot form now asks which brand a robot is, offering each with what its
10
+ protocol actually allows in plain words. There is no safe default — sending a
11
+ robot a command in another brand's protocol is the one mistake the adapter layer
12
+ exists to prevent — so a brand is preselected only when there is no choice.
13
+
14
+ The fleet screen follows each robot's position while it is open, via the
15
+ `/track` stream, and stops every stream on unmount: the server holds one
16
+ connection to the robot cloud for each open one.
17
+
18
+ Losing a stream marks a robot `UNAVAILABLE` rather than leaving its last known
19
+ mode, which would advertise it as ready for work forever.
20
+
21
+ Adds "Clean area", so zones can be chosen from the robot's own maps rather than
22
+ cleaning everything. Battery is shown only when the brand reports one — a brand
23
+ that cannot measure it must not render as 0%, which reads as flat.
24
+
3
25
  ## 4.24.0
4
26
 
5
27
  ### Minor Changes
@@ -1301,11 +1323,11 @@
1301
1323
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
1302
1324
  own rule from two endpoints the console already calls, unprojected:
1303
1325
 
1304
- GET /api/members/user/:user/app/admin the Seven365 staff membership
1305
- GET /api/roles/id/:role that membership's role document
1326
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
1327
+ GET /api/roles/id/:role that membership's role document
1306
1328
 
1307
- owner = member.type === "admin" && role.type === "admin" && role.default === true
1308
- staff = member.type === "admin" && role.type === "admin"
1329
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
1330
+ staff = member.type === "admin" && role.type === "admin"
1309
1331
 
1310
1332
  `role.default` is the marker because it is the only property of a platform
1311
1333
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -103,9 +103,21 @@
103
103
  </template>
104
104
 
105
105
  <template #item.floor="{ item }">
106
- <span class="text-body-2 text-medium-emphasis">
107
- {{ floorLabel(states[item._id]) }}
108
- </span>
106
+ <div class="d-flex flex-column">
107
+ <span class="text-body-2 text-medium-emphasis">
108
+ {{ floorLabel(states[item._id]) }}
109
+ </span>
110
+ <!--
111
+ Battery is shown only when the brand reports one. A brand that
112
+ cannot measure it must not render as 0% - which reads as flat.
113
+ -->
114
+ <span
115
+ v-if="typeof states[item._id]?.batteryPercent === 'number'"
116
+ class="text-caption text-medium-emphasis"
117
+ >
118
+ {{ states[item._id].batteryPercent }}% battery
119
+ </span>
120
+ </div>
109
121
  </template>
110
122
 
111
123
  <template #item.actions="{ item }">
@@ -130,6 +142,15 @@
130
142
  >
131
143
  Return to dock
132
144
  </AppButton>
145
+ <AppButton
146
+ v-if="canCommand"
147
+ size="small"
148
+ variant="text"
149
+ :disabled="!canDispatch(states[item._id]) || busy === item._id"
150
+ @click="openAreas(item)"
151
+ >
152
+ Clean area
153
+ </AppButton>
133
154
  <AppButton size="small" variant="text" @click="openMap(item)">
134
155
  View layout
135
156
  </AppButton>
@@ -166,6 +187,55 @@
166
187
  </AppCard>
167
188
  </v-dialog>
168
189
 
190
+ <!--
191
+ Choosing zones rather than cleaning everything. The areas come from the
192
+ robot's own maps, so the names are the ones its operator already knows.
193
+ -->
194
+ <v-dialog v-model="areaDialog" width="520" scrollable>
195
+ <AppCard class="pa-0">
196
+ <v-toolbar density="comfortable" class="pl-4">
197
+ <span class="font-weight-medium text-h6">Clean areas — {{ areaRobot?.name }}</span>
198
+ </v-toolbar>
199
+ <v-card-text style="max-height: 55vh">
200
+ <div v-if="loadingAreas" class="py-6 text-center">
201
+ <v-progress-circular indeterminate size="28" />
202
+ </div>
203
+ <v-alert v-else-if="areaError" type="error" variant="tonal" :text="areaError" />
204
+ <div v-else-if="!areaOptions.length" class="py-6 text-center text-body-2 text-medium-emphasis">
205
+ This robot's maps define no cleaning areas.
206
+ </div>
207
+ <template v-else>
208
+ <p class="text-body-2 text-medium-emphasis mb-3">
209
+ Pick the areas to clean. The robot cleans them in the order shown.
210
+ </p>
211
+ <v-checkbox
212
+ v-for="area in areaOptions"
213
+ :key="area.value"
214
+ v-model="chosenAreas"
215
+ :value="area.value"
216
+ :label="area.title"
217
+ density="compact"
218
+ hide-details
219
+ />
220
+ </template>
221
+ </v-card-text>
222
+ <v-toolbar density="compact">
223
+ <v-row no-gutters>
224
+ <v-col cols="6">
225
+ <v-btn tile block variant="flat" size="48" class="text-none" color="#EFEFEF"
226
+ :disabled="sendingAreas" @click="areaDialog = false">Close</v-btn>
227
+ </v-col>
228
+ <v-col cols="6">
229
+ <v-btn tile block variant="flat" size="48" class="text-none" color="primary"
230
+ :loading="sendingAreas" :disabled="!chosenAreas.length" @click="sendAreas">
231
+ Clean {{ chosenAreas.length || "" }}
232
+ </v-btn>
233
+ </v-col>
234
+ </v-row>
235
+ </v-toolbar>
236
+ </AppCard>
237
+ </v-dialog>
238
+
169
239
  <v-dialog v-model="dialog" width="460" persistent>
170
240
  <RobotForm
171
241
  :organization="organization"
@@ -212,7 +282,7 @@ const props = withDefaults(
212
282
  { robotType: "cleaning", title: "Robots", canAdd: false, canCommand: false },
213
283
  );
214
284
 
215
- const { getRobots, getRobotState, sendRobotCommand } = useRobots();
285
+ const { getRobots, getRobotState, sendRobotCommand, getRobotMaps, trackRobot } = useRobots();
216
286
 
217
287
  // The house pattern is a local Snackbar with local state, as
218
288
  // `AccessCardPreviewDialog.vue` does - there is no global toast composable.
@@ -238,6 +308,107 @@ const dialog = ref(false);
238
308
  const mapDialog = ref(false);
239
309
  const mapRobot = ref<Record<string, any> | null>(null);
240
310
 
311
+ const areaDialog = ref(false);
312
+ const areaRobot = ref<Record<string, any> | null>(null);
313
+ const areaOptions = ref<Array<{ title: string; value: string }>>([]);
314
+ const chosenAreas = ref<string[]>([]);
315
+ const loadingAreas = ref(false);
316
+ const sendingAreas = ref(false);
317
+ const areaError = ref("");
318
+
319
+ /** One open stream per robot, so they can all be stopped on unmount. */
320
+ const streams = new Map<string, { stop: () => void }>();
321
+
322
+ async function openAreas(robot: Record<string, any>) {
323
+ areaRobot.value = robot;
324
+ chosenAreas.value = [];
325
+ areaOptions.value = [];
326
+ areaError.value = "";
327
+ areaDialog.value = true;
328
+ loadingAreas.value = true;
329
+ try {
330
+ const res = await getRobotMaps(robot._id);
331
+ // Areas are per floor, and the same name can appear on more than one, so
332
+ // they are labelled with their floor rather than silently de-duplicated.
333
+ const options: Array<{ title: string; value: string }> = [];
334
+ for (const map of res?.items ?? []) {
335
+ for (const area of map.areaList ?? []) {
336
+ options.push({
337
+ title: `${area.areaName} — ${map.mapName?.trim() || `Floor ${map.floorNo}`}`,
338
+ value: area.areaName,
339
+ });
340
+ }
341
+ }
342
+ areaOptions.value = options;
343
+ } catch (e) {
344
+ areaError.value = robotErrorMessage(e, "Could not load this robot's areas.");
345
+ } finally {
346
+ loadingAreas.value = false;
347
+ }
348
+ }
349
+
350
+ async function sendAreas() {
351
+ const robot = areaRobot.value;
352
+ if (!robot || !chosenAreas.value.length) return;
353
+ sendingAreas.value = true;
354
+ try {
355
+ await sendRobotCommand(robot._id, { kind: "area", areas: [...chosenAreas.value] });
356
+ showToast(`${robot.name} has been sent to clean ${chosenAreas.value.length} area(s).`, "success");
357
+ areaDialog.value = false;
358
+ // Re-read rather than assume: the API returns no job id, so the robot's own
359
+ // state is the only truthful confirmation anything happened.
360
+ states.value = { ...states.value, [robot._id]: await getRobotState(robot._id) };
361
+ } catch (e) {
362
+ showToast(robotErrorMessage(e), "error");
363
+ } finally {
364
+ sendingAreas.value = false;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Follow each robot's position while this screen is open.
370
+ *
371
+ * The server holds one connection to the robot cloud for as long as each of
372
+ * these is open, so they are all stopped on unmount - leaving them running
373
+ * would consume the vendor's stream budget for a screen nobody is looking at.
374
+ */
375
+ function watchRobots() {
376
+ stopWatching();
377
+ for (const robot of items.value) {
378
+ streams.set(
379
+ robot._id,
380
+ trackRobot(robot._id, (event) => {
381
+ if (event?.type === "pose" && event.pose) {
382
+ const current = states.value[robot._id] ?? {};
383
+ states.value = {
384
+ ...states.value,
385
+ [robot._id]: {
386
+ ...current,
387
+ mode: event.pose.mode ?? current.mode,
388
+ position: { x: event.pose.x, y: event.pose.y, theta: event.pose.theta },
389
+ },
390
+ };
391
+ return;
392
+ }
393
+ if (event?.type === "lost") {
394
+ // Losing the stream is not the same as the robot being idle: the last
395
+ // known mode would keep it advertised as ready for work forever.
396
+ const current = states.value[robot._id] ?? {};
397
+ states.value = {
398
+ ...states.value,
399
+ [robot._id]: { ...current, mode: "UNAVAILABLE", dispatchable: false },
400
+ };
401
+ }
402
+ }),
403
+ );
404
+ }
405
+ }
406
+
407
+ function stopWatching() {
408
+ for (const stream of streams.values()) stream.stop();
409
+ streams.clear();
410
+ }
411
+
241
412
  function openMap(robot: Record<string, any>) {
242
413
  mapRobot.value = robot;
243
414
  mapDialog.value = true;
@@ -277,7 +448,7 @@ async function load() {
277
448
  pages.value = Math.max(1, Number(res?.totalPages ?? 1));
278
449
  // Deliberately not awaited: the table renders from our own database
279
450
  // immediately, and each robot's chip fills in as its cloud call returns.
280
- loadStates();
451
+ loadStates().then(watchRobots);
281
452
  } catch (e) {
282
453
  error.value = robotErrorMessage(e, "Could not load the robots for this site.");
283
454
  items.value = [];
@@ -346,6 +517,7 @@ function onCreated() {
346
517
  }
347
518
 
348
519
  onMounted(load);
520
+ onBeforeUnmount(stopWatching);
349
521
  </script>
350
522
 
351
523
  <style scoped>
@@ -25,6 +25,23 @@
25
25
  />
26
26
  </v-col>
27
27
 
28
+ <v-col cols="12">
29
+ <InputLabel class="font-weight-bold" title="Brand" required />
30
+ <AppSelect
31
+ v-model="brand"
32
+ :items="brands"
33
+ item-title="label"
34
+ item-value="brand"
35
+ density="comfortable"
36
+ :loading="loadingBrands"
37
+ :rules="[requiredRule]"
38
+ :disabled="saving"
39
+ />
40
+ <p class="text-caption text-medium-emphasis mt-n3 mb-2">
41
+ {{ brandHint }}
42
+ </p>
43
+ </v-col>
44
+
28
45
  <v-col cols="12">
29
46
  <InputLabel class="font-weight-bold" title="App key" required />
30
47
  <v-text-field
@@ -129,11 +146,14 @@ const props = withDefaults(
129
146
 
130
147
  const emit = defineEmits<{ cancel: []; created: [] }>();
131
148
 
132
- const { createRobot } = useRobots();
149
+ const { createRobot, getRobotBrands } = useRobots();
133
150
  const { requiredRule } = useUtils();
134
151
 
135
152
  const form = ref();
136
153
  const name = ref("");
154
+ const brand = ref("");
155
+ const brands = ref<Array<Record<string, any>>>([]);
156
+ const loadingBrands = ref(false);
137
157
  const appKey = ref("");
138
158
  const appToken = ref("");
139
159
  const robotSn = ref("");
@@ -143,6 +163,46 @@ const error = ref("");
143
163
 
144
164
  const typeLabel = computed(() => (props.type === "security" ? "security" : "cleaning"));
145
165
 
166
+ /**
167
+ * What each brand's protocol will actually allow, in plain words.
168
+ *
169
+ * The tier comes from Open-RMF's published categories, so this is not a Seven365
170
+ * opinion - and somebody choosing a brand should know before they commit that
171
+ * one of them cannot be paused or told where to go.
172
+ */
173
+ const TIER_HINT: Record<string, string> = {
174
+ "full-control": "Full control — position, battery, navigation, pause and resume.",
175
+ "traffic-light": "Position, battery, and pause/resume. No navigation to a point.",
176
+ "read-only": "Position only. This brand cannot be given jobs through its API.",
177
+ "no-interface":
178
+ "Limited: the published API does not yet report battery or progress. Cleaning and return-to-dock work.",
179
+ };
180
+
181
+ const brandHint = computed(() => {
182
+ const chosen = brands.value.find((b) => b.brand === brand.value);
183
+ return chosen ? TIER_HINT[chosen.tier] ?? "" : "Which robot this is. Ask your supplier if unsure.";
184
+ });
185
+
186
+ async function loadBrands() {
187
+ loadingBrands.value = true;
188
+ try {
189
+ const res = await getRobotBrands();
190
+ brands.value = (res?.items ?? []).map((b: any) => ({
191
+ ...b,
192
+ label: b.displayName ?? b.brand,
193
+ }));
194
+ // Only preselect when there is no choice to make. Guessing a brand is how a
195
+ // robot ends up being sent commands in a protocol it does not speak.
196
+ if (brands.value.length === 1) brand.value = brands.value[0].brand;
197
+ } catch {
198
+ brands.value = [];
199
+ } finally {
200
+ loadingBrands.value = false;
201
+ }
202
+ }
203
+
204
+ onMounted(loadBrands);
205
+
146
206
  async function submit() {
147
207
  const { valid } = await form.value?.validate?.() ?? { valid: false };
148
208
  if (!valid) return;
@@ -152,6 +212,7 @@ async function submit() {
152
212
  try {
153
213
  await createRobot({
154
214
  name: name.value.trim(),
215
+ brand: brand.value,
155
216
  appKey: appKey.value.trim(),
156
217
  appToken: appToken.value.trim(),
157
218
  type: props.type,
@@ -83,6 +83,92 @@ export default function useRobots() {
83
83
  );
84
84
  }
85
85
 
86
+ /**
87
+ * The robot brands this platform can talk to.
88
+ *
89
+ * A robot record has to name its brand and there is no safe default - sending
90
+ * a robot a command in another brand's protocol is the one mistake the
91
+ * adapter layer exists to prevent. Each brand reports its Open-RMF tier, so
92
+ * somebody choosing one can see what that protocol allows before committing.
93
+ */
94
+ function getRobotBrands() {
95
+ return useNuxtApp().$api<Record<string, any>>("/api/robots/brands", {
96
+ method: "GET",
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Watch one robot's position.
102
+ *
103
+ * `fetch` with a stream reader rather than `EventSource`, because EventSource
104
+ * cannot carry the headers `$api` adds - it would be an unauthenticated
105
+ * request that simply 401s.
106
+ *
107
+ * Returns a `stop`. Calling it aborts the request, which closes the upstream
108
+ * connection to the robot cloud - the server holds one for as long as this
109
+ * one is open, so leaving it running is not free.
110
+ */
111
+ function trackRobot(
112
+ id: string,
113
+ onEvent: (event: Record<string, any>) => void,
114
+ ): { stop: () => void } {
115
+ const controller = new AbortController();
116
+ const base = useRuntimeConfig().public?.apiBase ?? "";
117
+ const query = appSlug ? `?appSlug=${encodeURIComponent(appSlug)}` : "";
118
+
119
+ (async () => {
120
+ try {
121
+ const response = await fetch(`${base}/api/robots/${id}/track${query}`, {
122
+ method: "GET",
123
+ headers: { Accept: "text/event-stream" },
124
+ credentials: "include",
125
+ signal: controller.signal,
126
+ });
127
+ if (!response.ok || !response.body) {
128
+ onEvent({ type: "lost", reason: `The robot stream refused (${response.status}).` });
129
+ return;
130
+ }
131
+
132
+ const reader = response.body.getReader();
133
+ const decoder = new TextDecoder();
134
+ let buffer = "";
135
+
136
+ // Events do not respect chunk boundaries: whatever follows the last
137
+ // blank line stays buffered for the next read, or a pose arriving in
138
+ // two pieces is dropped.
139
+ for (;;) {
140
+ const { done, value } = await reader.read();
141
+ if (done) break;
142
+
143
+ buffer += decoder.decode(value, { stream: true });
144
+ buffer = buffer.replace(/\r\n|\r/g, "\n");
145
+
146
+ const frames = buffer.split("\n\n");
147
+ buffer = frames.pop() ?? "";
148
+
149
+ for (const frame of frames) {
150
+ for (const line of frame.split("\n")) {
151
+ // A line starting ":" is a keep-alive comment, not an event.
152
+ if (!line.startsWith("data:")) continue;
153
+ try {
154
+ onEvent(JSON.parse(line.slice(5).trim()));
155
+ } catch {
156
+ // One malformed frame must not tear down a stream that is
157
+ // otherwise delivering good poses.
158
+ }
159
+ }
160
+ }
161
+ }
162
+ onEvent({ type: "lost", reason: "The robot stream ended." });
163
+ } catch (error: any) {
164
+ if (error?.name === "AbortError") return;
165
+ onEvent({ type: "lost", reason: error?.message ?? "The robot stream failed." });
166
+ }
167
+ })();
168
+
169
+ return { stop: () => controller.abort() };
170
+ }
171
+
86
172
  /** The cleaning schedule the vendor cloud holds for this robot. */
87
173
  function getRobotPlans(id: string) {
88
174
  return useNuxtApp().$api<Record<string, any>>(
@@ -115,6 +201,8 @@ export default function useRobots() {
115
201
 
116
202
  return {
117
203
  getRobots,
204
+ getRobotBrands,
205
+ trackRobot,
118
206
  createRobot,
119
207
  getRobotState,
120
208
  getRobotMaps,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.24.0",
5
+ "version": "4.25.0",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",