@wandelbots/wandelbots-js-react-components 6.3.0 → 6.4.0-pr.chore-public-names.673.cb7ee37

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.
Files changed (196) hide show
  1. package/README.md +255 -122
  2. package/dist/3d.cjs +1 -1
  3. package/dist/3d.d.ts +7 -3
  4. package/dist/3d.js +20 -20
  5. package/dist/CurrentPoseBar/index.cjs +1 -0
  6. package/dist/CurrentPoseBar/index.d.ts +2 -0
  7. package/dist/CurrentPoseBar/index.js +5 -0
  8. package/dist/JoggingButtons/index.cjs +1 -0
  9. package/dist/JoggingButtons/index.d.ts +3 -0
  10. package/dist/JoggingButtons/index.js +5 -0
  11. package/dist/JoggingGizmo/index.cjs +1 -0
  12. package/dist/JoggingGizmo/index.d.ts +5 -0
  13. package/dist/JoggingGizmo/index.js +6 -0
  14. package/dist/JoggingJointSlider/index.cjs +1 -0
  15. package/dist/JoggingJointSlider/index.d.ts +2 -0
  16. package/dist/JoggingJointSlider/index.js +5 -0
  17. package/dist/SafetyBar/index.cjs +1 -1
  18. package/dist/SafetyBar/index.js +1 -1
  19. package/dist/chunks/ConnectedMotionGroup-D9JJSyXB.js +1822 -0
  20. package/dist/chunks/ConnectedMotionGroup-ir7Vf690.cjs +3 -0
  21. package/dist/chunks/CurrentPoseBar-Cbz4AO36.cjs +1 -0
  22. package/dist/chunks/CurrentPoseBar-CpwvWpEY.js +619 -0
  23. package/dist/chunks/JoggingButtons-i8FdMpCx.js +108 -0
  24. package/dist/chunks/JoggingButtons-paQCBXf4.cjs +1 -0
  25. package/dist/chunks/JoggingGizmoOrientation-CKZeLcMp.js +893 -0
  26. package/dist/chunks/JoggingGizmoOrientation-EPtBeAun.cjs +1 -0
  27. package/dist/chunks/JoggingJointSlider-DQhJOmcc.js +378 -0
  28. package/dist/chunks/JoggingJointSlider-YcEBMgF1.cjs +1 -0
  29. package/dist/chunks/Pose3-Ci1bxEvz.js +1373 -0
  30. package/dist/chunks/Pose3-DwMOSTKO.cjs +1 -0
  31. package/dist/chunks/SafetyBar-Be1c6Vz9.cjs +1 -0
  32. package/dist/chunks/{SafetyBar-Cy9DiXp9.js → SafetyBar-WXLP3Yi0.js} +34 -32
  33. package/dist/chunks/{externalizeComponent-EDymnaGR.js → externalizeComponent-7OVHUIUh.js} +84 -134
  34. package/dist/chunks/externalizeComponent-B0n_tR3v.cjs +2 -0
  35. package/dist/chunks/holdSafety-Cbej6-Kc.js +62 -0
  36. package/dist/chunks/holdSafety-TeMXlYQe.cjs +1 -0
  37. package/dist/chunks/joggingColors-BKRoSGQu.js +132 -0
  38. package/dist/chunks/joggingColors-BkPm75Hr.cjs +1 -0
  39. package/dist/chunks/json-3cqBD7UQ.js +18 -0
  40. package/dist/chunks/json-Bd6uGfgP.cjs +1 -0
  41. package/dist/chunks/loadRobotSession-Bt1-Brjp.js +3761 -0
  42. package/dist/chunks/loadRobotSession-DHVuK_pj.cjs +1 -0
  43. package/dist/chunks/novaConnection-BTSIgWd1.cjs +1 -0
  44. package/dist/chunks/novaConnection-J6_ohIQ0.js +14 -0
  45. package/dist/chunks/poseText-BXUaQWnK.cjs +1 -0
  46. package/dist/chunks/poseText-CtdXIeT_.js +41 -0
  47. package/dist/chunks/useSmoothedMotionState-C_Vo0py0.js +202 -0
  48. package/dist/chunks/useSmoothedMotionState-Ce9NjwBu.cjs +1 -0
  49. package/dist/components/AppHeader.d.ts +1 -1
  50. package/dist/components/VelocitySlider.d.ts +6 -1
  51. package/dist/components/currentPoseBar/CurrentPoseBar.d.ts +48 -0
  52. package/dist/components/currentPoseBar/OrientationFormatPopover.d.ts +19 -0
  53. package/dist/components/currentPoseBar/StreamStatus.d.ts +10 -0
  54. package/dist/components/currentPoseBar/orientation.d.ts +34 -0
  55. package/dist/components/currentPoseBar/poseValues.d.ts +15 -0
  56. package/dist/components/jogging/JoggingButtons.d.ts +18 -0
  57. package/dist/components/jogging/JoggingCartesianAxisControl.d.ts +8 -2
  58. package/dist/components/jogging/JoggingCartesianTab.d.ts +3 -0
  59. package/dist/components/jogging/JoggingJointTab.d.ts +4 -1
  60. package/dist/components/jogging/JoggingJointValueControl.d.ts +7 -1
  61. package/dist/components/jogging/JoggingPanel.d.ts +6 -3
  62. package/dist/components/jogging/JoggingRefusedError.d.ts +24 -0
  63. package/dist/components/jogging/JoggingStore.d.ts +382 -40
  64. package/dist/components/jogging/gizmo/JoggingGizmo.d.ts +53 -0
  65. package/dist/components/jogging/gizmo/JoggingGizmoOrientation.d.ts +26 -0
  66. package/dist/components/jogging/gizmo/RotationHandles.d.ts +7 -0
  67. package/dist/components/jogging/gizmo/RotationScene.d.ts +6 -0
  68. package/dist/components/jogging/gizmo/TranslationHandles.d.ts +6 -0
  69. package/dist/components/jogging/gizmo/TranslationScene.d.ts +6 -0
  70. package/dist/components/jogging/gizmo/arcGrabAreas.d.ts +58 -0
  71. package/dist/components/jogging/gizmo/arcs.d.ts +54 -0
  72. package/dist/components/jogging/gizmo/arrows.d.ts +63 -0
  73. package/dist/components/jogging/gizmo/gizmoShared.d.ts +135 -0
  74. package/dist/components/jogging/gizmo/gizmoView.d.ts +42 -0
  75. package/dist/components/jogging/gizmo/useGizmoTurn.d.ts +11 -0
  76. package/dist/components/jogging/holdSafety.d.ts +82 -0
  77. package/dist/components/jogging/jogError.d.ts +9 -0
  78. package/dist/components/jogging/jogHandle.d.ts +23 -0
  79. package/dist/components/jogging/joggingColors.d.ts +30 -0
  80. package/dist/components/jogging/joggingVelocity.d.ts +21 -0
  81. package/dist/components/jogging/joint/JoggingJointSlider.d.ts +56 -0
  82. package/dist/components/jogging/joint/JointSliderTrack.d.ts +27 -0
  83. package/dist/components/jogging/joint/jointJog.d.ts +55 -0
  84. package/dist/components/jogging/joint/useJointJogHold.d.ts +43 -0
  85. package/dist/components/jogging/useHold.d.ts +42 -0
  86. package/dist/components/jogging/useJogControls.d.ts +44 -0
  87. package/dist/components/robotControl/PanelSelect.d.ts +13 -0
  88. package/dist/components/robotControl/SmallSelect.d.ts +15 -0
  89. package/dist/components/robotControl/poseText.d.ts +43 -0
  90. package/dist/components/robotControl/robotControlTypes.d.ts +36 -0
  91. package/dist/components/robotControl/useCopyText.d.ts +12 -0
  92. package/dist/components/robotControl/useEveryFrame.d.ts +6 -0
  93. package/dist/components/robots/GenericRobot.d.ts +2 -1
  94. package/dist/components/robots/LinearAxis.d.ts +1 -1
  95. package/dist/components/robots/LinearAxisAnimator.d.ts +11 -2
  96. package/dist/components/robots/Robot.d.ts +1 -1
  97. package/dist/components/robots/robotModelLogic.d.ts +11 -9
  98. package/dist/components/utils/converters.d.ts +0 -2
  99. package/dist/components/utils/hooks.d.ts +1 -6
  100. package/dist/components/utils/json.d.ts +4 -0
  101. package/dist/components/utils/useSmoothedMotionState.d.ts +11 -2
  102. package/dist/components/utils/useWebGLRenderer.d.ts +32 -0
  103. package/dist/components/utils/webglSupport.d.ts +11 -0
  104. package/dist/core.cjs +1 -1
  105. package/dist/core.d.ts +28 -20
  106. package/dist/core.js +57 -54
  107. package/dist/index.cjs +1 -1
  108. package/dist/index.js +73 -70
  109. package/dist/lib/ConnectedMotionGroup.d.ts +9 -8
  110. package/dist/lib/ControllerStateStream.d.ts +125 -0
  111. package/dist/lib/JoggerConnection.d.ts +172 -27
  112. package/dist/lib/MotionStreamConnection.d.ts +16 -6
  113. package/dist/lib/Pose3.d.ts +22 -0
  114. package/dist/lib/PoseTransformer.d.ts +44 -0
  115. package/dist/lib/TrajectoryExecutionStore.d.ts +260 -0
  116. package/dist/lib/connectionLogger.d.ts +9 -0
  117. package/dist/lib/controllerStateSource.d.ts +38 -0
  118. package/dist/lib/incrementalCartesianMotion.d.ts +40 -0
  119. package/dist/lib/motionGroupModelResources.d.ts +1 -0
  120. package/dist/lib/motionStateUpdate.d.ts +44 -0
  121. package/dist/lib/nats/natsControllerStateSource.d.ts +27 -0
  122. package/dist/lib/novaConnection.d.ts +23 -0
  123. package/dist/lib/planErrorTranslation.d.ts +8 -0
  124. package/dist/lib/poseMath.d.ts +51 -0
  125. package/dist/lib/robotSession/RobotActivation.d.ts +90 -0
  126. package/dist/lib/robotSession/RobotDescription.d.ts +84 -0
  127. package/dist/lib/robotSession/RobotLiveState.d.ts +65 -0
  128. package/dist/lib/robotSession/RobotLoadProgress.d.ts +72 -0
  129. package/dist/lib/robotSession/RobotSafety.d.ts +59 -0
  130. package/dist/lib/robotSession/RobotSession.d.ts +117 -0
  131. package/dist/lib/robotSession/RobotTargetPose.d.ts +116 -0
  132. package/dist/lib/robotSession/loadRobotResources.d.ts +46 -0
  133. package/dist/lib/robotSession/loadRobotSession.d.ts +81 -0
  134. package/dist/lib/robotSession/robotPose.d.ts +27 -0
  135. package/dist/lib/rotation.d.ts +12 -0
  136. package/dist/nats.cjs +1 -0
  137. package/dist/nats.d.ts +4 -0
  138. package/dist/nats.js +131 -0
  139. package/dist/session.cjs +1 -0
  140. package/dist/session.d.ts +22 -0
  141. package/dist/session.js +33 -0
  142. package/package.json +68 -66
  143. package/dist/Setup.d.ts +0 -11
  144. package/dist/chunks/MotionGroupVisualizer-DshWR1wY.js +0 -1653
  145. package/dist/chunks/MotionGroupVisualizer-eD7yFEcF.cjs +0 -1
  146. package/dist/chunks/SafetyBar-DPrv_OQA.cjs +0 -1
  147. package/dist/chunks/externalizeComponent-OO4jcrz5.cjs +0 -2
  148. package/dist/chunks/theming-DfSy4-Ic.cjs +0 -4
  149. package/dist/chunks/theming-mF9Rt8SS.js +0 -5542
  150. package/dist/chunks/useSmoothedMotionState-DyDgSVYX.js +0 -478
  151. package/dist/chunks/useSmoothedMotionState-VYxEIyfr.cjs +0 -1
  152. package/dist/components/3d-viewport/CoordinateSystemTransform.d.ts +0 -11
  153. package/dist/components/AdornedTextField.d.ts +0 -7
  154. package/dist/components/CopyableText.d.ts +0 -6
  155. package/dist/components/CycleTimer/CycleTimer.d.ts +0 -3
  156. package/dist/components/CycleTimer/DefaultVariant.d.ts +0 -9
  157. package/dist/components/CycleTimer/SmallVariant.d.ts +0 -10
  158. package/dist/components/CycleTimer/index.d.ts +0 -27
  159. package/dist/components/CycleTimer/types.d.ts +0 -49
  160. package/dist/components/CycleTimer/useAnimations.d.ts +0 -14
  161. package/dist/components/CycleTimer/useTimerLogic.d.ts +0 -24
  162. package/dist/components/CycleTimer/utils.d.ts +0 -21
  163. package/dist/components/CycleTimer.d.ts +0 -3
  164. package/dist/components/DataGrid.d.ts +0 -66
  165. package/dist/components/LogPanel.d.ts +0 -38
  166. package/dist/components/LogStore.d.ts +0 -12
  167. package/dist/components/LogViewer.d.ts +0 -46
  168. package/dist/components/ProgramControl.d.ts +0 -55
  169. package/dist/components/ProgramStateIndicator.d.ts +0 -26
  170. package/dist/components/RobotCard.d.ts +0 -98
  171. package/dist/components/RobotListItem.d.ts +0 -34
  172. package/dist/components/RobotSetupReadinessIndicator.d.ts +0 -37
  173. package/dist/components/SelectableFab.d.ts +0 -7
  174. package/dist/components/TabBar.d.ts +0 -45
  175. package/dist/components/ThemeSelect.d.ts +0 -6
  176. package/dist/components/Timer/Timer.d.ts +0 -3
  177. package/dist/components/Timer/TimerDefaultVariant.d.ts +0 -9
  178. package/dist/components/Timer/TimerSmallVariant.d.ts +0 -10
  179. package/dist/components/Timer/index.d.ts +0 -19
  180. package/dist/components/Timer/types.d.ts +0 -35
  181. package/dist/components/Timer/useTimerAnimations.d.ts +0 -10
  182. package/dist/components/Timer/useTimerLogic.d.ts +0 -19
  183. package/dist/components/Timer/utils.d.ts +0 -17
  184. package/dist/components/Timer.d.ts +0 -3
  185. package/dist/components/TransparentOverlay.d.ts +0 -4
  186. package/dist/components/jogging/JoggingFreedriveTab.d.ts +0 -1
  187. package/dist/components/jogging/PoseCartesianValues.d.ts +0 -9
  188. package/dist/components/jogging/PoseJointValues.d.ts +0 -8
  189. package/dist/components/robots/AxisConfig.d.ts +0 -2
  190. package/dist/components/robots/manufacturerHomePositions.d.ts +0 -20
  191. package/dist/icons/DropdownArrowIcon.d.ts +0 -2
  192. package/dist/icons/index.d.ts +0 -12
  193. package/dist/lib/novaCompat.d.ts +0 -16
  194. package/dist/themes/createDarkTheme.d.ts +0 -7
  195. package/dist/themes/themeTypes.d.ts +0 -40
  196. package/dist/themes/theming.d.ts +0 -24
@@ -0,0 +1,3761 @@
1
+ import { tryParseJson as C, degreesToRadians as Kt, makeErrorMessage as R } from "@wandelbots/nova-js";
2
+ import { runInAction as _, makeAutoObservable as w, computed as Tt, when as A, autorun as ht, reaction as M } from "mobx";
3
+ import { t as vt } from "./json-3cqBD7UQ.js";
4
+ import { c as G, a as ct } from "./novaConnection-J6_ohIQ0.js";
5
+ import { isAxiosError as Mt } from "axios";
6
+ import { JointTypeEnum as O } from "@wandelbots/nova-js/v2";
7
+ import { keyBy as D, countBy as Qt, uniqueId as qt, isEqual as Zt } from "lodash-es";
8
+ import { j as gt, p as ut, a as Xt, b as te } from "./poseText-CtdXIeT_.js";
9
+ function ee(i) {
10
+ switch (i.code) {
11
+ case "locked":
12
+ return "jogging is locked";
13
+ case "blocked":
14
+ return "another client holds the jogging connection";
15
+ case "disconnected":
16
+ return "the robot's live state stopped coming";
17
+ case "safety_state":
18
+ return `the safety state is ${i.value}`;
19
+ case "operation_mode":
20
+ return `the operation mode is ${i.value}`;
21
+ case "deactivated":
22
+ return "the robot is not activated";
23
+ }
24
+ }
25
+ class U extends Error {
26
+ /** @internal The jogging store makes it, see JoggingStore */
27
+ constructor(t) {
28
+ super(`Jogging refused: ${ee(t)}`), this.name = "JoggingRefusedError", this.reason = t;
29
+ }
30
+ }
31
+ const Y = { x: 0, y: 0, z: 0, w: 1 }, oe = { x: 0, y: 1, z: 2 };
32
+ function F([i, t, e]) {
33
+ return Math.sqrt(i * i + t * t + e * e);
34
+ }
35
+ function J([i, t, e], o) {
36
+ return [i * o, t * o, e * o];
37
+ }
38
+ function B(i) {
39
+ return J(i, 1 / (F(i) || 1));
40
+ }
41
+ function ie(i, t) {
42
+ return i[0] * t[0] + i[1] * t[1] + i[2] * t[2];
43
+ }
44
+ function ot(i, t) {
45
+ const e = [0, 0, 0];
46
+ return e[oe[i]] = t, e;
47
+ }
48
+ function k([i, t, e], { x: o, y: s, z: n, w: r }) {
49
+ const a = 2 * (s * e - n * t), d = 2 * (n * i - o * e), c = 2 * (o * t - s * i);
50
+ return [
51
+ i + r * a + s * c - n * d,
52
+ t + r * d + n * a - o * c,
53
+ e + r * c + o * d - s * a
54
+ ];
55
+ }
56
+ function Ot(i, t) {
57
+ const e = t / 2, o = Math.sin(e);
58
+ return {
59
+ x: i[0] * o,
60
+ y: i[1] * o,
61
+ z: i[2] * o,
62
+ w: Math.cos(e)
63
+ };
64
+ }
65
+ function it(i, t) {
66
+ return {
67
+ x: i.x * t.w + i.w * t.x + i.y * t.z - i.z * t.y,
68
+ y: i.y * t.w + i.w * t.y + i.z * t.x - i.x * t.z,
69
+ z: i.z * t.w + i.w * t.z + i.x * t.y - i.y * t.x,
70
+ w: i.w * t.w - i.x * t.x - i.y * t.y - i.z * t.z
71
+ };
72
+ }
73
+ function se(i) {
74
+ const { x: t, y: e, z: o, w: s } = i, n = Math.sqrt(t * t + e * e + o * o + s * s);
75
+ if (n === 0)
76
+ return Y;
77
+ const r = 1 / n;
78
+ return { x: t * r, y: e * r, z: o * r, w: s * r };
79
+ }
80
+ function ne({ x: i, y: t, z: e, w: o }) {
81
+ return { x: -i, y: -t, z: -e, w: o };
82
+ }
83
+ function W(i, t) {
84
+ if (t === "QUATERNION" && i) {
85
+ const [e = 0, o = 0, s = 0, n = 1] = i;
86
+ return { x: e, y: o, z: s, w: n };
87
+ }
88
+ if (t === "ROTATION_VECTOR" && i) {
89
+ if (i.length < 3)
90
+ throw new Error(
91
+ `Invalid rotation vector length: ${i.length}. Expected at least 3 values.`
92
+ );
93
+ const [e = 0, o = 0, s = 0] = i, n = [e, o, s];
94
+ return Ot(
95
+ B(n),
96
+ F(n)
97
+ );
98
+ }
99
+ return console.warn(
100
+ `Unsupported rotation type '${t}'. Only QUATERNION and ROTATION_VECTOR are supported for now.`
101
+ ), Y;
102
+ }
103
+ function Ct({ x: i, y: t, z: e, w: o }) {
104
+ const s = [i, t, e], n = 2 * Math.atan2(F(s), Math.abs(o)), r = (o >= 0 ? 1 : 0) - (o < 0 ? 1 : 0);
105
+ return J(J(B(s), r), n);
106
+ }
107
+ function Rt(i) {
108
+ return [(i == null ? void 0 : i[0]) ?? 0, (i == null ? void 0 : i[1]) ?? 0, (i == null ? void 0 : i[2]) ?? 0];
109
+ }
110
+ function bt(i) {
111
+ return {
112
+ position: Rt(i.position),
113
+ quaternion: i.orientation ? W(i.orientation, "ROTATION_VECTOR") : Y
114
+ };
115
+ }
116
+ function b(i) {
117
+ return {
118
+ position: Rt(i.position),
119
+ quaternion: i.orientation ? W(
120
+ i.orientation,
121
+ i.orientation_type ?? "ROTATION_VECTOR"
122
+ ) : Y
123
+ };
124
+ }
125
+ function $(i, t) {
126
+ const e = k(t.position, i.quaternion);
127
+ return {
128
+ position: [
129
+ i.position[0] + e[0],
130
+ i.position[1] + e[1],
131
+ i.position[2] + e[2]
132
+ ],
133
+ quaternion: se(
134
+ it(i.quaternion, t.quaternion)
135
+ )
136
+ };
137
+ }
138
+ function Pt(i) {
139
+ const t = ne(i.quaternion);
140
+ return {
141
+ position: J(k(i.position, t), -1),
142
+ quaternion: t
143
+ };
144
+ }
145
+ function re({
146
+ currentTcpPose: i,
147
+ axis: t,
148
+ direction: e,
149
+ motion: o,
150
+ useToolCoordinateSystem: s,
151
+ coordinateSystemRotation: n
152
+ }) {
153
+ const r = e === "-" ? -1 : 1;
154
+ if (o.type === "translate") {
155
+ if (!i.position)
156
+ throw new Error(
157
+ "Current pose has no position, cannot perform translation"
158
+ );
159
+ let h = ot(t, o.distanceMm * r);
160
+ if (s) {
161
+ if (!i.orientation)
162
+ throw new Error(
163
+ "Current pose has no orientation, cannot translate relative to tool"
164
+ );
165
+ h = k(
166
+ h,
167
+ W(i.orientation, "ROTATION_VECTOR")
168
+ );
169
+ } else n && (h = k(h, n));
170
+ const g = [...i.position];
171
+ return g[0] = (g[0] ?? 0) + h[0], g[1] = (g[1] ?? 0) + h[1], g[2] = (g[2] ?? 0) + h[2], {
172
+ position: g,
173
+ orientation: i.orientation
174
+ };
175
+ }
176
+ if (!i.orientation)
177
+ throw new Error("Current pose has no orientation, cannot perform rotation");
178
+ const a = W(
179
+ i.orientation,
180
+ "ROTATION_VECTOR"
181
+ );
182
+ let d = ot(t, 1);
183
+ !s && n && (d = k(d, n));
184
+ const c = Ot(
185
+ d,
186
+ o.distanceRads * r
187
+ ), l = s ? it(a, c) : it(c, a);
188
+ return {
189
+ position: i.position,
190
+ orientation: Ct(l)
191
+ };
192
+ }
193
+ function K(i, t, e) {
194
+ return t.length !== i.length ? !1 : kt(i, t, e);
195
+ }
196
+ function ae(i, t, e) {
197
+ return t.length !== i.length ? !0 : kt(i, t, e);
198
+ }
199
+ function kt(i, t, e) {
200
+ for (let o = 0; o < t.length; o++)
201
+ if (Math.abs(
202
+ (t[o] ?? 0) - (i[o] ?? 0)
203
+ ) > e)
204
+ return !1;
205
+ return !0;
206
+ }
207
+ function ce(i, t, e) {
208
+ if (i === void 0 && t || i && t === void 0 || (i == null ? void 0 : i.orientation) === void 0 || (t == null ? void 0 : t.orientation) === void 0 || (i == null ? void 0 : i.position) === void 0 || (t == null ? void 0 : t.position) === void 0)
209
+ return !1;
210
+ if (i === void 0 || t === void 0)
211
+ return !0;
212
+ let o = 0;
213
+ return o += Math.abs(i.orientation[0] - t.orientation[0]), o += Math.abs(i.orientation[1] - t.orientation[1]), o += Math.abs(i.orientation[2] - t.orientation[2]), o += Math.abs(i.position[0] - t.position[0]), o += Math.abs(i.position[1] - t.position[1]), o += Math.abs(i.position[2] - t.position[2]), o <= e;
214
+ }
215
+ function le(i, t, e) {
216
+ return i.coordinate_system === t.coordinate_system && i.tcp === t.tcp && ce(
217
+ i.tcp_pose,
218
+ t.tcp_pose,
219
+ e
220
+ );
221
+ }
222
+ function At(i, t) {
223
+ const [e = 0, o = 0, s = 0] = t, n = [e, o, s], [r = 0, a = 0, d = 0] = i, c = [r, a, d], l = F(n), h = B(n);
224
+ let g = F(c), f = B(c);
225
+ ie(f, h) < 0 && (g = -g, f = J(f, -1));
226
+ let p = g - l;
227
+ return p -= 2 * Math.PI * Math.floor((p + Math.PI) / (2 * Math.PI)), g = l + p, J(f, g);
228
+ }
229
+ const de = 2e-4;
230
+ function Jt(i) {
231
+ const { joint_position: t, tcp_pose: e, tcp: o, coordinate_system: s } = i;
232
+ return { joint_position: t, tcp_pose: e, tcp: o, coordinate_system: s };
233
+ }
234
+ function Nt(i, t) {
235
+ return i.tcp === t.tcp && i.coordinate_system === t.coordinate_system && i.tcp_pose === void 0 == (t.tcp_pose === void 0) && K(
236
+ i.joint_position,
237
+ t.joint_position,
238
+ de
239
+ );
240
+ }
241
+ const pt = 1e-4;
242
+ class Q {
243
+ constructor(t, e, o, s, n, r, a = "cell", d = {}) {
244
+ this.controller = e, this.motionGroup = o, this.description = s, this.initialMotionState = n, this.motionStateSocket = r, this.cellId = a, this.nova = G(t), this.logger = d.logger ?? console, this.rapidlyChangingMotionState = n, r.addEventListener("message", (c) => {
245
+ var f;
246
+ const l = (f = C(c.data)) == null ? void 0 : f.result;
247
+ if (!l)
248
+ throw new Error(
249
+ `Failed to get motion state for ${this.motionGroupId}: ${c.data}`
250
+ );
251
+ le(
252
+ this.rapidlyChangingMotionState,
253
+ l,
254
+ pt
255
+ ) || _(() => {
256
+ var p, y, u;
257
+ this.rapidlyChangingMotionState.tcp_pose == null ? this.rapidlyChangingMotionState.tcp_pose = l.tcp_pose : (p = l.tcp_pose) != null && p.orientation && ((y = l.tcp_pose) != null && y.position) && ((u = this.rapidlyChangingMotionState.tcp_pose) != null && u.orientation) ? this.rapidlyChangingMotionState.tcp_pose = {
258
+ position: l.tcp_pose.position,
259
+ orientation: At(
260
+ l.tcp_pose.orientation,
261
+ this.rapidlyChangingMotionState.tcp_pose.orientation
262
+ )
263
+ } : this.logger.debug("Received incomplete tcp_pose, ignoring", {
264
+ tcpPose: l.tcp_pose
265
+ });
266
+ }), ae(
267
+ this.rapidlyChangingMotionState.joint_position,
268
+ l.joint_position,
269
+ pt
270
+ ) || _(() => {
271
+ this.rapidlyChangingMotionState.joint_position = l.joint_position;
272
+ }), l.tcp !== void 0 && this.rapidlyChangingMotionState.tcp !== l.tcp && _(() => {
273
+ this.rapidlyChangingMotionState.tcp = l.tcp;
274
+ }), this.rapidlyChangingMotionState.standstill !== l.standstill && _(() => {
275
+ this.rapidlyChangingMotionState.standstill = l.standstill;
276
+ });
277
+ const h = this.rapidlyChangingMotionState.joint_limit_reached.limit_reached, g = l.joint_limit_reached.limit_reached;
278
+ h.some((p, y) => p !== g[y]) && _(() => {
279
+ this.rapidlyChangingMotionState.joint_limit_reached = l.joint_limit_reached;
280
+ }), this.rapidlyChangingMotionState.execute !== l.execute && _(() => {
281
+ this.rapidlyChangingMotionState.execute = l.execute;
282
+ });
283
+ }), w(this, {
284
+ logger: !1,
285
+ // keepAlive: pose readouts poll it from requestAnimationFrame, which
286
+ // MobX does not track, and a computed nobody observes is recomputed on
287
+ // every read without consulting `equals`
288
+ readoutState: Tt({ equals: Nt, keepAlive: !0 })
289
+ });
290
+ }
291
+ static async open(t, e, o = {}) {
292
+ var y;
293
+ const s = G(t), n = o.cellId ?? ct(t) ?? "cell", [r, a] = e.split("@"), d = await s.api.controller.getCurrentRobotControllerState(
294
+ n,
295
+ a
296
+ ), c = d == null ? void 0 : d.motion_groups.find(
297
+ (u) => u.motion_group === e
298
+ );
299
+ if (!d || !c)
300
+ throw new Error(
301
+ `Controller ${a} or motion group ${e} not found`
302
+ );
303
+ const l = s.openReconnectingWebsocket(
304
+ `/cells/${n}/controllers/${a}/motion-groups/${e}/state-stream`
305
+ ), h = await l.firstMessage(), g = (y = C(h.data)) == null ? void 0 : y.result;
306
+ if (!g)
307
+ throw new Error(
308
+ `Unable to parse initial motion state message ${h.data}`
309
+ );
310
+ const f = o.logger ?? console;
311
+ f.info("Connected motion state websocket to motion group", {
312
+ motionGroup: c.motion_group,
313
+ initialMotionState: g
314
+ });
315
+ const p = await s.api.motionGroup.getMotionGroupDescription(
316
+ n,
317
+ a,
318
+ c.motion_group
319
+ );
320
+ return new Q(
321
+ s,
322
+ d,
323
+ c,
324
+ p,
325
+ g,
326
+ l,
327
+ n,
328
+ { logger: f }
329
+ );
330
+ }
331
+ /**
332
+ * What pose readouts show (joints, TCP pose): it holds the previous reading
333
+ * while the joints only jitter (less than 0.0002 rad), and while the TCP and
334
+ * the coordinate system stay. Kept alive, so it also holds for untracked
335
+ * reads, e.g. from requestAnimationFrame.
336
+ */
337
+ get readoutState() {
338
+ return Jt(this.rapidlyChangingMotionState);
339
+ }
340
+ get motionGroupId() {
341
+ return this.motionGroup.motion_group;
342
+ }
343
+ get controllerId() {
344
+ return this.controller.controller;
345
+ }
346
+ get joints() {
347
+ return this.initialMotionState.joint_position.map((t, e) => ({
348
+ index: e
349
+ }));
350
+ }
351
+ dispose() {
352
+ this.motionStateSocket.close();
353
+ }
354
+ }
355
+ const mt = "Movement request rejected. Another client is currently executing a 'Jogging' motion!", he = 1, ge = 5e3;
356
+ function ue(i) {
357
+ var e;
358
+ return (((e = i.times) == null ? void 0 : e[i.times.length - 1]) ?? 0) * 2e3 + ge;
359
+ }
360
+ class lt {
361
+ constructor(t, e = {}) {
362
+ this.motionStream = t, this.options = e, this.DEFAULT_MODE = "off", this.DEFAULT_TCP = "Flange", this.NO_TCP = void 0, this.DEFAULT_INIT_TIMEOUT = 5e3, this.DEFAULT_ORIENTATION = "coordsys", this.mode = "off", this.joggingSocket = null, this.trajectorySocket = null, this.timeout = this.DEFAULT_INIT_TIMEOUT, this.incrementalMotionInFlight = !1, this.ownsMotionStream = !1, this.tcp = (e == null ? void 0 : e.tcp) || t.motionGroup.tcp || this.getDefaultTcp(t), this.coordinateSystem = e == null ? void 0 : e.coordinateSystem, this.orientation = (e == null ? void 0 : e.orientation) || this.DEFAULT_ORIENTATION, this.timeout = (e == null ? void 0 : e.timeout) || this.DEFAULT_INIT_TIMEOUT, this.mode = (e == null ? void 0 : e.mode) || this.DEFAULT_MODE, this.onError = e == null ? void 0 : e.onError, this.logger = (e == null ? void 0 : e.logger) ?? console;
363
+ }
364
+ /**
365
+ * Initialize the jogging connection using jogging endpoint or trajectory endpoint depending on the selected mode.
366
+ *
367
+ * @param connection - The base URL of a NOVA instance, or a NOVA client of the app (see `NovaConnection`)
368
+ * @param motionGroupId - The ID of the motion group to connect to
369
+ * @param options - Configuration options for the jogger connection
370
+ * @param options.mode - The jogging mode to initialize:
371
+ * - "jogging": Continuous jogging mode with persistent websocket for real-time velocity commands
372
+ * - "trajectory": Incremental jogging mode for fixed-distance motions via trajectory planning
373
+ * - "off": No jogging enabled, all websockets closed (default)
374
+ * @param options.timeout - Timeout in milliseconds for websocket initialization (default: 5000ms)
375
+ * @param options.tcp - TCP frame to use for motions (default: from motion group)
376
+ * @param options.coordinateSystem - Coordinate system whose axes cartesian jogging moves along, relative to world (default: world)
377
+ * @param options.orientation - If set to "tool", jogging TcpVelocityRequest will use `use_tool_coordinate_system` option (default: "coordsys")
378
+ * @param options.onError - Error handler for websocket errors and step jogs
379
+ * @param options.motionGroupModel - Model name for planning step jogs (default: from the motion group description)
380
+ * @param options.logger - Where the jogger and its motion stream log (default: the console)
381
+ * @returns Promise resolving to initialized JoggerConnection instance. Its
382
+ * `dispose()` also closes the motion stream that this function opens.
383
+ */
384
+ static async open(t, e, o = {}) {
385
+ const s = await Q.open(
386
+ t,
387
+ e,
388
+ {
389
+ cellId: o.cellId,
390
+ logger: o.logger
391
+ }
392
+ ), n = new lt(s, o);
393
+ n.ownsMotionStream = !0;
394
+ try {
395
+ await n.setJoggingMode(n.mode);
396
+ } catch (r) {
397
+ throw n.dispose(), r;
398
+ }
399
+ return n;
400
+ }
401
+ getDefaultTcp(t) {
402
+ var o, s;
403
+ const e = (s = (o = t.description.dh_parameters) == null ? void 0 : o[0]) == null ? void 0 : s.type;
404
+ return t.joints.length < 6 && (e === O.RevoluteJoint || e === O.PrismaticJoint) ? this.NO_TCP : this.DEFAULT_TCP;
405
+ }
406
+ // Set a new tcp or other options. If current mode is jogging, will reinitialize the jogging websocket
407
+ async setOptions(t) {
408
+ return t.tcp && (this.tcp = t.tcp), t.orientation && (this.orientation = t.orientation), "coordinateSystem" in t && (this.coordinateSystem = t.coordinateSystem), t.timeout && (this.timeout = t.timeout), t.mode && (this.mode = t.mode), t.onError && (this.onError = t.onError), this.setJoggingMode(this.mode, !1);
409
+ }
410
+ get motionGroupId() {
411
+ return this.motionStream.motionGroupId;
412
+ }
413
+ /**
414
+ * The library's own NOVA client of the motion stream
415
+ * @internal
416
+ */
417
+ get nova() {
418
+ return this.motionStream.nova;
419
+ }
420
+ get cellId() {
421
+ return this.motionStream.cellId;
422
+ }
423
+ get numJoints() {
424
+ return this.motionStream.joints.length;
425
+ }
426
+ // get activeJoggingMode() {
427
+ // return this.mode
428
+ // }
429
+ // get activeWebsocket() {
430
+ // return this.mode === "jogging" ? this.joggingSocket : this.trajectorySocket;
431
+ // }
432
+ // Sends stop movement command to robot
433
+ async stop() {
434
+ if (this.joggingSocket) {
435
+ const t = new Array(this.numJoints).fill(0);
436
+ this.joggingSocket.sendJson({
437
+ message_type: "JointVelocityRequest",
438
+ velocity: t
439
+ });
440
+ }
441
+ this.trajectorySocket && this.trajectorySocket.sendJson({
442
+ message_type: "PauseMovementRequest"
443
+ });
444
+ }
445
+ /**
446
+ * Dispose the jogger, closing all open websockets: the jogging websockets,
447
+ * and the motion stream if the jogger opened it (in `open()`). A motion
448
+ * stream given to the constructor stays open: its caller closes it.
449
+ */
450
+ async dispose() {
451
+ const t = this.closeJoggingSockets();
452
+ return this.ownsMotionStream && this.motionStream.dispose(), t;
453
+ }
454
+ /** Closes the jogging and trajectory websockets */
455
+ closeJoggingSockets() {
456
+ var e, o;
457
+ (e = this.endJoggingInit) == null || e.call(this), (o = this.endIncrementalMotion) == null || o.call(this);
458
+ const t = [this.joggingSocket, this.trajectorySocket].filter(
459
+ (s) => s !== null
460
+ );
461
+ return t.forEach((s) => {
462
+ s.dispose();
463
+ }), this.joggingSocket = null, this.trajectorySocket = null, Promise.all(t.map((s) => s.closed()));
464
+ }
465
+ // Activate jogger in one of the supported modes
466
+ // Will iniitialize or close websockets as necessary
467
+ // If mode is unchanged, does nothing (unless skipReinitializeIfSameMode is false)
468
+ async setJoggingMode(t, e = !0) {
469
+ if (!(this.mode === t && e) && (this.closeJoggingSockets(), this.mode = t, this.mode === "jogging"))
470
+ return this.initializeJoggingWebsocket();
471
+ }
472
+ /**
473
+ * Opens the continuous jogging websocket and initializes it; called by
474
+ * `setJoggingMode("jogging")`. The promise settles once:
475
+ * - it resolves when NOVA confirms the initialization (INITIALIZE_RECEIVED),
476
+ * when the jogger closes the websocket before that (`setJoggingMode`,
477
+ * `dispose`), or when an error message goes to `onBlocked` or `onError`;
478
+ * - it rejects on an error message without such a handler, and when NOVA
479
+ * does not confirm the initialization within `timeout` milliseconds.
480
+ */
481
+ async initializeJoggingWebsocket() {
482
+ return new Promise((t, e) => {
483
+ const o = this.nova.openReconnectingWebsocket(
484
+ `/cells/${this.cellId}/controllers/${this.motionStream.controllerId}/execution/jogging`
485
+ );
486
+ this.joggingSocket = o;
487
+ let s = !1;
488
+ const n = setTimeout(() => {
489
+ r(
490
+ new Error(`Jogging initialization timeout after ${this.timeout} ms`)
491
+ );
492
+ }, this.timeout), r = (c) => {
493
+ s || (s = !0, clearTimeout(n), o.removeEventListener("close", d), this.endJoggingInit === a && (this.endJoggingInit = void 0), c ? e(c) : t());
494
+ }, a = () => r(), d = () => {
495
+ o.disposed && r();
496
+ };
497
+ this.endJoggingInit = a, o.addEventListener("close", d), o.addEventListener("message", (c) => {
498
+ var h, g, f;
499
+ const l = C(c.data);
500
+ if (((h = l == null ? void 0 : l.result) == null ? void 0 : h.kind) === "INITIALIZE_RECEIVED") {
501
+ r();
502
+ return;
503
+ }
504
+ if (((g = l == null ? void 0 : l.result) == null ? void 0 : g.kind) === "MOTION_ERROR")
505
+ if (this.onBlocked && ((f = l == null ? void 0 : l.result) != null && f.message.includes(mt))) {
506
+ r(), o.dispose(), this.onBlocked();
507
+ return;
508
+ } else this.onError ? (r(), this.onError(c.data)) : r(new Error(c.data));
509
+ }), o.sendJson({
510
+ message_type: "InitializeJoggingRequest",
511
+ motion_group: this.motionGroupId,
512
+ ...this.tcp ? { tcp: this.tcp } : {}
513
+ });
514
+ });
515
+ }
516
+ /**
517
+ * Jogging: Start rotation of a single robot joint at the specified velocity
518
+ */
519
+ async rotateJoints({
520
+ joint: t,
521
+ direction: e,
522
+ velocityValue: o,
523
+ velocityUnit: s
524
+ }) {
525
+ if (!this.joggingSocket || this.mode !== "jogging")
526
+ throw new Error(
527
+ "Joint jogging websocket not connected; create one by setting jogging mode to 'jogging'"
528
+ );
529
+ const n = new Array(this.numJoints).fill(0);
530
+ n[t] = e === "-" ? -o : o, this.joggingSocket.sendJson({
531
+ message_type: "JointVelocityRequest",
532
+ velocity: n
533
+ });
534
+ }
535
+ /**
536
+ * Jogging: Start the TCP moving along a specified axis at a given velocity
537
+ */
538
+ async translateTCP({
539
+ axis: t,
540
+ direction: e,
541
+ velocityMmPerSec: o
542
+ }) {
543
+ if (!this.joggingSocket || this.mode !== "jogging")
544
+ throw new Error(
545
+ "Continuous jogging websocket not connected; create one by setting jogging mode to 'jogging'"
546
+ );
547
+ this.joggingSocket.sendJson({
548
+ message_type: "TcpVelocityRequest",
549
+ translation: this.velocityAlongAxis(
550
+ t,
551
+ e === "-" ? -o : o
552
+ ),
553
+ rotation: [0, 0, 0],
554
+ use_tool_coordinate_system: this.orientation === "tool"
555
+ });
556
+ }
557
+ /**
558
+ * Jogging: Start the TCP rotating around a specified axis at a given velocity
559
+ */
560
+ async rotateTCP({
561
+ axis: t,
562
+ direction: e,
563
+ velocityRadsPerSec: o
564
+ }) {
565
+ if (!this.joggingSocket || this.mode !== "jogging")
566
+ throw new Error(
567
+ "Continuous jogging websocket not connected; create one by setting jogging mode to 'jogging'"
568
+ );
569
+ this.joggingSocket.sendJson({
570
+ message_type: "TcpVelocityRequest",
571
+ translation: [0, 0, 0],
572
+ rotation: this.velocityAlongAxis(
573
+ t,
574
+ e === "-" ? -o : o
575
+ ),
576
+ use_tool_coordinate_system: this.orientation === "tool"
577
+ });
578
+ }
579
+ /**
580
+ * Rotation from {@link JoggerConnection.coordinateSystem} into world,
581
+ * while jogging along its axes. Undefined when jogging along world or tool
582
+ * axes.
583
+ */
584
+ get coordinateSystemRotation() {
585
+ if (!(this.orientation === "tool" || !this.coordinateSystem))
586
+ return b(this.coordinateSystem).quaternion;
587
+ }
588
+ /**
589
+ * Velocity vector along one axis of the jogging frame. The API takes TCP
590
+ * velocities in either the tool frame or world, so an axis of
591
+ * {@link JoggerConnection.coordinateSystem} is rotated into world here.
592
+ */
593
+ velocityAlongAxis(t, e) {
594
+ const o = ot(t, e), s = this.coordinateSystemRotation;
595
+ return s ? k(o, s) : o;
596
+ }
597
+ /**
598
+ * Trajectory jogging:
599
+ *
600
+ * Move the robot by a fixed distance in a single cartesian
601
+ * axis, either rotating or translating relative to the TCP.
602
+ * The axis is one of the tool in tool orientation, else one of
603
+ * {@link JoggerConnection.coordinateSystem} (default: world).
604
+ *
605
+ * Promise resolves only after the motion has completed: once NOVA reports
606
+ * the trajectory at its end, or no longer as running (`stop()`), and the
607
+ * robot stands still, or after a watchdog of twice the planned duration
608
+ * plus 5 s, which also ends a step that never starts. A step requested
609
+ * while another one runs is dropped (resolves at once). Every error (a
610
+ * refused or failed plan, a refused trajectory, an error of the
611
+ * controller, the watchdog) goes to `onError`, or without it rejects the
612
+ * promise. A step that the robot may no longer make (see
613
+ * {@link IncrementalCartesianMotionRequest.refusedReason}) rejects with a
614
+ * `JoggingRefusedError`.
615
+ */
616
+ async runIncrementalCartesianMotion(t) {
617
+ if (this.mode !== "trajectory")
618
+ throw new Error(
619
+ "Set jogging mode to 'trajectory' to run incremental cartesian motions"
620
+ );
621
+ if (!this.incrementalMotionInFlight) {
622
+ this.incrementalMotionInFlight = !0;
623
+ try {
624
+ const e = await this.planIncrementalCartesianMotion(t);
625
+ e && await this.executeTrajectory(e, t.refusedReason);
626
+ } finally {
627
+ this.incrementalMotionInFlight = !1;
628
+ }
629
+ }
630
+ }
631
+ /**
632
+ * Plan the trajectory for a single incremental jog. Returns undefined when
633
+ * no trajectory could be produced; the reason (a planner rejection such as a
634
+ * singularity, or a motion group without a cycle time) is reported through
635
+ * {@link JoggerConnection.onError} or logged.
636
+ */
637
+ async planIncrementalCartesianMotion({
638
+ currentTcpPose: t,
639
+ currentJoints: e,
640
+ velocityInRelevantUnits: o,
641
+ axis: s,
642
+ direction: n,
643
+ motion: r
644
+ }) {
645
+ var y, u, m;
646
+ const a = [], d = re({
647
+ currentTcpPose: t,
648
+ axis: s,
649
+ direction: n,
650
+ motion: r,
651
+ useToolCoordinateSystem: this.orientation === "tool",
652
+ coordinateSystemRotation: this.coordinateSystemRotation
653
+ });
654
+ a.push({
655
+ limits_override: r.type === "translate" ? { tcp_velocity_limit: o } : { tcp_orientation_velocity_limit: o },
656
+ path: {
657
+ path_definition_name: "PathLine",
658
+ target_pose: {
659
+ position: d.position,
660
+ orientation: d.orientation
661
+ }
662
+ }
663
+ });
664
+ const c = this.motionStream.description;
665
+ if (c.cycle_time === void 0) {
666
+ this.logger.warn(
667
+ "Current motion group has no cycle time, cannot plan jogging motion"
668
+ );
669
+ return;
670
+ }
671
+ const l = this.motionStream.rapidlyChangingMotionState.tcp, h = l ? (u = (y = c.tcps) == null ? void 0 : y[l]) == null ? void 0 : u.pose : void 0, g = {
672
+ motion_group_model: ((m = this.options) == null ? void 0 : m.motionGroupModel) ?? c.motion_group_model,
673
+ cycle_time: c.cycle_time,
674
+ mounting: c.mounting,
675
+ tcp_offset: h,
676
+ // FIXME use proper mode's limits if set
677
+ global: c.operation_limits.auto_limits
678
+ }, f = await this.nova.api.trajectoryPlanning.planTrajectory(
679
+ this.cellId,
680
+ {
681
+ motion_group_setup: g,
682
+ start_joint_position: e,
683
+ motion_commands: a
684
+ }
685
+ ), p = f.response;
686
+ if (!p)
687
+ throw new Error(
688
+ `Failed to plan jogging increment motion ${JSON.stringify(f)}`
689
+ );
690
+ if ("error_feedback" in p) {
691
+ if (this.onError) {
692
+ this.onError(p);
693
+ return;
694
+ }
695
+ throw new Error(
696
+ `Failed to plan jogging increment motion: ${JSON.stringify(p.error_feedback)}`
697
+ );
698
+ }
699
+ return p;
700
+ }
701
+ /**
702
+ * Execute a planned trajectory https://portal.wandelbots.io/docs/api/v2/ui/#/operations/executeTrajectory
703
+ * and resolve once the robot has run it to its end and stands still again
704
+ * (see {@link JoggerConnection.waitForMotionToFinish}), so that the caller
705
+ * -- and with it the jogging UI's motion lock -- stays blocked for the
706
+ * whole motion. It also resolves when the jogger closes the websocket
707
+ * (`setJoggingMode`, `dispose`).
708
+ *
709
+ * Each call owns its own websocket. Sharing
710
+ * {@link JoggerConnection.trajectorySocket} across motions meant a finishing
711
+ * motion closed the socket of a later one.
712
+ *
713
+ * `refusedReason` is asked right before the trajectory and its start go to
714
+ * NOVA, see {@link IncrementalCartesianMotionRequest.refusedReason}
715
+ */
716
+ async executeTrajectory(t, e = () => null) {
717
+ const o = e();
718
+ if (o)
719
+ throw new U(o);
720
+ const s = this.nova.openReconnectingWebsocket(
721
+ `/cells/${this.cellId}/controllers/${this.motionStream.controllerId}/execution/trajectory`
722
+ );
723
+ this.trajectorySocket = s;
724
+ const n = new AbortController();
725
+ let r, a;
726
+ try {
727
+ await new Promise((d, c) => {
728
+ let l = !1;
729
+ const h = () => {
730
+ l || (l = !0, d());
731
+ }, g = (u) => {
732
+ if (!l) {
733
+ if (l = !0, this.onError) {
734
+ this.onError(u), d();
735
+ return;
736
+ }
737
+ c(
738
+ u instanceof Error ? u : new Error(
739
+ `Failed to execute trajectory: ${JSON.stringify(u)}`
740
+ )
741
+ );
742
+ }
743
+ }, f = () => {
744
+ const u = e();
745
+ return u ? (l || (l = !0, c(new U(u))), !0) : !1;
746
+ };
747
+ a = h, this.endIncrementalMotion = h;
748
+ const p = ue(t);
749
+ r = setTimeout(() => {
750
+ g(
751
+ new Error(`Jogging motion did not complete within ${p}ms`)
752
+ );
753
+ }, p), s.addEventListener("message", (u) => {
754
+ var T, v;
755
+ const m = (T = C(u.data)) == null ? void 0 : T.result;
756
+ if (!(m != null && m.kind)) {
757
+ g(
758
+ new Error(
759
+ `Failed to execute trajectory: Received invalid message ${u.data}`
760
+ )
761
+ );
762
+ return;
763
+ }
764
+ if (this.onBlocked && ((v = m.message) != null && v.includes(mt))) {
765
+ this.onBlocked(), h();
766
+ return;
767
+ }
768
+ if (m.kind === "INITIALIZE_RECEIVED") {
769
+ if (m.add_trajectory_error || m.message) {
770
+ g(m);
771
+ return;
772
+ }
773
+ if (f()) return;
774
+ s.sendJson({
775
+ message_type: "StartMovementRequest",
776
+ direction: "DIRECTION_FORWARD"
777
+ });
778
+ } else if (m.kind === "START_RECEIVED") {
779
+ if (m.message) {
780
+ g(m);
781
+ return;
782
+ }
783
+ this.waitForMotionToFinish(t, n.signal).then(
784
+ h,
785
+ g
786
+ );
787
+ } else m.kind === "PAUSE_RECEIVED" ? this.waitUntilStopped(n.signal).then(h, g) : m.kind === "MOTION_ERROR" && m.message ? g(m) : g(
788
+ new Error(
789
+ `Failed to execute trajectory, cannot handle message type "${m.kind}"`
790
+ )
791
+ );
792
+ });
793
+ const y = () => {
794
+ f() || s.sendJson({
795
+ message_type: "InitializeMovementRequest",
796
+ trajectory: {
797
+ message_type: "TrajectoryData",
798
+ motion_group: this.motionGroupId,
799
+ data: t,
800
+ tcp: this.tcp
801
+ }
802
+ });
803
+ };
804
+ if (s.readyState === he)
805
+ y();
806
+ else {
807
+ const u = () => {
808
+ s.removeEventListener("open", u), y();
809
+ };
810
+ s.addEventListener("open", u);
811
+ }
812
+ });
813
+ } finally {
814
+ clearTimeout(r), n.abort(), this.endIncrementalMotion === a && (this.endIncrementalMotion = void 0), s.dispose(), this.trajectorySocket === s && (this.trajectorySocket = null);
815
+ }
816
+ }
817
+ /**
818
+ * Resolve once the robot has finished executing a trajectory.
819
+ *
820
+ * What says so is the execution state in the motion stream (`execute`),
821
+ * which NOVA gives to follow a movement. `standstill` alone does not: it
822
+ * says that NOVA treats the measured joint velocities as 0, which is so
823
+ * before the robot picks up speed and can be so for the whole of a slow
824
+ * motion. A step that took `standstill` as its end closed its websocket,
825
+ * and with it stopped the robot, soon after the start of a 5° turn at
826
+ * 1 °/s.
827
+ *
828
+ * So the step is over when NOVA has run the trajectory to its end, or no
829
+ * longer runs it after it did (NOVA executes nothing any more), and the
830
+ * robot stands still. A step that never starts does not get here: the
831
+ * watchdog of `executeTrajectory` ends it with an error.
832
+ */
833
+ async waitForMotionToFinish(t, e) {
834
+ const { locations: o } = t, s = (((o == null ? void 0 : o[0]) ?? 0) + ((o == null ? void 0 : o[o.length - 1]) ?? 0)) / 2, n = () => {
835
+ const r = this.executedTrajectory;
836
+ return (r == null ? void 0 : r.state.kind) === "END_OF_TRAJECTORY" && r.location >= s;
837
+ };
838
+ await A(() => this.isTrajectoryRunning || n(), { signal: e }), await this.waitUntilStopped(e);
839
+ }
840
+ /**
841
+ * Resolve once NOVA no longer runs a trajectory and the robot stands
842
+ * still: at the end of the trajectory, or after a pause
843
+ */
844
+ async waitUntilStopped(t) {
845
+ await A(
846
+ () => !this.isTrajectoryRunning && this.motionStream.rapidlyChangingMotionState.standstill,
847
+ { signal: t }
848
+ );
849
+ }
850
+ /** The trajectory that NOVA executes now, as the motion stream reports it */
851
+ get executedTrajectory() {
852
+ var e;
853
+ const t = (e = this.motionStream.rapidlyChangingMotionState.execute) == null ? void 0 : e.details;
854
+ return (t == null ? void 0 : t.kind) === "TRAJECTORY" ? t : void 0;
855
+ }
856
+ /** Whether NOVA moves the robot along a trajectory, or is about to */
857
+ get isTrajectoryRunning() {
858
+ var e;
859
+ const t = (e = this.executedTrajectory) == null ? void 0 : e.state.kind;
860
+ return t === "RUNNING" || t === "WAIT_FOR_IO";
861
+ }
862
+ }
863
+ function dt({ position: i, quaternion: t }) {
864
+ return {
865
+ position: [...i],
866
+ orientation: Ct(t)
867
+ };
868
+ }
869
+ function ft(i) {
870
+ const t = i.lastIndexOf("On");
871
+ return t > 0 ? i.slice(0, t) : i;
872
+ }
873
+ function Dt(i, t) {
874
+ const e = i[t];
875
+ if (e)
876
+ return e;
877
+ const o = ft(t), s = i[o];
878
+ if (s)
879
+ return s;
880
+ const n = Object.keys(i).filter(
881
+ (a) => ft(a) === o
882
+ );
883
+ if (n.length !== 1)
884
+ return;
885
+ const r = n[0];
886
+ return r ? i[r] : void 0;
887
+ }
888
+ const pe = {
889
+ coordinate_system: "world",
890
+ name: "world",
891
+ reference_coordinate_system: "",
892
+ position: [0, 0, 0],
893
+ orientation: [0, 0, 0],
894
+ orientation_type: "ROTATION_VECTOR"
895
+ };
896
+ function Ft(i) {
897
+ const t = D(
898
+ i.map((s) => ({
899
+ ...s,
900
+ coordinate_system: s.coordinate_system || "world"
901
+ })),
902
+ "coordinate_system"
903
+ );
904
+ t.world ?? (t.world = pe);
905
+ const e = {}, o = (s) => {
906
+ const n = e[s];
907
+ if (n)
908
+ return n;
909
+ const r = Dt(t, s);
910
+ if (!r)
911
+ throw new Error(
912
+ `Unknown coordinate system ${s}. Known coordinate systems are: ${Object.keys(t).join(", ")}`
913
+ );
914
+ const a = r.reference_coordinate_system || "world";
915
+ let d;
916
+ if (a === "world")
917
+ d = r;
918
+ else {
919
+ const c = o(a);
920
+ d = {
921
+ ...r,
922
+ ...dt(
923
+ $(b(c), b(r))
924
+ ),
925
+ orientation_type: "ROTATION_VECTOR",
926
+ reference_coordinate_system: c.reference_coordinate_system
927
+ };
928
+ }
929
+ return e[s] = d, d;
930
+ };
931
+ return Object.fromEntries(
932
+ Object.keys(t).map((s) => [
933
+ s,
934
+ o(s)
935
+ ])
936
+ );
937
+ }
938
+ function st(i, t) {
939
+ const e = Dt(
940
+ i,
941
+ t || "world"
942
+ );
943
+ if (!e)
944
+ throw new Error(
945
+ `Unknown coordinate system ${t}. Known coordinate systems are: ${Object.keys(i).join(", ")}`
946
+ );
947
+ return e;
948
+ }
949
+ function me(i, t) {
950
+ return st(
951
+ Ft(t),
952
+ i
953
+ );
954
+ }
955
+ function H(i, t, e) {
956
+ if (i.coordinateSystemId === t)
957
+ return i;
958
+ const o = Ft(e), s = st(
959
+ o,
960
+ i.coordinateSystemId || "world"
961
+ ), n = st(
962
+ o,
963
+ t
964
+ );
965
+ if (s.coordinate_system === n.coordinate_system)
966
+ return {
967
+ ...i,
968
+ coordinateSystemId: n.coordinate_system
969
+ };
970
+ const r = $(
971
+ Pt(b(n)),
972
+ $(b(s), bt(i.pose))
973
+ );
974
+ return {
975
+ ...i,
976
+ pose: dt(r),
977
+ coordinateSystemId: n.coordinate_system
978
+ };
979
+ }
980
+ function $t(i, t, e) {
981
+ return dt(
982
+ $(
983
+ $(bt(i), Pt(b(t))),
984
+ b(e)
985
+ )
986
+ );
987
+ }
988
+ function yt(i, t) {
989
+ const e = i == null ? void 0 : i[t];
990
+ if (!e)
991
+ throw new Error(
992
+ `Unknown TCP ${t}. Known TCPs are: ${Object.keys(i ?? {}).join(", ")}`
993
+ );
994
+ return {
995
+ position: e.pose.position ?? [0, 0, 0],
996
+ orientation: e.pose.orientation ?? [0, 0, 0],
997
+ orientation_type: "ROTATION_VECTOR"
998
+ };
999
+ }
1000
+ function St({
1001
+ inputPose: i,
1002
+ selectedTcpId: t,
1003
+ selectedCoordinateSystemId: e,
1004
+ tcpOffsetsById: o,
1005
+ coordinateSystems: s
1006
+ }) {
1007
+ const n = t && t !== i.tcpId ? {
1008
+ ...i,
1009
+ pose: $t(
1010
+ i.pose,
1011
+ yt(o, i.tcpId),
1012
+ yt(o, t)
1013
+ ),
1014
+ tcpId: t
1015
+ } : i;
1016
+ return e ? H(
1017
+ n,
1018
+ e,
1019
+ s
1020
+ ) : n;
1021
+ }
1022
+ function Lt(i) {
1023
+ var t, e, o, s, n;
1024
+ if (typeof i == "string") {
1025
+ const r = C(i);
1026
+ return r ? Lt(r) : i;
1027
+ }
1028
+ if (i && typeof i == "object") {
1029
+ const r = i;
1030
+ return (
1031
+ // PlanTrajectoryFailedResponse: the feedback name identifies the
1032
+ // failure cause (e.g. "FeedbackSingularity") and is translated to a
1033
+ // friendly message by getJogErrorTranslationKey
1034
+ ((t = r.error_feedback) == null ? void 0 : t.error_feedback_name) || ((e = r.add_trajectory_error) == null ? void 0 : e.message) || r.message || ((s = (o = r.result) == null ? void 0 : o.add_trajectory_error) == null ? void 0 : s.message) || ((n = r.result) == null ? void 0 : n.message) || "Jogging motion failed"
1035
+ );
1036
+ }
1037
+ return "Jogging motion failed";
1038
+ }
1039
+ const fe = [
1040
+ // Trajectory-planning failure causes, identified by the error_feedback_name
1041
+ // of a PlanTrajectoryFailedResponse (see extractJogErrorMessage)
1042
+ {
1043
+ pattern: /^FeedbackSingularity$/,
1044
+ translationKey: "Jogging.StreamStateSection.Error.Singularity.lb"
1045
+ },
1046
+ {
1047
+ pattern: /^FeedbackJointLimitExceeded$/,
1048
+ translationKey: "Jogging.StreamStateSection.Error.JointLimit.lb"
1049
+ },
1050
+ {
1051
+ pattern: /^FeedbackOutOfWorkspace$/,
1052
+ translationKey: "Jogging.StreamStateSection.Error.OutOfWorkspace.lb"
1053
+ },
1054
+ {
1055
+ pattern: /^FeedbackCollision$/,
1056
+ translationKey: "Jogging.StreamStateSection.Error.Collision.lb"
1057
+ },
1058
+ {
1059
+ pattern: /^FeedbackNoSolutionInCurrentConfiguration$/,
1060
+ translationKey: "Jogging.StreamStateSection.Error.NoSolutionInConfiguration.lb"
1061
+ },
1062
+ {
1063
+ // Catch-all for the remaining Feedback* causes we have no specific
1064
+ // message for -- must stay after the specific patterns above
1065
+ pattern: /^Feedback\w+$/,
1066
+ translationKey: "Jogging.StreamStateSection.Error.PlanningFailed.lb"
1067
+ }
1068
+ ];
1069
+ function ye(i) {
1070
+ var t;
1071
+ return ((t = fe.find(({ pattern: e }) => e.test(i))) == null ? void 0 : t.translationKey) ?? null;
1072
+ }
1073
+ const Se = 5, _e = 250;
1074
+ function Ie(i) {
1075
+ var o, s, n, r;
1076
+ const t = [
1077
+ (s = (o = i == null ? void 0 : i.manual_t1_limits) == null ? void 0 : o.tcp) == null ? void 0 : s.velocity,
1078
+ (r = (n = i == null ? void 0 : i.manual_limits) == null ? void 0 : n.tcp) == null ? void 0 : r.velocity
1079
+ ].filter(
1080
+ (a) => typeof a == "number" && Number.isFinite(a) && a > 0
1081
+ );
1082
+ return Math.min(_e, ...t) / 10;
1083
+ }
1084
+ const nt = [
1085
+ { id: "0.1", mm: 0.1, degrees: 0.05 },
1086
+ { id: "1", mm: 1, degrees: 0.5 },
1087
+ { id: "5", mm: 5, degrees: 2.5 },
1088
+ { id: "10", mm: 10, degrees: 5 }
1089
+ ], we = [
1090
+ { id: "continuous" },
1091
+ ...nt
1092
+ ], fo = ["coordsys", "tool"], _t = "joggingToolStore", It = { code: "locked" }, je = () => typeof localStorage > "u" ? void 0 : localStorage;
1093
+ class z {
1094
+ constructor(t, e, o, s, n, r = {}) {
1095
+ var d, c, l;
1096
+ this.jogger = t, this.coordSystems = e, this.motionGroupDescription = o, this.tcps = s, this.inverseSolverValue = n, this.selectedTabId = "cartesian", this.locks = /* @__PURE__ */ new Set(), this.blocked = !1, this.selectedCoordSystemId = "world", this.jogCoordSystemId = "world", this.selectedTcpId = "", this.tcpChangeInProgress = !1, this.selectedOrientation = "coordsys", this.selectedIncrementId = "continuous", this.selectedCartesianMotionType = "translate", this.incrementJogInProgress = null, this.lastJogError = null, this.onBeforeActivate = null, this.rotationVelocityDegPerSec = Se, this.minTranslationVelocityMmPerSec = 1, this.maxTranslationVelocityMmPerSec = 250, this.minRotationVelocityDegPerSec = 1, this.maxRotationVelocityDegPerSec = 60, this.showCoordSystemSelect = !1, this.showTcpSelect = !0, this.showOrientationSelect = !0, this.showIncrementSelect = !0, this.showTabIcons = !1, this.showVelocitySliderLabel = !0, this.showVelocityLegend = !1, this.showJointsLegend = !1, this.disposers = [], this.inverseSolver = void 0, this.jointType = O.RevoluteJoint, this.jogPress = 0, this.stoppedLast = !1, this.runningStep = null, this.disposed = !1, this.endHeldJogWatch = null, this.storage = r.storage ?? je(), this.notMoveableReason = r.notMoveableReason;
1097
+ for (const h of e)
1098
+ if (h.coordinate_system === "") {
1099
+ h.coordinate_system = "world";
1100
+ break;
1101
+ }
1102
+ this.selectedCoordSystemId = ((d = e[0]) == null ? void 0 : d.coordinate_system) || "world", this.jogCoordSystemId = this.selectedCoordSystemId, this.selectedTcpId = t.motionStream.rapidlyChangingMotionState.tcp ?? "", this.tcpChangeInProgress = this.tcps.length > 0 && !this.selectedTcpId, this.inverseSolver = n, this.translationVelocityMmPerSec = Ie(
1103
+ o == null ? void 0 : o.operation_limits
1104
+ ), this.jointType = ((l = (c = o == null ? void 0 : o.dh_parameters) == null ? void 0 : c[0]) == null ? void 0 : l.type) ?? O.RevoluteJoint, w(
1105
+ this,
1106
+ {
1107
+ storage: !1,
1108
+ notMoveableReason: !1,
1109
+ jogPress: !1,
1110
+ stoppedLast: !1,
1111
+ runningStep: !1,
1112
+ endHeldJogWatch: !1
1113
+ },
1114
+ { autoBind: !0 }
1115
+ ), this.jogger.onBlocked = () => {
1116
+ this.block();
1117
+ };
1118
+ const a = this.jogger.onError;
1119
+ this.jogger.onError = (h) => {
1120
+ this.setLastJogError(Lt(h)), a == null || a(h);
1121
+ }, this.loadFromLocalStorage(), this.disposers.push(ht(() => this.saveToLocalStorage())), this.disposers.push(
1122
+ ht(() => {
1123
+ const h = this.jogger.motionStream.rapidlyChangingMotionState.tcp;
1124
+ h && h !== this.selectedTcpId && _(() => {
1125
+ this.selectedTcpId = h, this.tcpChangeInProgress = !1;
1126
+ });
1127
+ })
1128
+ );
1129
+ }
1130
+ /**
1131
+ * Load a jogging store with the relevant data it needs
1132
+ * from the backend
1133
+ */
1134
+ static async loadFor(t, e = {}) {
1135
+ const { nova: o, cellId: s } = t, [n, r] = await Promise.all([
1136
+ // Fetch coord systems so user can select between them
1137
+ o.api.controller.listCoordinateSystems(
1138
+ s,
1139
+ t.motionStream.controllerId,
1140
+ "ROTATION_VECTOR"
1141
+ ),
1142
+ // Same for TCPs and other info from description
1143
+ o.api.motionGroup.getMotionGroupDescription(
1144
+ s,
1145
+ t.motionStream.controllerId,
1146
+ t.motionGroupId
1147
+ )
1148
+ ]), a = await o.api.motionGroupModels.getMotionGroupKinematicModel(
1149
+ r.motion_group_model
1150
+ );
1151
+ return z.create(
1152
+ t,
1153
+ {
1154
+ coordinateSystems: n || [],
1155
+ description: r,
1156
+ kinematicModel: a
1157
+ },
1158
+ e
1159
+ );
1160
+ }
1161
+ /**
1162
+ * Make a jogging store from data that was loaded before: the coordinate
1163
+ * systems of the controller, the description and the kinematic model of the
1164
+ * motion group. An app that loads them once for several stores uses this
1165
+ * instead of {@link JoggingStore.loadFor}.
1166
+ */
1167
+ static create(t, e, o = {}) {
1168
+ const { coordinateSystems: s, description: n, kinematicModel: r } = e, a = Object.entries(n.tcps || {}).map(([d, c]) => ({
1169
+ id: d,
1170
+ readable_name: c.name,
1171
+ position: c.pose.position,
1172
+ orientation: c.pose.orientation
1173
+ }));
1174
+ return new z(
1175
+ t,
1176
+ s,
1177
+ n,
1178
+ a,
1179
+ r.inverse_solver,
1180
+ o
1181
+ );
1182
+ }
1183
+ /**
1184
+ * Closes the jogger's websockets. The store starts no jog afterwards: a
1185
+ * start rejects with a {@link JoggingRefusedError} ("disconnected"), and
1186
+ * opens nothing.
1187
+ */
1188
+ dispose() {
1189
+ this.disposed = !0;
1190
+ for (const t of this.disposers)
1191
+ t();
1192
+ this.jogger.dispose();
1193
+ }
1194
+ // The types are written out: inferred, they come from lodash, which an app
1195
+ // does not have (see the consumer test of the type declarations)
1196
+ get coordSystemCountByName() {
1197
+ return Qt(this.coordSystems, (t) => t.name);
1198
+ }
1199
+ async deactivate() {
1200
+ this.jogger.mode === "jogging" && await this.jogger.setJoggingMode("off");
1201
+ }
1202
+ /**
1203
+ * Activate the jogger with current settings: for the tab that is selected
1204
+ * and, on the Cartesian tab, for a step while an increment is selected.
1205
+ * Resolves when the jogging websocket is initialized, or when the jogging
1206
+ * was stopped before that (`deactivate`).
1207
+ *
1208
+ * Rejects with a {@link JoggingRefusedError} while the store is locked or
1209
+ * its owner says that the robot may not move (see
1210
+ * {@link JoggingStoreOptions}): nothing is sent to the robot then, and no
1211
+ * jogging websocket opens. Also when that came to be while the jogging
1212
+ * websocket opened: the store closes it again.
1213
+ *
1214
+ * {@link JoggingStore.startCartesianJogging},
1215
+ * {@link JoggingStore.startJointJogging} and
1216
+ * {@link JoggingStore.runIncrementalCartesianJog} activate what they need
1217
+ * themselves.
1218
+ */
1219
+ async activate() {
1220
+ return this.currentTab.id !== "cartesian" ? this.activateFor("joint") : this.activateFor(
1221
+ this.activeDiscreteIncrement ? "cartesianStep" : "cartesian"
1222
+ );
1223
+ }
1224
+ /**
1225
+ * Activates the jogger for a jog of the given kind, unless it is refused
1226
+ * (see {@link JoggingStore.refuseUnlessJoggable}, also for `ownLock`)
1227
+ */
1228
+ async activateFor(t, e) {
1229
+ var o;
1230
+ return this.refuseUnlessJoggable(e), this.lastJogError = null, await ((o = this.onBeforeActivate) == null ? void 0 : o.call(this)), this.refuseUnlessJoggable(e), t !== "joint" && ((this.jogger.tcp !== this.selectedTcpId || this.jogger.orientation !== this.selectedOrientation) && await this.jogger.setOptions({
1231
+ tcp: this.selectedTcpId || void 0,
1232
+ orientation: this.selectedOrientation
1233
+ }), this.jogger.coordinateSystem = this.jogCoordSystem), t === "cartesianStep" ? await this.jogger.setJoggingMode("trajectory") : await this.openJoggingWebsocket(), this.jogger;
1234
+ }
1235
+ /**
1236
+ * Opens the jogging websocket of the jogger, unless a jog may not start
1237
+ * (see {@link JoggingStore.refuseUnlessJoggable}). It is a movement
1238
+ * connection, for which NOVA switches a controller to control mode by
1239
+ * itself and holds it there: the store opens it only here, for a jog, a
1240
+ * TCP change or its robot session.
1241
+ *
1242
+ * It asks before it opens the websocket, and again once it is open: that
1243
+ * takes 0.1 to 0.5 s, in which the robot may have been deactivated or
1244
+ * stopped. Refused then, the websocket closes again before anything moves.
1245
+ *
1246
+ * `reinitialize` opens it anew when it is open already, for another TCP.
1247
+ */
1248
+ async openJoggingWebsocket(t = !1) {
1249
+ this.refuseUnlessJoggable(), t ? await this.jogger.setJoggingMode("jogging", !1) : await this.jogger.setJoggingMode("jogging");
1250
+ try {
1251
+ this.refuseUnlessJoggable();
1252
+ } catch (e) {
1253
+ throw await this.deactivate(), e;
1254
+ }
1255
+ }
1256
+ /**
1257
+ * Hands the jogger to jogging: opens its jogging websocket, as a held jog
1258
+ * does, and rejects with a {@link JoggingRefusedError} as one.
1259
+ * @internal For the store's robot session, see
1260
+ * `RobotSession.ensureMovementOwnership`
1261
+ */
1262
+ async claimForJogging() {
1263
+ await this.openJoggingWebsocket();
1264
+ }
1265
+ /**
1266
+ * Throws a {@link JoggingRefusedError} while a jog may not start: once
1267
+ * the store is disposed ("disconnected"), with the
1268
+ * owner's reason that the robot may not move, else while another client
1269
+ * holds the jogging connection ({@link JoggingStore.blocked}), else while
1270
+ * the store is locked. `ownLock` is the lock of the step that asks: it
1271
+ * locks the store against other jogs, not against itself.
1272
+ */
1273
+ refuseUnlessJoggable(t) {
1274
+ const e = this.refusedReason(t);
1275
+ if (e)
1276
+ throw new U(e);
1277
+ }
1278
+ /**
1279
+ * Why a jog may not start now, or null: see
1280
+ * {@link JoggingStore.refuseUnlessJoggable}. Observed while a step runs,
1281
+ * which it stops.
1282
+ */
1283
+ refusedReason(t) {
1284
+ var o;
1285
+ if (this.disposed) return { code: "disconnected" };
1286
+ const e = ((o = this.notMoveableReason) == null ? void 0 : o.call(this)) ?? null;
1287
+ if (e) return e;
1288
+ if (this.blocked) return { code: "blocked" };
1289
+ for (const s of this.locks)
1290
+ if (s !== t) return { code: "locked" };
1291
+ return null;
1292
+ }
1293
+ /**
1294
+ * Starts jogging the TCP along an axis (`translate`) or about it
1295
+ * (`rotate`) until {@link JoggingStore.stopJogging}, with the store's
1296
+ * velocity, TCP and "Move relative to". For a jog control that is held:
1297
+ * call this on the press and `stopJogging` on the release.
1298
+ *
1299
+ * The robot moves once the jogging websocket is ready, about 0.1 to 0.5 s
1300
+ * later. A press that was stopped by then, or that another press followed,
1301
+ * moves nothing. Rejects with a {@link JoggingRefusedError} as
1302
+ * {@link JoggingStore.activate} does: while the store is locked or the
1303
+ * robot may not move, also when that came to be while the websocket
1304
+ * opened.
1305
+ *
1306
+ * A jog that moves is stopped as by its release (see
1307
+ * {@link JoggingStore.stopJogging}) once a jog would be refused: when the
1308
+ * robot may no longer move, another client takes the jogging connection or
1309
+ * the store gets locked. It stays stopped until the next press, also when
1310
+ * the reason goes away; the release still comes and changes nothing.
1311
+ */
1312
+ async startCartesianJogging(t, e, o) {
1313
+ await this.openForHeldJog("cartesian") && (t === "translate" ? await this.jogger.translateTCP({
1314
+ axis: e,
1315
+ direction: o,
1316
+ velocityMmPerSec: this.translationVelocityMmPerSec
1317
+ }) : await this.jogger.rotateTCP({
1318
+ axis: e,
1319
+ direction: o,
1320
+ velocityRadsPerSec: this.rotationVelocityRadsPerSec
1321
+ }), this.watchHeldJog());
1322
+ }
1323
+ /**
1324
+ * Starts jogging one joint (by its index) until
1325
+ * {@link JoggingStore.stopJogging}, with the store's rotation velocity, or
1326
+ * its translation velocity for a linear axis. As
1327
+ * {@link JoggingStore.startCartesianJogging}, for a control that is held,
1328
+ * and refused and stopped as it.
1329
+ */
1330
+ async startJointJogging(t, e) {
1331
+ if (!await this.openForHeldJog("joint")) return;
1332
+ const o = this.jointType === O.PrismaticJoint;
1333
+ await this.jogger.rotateJoints({
1334
+ joint: t,
1335
+ direction: e,
1336
+ velocityUnit: o ? "mm/s" : "rad/s",
1337
+ velocityValue: o ? this.translationVelocityMmPerSec : this.rotationVelocityRadsPerSec
1338
+ }), this.watchHeldJog();
1339
+ }
1340
+ /**
1341
+ * Follows the held jog that moves now, until its release or the press
1342
+ * that follows it: stops it as its release does once a jog would be
1343
+ * refused, see {@link JoggingStore.startCartesianJogging}. NOVA jogs on
1344
+ * at the last velocity for as long as the jogging websocket is open.
1345
+ */
1346
+ watchHeldJog() {
1347
+ var o;
1348
+ (o = this.endHeldJogWatch) == null || o.call(this);
1349
+ const t = M(
1350
+ () => this.refusedReason(),
1351
+ (s) => {
1352
+ s && this.stopJogging().catch((n) => {
1353
+ console.error("Failed to stop jogging:", n);
1354
+ });
1355
+ }
1356
+ ), e = () => {
1357
+ t(), this.endHeldJogWatch === e && (this.endHeldJogWatch = null);
1358
+ };
1359
+ this.endHeldJogWatch = e;
1360
+ }
1361
+ /**
1362
+ * Opens the jogging websocket for a held jog. Resolves to whether this
1363
+ * press is still the latest once it is open: a press that was stopped by
1364
+ * then, or that another press followed, moves nothing.
1365
+ *
1366
+ * A start that fails or is refused leaves no jogging websocket open. A stop
1367
+ * that came in the same event kept it for this start (see
1368
+ * {@link JoggingStore.stopJogging}), and no other stop may follow. A stop
1369
+ * that came while the start waited, before the websocket opened (for
1370
+ * `onBeforeActivate`, or for the TCP and orientation), found nothing to
1371
+ * close: the start closes it then, unless another press followed the
1372
+ * stop, which owns it.
1373
+ */
1374
+ async openForHeldJog(t) {
1375
+ const e = ++this.jogPress;
1376
+ this.stoppedLast = !1;
1377
+ try {
1378
+ await this.activateFor(t);
1379
+ } catch (o) {
1380
+ throw (e === this.jogPress || this.stoppedLast) && await this.deactivate().catch(() => {
1381
+ }), o;
1382
+ }
1383
+ return e === this.jogPress ? !0 : (this.stoppedLast && await this.deactivate(), !1);
1384
+ }
1385
+ /**
1386
+ * Stops the jog of {@link JoggingStore.startCartesianJogging} or
1387
+ * {@link JoggingStore.startJointJogging} and closes the jogging websocket.
1388
+ * Never refused, also while the store is locked or the robot may not move:
1389
+ * a jog always gets its stop.
1390
+ *
1391
+ * A start that comes while the robot is told to stop keeps the websocket,
1392
+ * e.g. a joint slider that turns around stops and starts in one event.
1393
+ *
1394
+ * A step that runs is no held jog, and is left alone: a held jog is
1395
+ * refused meanwhile, so the stop of its control belongs to none.
1396
+ */
1397
+ async stopJogging() {
1398
+ var e;
1399
+ const t = ++this.jogPress;
1400
+ this.stoppedLast = !0, (e = this.endHeldJogWatch) == null || e.call(this), this.runningStep || await this.jogger.stop(), t === this.jogPress && await this.deactivate();
1401
+ }
1402
+ /**
1403
+ * Moves the TCP one step along an axis (`translate`, by the increment's
1404
+ * mm) or about it (`rotate`, by its degrees), with the store's velocity,
1405
+ * TCP and "Move relative to". `increment` is one of
1406
+ * {@link JoggingStore.discreteIncrementOptions}. Resolves once the robot
1407
+ * has made the step.
1408
+ *
1409
+ * One step runs at a time: the store is locked while it runs (as by
1410
+ * {@link JoggingStore.withMotionLock}) and shows it as
1411
+ * {@link JoggingStore.incrementJogInProgress}. Rejects with a
1412
+ * {@link JoggingRefusedError} as {@link JoggingStore.activate} does: while
1413
+ * the store is locked, so also while another step runs, or the robot may
1414
+ * not move.
1415
+ *
1416
+ * A step that the robot may no longer make is stopped: when the robot may
1417
+ * no longer move, another client takes the jogging connection or
1418
+ * something else locks the store. Before its trajectory went to NOVA
1419
+ * (planning it takes a round trip) or was started, it rejects with a
1420
+ * {@link JoggingRefusedError} then; once it runs, it is paused and
1421
+ * resolves when the robot stands still. A stopped step stays stopped,
1422
+ * also when the reason goes away.
1423
+ */
1424
+ async runIncrementalCartesianJog(t, e, o, s) {
1425
+ this.refuseUnlessJoggable(), await this.withOwnLock(async (n) => {
1426
+ const r = this.watchStep(n);
1427
+ try {
1428
+ const a = await this.activateFor("cartesianStep", n), d = a.motionStream.rapidlyChangingMotionState;
1429
+ if (!d.tcp_pose) return;
1430
+ this.setCurrentIncrementJog({ axis: e, direction: o }), await a.runIncrementalCartesianMotion({
1431
+ currentTcpPose: d.tcp_pose,
1432
+ currentJoints: d.joint_position,
1433
+ velocityInRelevantUnits: t === "translate" ? this.translationVelocityMmPerSec : this.rotationVelocityRadsPerSec,
1434
+ axis: e,
1435
+ direction: o,
1436
+ motion: t === "translate" ? { type: "translate", distanceMm: s.mm } : {
1437
+ type: "rotate",
1438
+ distanceRads: Kt(s.degrees)
1439
+ },
1440
+ // The jogger asks right before the step goes to NOVA
1441
+ refusedReason: r.refusedReason
1442
+ });
1443
+ } catch (a) {
1444
+ if (r.stoppedByStarter() && a instanceof U)
1445
+ return;
1446
+ throw a;
1447
+ } finally {
1448
+ r.end(), this.setCurrentIncrementJog(null), await this.deactivate();
1449
+ }
1450
+ });
1451
+ }
1452
+ /**
1453
+ * Stops the step that runs, and resolves once it is over: the robot
1454
+ * stands still and its trajectory websocket is closed. Resolves at once
1455
+ * without a step.
1456
+ *
1457
+ * With a reason, as when the robot may no longer move (see
1458
+ * {@link JoggingStore.runIncrementalCartesianJog}): a step that has not
1459
+ * gone to NOVA yet rejects with a {@link JoggingRefusedError} of it.
1460
+ * Without one, its starter stops it, as the release of a held jog: a step
1461
+ * that has not gone to NOVA yet moves nothing and resolves.
1462
+ * @internal For the store's robot session (a step holds the controller in
1463
+ * control mode, and NOVA runs it to its end, so it goes before the robot
1464
+ * is deactivated), and for the panel that started the step
1465
+ */
1466
+ async stopIncrementalJog(t) {
1467
+ const e = this.runningStep;
1468
+ e && (e.stop(t), await e.over);
1469
+ }
1470
+ /**
1471
+ * Follows the step of the lock `lock` until `end`: stops it once a jog
1472
+ * would be refused for another reason than its own lock, see
1473
+ * {@link JoggingStore.runIncrementalCartesianJog}. `refusedReason` is what
1474
+ * the jogger asks: the reason that stopped the step, else why a jog would
1475
+ * be refused now.
1476
+ */
1477
+ watchStep(t) {
1478
+ let e = null, o = () => {
1479
+ };
1480
+ const s = {
1481
+ stop: (r = It) => {
1482
+ e || (e = r, this.jogger.stop().catch((a) => {
1483
+ console.error("Failed to stop the step:", a);
1484
+ }));
1485
+ },
1486
+ over: new Promise((r) => {
1487
+ o = r;
1488
+ })
1489
+ };
1490
+ this.runningStep = s;
1491
+ const n = M(
1492
+ () => this.refusedReason(t),
1493
+ (r) => {
1494
+ r && s.stop(r);
1495
+ }
1496
+ );
1497
+ return {
1498
+ refusedReason: () => e ?? this.refusedReason(t),
1499
+ stoppedByStarter: () => e === It,
1500
+ end: () => {
1501
+ n(), this.runningStep === s && (this.runningStep = null), o();
1502
+ }
1503
+ };
1504
+ }
1505
+ /**
1506
+ * Takes the user's settings from the storage (see
1507
+ * {@link JoggingStoreOptions}), which is `localStorage` only by default
1508
+ */
1509
+ loadFromLocalStorage() {
1510
+ var o;
1511
+ const t = (o = this.storage) == null ? void 0 : o.getItem(_t), e = t ? C(t) : void 0;
1512
+ e && (this.tabsById[e.selectedTabId] && (this.selectedTabId = e.selectedTabId), this.coordSystemsById[e.selectedCoordSystemId] && (this.selectedCoordSystemId = e.selectedCoordSystemId), this.coordSystemsById[e.jogCoordSystemId] && (this.jogCoordSystemId = e.jogCoordSystemId), this.incrementOptionsById[e.selectedIncrementId] && (this.selectedIncrementId = e.selectedIncrementId), ["translate", "rotate"].includes(e.selectedCartesianMotionType) && (this.selectedCartesianMotionType = e.selectedCartesianMotionType), ["coordsys", "tool"].includes(e.selectedOrientation) && (this.selectedOrientation = e.selectedOrientation));
1513
+ }
1514
+ /**
1515
+ * Keeps the user's settings in the storage (see
1516
+ * {@link JoggingStoreOptions}), which is `localStorage` only by default
1517
+ */
1518
+ saveToLocalStorage() {
1519
+ var t;
1520
+ (t = this.storage) == null || t.setItem(_t, JSON.stringify(this.localStorageSave));
1521
+ }
1522
+ get isLocked() {
1523
+ return this.locks.size > 0;
1524
+ }
1525
+ /**
1526
+ * Translation key for a friendlier version of
1527
+ * {@link JoggingStore.lastJogError}, if the raw backend message is
1528
+ * recognized. `null` when there's no latched error or the message isn't one
1529
+ * we have a friendlier version for (in which case the raw message should be
1530
+ * shown as-is).
1531
+ */
1532
+ get lastJogErrorTranslationKey() {
1533
+ return this.lastJogError ? ye(this.lastJogError) : null;
1534
+ }
1535
+ get localStorageSave() {
1536
+ return {
1537
+ selectedTabId: this.selectedTabId,
1538
+ selectedCoordSystemId: this.selectedCoordSystemId,
1539
+ jogCoordSystemId: this.jogCoordSystemId,
1540
+ selectedOrientation: this.selectedOrientation,
1541
+ selectedIncrementId: this.selectedIncrementId,
1542
+ selectedCartesianMotionType: this.selectedCartesianMotionType
1543
+ };
1544
+ }
1545
+ /**
1546
+ * Whether the robot can jog its TCP along axes (translate, rotate): with an
1547
+ * inverse solver, or when none could be loaded (as a default). A kinematic
1548
+ * model without a solver (null), e.g. a linear axis or a turntable, jogs
1549
+ * its joints only.
1550
+ */
1551
+ get canJogCartesian() {
1552
+ return this.inverseSolver !== null;
1553
+ }
1554
+ /**
1555
+ * The tabs of `JoggingPanel`: Cartesian (where the robot can jog its TCP)
1556
+ * and Joints
1557
+ */
1558
+ get tabs() {
1559
+ const t = [
1560
+ {
1561
+ id: "joint",
1562
+ label: "Joints"
1563
+ }
1564
+ ];
1565
+ return this.canJogCartesian && t.unshift({
1566
+ id: "cartesian",
1567
+ label: "Cartesian"
1568
+ }), t;
1569
+ }
1570
+ get incrementOptions() {
1571
+ return we;
1572
+ }
1573
+ get discreteIncrementOptions() {
1574
+ return nt;
1575
+ }
1576
+ get incrementOptionsById() {
1577
+ return D(this.incrementOptions, (t) => t.id);
1578
+ }
1579
+ get tabsById() {
1580
+ return D(this.tabs, (t) => t.id);
1581
+ }
1582
+ /**
1583
+ * The selected tab, or the first where the robot has not the selected one
1584
+ * (no Cartesian tab without an inverse solver)
1585
+ */
1586
+ get currentTab() {
1587
+ return this.tabsById[this.selectedTabId] || this.tabs[0];
1588
+ }
1589
+ /**
1590
+ * The index of the selected tab in {@link JoggingStore.tabs}, for the MUI
1591
+ * `Tabs` of `JoggingPanel`
1592
+ */
1593
+ get tabIndex() {
1594
+ return this.tabs.indexOf(this.currentTab);
1595
+ }
1596
+ get coordSystemsById() {
1597
+ return D(this.coordSystems, (t) => t.coordinate_system);
1598
+ }
1599
+ /**
1600
+ * The id of the coordinate system to use for jogging.
1601
+ * If in tool orientation, this is set to "tool", not the
1602
+ * selected coordinate system.
1603
+ */
1604
+ get activeCoordSystemId() {
1605
+ return this.selectedOrientation === "tool" ? "tool" : this.selectedCoordSystemId;
1606
+ }
1607
+ /** The coordinate system to jog along, resolved relative to world */
1608
+ get jogCoordSystem() {
1609
+ return me(
1610
+ this.jogCoordSystemId,
1611
+ this.coordSystems
1612
+ );
1613
+ }
1614
+ /**
1615
+ * The streamed TCP pose (its readout, see
1616
+ * {@link MotionStreamConnection.readoutState}) expressed in the selected
1617
+ * coordinate system, for values that show what a pose field in that
1618
+ * coordinate system shows.
1619
+ */
1620
+ get tcpPoseInSelectedCoordSystem() {
1621
+ const { tcp_pose: t, coordinate_system: e } = this.jogger.motionStream.readoutState;
1622
+ return !(t != null && t.position) || !t.orientation ? t : H(
1623
+ {
1624
+ pose: {
1625
+ position: t.position,
1626
+ orientation: t.orientation
1627
+ },
1628
+ coordinateSystemId: e || "world"
1629
+ },
1630
+ this.selectedCoordSystemId,
1631
+ this.coordSystems
1632
+ ).pose;
1633
+ }
1634
+ get tcpsById() {
1635
+ return D(this.tcps, (t) => t.id);
1636
+ }
1637
+ /**
1638
+ * The streamed TCP pose (its readout) as the pose of a TCP, relative to a
1639
+ * coordinate system: for a pose display with a TCP and frame of its own,
1640
+ * like CurrentPoseBar. Undefined without a pose, or for an unknown TCP or
1641
+ * coordinate system.
1642
+ */
1643
+ tcpPoseIn(t, e) {
1644
+ const { tcp_pose: o, tcp: s, coordinate_system: n } = this.jogger.motionStream.readoutState, r = this.tcpsById[s || this.selectedTcpId], a = this.tcpsById[t];
1645
+ if (!(!(o != null && o.position) || !o.orientation) && !(!r || !a))
1646
+ try {
1647
+ return H(
1648
+ {
1649
+ pose: $t(o, r, a),
1650
+ coordinateSystemId: n || "world"
1651
+ },
1652
+ e,
1653
+ this.coordSystems
1654
+ ).pose;
1655
+ } catch {
1656
+ return;
1657
+ }
1658
+ }
1659
+ /**
1660
+ * The step of the selected increment, or undefined for continuous jogging.
1661
+ * In tool orientation, a step moves along the tool's axes.
1662
+ */
1663
+ get activeDiscreteIncrement() {
1664
+ return nt.find(
1665
+ (t) => t.id === this.selectedIncrementId
1666
+ );
1667
+ }
1668
+ /** The selected rotation velocity converted to radians per second */
1669
+ get rotationVelocityRadsPerSec() {
1670
+ return this.rotationVelocityDegPerSec * Math.PI / 180;
1671
+ }
1672
+ /** Selected velocity in mm/sec or deg/sec */
1673
+ velocityInDisplayUnits(t) {
1674
+ return t ? this.rotationVelocityDegPerSec : this.translationVelocityMmPerSec;
1675
+ }
1676
+ /** Minimum selectable velocity in mm/sec or deg/sec */
1677
+ minVelocityInDisplayUnits(t) {
1678
+ return t ? this.minRotationVelocityDegPerSec : this.minTranslationVelocityMmPerSec;
1679
+ }
1680
+ /** Maximum selectable velocity in mm/sec or deg/sec */
1681
+ maxVelocityInDisplayUnits(t) {
1682
+ return t ? this.maxRotationVelocityDegPerSec : this.maxTranslationVelocityMmPerSec;
1683
+ }
1684
+ /**
1685
+ * The `onChange` of the MUI `Tabs` of `JoggingPanel`
1686
+ */
1687
+ onTabChange(t, e) {
1688
+ const o = this.tabs[e] || this.tabs[0];
1689
+ this.selectedTabId = o.id;
1690
+ }
1691
+ setSelectedCoordSystemId(t) {
1692
+ this.selectedCoordSystemId = t;
1693
+ }
1694
+ /**
1695
+ * @deprecated Use {@link JoggingStore.requestTcpChange} instead. This method now delegates
1696
+ * to `requestTcpChange` which properly communicates the TCP change to the server.
1697
+ */
1698
+ setSelectedTcpId(t) {
1699
+ this.requestTcpChange(t).catch((e) => {
1700
+ console.error("Failed to change TCP:", e);
1701
+ });
1702
+ }
1703
+ /**
1704
+ * Request a TCP change on the server. Sends an InitializeJoggingRequest
1705
+ * with the new TCP to the backend via the jogging websocket.
1706
+ *
1707
+ * If the jogger is actively jogging, the websocket is reinitialised with the new TCP.
1708
+ * If the jogger is idle, a jogging websocket is briefly opened to communicate the
1709
+ * TCP change. The websocket is kept open until the state-stream confirms the
1710
+ * change (or a 1s timeout), to ensure the backend has time to process it.
1711
+ *
1712
+ * The jogging websocket is a movement connection, for which NOVA switches a
1713
+ * controller to control mode by itself. So the change rejects with a
1714
+ * {@link JoggingRefusedError} as a jog does, while the store is locked or
1715
+ * its owner says that the robot may not move: the TCP stays, and no
1716
+ * websocket opens (or it closes again, see {@link JoggingStore.activate}).
1717
+ * As for a jog, {@link JoggingStore.onBeforeActivate} ends another motion
1718
+ * first; when it rejects, the TCP stays.
1719
+ */
1720
+ async requestTcpChange(t) {
1721
+ var n;
1722
+ if (t === this.selectedTcpId) return;
1723
+ this.refuseUnlessJoggable(), this.tcpChangeInProgress = !0;
1724
+ const e = this.jogger.tcp;
1725
+ let o = !0, s = !1;
1726
+ try {
1727
+ await ((n = this.onBeforeActivate) == null ? void 0 : n.call(this)), o = this.jogger.mode !== "jogging", this.jogger.tcp = t, s = !0, await this.openJoggingWebsocket(!o);
1728
+ let r = await this.waitForTcpConfirmation(t, 1e3);
1729
+ o && await this.jogger.setJoggingMode("off"), r || (r = await this.waitForTcpConfirmation(t, 2e3)), _(() => {
1730
+ r ? this.selectedTcpId = t : (this.jogger.tcp = e, this.selectedTcpId = this.jogger.motionStream.rapidlyChangingMotionState.tcp ?? "");
1731
+ });
1732
+ } catch (r) {
1733
+ throw s && o && await this.jogger.setJoggingMode("off").catch(() => {
1734
+ }), _(() => {
1735
+ this.jogger.tcp = e, this.selectedTcpId = this.jogger.motionStream.rapidlyChangingMotionState.tcp ?? "";
1736
+ }), r;
1737
+ } finally {
1738
+ _(() => {
1739
+ this.tcpChangeInProgress = !1;
1740
+ });
1741
+ }
1742
+ }
1743
+ waitForTcpConfirmation(t, e) {
1744
+ return new Promise((o) => {
1745
+ const s = setTimeout(() => {
1746
+ n(), o(!1);
1747
+ }, e), n = A(
1748
+ () => this.jogger.motionStream.rapidlyChangingMotionState.tcp === t,
1749
+ () => {
1750
+ clearTimeout(s), o(!0);
1751
+ }
1752
+ );
1753
+ });
1754
+ }
1755
+ setSelectedOrientation(t) {
1756
+ this.selectedOrientation = t;
1757
+ }
1758
+ /** "Move relative to" the selected TCP: jog along its own axes */
1759
+ setMoveRelativeToSelectedTcp() {
1760
+ this.selectedOrientation = "tool";
1761
+ }
1762
+ /** "Move relative to" a coordinate system: jog along its axes */
1763
+ setMoveRelativeToCoordSystem(t) {
1764
+ this.selectedOrientation = "coordsys", this.jogCoordSystemId = t;
1765
+ }
1766
+ setSelectedIncrementId(t) {
1767
+ this.selectedIncrementId = t;
1768
+ }
1769
+ setCurrentIncrementJog(t) {
1770
+ this.incrementJogInProgress = t;
1771
+ }
1772
+ setLastJogError(t) {
1773
+ this.lastJogError = t;
1774
+ }
1775
+ /**
1776
+ * Set the selected velocity in mm/s or °/s, from the slider or a velocity
1777
+ * text field. Values outside the slider range (and values that are not a
1778
+ * finite number) are ignored; a text field reports them to the user
1779
+ * instead of applying them.
1780
+ */
1781
+ setVelocityFromSlider(t, e) {
1782
+ !Number.isFinite(t) || t < this.minVelocityInDisplayUnits(e) || t > this.maxVelocityInDisplayUnits(e) || (e ? this.rotationVelocityDegPerSec = t : this.translationVelocityMmPerSec = t);
1783
+ }
1784
+ setSelectedCartesianMotionType(t) {
1785
+ this.selectedCartesianMotionType = t;
1786
+ }
1787
+ lock(t) {
1788
+ this.locks.add(t);
1789
+ }
1790
+ unlock(t) {
1791
+ this.locks.delete(t);
1792
+ }
1793
+ block() {
1794
+ this.blocked = !0;
1795
+ }
1796
+ /**
1797
+ * Ends {@link JoggingStore.blocked}, so that jogging can be tried again.
1798
+ * For a jogger that is still in jogging mode (one that an app keeps there),
1799
+ * it opens the jogging websocket again, unless a jog may not start: then
1800
+ * the jogger is switched off instead.
1801
+ */
1802
+ unblock() {
1803
+ if (this.blocked = !1, this.jogger.mode === "jogging") {
1804
+ try {
1805
+ this.refuseUnlessJoggable();
1806
+ } catch {
1807
+ this.deactivate().catch((t) => {
1808
+ console.error("Failed to stop jogging:", t);
1809
+ });
1810
+ return;
1811
+ }
1812
+ this.jogger.initializeJoggingWebsocket().catch((t) => {
1813
+ console.error("Failed to initialize jogging:", t);
1814
+ });
1815
+ }
1816
+ }
1817
+ /** Lock the UI until the given async callback resolves */
1818
+ async withMotionLock(t) {
1819
+ return this.withOwnLock(() => t());
1820
+ }
1821
+ /**
1822
+ * Locks the store until the callback resolves, and gives the callback the
1823
+ * id of its lock: for a jog that starts under it (see
1824
+ * {@link JoggingStore.refuseUnlessJoggable})
1825
+ */
1826
+ async withOwnLock(t) {
1827
+ const e = qt();
1828
+ this.lock(e);
1829
+ try {
1830
+ return await t(e);
1831
+ } finally {
1832
+ this.unlock(e);
1833
+ }
1834
+ }
1835
+ }
1836
+ const xt = 1e-4, Ee = /* @__PURE__ */ new Set([
1837
+ "timestamp",
1838
+ "sequence_number",
1839
+ "joint_position",
1840
+ "joint_torque",
1841
+ "joint_current",
1842
+ "flange_pose",
1843
+ "tcp_pose",
1844
+ "flange_velocity",
1845
+ "tcp_velocity"
1846
+ ]), Te = 1, wt = (i) => Array.isArray(i) && i.length === 3 && i.every((t) => typeof t == "number");
1847
+ class ve {
1848
+ /**
1849
+ * @internal The session makes it from its `stateSource`, see
1850
+ * `RobotSession` and `loadRobotSession`
1851
+ */
1852
+ constructor(t, e, o, s = {}) {
1853
+ this.source = t, this.motionGroupId = e, this.lastMessageReceivedAt = Date.now(), this.lastInvalidStateMessage = null, this.connectionQuality = "good";
1854
+ const n = o.motion_groups.find(
1855
+ (r) => r.motion_group === e
1856
+ );
1857
+ if (!n)
1858
+ throw new Error(
1859
+ `Motion group ${e} not found in initial controller state`
1860
+ );
1861
+ this.isVirtual = s.isVirtual ?? !1, this.onError = s.onError, this.reconnectsOnFocus = (s.reconnectOnFocus ?? !0) && typeof window < "u", this.rapidlyChangingMotionState = n, this.lastValidStateMessage = {
1862
+ receivedAt: Date.now(),
1863
+ data: o
1864
+ }, w(
1865
+ this,
1866
+ {
1867
+ source: !1,
1868
+ lastMessageReceivedAt: !1,
1869
+ connectionQualityInterval: !1,
1870
+ isVirtual: !1,
1871
+ onError: !1,
1872
+ reconnectsOnFocus: !1,
1873
+ // keepAlive: a computed nobody observes is recomputed on every read
1874
+ // without consulting `equals`, so the hold would depend on a component
1875
+ // happening to observe the readout at the time.
1876
+ readoutState: Tt({ equals: Nt, keepAlive: !0 })
1877
+ },
1878
+ { autoBind: !0 }
1879
+ ), this.source.addEventListener("message", this.handleMessage), this.connectionQualityInterval = setInterval(
1880
+ this.updateConnectionQuality,
1881
+ 500
1882
+ ), this.reconnectsOnFocus && window.addEventListener("focus", this.handleWindowFocus);
1883
+ }
1884
+ /** The controller's state as of the last message that changed it */
1885
+ get controllerState() {
1886
+ return this.lastValidStateMessage.data;
1887
+ }
1888
+ /**
1889
+ * What pose and joint readouts show. Holds the previous reading while the
1890
+ * joints only jitter (less than 0.0002 rad), and while the TCP and the
1891
+ * coordinate system stay; kept alive so it also holds for untracked reads.
1892
+ */
1893
+ get readoutState() {
1894
+ return Jt(this.rapidlyChangingMotionState);
1895
+ }
1896
+ /** The motion group's state in the next message of the source */
1897
+ async nextMotionState() {
1898
+ var o, s;
1899
+ const t = await this.source.nextMessage(), e = (s = (o = this.source.parse(t.data)) == null ? void 0 : o.motion_groups) == null ? void 0 : s.find((n) => n.motion_group === this.motionGroupId);
1900
+ if (!e)
1901
+ throw new Error(
1902
+ `Failed to get motion state for ${this.motionGroupId}: ${t.data}`
1903
+ );
1904
+ return e;
1905
+ }
1906
+ setLastInvalidStateMessage(t) {
1907
+ this.lastInvalidStateMessage = {
1908
+ receivedAt: Date.now(),
1909
+ data: t
1910
+ };
1911
+ }
1912
+ setLastValidStateMessage(t) {
1913
+ this.lastValidStateMessage = {
1914
+ receivedAt: Date.now(),
1915
+ data: t
1916
+ };
1917
+ }
1918
+ /**
1919
+ * Merge the latest motion state onto the existing object instead of replacing
1920
+ * it, so this stream owns exactly one live motion state object for the whole
1921
+ * time it is connected.
1922
+ *
1923
+ * Consumers subscribe to *properties* of the object they are holding — the 3D
1924
+ * animators keep it in a ref and read `joint_position` inside a MobX
1925
+ * reaction. Replacing the object leaves those reactions subscribed to an
1926
+ * orphan that never changes again, so the robot model stopped getting joint
1927
+ * targets from the stream and only moved when React happened to re-render it
1928
+ * (~5 updates/s against a ~134/s stream).
1929
+ *
1930
+ * Only fields whose value actually changed are written. A blanket
1931
+ * `Object.assign` puts a fresh object into every nested field, and MobX
1932
+ * compares with `===`, so each of `flange_pose`, `tcp_pose` and
1933
+ * `joint_limit_reached` would notify its observers on every message of a
1934
+ * ~134/s stream even while standing still. This mirrors how
1935
+ * MotionStreamConnection guards each of its own field writes.
1936
+ *
1937
+ * Fields the message does not carry are removed rather than left behind: a
1938
+ * merge must not make a stale pose read as the current one, which replacing
1939
+ * the whole object never did.
1940
+ *
1941
+ * Runs as a MobX action (see `makeAutoObservable` with `autoBind` above), so
1942
+ * the per-field writes notify observers once, as a single batch.
1943
+ *
1944
+ * `skipFields` leaves the named fields exactly as they are — neither updated
1945
+ * nor removed — which is how a standstill message updates the discrete state
1946
+ * without churning the jittery pose readings.
1947
+ */
1948
+ updateRapidlyChangingMotionState(t, e) {
1949
+ const o = this.rapidlyChangingMotionState, s = t;
1950
+ for (const n of Object.keys(s))
1951
+ e != null && e.has(n) || Zt(o[n], s[n]) || (o[n] = s[n]);
1952
+ for (const n of Object.keys(o))
1953
+ e != null && e.has(n) || n in s || delete o[n];
1954
+ }
1955
+ setConnectionQuality(t) {
1956
+ this.connectionQuality = t;
1957
+ }
1958
+ handleWindowFocus() {
1959
+ this.source.reconnect();
1960
+ }
1961
+ updateConnectionQuality() {
1962
+ const t = Date.now() - this.lastMessageReceivedAt, e = this.isVirtual ? 3e3 : 1e3, o = this.isVirtual ? 6e3 : 3e3;
1963
+ if (t > o) {
1964
+ this.source.readyState === Te && this.source.reconnect(), this.setConnectionQuality("critical");
1965
+ return;
1966
+ }
1967
+ if (t > e) {
1968
+ this.setConnectionQuality("struggling");
1969
+ return;
1970
+ }
1971
+ this.setConnectionQuality("good");
1972
+ }
1973
+ /**
1974
+ * Stops listening to the source; the source's owner closes it. The
1975
+ * connection is critical from then on: no state comes any more, and the
1976
+ * last one is not the robot's now (a robot that may move, for whatever
1977
+ * still reads it).
1978
+ */
1979
+ dispose() {
1980
+ this.source.removeEventListener("message", this.handleMessage), clearInterval(this.connectionQualityInterval), this.reconnectsOnFocus && window.removeEventListener("focus", this.handleWindowFocus), this.setConnectionQuality("critical");
1981
+ }
1982
+ handleMessage(t) {
1983
+ var c, l;
1984
+ const e = this.source.parse(t.data);
1985
+ if (!(e != null && e.motion_groups)) {
1986
+ (c = this.onError) == null || c.call(this, {
1987
+ message: R(t.data),
1988
+ url: this.source.url
1989
+ }), this.setLastInvalidStateMessage(t.data);
1990
+ return;
1991
+ }
1992
+ this.lastMessageReceivedAt = Date.now();
1993
+ const o = this.lastValidStateMessage.data;
1994
+ (o.safety_state !== e.safety_state || o.operation_mode !== e.operation_mode || o.mode !== e.mode) && this.setLastValidStateMessage(e);
1995
+ const s = e.motion_groups.find(
1996
+ (h) => h.motion_group === this.motionGroupId
1997
+ );
1998
+ if (!s) {
1999
+ (l = this.onError) == null || l.call(this, {
2000
+ message: `Motion group ${this.motionGroupId} not found in controller state: ${JSON.stringify(t.data)}`,
2001
+ url: this.source.url
2002
+ }), this.setLastInvalidStateMessage(t.data);
2003
+ return;
2004
+ }
2005
+ const n = !K(
2006
+ this.rapidlyChangingMotionState.joint_position,
2007
+ s.joint_position,
2008
+ xt
2009
+ ), r = this.rapidlyChangingMotionState.tcp !== s.tcp;
2010
+ if (!n && !r) {
2011
+ this.updateRapidlyChangingMotionState(
2012
+ s,
2013
+ Ee
2014
+ );
2015
+ return;
2016
+ }
2017
+ const a = this.rapidlyChangingMotionState.flange_pose, d = s.flange_pose;
2018
+ if ((d == null ? void 0 : d.orientation) == null || !wt(d.orientation)) {
2019
+ const h = d == null ? void 0 : d.orientation;
2020
+ throw new Error(
2021
+ `Invalid newFlangePose.orientation: expected [number, number, number] (got ${h == null ? "null" : h.length})`
2022
+ );
2023
+ }
2024
+ if ((a == null ? void 0 : a.orientation) == null || !wt(a.orientation)) {
2025
+ const h = a == null ? void 0 : a.orientation;
2026
+ throw new Error(
2027
+ `Invalid oldFlangePose.orientation: expected [number, number, number] (got ${h == null ? "null" : h.length})`
2028
+ );
2029
+ }
2030
+ d.orientation = At(
2031
+ d.orientation,
2032
+ a.orientation
2033
+ ), this.updateRapidlyChangingMotionState(s);
2034
+ }
2035
+ }
2036
+ const Me = [
2037
+ "FeedbackOutOfWorkspace",
2038
+ "FeedbackJointLimitExceeded",
2039
+ "FeedbackAxisRangeExceeded",
2040
+ "FeedbackNoSolutionInCurrentConfiguration"
2041
+ ];
2042
+ function Oe(i) {
2043
+ return i === "FeedbackSingularity" ? "Jogging.TargetPose.Error.Singularity.lb" : i === "FeedbackCollision" ? "Jogging.TargetPose.Error.Collision.lb" : Me.includes(i) ? "Jogging.TargetPose.Error.NotReachable.lb" : "Jogging.TargetPose.Error.PlanningFailed.lb";
2044
+ }
2045
+ function Ce(i) {
2046
+ return {
2047
+ get url() {
2048
+ return i.url;
2049
+ },
2050
+ get readyState() {
2051
+ return i.readyState;
2052
+ },
2053
+ addEventListener: (t, e) => i.addEventListener(t, e),
2054
+ removeEventListener: (t, e) => i.removeEventListener(t, e),
2055
+ firstMessage: () => i.firstMessage(),
2056
+ nextMessage: () => i.nextMessage(),
2057
+ reconnect: () => i.reconnect(),
2058
+ close: () => i.close(),
2059
+ parse: (t) => {
2060
+ var e;
2061
+ return (e = vt(t)) == null ? void 0 : e.result;
2062
+ }
2063
+ };
2064
+ }
2065
+ function Re(i, {
2066
+ controllerId: t,
2067
+ cellId: e,
2068
+ responseRateMs: o
2069
+ }) {
2070
+ const s = G(i), n = e ?? ct(i) ?? "cell", r = o === void 0 ? "" : `?response_rate=${o}`;
2071
+ return Ce(
2072
+ s.openReconnectingWebsocket(
2073
+ `/cells/${n}/controllers/${t}/state-stream${r}`
2074
+ )
2075
+ );
2076
+ }
2077
+ function Vt(i) {
2078
+ const t = i.api.opts.axiosInstance;
2079
+ if (!t)
2080
+ throw new Error("Nova API client has no configured HTTP transport");
2081
+ return t;
2082
+ }
2083
+ function rt(i, t) {
2084
+ const e = i.api.opts.baseOptions ?? {}, o = { ...e, ...t };
2085
+ return (e.headers || t.headers) && (o.headers = {
2086
+ ...e.headers,
2087
+ ...t.headers
2088
+ }), (e.params || t.params) && (o.params = {
2089
+ ...e.params,
2090
+ ...t.params
2091
+ }), o;
2092
+ }
2093
+ async function be(i, t, e, o) {
2094
+ var n;
2095
+ if (!e) return t;
2096
+ const s = `/experimental/motion-group-models/${encodeURIComponent(t)}/description`;
2097
+ o == null || o(`${s}?serial_number=${encodeURIComponent(e)}`);
2098
+ try {
2099
+ return (await Vt(i).get(
2100
+ s,
2101
+ rt(i, { params: { serial_number: e } })
2102
+ )).data.name;
2103
+ } catch (r) {
2104
+ if (!Mt(r) || ((n = r.response) == null ? void 0 : n.status) !== 404)
2105
+ throw r;
2106
+ return t;
2107
+ }
2108
+ }
2109
+ async function Pe(i, t, e, o, s) {
2110
+ var c;
2111
+ const n = Vt(i), r = `/motion-group-models/${encodeURIComponent(t)}/${o}`, a = {};
2112
+ if (e) {
2113
+ const l = `/experimental${r}`;
2114
+ s == null || s(
2115
+ `${l}?serial_number=${encodeURIComponent(e)}`
2116
+ );
2117
+ try {
2118
+ return (await n.get(
2119
+ l,
2120
+ rt(i, {
2121
+ ...a,
2122
+ params: { serial_number: e }
2123
+ })
2124
+ )).data;
2125
+ } catch (h) {
2126
+ if (!Mt(h) || ((c = h.response) == null ? void 0 : c.status) !== 404)
2127
+ throw h;
2128
+ }
2129
+ }
2130
+ return s == null || s(r), (await n.get(
2131
+ r,
2132
+ rt(i, a)
2133
+ )).data;
2134
+ }
2135
+ const ke = [
2136
+ "motionGroupDescription",
2137
+ "controllerConfiguration",
2138
+ "kinematicModel",
2139
+ "motionGroupModel",
2140
+ "coordinateSystems",
2141
+ "controllerState",
2142
+ "motionStateStream",
2143
+ "controllerStateStream"
2144
+ ];
2145
+ class Gt extends Error {
2146
+ constructor(t, e, o) {
2147
+ super(o), this.stepId = t, this.cause = e, this.name = "RobotLoadStepError";
2148
+ }
2149
+ }
2150
+ function Z(i) {
2151
+ return i instanceof Gt;
2152
+ }
2153
+ class Ae {
2154
+ /**
2155
+ * One instance tracks one load. Concurrent loads must not share one — a load
2156
+ * that has been superseded keeps reporting for a step or two before it
2157
+ * notices, and those reports would otherwise overwrite the state of the load
2158
+ * that replaced it (clearing a recorded failure, for instance).
2159
+ */
2160
+ constructor(t = null, e = null) {
2161
+ this.motionGroupId = null, this.controllerId = null, this.steps = [], this.retryAttempt = 0, this.fatalError = null, this.currentStepStartedAt = null, this.motionGroupId = t, this.controllerId = e, this.steps = ke.map((o) => ({
2162
+ id: o,
2163
+ status: "pending",
2164
+ url: null,
2165
+ error: null
2166
+ })), w(this, {}, { autoBind: !0 });
2167
+ }
2168
+ /** Reset the step states for another attempt at the same robot */
2169
+ beginRetry(t) {
2170
+ for (const e of this.steps)
2171
+ e.status = "pending", e.url = null, e.error = null;
2172
+ this.retryAttempt = t, this.fatalError = null, this.currentStepStartedAt = null;
2173
+ }
2174
+ stepById(t) {
2175
+ return this.steps.find((e) => e.id === t);
2176
+ }
2177
+ startStep(t, e) {
2178
+ const o = this.stepById(t);
2179
+ o && (o.status = "running", o.url = e, o.error = null, this.currentStepStartedAt = Date.now());
2180
+ }
2181
+ updateStepUrl(t, e) {
2182
+ const o = this.stepById(t);
2183
+ o && (o.url = e);
2184
+ }
2185
+ succeedStep(t) {
2186
+ const e = this.stepById(t);
2187
+ e && (e.status = "succeeded", this.currentStepStartedAt = null);
2188
+ }
2189
+ failStep(t, e) {
2190
+ const o = this.stepById(t);
2191
+ o && (o.status = "failed", o.error = e, this.currentStepStartedAt = null);
2192
+ }
2193
+ /** A failure that is not tied to a specific step (e.g. an invalid selection) */
2194
+ failWith(t) {
2195
+ this.fatalError = t, this.currentStepStartedAt = null;
2196
+ }
2197
+ get totalCount() {
2198
+ return this.steps.length;
2199
+ }
2200
+ get succeededCount() {
2201
+ return this.steps.filter((t) => t.status === "succeeded").length;
2202
+ }
2203
+ get runningStep() {
2204
+ return this.steps.find((t) => t.status === "running");
2205
+ }
2206
+ get failedStep() {
2207
+ return this.steps.find((t) => t.status === "failed");
2208
+ }
2209
+ get isFailed() {
2210
+ return this.fatalError !== null || this.failedStep !== void 0;
2211
+ }
2212
+ get isComplete() {
2213
+ return this.steps.length > 0 && this.steps.every((t) => t.status === "succeeded");
2214
+ }
2215
+ }
2216
+ const Je = 1e4;
2217
+ async function jt(i, t, e) {
2218
+ let o;
2219
+ i.catch(() => {
2220
+ });
2221
+ try {
2222
+ return await Promise.race([
2223
+ i,
2224
+ new Promise((s, n) => {
2225
+ o = setTimeout(() => n(new Error(e)), t);
2226
+ })
2227
+ ]);
2228
+ } finally {
2229
+ clearTimeout(o);
2230
+ }
2231
+ }
2232
+ async function Ne({
2233
+ nova: i,
2234
+ cellId: t,
2235
+ controllerId: e,
2236
+ motionGroupId: o,
2237
+ progress: s,
2238
+ createStateSource: n,
2239
+ isStale: r = () => !1,
2240
+ socketTimeoutMs: a = Je
2241
+ }) {
2242
+ let d, c, l = !1;
2243
+ function h() {
2244
+ d == null || d.dispose(), c == null || c.close();
2245
+ }
2246
+ async function g(f, p, y) {
2247
+ s.startStep(f, p);
2248
+ try {
2249
+ const u = await y();
2250
+ return s.succeedStep(f), u;
2251
+ } catch (u) {
2252
+ throw s.failStep(f, u), new Gt(f, u, R(u));
2253
+ }
2254
+ }
2255
+ try {
2256
+ if (r()) return null;
2257
+ const f = `/cells/${t}/controllers/${e}/motion-groups/${o}`, p = `/cells/${t}/controllers/${e}`, y = await g(
2258
+ "motionGroupDescription",
2259
+ `${f}/description`,
2260
+ () => i.api.motionGroup.getMotionGroupDescription(
2261
+ t,
2262
+ e,
2263
+ o
2264
+ )
2265
+ );
2266
+ if (r()) return null;
2267
+ const { configuration: u } = await g(
2268
+ "controllerConfiguration",
2269
+ p,
2270
+ () => i.api.controller.getRobotController(t, e)
2271
+ );
2272
+ if (r()) return null;
2273
+ const m = {
2274
+ model: y.motion_group_model,
2275
+ serialNumber: y.serial_number
2276
+ }, T = m.serialNumber ? `?serial_number=${encodeURIComponent(m.serialNumber)}` : "", v = await g(
2277
+ "kinematicModel",
2278
+ `/experimental/motion-group-models/${encodeURIComponent(m.model)}/kinematic${T}`,
2279
+ () => Pe(
2280
+ i,
2281
+ m.model,
2282
+ m.serialNumber,
2283
+ "kinematic",
2284
+ (S) => s.updateStepUrl("kinematicModel", S)
2285
+ )
2286
+ );
2287
+ if (r()) return null;
2288
+ const L = await g(
2289
+ "motionGroupModel",
2290
+ `/experimental/motion-group-models/${encodeURIComponent(m.model)}/description${T}`,
2291
+ () => be(
2292
+ i,
2293
+ m.model,
2294
+ m.serialNumber,
2295
+ (S) => s.updateStepUrl("motionGroupModel", S)
2296
+ )
2297
+ );
2298
+ if (r()) return null;
2299
+ const x = await g(
2300
+ "coordinateSystems",
2301
+ `${p}/coordinate-systems?orientation_type=ROTATION_VECTOR`,
2302
+ async () => await i.api.controller.listCoordinateSystems(
2303
+ t,
2304
+ e,
2305
+ "ROTATION_VECTOR"
2306
+ ) ?? []
2307
+ );
2308
+ if (r()) return null;
2309
+ const { controllerState: I, motionGroupState: V } = await g(
2310
+ "controllerState",
2311
+ `${p}/state`,
2312
+ async () => {
2313
+ const S = await i.api.controller.getCurrentRobotControllerState(
2314
+ t,
2315
+ e
2316
+ ), j = S == null ? void 0 : S.motion_groups.find(
2317
+ (E) => E.motion_group === o
2318
+ );
2319
+ if (!S || !j)
2320
+ throw new Error(
2321
+ `Controller ${e} or motion group ${o} not found`
2322
+ );
2323
+ return { controllerState: S, motionGroupState: j };
2324
+ }
2325
+ );
2326
+ if (r()) return null;
2327
+ const q = `${f}/state-stream`, { socket: Bt, initialMotionState: Wt } = await g(
2328
+ "motionStateStream",
2329
+ q,
2330
+ async () => {
2331
+ var N;
2332
+ const S = i.openReconnectingWebsocket(q);
2333
+ d = S;
2334
+ const j = await jt(
2335
+ S.firstMessage(),
2336
+ a,
2337
+ `No motion state received from ${q} within ${a / 1e3}s`
2338
+ ), E = (N = vt(j.data)) == null ? void 0 : N.result;
2339
+ if (!E)
2340
+ throw new Error(
2341
+ `Unable to parse initial motion state message ${j.data}`
2342
+ );
2343
+ return { socket: S, initialMotionState: E };
2344
+ }
2345
+ );
2346
+ if (r()) return null;
2347
+ const { source: Ht, initialControllerState: zt } = await g(
2348
+ "controllerStateStream",
2349
+ `${p}/state`,
2350
+ async () => {
2351
+ var N;
2352
+ const S = n({ cellId: t, controllerId: e });
2353
+ c = S, s.updateStepUrl("controllerStateStream", S.url);
2354
+ const j = await jt(
2355
+ S.firstMessage(),
2356
+ a,
2357
+ `No controller state received from ${S.url} within ${a / 1e3}s`
2358
+ ), E = S.parse(j.data);
2359
+ if (!E)
2360
+ throw new Error(
2361
+ `Unable to parse initial controller state message ${j.data}`
2362
+ );
2363
+ if (!((N = E.motion_groups) != null && N.some((Yt) => Yt.motion_group === o)))
2364
+ throw new Error(
2365
+ `Controller state from ${S.url} does not list motion group ${o} yet`
2366
+ );
2367
+ return { source: S, initialControllerState: E };
2368
+ }
2369
+ );
2370
+ return r() ? null : (l = !0, {
2371
+ motionGroupDescription: y,
2372
+ controllerConfiguration: u,
2373
+ kinematicModel: v,
2374
+ motionGroupModelName: L,
2375
+ coordinateSystems: x,
2376
+ controllerState: I,
2377
+ motionGroupState: V,
2378
+ initialMotionState: Wt,
2379
+ motionStateSocket: Bt,
2380
+ stateSource: Ht,
2381
+ initialControllerState: zt,
2382
+ dispose: h
2383
+ });
2384
+ } finally {
2385
+ l || h();
2386
+ }
2387
+ }
2388
+ function at(i) {
2389
+ return i.type === "joint" ? { type: "joint", joints: i.joints } : {
2390
+ type: "cartesian",
2391
+ pose: i.tcpPose.pose,
2392
+ coordinateSystemId: i.tcpPose.coordSystemId
2393
+ };
2394
+ }
2395
+ const X = (i = [0, 0, 0], t = [0, 0, 0]) => i.length === t.length && i.every((e, o) => e === t[o]);
2396
+ function De(i, t) {
2397
+ return i.motionGroupId !== t.motionGroupId ? !1 : i.type === "joint" ? t.type === "joint" && X(i.joints, t.joints) : t.type === "joint" ? !1 : i.tcpPose.tcpId === t.tcpPose.tcpId && i.tcpPose.coordSystemId === t.tcpPose.coordSystemId && X(i.tcpPose.pose.position, t.tcpPose.pose.position) && X(i.tcpPose.pose.orientation, t.tcpPose.pose.orientation);
2398
+ }
2399
+ const P = (i) => i ?? [0, 0, 0], tt = (i, t) => i.length === t.length && i.every((e, o) => e === t[o]);
2400
+ function Fe(i, t) {
2401
+ return i.type === "joint" ? t.type === "joint" && tt(i.joints, t.joints) : t.type === "joint" ? !1 : (i.coordinateSystemId || "world") === (t.coordinateSystemId || "world") && tt(P(i.pose.position), P(t.pose.position)) && tt(P(i.pose.orientation), P(t.pose.orientation));
2402
+ }
2403
+ function $e(i) {
2404
+ return i.type === "joint" ? { type: "joint", joints: [...i.joints] } : {
2405
+ type: "cartesian",
2406
+ pose: {
2407
+ position: [...P(i.pose.position)],
2408
+ orientation: [...P(i.pose.orientation)]
2409
+ },
2410
+ coordinateSystemId: i.coordinateSystemId
2411
+ };
2412
+ }
2413
+ class Le {
2414
+ /** @internal The session makes it, see RobotSession */
2415
+ constructor(t) {
2416
+ this.options = t, this.plannedTrajectory = null, this.trajectoryState = "idle", this.lastError = null, this.armed = !1, this.plannedFor = null, this.motion = null, this.releaseOnStart = !1, this.disposed = !1, this.disposers = [], this.logger = t.logger ?? console, w(
2417
+ this,
2418
+ {
2419
+ socket: !1,
2420
+ disposers: !1,
2421
+ logger: !1,
2422
+ options: !1
2423
+ },
2424
+ { autoBind: !0 }
2425
+ ), this.socket = this.openSocket(), this.disposers.push(
2426
+ M(
2427
+ () => this.executionState,
2428
+ (e) => {
2429
+ e === "END_OF_TRAJECTORY" && (this.motion = null, this.reset());
2430
+ }
2431
+ )
2432
+ );
2433
+ }
2434
+ get joggingStore() {
2435
+ return this.options.joggingStore;
2436
+ }
2437
+ get jogger() {
2438
+ return this.options.joggingStore.jogger;
2439
+ }
2440
+ get motionStream() {
2441
+ return this.options.joggingStore.jogger.motionStream;
2442
+ }
2443
+ /**
2444
+ * Whether NOVA may still hold a trajectory of this store, and with it the
2445
+ * controller's execution session, which blocks jogging and keeps the
2446
+ * controller in control mode: from a plan that NOVA got until
2447
+ * `stopAndReset`. Also after `reset`, after the robot arrived and after a
2448
+ * failed move, which only drop the plan here.
2449
+ */
2450
+ get holdsExecutionSession() {
2451
+ return this.armed;
2452
+ }
2453
+ /**
2454
+ * Whether the planned trajectory was planned with another velocity than
2455
+ * the jogging store has now: the velocity is part of the trajectory, and
2456
+ * the store's slider stays live. `hold` does not start such a trajectory;
2457
+ * plan the target again to move at the velocity that shows.
2458
+ */
2459
+ get isPlanOutdated() {
2460
+ return this.plannedFor !== null && // Not `!==`: a velocity that is no number would be outdated for ever
2461
+ !Object.is(
2462
+ this.plannedFor.velocity,
2463
+ this.velocityFor(this.plannedFor.target)
2464
+ );
2465
+ }
2466
+ /** The target of a pose of this motion group; null for another's */
2467
+ targetOf(t) {
2468
+ return "motionGroupId" in t ? t.motionGroupId !== this.jogger.motionGroupId ? null : at(t) : t;
2469
+ }
2470
+ /** The execution state that the motion stream reports, e.g. "RUNNING" */
2471
+ get executionState() {
2472
+ var t, e;
2473
+ return (e = (t = this.motionStream.rapidlyChangingMotionState.execute) == null ? void 0 : t.details) == null ? void 0 : e.state.kind;
2474
+ }
2475
+ /**
2476
+ * Plans a trajectory from the current joints to the target and initializes
2477
+ * it on the execution websocket. The store is "planned" once NOVA accepted
2478
+ * it. Returns a planner rejection as a value; throws while the app locks
2479
+ * the robot or the robot may not move (see
2480
+ * `TrajectoryExecutionStoreOptions`), also when that came to be while the
2481
+ * planner worked, and when the planner cannot be reached. A target that
2482
+ * cannot be planned leaves no trajectory, also not the one before it on
2483
+ * the controller.
2484
+ *
2485
+ * `to` is a target, or a pose as an app saves it (`RobotPose`): its joints,
2486
+ * or its TCP pose in its coordinate system, planned for the selected TCP.
2487
+ * Throws for a pose of another motion group, and plans nothing then.
2488
+ */
2489
+ async planTrajectory(t) {
2490
+ var v, L, x;
2491
+ const e = this.targetOf(t);
2492
+ if (!e)
2493
+ throw new Error(
2494
+ `Not planning a pose of motion group "${t.motionGroupId}" for motion group "${this.jogger.motionGroupId}"`
2495
+ );
2496
+ await this.dropPlanIfRefused(), this.armed && !this.plannedTrajectory && await this.stopAndReset(), await this.ensureMovementOwnership();
2497
+ const o = this.motionStream.rapidlyChangingMotionState.joint_position ?? [], { cycle_time: s, mounting: n, motion_group_model: r, tcps: a } = this.motionStream.description, d = this.joggingStore.selectedTcpId, c = d ? (v = a == null ? void 0 : a[d]) == null ? void 0 : v.pose : void 0, l = {
2498
+ // The model the jogger plans step jogs with: the custom copy that holds
2499
+ // this robot's data, if the app gave one
2500
+ motion_group_model: ((L = this.jogger.options) == null ? void 0 : L.motionGroupModel) ?? r,
2501
+ cycle_time: s ?? 0,
2502
+ mounting: n,
2503
+ ...c && { tcp_offset: c }
2504
+ }, h = this.velocityFor(e);
2505
+ let g;
2506
+ if (e.type === "cartesian") {
2507
+ let I = e.pose;
2508
+ const V = e.coordinateSystemId || "world";
2509
+ if (V !== "world")
2510
+ try {
2511
+ I = H(
2512
+ {
2513
+ pose: {
2514
+ position: I.position ?? [0, 0, 0],
2515
+ orientation: I.orientation ?? [0, 0, 0]
2516
+ },
2517
+ coordinateSystemId: V
2518
+ },
2519
+ "world",
2520
+ this.joggingStore.coordSystems
2521
+ ).pose;
2522
+ } catch {
2523
+ return await this.dropPlan(), { ok: !1, errorFeedbackName: "FeedbackUnknown" };
2524
+ }
2525
+ g = {
2526
+ limits_override: {
2527
+ tcp_velocity_limit: h
2528
+ },
2529
+ path: {
2530
+ target_pose: I,
2531
+ path_definition_name: "PathCartesianPTP"
2532
+ }
2533
+ };
2534
+ } else
2535
+ g = {
2536
+ limits_override: {
2537
+ joint_velocity_limits: Array(o.length).fill(h)
2538
+ },
2539
+ path: {
2540
+ target_joint_position: e.joints,
2541
+ path_definition_name: "PathJointPTP"
2542
+ }
2543
+ };
2544
+ _(() => {
2545
+ this.lastError = null, this.trajectoryState = "planning";
2546
+ });
2547
+ let f;
2548
+ try {
2549
+ f = await this.jogger.nova.api.trajectoryPlanning.planTrajectory(
2550
+ this.jogger.cellId,
2551
+ {
2552
+ motion_group_setup: l,
2553
+ start_joint_position: o,
2554
+ motion_commands: [g]
2555
+ }
2556
+ );
2557
+ } catch (I) {
2558
+ throw await this.dropPlan(), I;
2559
+ }
2560
+ const p = f.response;
2561
+ if ("error_feedback" in p) {
2562
+ const I = ((x = p.error_feedback) == null ? void 0 : x.error_feedback_name) ?? "FeedbackUnknown";
2563
+ return await this.dropPlan(), { ok: !1, errorFeedbackName: I };
2564
+ }
2565
+ const y = p.joint_positions, u = y[0], m = y[y.length - 1];
2566
+ if (!u || !m)
2567
+ throw await this.dropPlan(), new Error("Trajectory returned invalid joint positions");
2568
+ const T = {
2569
+ message_type: "InitializeMovementRequest",
2570
+ trajectory: {
2571
+ message_type: "TrajectoryData",
2572
+ motion_group: this.jogger.motionGroupId,
2573
+ tcp: d || void 0,
2574
+ data: p
2575
+ }
2576
+ };
2577
+ return await this.dropPlanIfRefused(), this.socket.sendJson(T), _(() => {
2578
+ this.armed = !0, this.plannedTrajectory = { startJoints: u, endJoints: m }, this.plannedFor = { target: $e(e), velocity: h };
2579
+ }), { ok: !0 };
2580
+ }
2581
+ /**
2582
+ * The Move to button is held: starts the motion along the planned
2583
+ * trajectory, or goes on with a paused one. Returns whether the robot moves
2584
+ * for this hold: not without a trajectory that NOVA accepted, not while
2585
+ * the move before it still stops, not along a trajectory that was
2586
+ * planned with another velocity than now
2587
+ * ({@link TrajectoryExecutionStore.isPlanOutdated}), and not while the
2588
+ * robot may not move or the app locks it (see
2589
+ * `TrajectoryExecutionStoreOptions`). Safe to repeat while held.
2590
+ * {@link TrajectoryExecutionStore.release} ends the hold.
2591
+ *
2592
+ * `to` is where the button says it moves to, as `planTrajectory` got it:
2593
+ * the robot does not move along a trajectory that was planned for another
2594
+ * target, e.g. while the plan for the shown one is still to come or
2595
+ * failed, nor for a pose of another motion group. Without it, the hold
2596
+ * starts whatever is planned.
2597
+ */
2598
+ hold(t) {
2599
+ if (!this.plannedTrajectory) return !1;
2600
+ if (t) {
2601
+ const e = this.targetOf(t);
2602
+ if (!e || !(this.plannedFor && Fe(e, this.plannedFor.target)))
2603
+ return !1;
2604
+ }
2605
+ return this.motion === "starting" ? !this.releaseOnStart : this.trajectoryState === "moving" ? this.motion === "running" : this.trajectoryState !== "planned" || this.motion === "pausing" || this.executionState === "RUNNING" || // A move starts at the velocity that shows, or not at all
2606
+ this.isPlanOutdated || // NOVA would switch the controller to control mode for the start
2607
+ this.refusal() !== null ? !1 : (this.sendStart(), !0);
2608
+ }
2609
+ /**
2610
+ * The Move to button was let go: pauses the motion. Whatever the motion
2611
+ * stream shows by then, and also when the plan is gone here: only NOVA's
2612
+ * own word that the trajectory ended makes a pause needless. A release
2613
+ * before NOVA confirmed the start pauses as soon as it does, however late.
2614
+ * Resolves once the robot stands still; the trajectory stays planned, so
2615
+ * `hold` goes on from there. Does nothing when nothing moves, and is safe
2616
+ * to repeat.
2617
+ */
2618
+ async release() {
2619
+ this.motion === "starting" ? (this.releaseOnStart = !0, await A(() => this.motion !== "starting")) : this.motion === "running" && this.sendPause(), this.motion === "pausing" && await this.settlePause();
2620
+ }
2621
+ /**
2622
+ * Starts the motion along the planned trajectory. For a button that is
2623
+ * held, use {@link TrajectoryExecutionStore.hold}. Throws when nothing can
2624
+ * start, and while the robot may not move or the app locks it (see
2625
+ * `TrajectoryExecutionStoreOptions`).
2626
+ */
2627
+ start() {
2628
+ if (!this.plannedTrajectory)
2629
+ throw new Error("Cannot start trajectory: no planned trajectory exists");
2630
+ if (this.trajectoryState !== "planned")
2631
+ throw new Error(
2632
+ `Cannot start trajectory: expected state "planned", got "${this.trajectoryState}"`
2633
+ );
2634
+ if (this.executionState === "RUNNING")
2635
+ throw new Error("Cannot start trajectory: robot is already running");
2636
+ if (this.motion === "starting") return;
2637
+ const t = this.refusal();
2638
+ if (t)
2639
+ throw new Error(`Cannot start trajectory: ${t}`);
2640
+ this.sendStart();
2641
+ }
2642
+ /**
2643
+ * Why the store sends the robot no trajectory and no start now, or null:
2644
+ * the app locks the robot, or the robot may not move
2645
+ */
2646
+ refusal() {
2647
+ var e, o, s, n;
2648
+ if ((o = (e = this.options).isLocked) != null && o.call(e)) return "the robot is locked";
2649
+ const t = (n = (s = this.options).notMoveableReason) == null ? void 0 : n.call(s);
2650
+ return t ? `the robot may not move (${t.code})` : null;
2651
+ }
2652
+ /**
2653
+ * Drops the plan and throws while the store sends the robot no
2654
+ * trajectory, see {@link TrajectoryExecutionStore.planTrajectory}
2655
+ */
2656
+ async dropPlanIfRefused() {
2657
+ const t = this.refusal();
2658
+ if (t)
2659
+ throw await this.dropPlan(), new Error(`Cannot plan trajectory: ${t}`);
2660
+ }
2661
+ /**
2662
+ * Pauses the motion. Resolves once the robot stands still; the trajectory
2663
+ * stays planned, so `start` goes on from there. For a button that was let
2664
+ * go, use {@link TrajectoryExecutionStore.release}.
2665
+ */
2666
+ async pause() {
2667
+ if (this.trajectoryState !== "moving")
2668
+ throw new Error(
2669
+ `Cannot pause trajectory: expected state "moving", got "${this.trajectoryState}"`
2670
+ );
2671
+ this.sendPause(), await this.settlePause();
2672
+ }
2673
+ /**
2674
+ * Stops a moving robot, drops the trajectory and hands the controller's
2675
+ * execution session back: closes the execution websocket and opens a new
2676
+ * one for the next plan
2677
+ */
2678
+ async stopAndReset() {
2679
+ try {
2680
+ (this.executionState === "RUNNING" || this.trajectoryState === "moving" || // Also a start that NOVA has not confirmed: the pause goes right
2681
+ // behind it, and the websocket closes in any case
2682
+ this.motion) && (this.sendPause(), await this.waitUntilStopped());
2683
+ } catch (t) {
2684
+ this.logger.warn("Failed to stop trajectory execution cleanly", t);
2685
+ } finally {
2686
+ this.reset(), this.closeSocket(), this.disposed || (this.socket = this.openSocket());
2687
+ }
2688
+ }
2689
+ /**
2690
+ * Drops the planned trajectory here, without telling NOVA: it keeps the
2691
+ * trajectory and the execution session, see
2692
+ * {@link TrajectoryExecutionStore.holdsExecutionSession}
2693
+ */
2694
+ reset() {
2695
+ this.plannedTrajectory = null, this.plannedFor = null, this.trajectoryState = "idle";
2696
+ }
2697
+ /**
2698
+ * Drops the plan because its next target cannot be planned. The trajectory
2699
+ * before it is still armed on the controller, so the execution session goes
2700
+ * back as well: with no plan here, nothing else would ask for that.
2701
+ */
2702
+ async dropPlan() {
2703
+ this.armed ? await this.stopAndReset() : this.reset();
2704
+ }
2705
+ /** Removes {@link TrajectoryExecutionStore.lastError} */
2706
+ clearError() {
2707
+ this.lastError = null;
2708
+ }
2709
+ /**
2710
+ * Closes the execution websocket and stops following the motion stream.
2711
+ * No execution websocket opens afterwards.
2712
+ */
2713
+ dispose() {
2714
+ this.disposed = !0;
2715
+ for (const t of this.disposers)
2716
+ t();
2717
+ this.closeSocket();
2718
+ }
2719
+ /**
2720
+ * The velocity limit of a trajectory to a target: the jogging store's
2721
+ * translation velocity (mm/s) for a pose, and for joints the velocity
2722
+ * they are jogged with, which is its rotation velocity (rad/s), or its
2723
+ * translation velocity (mm/s) for linear axes
2724
+ */
2725
+ velocityFor(t) {
2726
+ return t.type === "cartesian" || this.joggingStore.jointType === O.PrismaticJoint ? this.joggingStore.translationVelocityMmPerSec : this.joggingStore.rotationVelocityRadsPerSec;
2727
+ }
2728
+ /** Ends continuous jogging, unless the app has its own way */
2729
+ async ensureMovementOwnership() {
2730
+ if (this.options.ensureMovementOwnership) {
2731
+ await this.options.ensureMovementOwnership();
2732
+ return;
2733
+ }
2734
+ this.jogger.mode !== "trajectory" && (await this.joggingStore.deactivate(), await this.jogger.setJoggingMode("trajectory"));
2735
+ }
2736
+ sendStart() {
2737
+ const t = {
2738
+ message_type: "StartMovementRequest",
2739
+ direction: "DIRECTION_FORWARD"
2740
+ };
2741
+ this.socket.sendJson(t), this.motion = "starting", this.releaseOnStart = !1;
2742
+ }
2743
+ /** Sends the pause of the move, once */
2744
+ sendPause() {
2745
+ if (this.motion === "pausing") return;
2746
+ const t = {
2747
+ message_type: "PauseMovementRequest"
2748
+ };
2749
+ this.socket.sendJson(t), this.motion = "pausing";
2750
+ }
2751
+ /**
2752
+ * After a pause: once the robot stands still, the trajectory is planned
2753
+ * again. Not when the robot was started again meanwhile: that move has a
2754
+ * pause of its own to wait for.
2755
+ */
2756
+ async settlePause() {
2757
+ await this.waitUntilStopped(), _(() => {
2758
+ this.motion === "pausing" && (this.motion = null, (this.trajectoryState === "moving" || this.trajectoryState === "stopping") && (this.trajectoryState = this.plannedTrajectory ? "planned" : "idle"));
2759
+ });
2760
+ }
2761
+ /** Resolves once the motion stream reports that the robot stands still */
2762
+ async waitUntilStopped() {
2763
+ await A(() => this.motionStream.rapidlyChangingMotionState.standstill);
2764
+ }
2765
+ handleMessage(t) {
2766
+ var o, s;
2767
+ const e = (o = C(t.data)) == null ? void 0 : o.result;
2768
+ if (e)
2769
+ switch (e.kind) {
2770
+ case "INITIALIZE_RECEIVED":
2771
+ e.add_trajectory_error || e.message ? (this.lastError = ((s = e.add_trajectory_error) == null ? void 0 : s.message) ?? e.message ?? "NOVA refused the trajectory", this.reset()) : this.trajectoryState = "planned";
2772
+ break;
2773
+ case "START_RECEIVED":
2774
+ this.motion = "running", this.trajectoryState = "moving", this.releaseOnStart && (this.releaseOnStart = !1, this.sendPause(), this.settlePause());
2775
+ break;
2776
+ case "PAUSE_RECEIVED":
2777
+ this.trajectoryState === "moving" && (this.trajectoryState = "stopping");
2778
+ break;
2779
+ case "MOTION_ERROR":
2780
+ this.lastError = e.message, this.motion === "starting" && (this.motion = null), this.reset();
2781
+ break;
2782
+ }
2783
+ }
2784
+ openSocket() {
2785
+ const t = this.jogger.nova.openReconnectingWebsocket(
2786
+ `/cells/${this.jogger.cellId}/controllers/${this.motionStream.controllerId}/execution/trajectory`
2787
+ );
2788
+ return t.addEventListener("message", this.handleMessage), t;
2789
+ }
2790
+ closeSocket() {
2791
+ this.socket.removeEventListener("message", this.handleMessage), this.socket.dispose(), this.armed = !1, this.motion = null;
2792
+ }
2793
+ }
2794
+ const xe = 3e4;
2795
+ class Ut extends Error {
2796
+ /** @internal The session makes it, see RobotSession */
2797
+ constructor(t, e, o) {
2798
+ super(t), this.url = e, this.cause = o, this.name = "RobotModeChangeError";
2799
+ }
2800
+ }
2801
+ class Ve {
2802
+ /** @internal The session makes it, see RobotSession */
2803
+ constructor(t, e, o, s, n, r = async () => {
2804
+ }) {
2805
+ this.nova = t, this.ids = e, this.live = o, this.safety = s, this.logger = n, this.releaseControl = r, this.pending = null, this.disposed = !1, w(
2806
+ this,
2807
+ {
2808
+ nova: !1,
2809
+ ids: !1,
2810
+ live: !1,
2811
+ safety: !1,
2812
+ logger: !1,
2813
+ releaseControl: !1,
2814
+ endPending: !1
2815
+ },
2816
+ { autoBind: !0 }
2817
+ );
2818
+ }
2819
+ /**
2820
+ * What the controller reports, or null while its live state does not
2821
+ * come: the mode cannot be confirmed then
2822
+ */
2823
+ get reported() {
2824
+ return this.live.connectionQuality === "critical" ? null : this.live.controllerState.mode === "MODE_CONTROL" ? "active" : "inactive";
2825
+ }
2826
+ /**
2827
+ * The mode change in progress, else what the controller reports. The
2828
+ * controller's mode is the source of truth: without a mode change, the
2829
+ * state is derived from the live state and nothing else, so it cannot
2830
+ * drift from it. Inactive while the live state does not come.
2831
+ */
2832
+ get state() {
2833
+ return this.pending ?? this.reported ?? "inactive";
2834
+ }
2835
+ /**
2836
+ * Switches the controller to control mode. Does nothing while a mode change
2837
+ * is in progress, when the safety state or operation mode would make
2838
+ * NOVA refuse it (see {@link RobotSafety.activationBlockedReason}), and
2839
+ * once the session is disposed. Rejects with a
2840
+ * {@link RobotModeChangeError} when NOVA refuses it.
2841
+ */
2842
+ async activate() {
2843
+ if (this.refusedAsDisposed()) return;
2844
+ if (this.state !== "inactive") {
2845
+ this.logger.warn("Tried to activate while already activating");
2846
+ return;
2847
+ }
2848
+ const t = this.safety().activationBlockedReason;
2849
+ if (t) {
2850
+ this.logger.warn(
2851
+ `Not enabling control mode for controller "${this.ids.controllerId}" because ${t}`
2852
+ );
2853
+ return;
2854
+ }
2855
+ await this.changeMode(
2856
+ "activating",
2857
+ () => this.setMode("ROBOT_SYSTEM_MODE_CONTROL")
2858
+ );
2859
+ }
2860
+ /**
2861
+ * Switches the controller to monitor mode, after handing back a planned
2862
+ * move, which holds it in control mode. Does nothing once the session is
2863
+ * disposed. Rejects with a {@link RobotModeChangeError} when NOVA refuses
2864
+ * it.
2865
+ */
2866
+ async deactivate() {
2867
+ if (!this.refusedAsDisposed()) {
2868
+ if (this.state !== "active") {
2869
+ this.logger.warn("Tried to deactivate while already deactivating");
2870
+ return;
2871
+ }
2872
+ await this.changeMode("deactivating", async () => {
2873
+ await this.releaseControl(), await this.setMode("ROBOT_SYSTEM_MODE_MONITOR");
2874
+ });
2875
+ }
2876
+ }
2877
+ /** Activates an inactive robot, deactivates an active one */
2878
+ async toggle() {
2879
+ this.state === "inactive" ? await this.activate() : this.state === "active" && await this.deactivate();
2880
+ }
2881
+ /** Ends a mode change's wait; no mode change is asked for afterwards */
2882
+ dispose() {
2883
+ var t;
2884
+ this.disposed = !0, (t = this.endPending) == null || t.call(this);
2885
+ }
2886
+ /** Whether the session is disposed, which then asks NOVA for nothing */
2887
+ refusedAsDisposed() {
2888
+ return this.disposed ? (this.logger.warn(
2889
+ `Not changing the mode of controller "${this.ids.controllerId}": its session is disposed`
2890
+ ), !0) : !1;
2891
+ }
2892
+ /**
2893
+ * Shows a mode change until it is over: the controller reports the mode
2894
+ * that was asked for, the request fails, or the controller has not
2895
+ * confirmed it after 30 s (`MODE_CHANGE_TIMEOUT_MS`). Then the state is
2896
+ * what the controller reports again, and the change can be asked for
2897
+ * again.
2898
+ */
2899
+ async changeMode(t, e) {
2900
+ var a;
2901
+ const o = t === "activating" ? "active" : "inactive";
2902
+ let s = () => {
2903
+ }, n;
2904
+ const r = () => {
2905
+ this.endPending === r && (this.endPending = void 0, s(), clearTimeout(n), this.setPending(null));
2906
+ };
2907
+ (a = this.endPending) == null || a.call(this), this.endPending = r, this.setPending(t), n = setTimeout(r, xe), s = A(() => this.reported === o, r);
2908
+ try {
2909
+ await e();
2910
+ } catch (d) {
2911
+ throw r(), d;
2912
+ }
2913
+ }
2914
+ setPending(t) {
2915
+ this.pending = t;
2916
+ }
2917
+ async setMode(t) {
2918
+ const { cellId: e, controllerId: o } = this.ids;
2919
+ try {
2920
+ await this.nova.api.controller.setDefaultMode(e, o, t);
2921
+ } catch (s) {
2922
+ const n = (typeof s == "object" && s !== null && "url" in s && typeof s.url == "string" ? s.url : void 0) ?? `/cells/${e}/controllers/${o}/mode`;
2923
+ throw new Ut(
2924
+ `Failed to set controller "${o}" to ${t}: ${R(s)}`,
2925
+ n,
2926
+ s
2927
+ );
2928
+ }
2929
+ }
2930
+ }
2931
+ const Ge = {
2932
+ a: 0,
2933
+ d: 0,
2934
+ alpha: 0,
2935
+ theta: 0,
2936
+ reverse_rotation_direction: !1
2937
+ };
2938
+ class Ue {
2939
+ /** @internal The session makes it, see RobotSession */
2940
+ constructor(t, e, o, s, n) {
2941
+ this.motionGroupDescription = t, this.controllerConfiguration = e, this.kinematicModel = o, this.resolvedMotionGroupModel = s, this.coordinateSystems = n, this.dhParameters = (t.dh_parameters ?? []).map(
2942
+ (r) => ({ ...Ge, ...r })
2943
+ );
2944
+ }
2945
+ /** A virtual robot of NOVA's simulation, not a physical one */
2946
+ get isVirtual() {
2947
+ return this.controllerConfiguration.kind === "VirtualController";
2948
+ }
2949
+ /** The model the controller reports */
2950
+ get motionGroupModel() {
2951
+ return this.motionGroupDescription.motion_group_model;
2952
+ }
2953
+ get serialNumber() {
2954
+ return this.motionGroupDescription.serial_number;
2955
+ }
2956
+ /**
2957
+ * The inverse solver of the model; null for a model without one, such as a
2958
+ * linear axis or a turntable, which jogs its joints only
2959
+ */
2960
+ get inverseSolver() {
2961
+ return this.kinematicModel.inverse_solver;
2962
+ }
2963
+ /** Revolute, or prismatic for a linear axis */
2964
+ get jointType() {
2965
+ var t, e;
2966
+ return ((e = (t = this.motionGroupDescription.dh_parameters) == null ? void 0 : t[0]) == null ? void 0 : e.type) ?? O.RevoluteJoint;
2967
+ }
2968
+ /** The joints' limits in automatic mode, one per joint */
2969
+ get jointLimits() {
2970
+ var t;
2971
+ return ((t = this.motionGroupDescription.operation_limits.auto_limits) == null ? void 0 : t.joints) ?? [];
2972
+ }
2973
+ get safetyZones() {
2974
+ return this.motionGroupDescription.safety_zones;
2975
+ }
2976
+ /**
2977
+ * Per-link safety colliders (`safety_link_colliders`): entry k is in the
2978
+ * frame after k DH transforms (entry 0 = the static base). Not every
2979
+ * controller gives them.
2980
+ */
2981
+ get safetyLinkColliders() {
2982
+ return this.motionGroupDescription.safety_link_colliders;
2983
+ }
2984
+ /** The collision shapes of each tool (TCP), at the flange */
2985
+ get safetyToolColliders() {
2986
+ return this.motionGroupDescription.safety_tool_colliders;
2987
+ }
2988
+ /**
2989
+ * Constant transformation between the motion group base frame and the start
2990
+ * of the DH chain. From the kinematic model, which always reflects the
2991
+ * current robot data; the motion group description is only the fallback, as
2992
+ * controllers snapshot the offset when they are created. Null means
2993
+ * identity.
2994
+ */
2995
+ get kinematicChainOffset() {
2996
+ return this.kinematicModel.kinematic_chain_offset ?? this.motionGroupDescription.kinematic_chain_offset ?? null;
2997
+ }
2998
+ /**
2999
+ * Constant transformation between the end of the DH chain and the flange
3000
+ * frame, sourced as {@link RobotDescription.kinematicChainOffset}
3001
+ */
3002
+ get flangeOffset() {
3003
+ return this.kinematicModel.flange_offset ?? this.motionGroupDescription.flange_offset ?? null;
3004
+ }
3005
+ /** Where the robot is mounted in the cell (mm, rotation vector), if set */
3006
+ get mounting() {
3007
+ return this.motionGroupDescription.mounting ?? null;
3008
+ }
3009
+ /** The robot's TCPs, by id and name */
3010
+ get tcps() {
3011
+ return Object.entries(this.motionGroupDescription.tcps ?? {}).map(
3012
+ ([t, e]) => ({ id: t, name: e.name })
3013
+ );
3014
+ }
3015
+ /** The TCPs' offsets from the flange, by TCP id */
3016
+ get tcpOffsetsById() {
3017
+ return this.motionGroupDescription.tcps ?? {};
3018
+ }
3019
+ }
3020
+ const Et = (i) => Array.isArray(i) && i.length === 3 && i.every((t) => typeof t == "number"), Be = 1e-3, We = 0.5, He = 0.01, et = (i, t, e) => !!(i && t && K([...i], [...t], e));
3021
+ class ze {
3022
+ /** @internal The session makes it, see RobotSession */
3023
+ constructor(t, e, o) {
3024
+ this.stream = t, this.description = e, this.jogging = o, w(
3025
+ this,
3026
+ { stream: !1, description: !1, jogging: !1 },
3027
+ { autoBind: !0 }
3028
+ );
3029
+ }
3030
+ /** Safety state, operation mode and mode of the controller */
3031
+ get controllerState() {
3032
+ return this.stream.controllerState;
3033
+ }
3034
+ /**
3035
+ * The motion state as the last message had it: one object for the whole
3036
+ * session, updated in place (see {@link ControllerStateStream})
3037
+ */
3038
+ get rapidlyChangingMotionState() {
3039
+ return this.stream.rapidlyChangingMotionState;
3040
+ }
3041
+ /** What readouts show: it holds while the joints only jitter */
3042
+ get readoutState() {
3043
+ return this.stream.readoutState;
3044
+ }
3045
+ /** The joints readouts show, from {@link RobotLiveState.readoutState} */
3046
+ get jointPose() {
3047
+ return this.stream.readoutState.joint_position;
3048
+ }
3049
+ get connectionQuality() {
3050
+ return this.stream.connectionQuality;
3051
+ }
3052
+ get lastValidStateMessage() {
3053
+ return this.stream.lastValidStateMessage;
3054
+ }
3055
+ get lastInvalidStateMessage() {
3056
+ return this.stream.lastInvalidStateMessage;
3057
+ }
3058
+ /**
3059
+ * The TCP pose as NOVA reports it, in its own TCP and coordinate system.
3060
+ * Throws for a motion group that reports no TCP pose.
3061
+ */
3062
+ get measuredTcpPoseReference() {
3063
+ return this.tcpPoseReferenceOf(this.rapidlyChangingMotionState);
3064
+ }
3065
+ /**
3066
+ * The measured TCP pose in the TCP and coordinate system that the jogging
3067
+ * store has selected: what a stored or typed pose uses. Throws for a motion
3068
+ * group that reports no TCP pose.
3069
+ */
3070
+ get displayedTcpPoseReference() {
3071
+ return this.inSelectedFrame(this.measuredTcpPoseReference);
3072
+ }
3073
+ /**
3074
+ * The pose readouts show, from {@link RobotLiveState.readoutState}, in the
3075
+ * selected frame. null for a motion group that reports no TCP pose (a
3076
+ * positioner, a turntable): a readout reads this while it renders, so it
3077
+ * does not throw as the poses to store and to plan do.
3078
+ */
3079
+ get displayedTcpPose() {
3080
+ return this.readoutState.tcp_pose ? this.inSelectedFrame(this.tcpPoseReferenceOf(this.readoutState)).pose : null;
3081
+ }
3082
+ /**
3083
+ * Whether the robot stands at a pose: its joints within 0.001, or its TCP
3084
+ * within 0.5 mm and 0.01 rad of the pose in the pose's TCP and coordinate
3085
+ * system. Not at a pose of a TCP or coordinate system it does not know.
3086
+ */
3087
+ isAt(t) {
3088
+ if (t.type === "joint")
3089
+ return et(
3090
+ t.joints,
3091
+ this.rapidlyChangingMotionState.joint_position,
3092
+ Be
3093
+ );
3094
+ try {
3095
+ const e = St({
3096
+ inputPose: this.measuredTcpPoseReference,
3097
+ selectedTcpId: t.tcpPose.tcpId,
3098
+ selectedCoordinateSystemId: t.tcpPose.coordSystemId,
3099
+ tcpOffsetsById: this.description.tcpOffsetsById,
3100
+ coordinateSystems: this.jogging.coordSystems
3101
+ });
3102
+ return et(
3103
+ t.tcpPose.pose.position,
3104
+ e.pose.position,
3105
+ We
3106
+ ) && et(
3107
+ t.tcpPose.pose.orientation,
3108
+ e.pose.orientation,
3109
+ He
3110
+ );
3111
+ } catch {
3112
+ return !1;
3113
+ }
3114
+ }
3115
+ /** The motion state in the stream's next message */
3116
+ nextMotionState() {
3117
+ return this.stream.nextMotionState();
3118
+ }
3119
+ /** Resolves once two messages in a row show the joints standing still */
3120
+ async waitUntilStopped() {
3121
+ let t = await this.stream.nextMotionState(), e = await this.stream.nextMotionState();
3122
+ for (; !K(
3123
+ t.joint_position,
3124
+ e.joint_position,
3125
+ xt
3126
+ ); )
3127
+ t = e, e = await this.stream.nextMotionState();
3128
+ }
3129
+ tcpPoseReferenceOf(t) {
3130
+ var s, n;
3131
+ const e = (s = t.tcp_pose) == null ? void 0 : s.position, o = (n = t.tcp_pose) == null ? void 0 : n.orientation;
3132
+ if (!e || !Et(e))
3133
+ throw new Error(
3134
+ `Invalid current TCP pose position for motion group ${this.stream.motionGroupId}`
3135
+ );
3136
+ if (!o || !Et(o))
3137
+ throw new Error(
3138
+ `Invalid current TCP pose orientation for motion group ${this.stream.motionGroupId}`
3139
+ );
3140
+ return {
3141
+ pose: { position: e, orientation: o },
3142
+ tcpId: t.tcp ?? "",
3143
+ coordinateSystemId: t.coordinate_system ?? "world"
3144
+ };
3145
+ }
3146
+ inSelectedFrame(t) {
3147
+ return St({
3148
+ inputPose: t,
3149
+ selectedTcpId: this.jogging.selectedTcpId,
3150
+ selectedCoordinateSystemId: this.jogging.selectedCoordSystemId,
3151
+ tcpOffsetsById: this.description.tcpOffsetsById,
3152
+ coordinateSystems: this.jogging.coordSystems
3153
+ });
3154
+ }
3155
+ }
3156
+ const Ye = [
3157
+ "SAFETY_STATE_ROBOT_EMERGENCY_STOP",
3158
+ "SAFETY_STATE_DEVICE_EMERGENCY_STOP"
3159
+ ], Ke = ["SAFETY_STATE_NORMAL", "SAFETY_STATE_REDUCED"], Qe = [
3160
+ "SAFETY_STATE_STOP",
3161
+ "SAFETY_STATE_STOP_0",
3162
+ "SAFETY_STATE_STOP_1",
3163
+ "SAFETY_STATE_STOP_2"
3164
+ ], qe = [
3165
+ "OPERATION_MODE_AUTO",
3166
+ "OPERATION_MODE_MANUAL",
3167
+ "OPERATION_MODE_MANUAL_T1",
3168
+ "OPERATION_MODE_MANUAL_T2"
3169
+ ];
3170
+ class Ze {
3171
+ /** @internal The session makes it, see RobotSession */
3172
+ constructor(t, e) {
3173
+ this.state = t, this.activationState = e, w(
3174
+ this,
3175
+ { state: !1, activationState: !1 },
3176
+ { autoBind: !0 }
3177
+ );
3178
+ }
3179
+ get safetyState() {
3180
+ return this.state.controllerState.safety_state;
3181
+ }
3182
+ get operationMode() {
3183
+ return this.state.controllerState.operation_mode;
3184
+ }
3185
+ /** Whether an emergency stop is active */
3186
+ get isEstopActive() {
3187
+ return Ye.includes(this.safetyState);
3188
+ }
3189
+ /** Whether the safety state allows movement */
3190
+ get isMoveableSafetyState() {
3191
+ return Ke.includes(this.safetyState);
3192
+ }
3193
+ /** Whether the operation mode allows movement */
3194
+ get isMoveableOperationMode() {
3195
+ return qe.includes(this.operationMode);
3196
+ }
3197
+ /**
3198
+ * Whether the safety state allows switching to control mode: the moveable
3199
+ * ones and the stop states (RPS-1296)
3200
+ */
3201
+ get isActivatableSafetyState() {
3202
+ return this.isMoveableSafetyState || Qe.includes(this.safetyState);
3203
+ }
3204
+ /**
3205
+ * Why the controller cannot be switched to control mode now, or null. NOVA
3206
+ * refuses the mode change then (an emergency stop needs a hand on the
3207
+ * physical controller), so it is not even requested.
3208
+ */
3209
+ get activationBlockedReason() {
3210
+ return this.isEstopActive ? `an emergency stop is active (${this.safetyState})` : this.isActivatableSafetyState ? this.isMoveableOperationMode ? null : `the operation mode is ${this.operationMode}` : `the safety state is ${this.safetyState}`;
3211
+ }
3212
+ /** Whether the robot may be activated now */
3213
+ get canBeActive() {
3214
+ return this.activationBlockedReason === null;
3215
+ }
3216
+ /** Why the robot cannot move now, or null when it can */
3217
+ get notMoveableReason() {
3218
+ return this.state.connectionQuality === "critical" ? { code: "disconnected" } : this.isMoveableSafetyState ? this.isMoveableOperationMode ? this.activationState() === "inactive" ? { code: "deactivated" } : null : { code: "operation_mode", value: this.operationMode } : { code: "safety_state", value: this.safetyState };
3219
+ }
3220
+ /**
3221
+ * Whether the robot can move now: a moveable safety state and operation
3222
+ * mode, activated, and its live state coming
3223
+ */
3224
+ get canBeMoved() {
3225
+ return this.isMoveableSafetyState && this.isMoveableOperationMode && this.activationState() === "active" && this.state.connectionQuality !== "critical";
3226
+ }
3227
+ }
3228
+ const Xe = "Jogging.TargetPose.Error.MoveFailed.lb";
3229
+ class to {
3230
+ /** @internal The session makes it, see RobotSession */
3231
+ constructor(t, e) {
3232
+ this.robot = t, this.logger = e, this.editing = !1, this.draft = "", this.confirming = !1, this.staged = null, this.moveStarted = !1, this.disposers = [], w(
3233
+ this,
3234
+ { robot: !1, logger: !1, disposers: !1, onBeforePlan: !1 },
3235
+ { autoBind: !0 }
3236
+ ), this.disposers.push(
3237
+ M(
3238
+ () => this.robot.jogging.selectedTabId,
3239
+ () => {
3240
+ (this.editing || this.staged) && this.resetToLive();
3241
+ }
3242
+ )
3243
+ ), this.disposers.push(
3244
+ M(
3245
+ () => ({
3246
+ trajectoryState: this.robot.trajectory.trajectoryState,
3247
+ executionState: this.robot.trajectory.executionState,
3248
+ isRobotAtStagedPose: this.isRobotAtStagedPose
3249
+ }),
3250
+ ({ trajectoryState: o, executionState: s, isRobotAtStagedPose: n }) => {
3251
+ if (!this.stagedPose) return;
3252
+ if (o === "moving") {
3253
+ this.moveStarted = !0;
3254
+ return;
3255
+ }
3256
+ (s === "END_OF_TRAJECTORY" || this.moveStarted && n && o !== "stopping") && this.resetToLive();
3257
+ }
3258
+ )
3259
+ ), this.disposers.push(
3260
+ M(
3261
+ () => this.robot.trajectory.lastError,
3262
+ (o) => {
3263
+ o && this.staged && !this.staged.errorKey && (this.staged = {
3264
+ ...this.staged,
3265
+ errorKey: Xe,
3266
+ errorMessage: o
3267
+ });
3268
+ }
3269
+ )
3270
+ ), this.disposers.push(
3271
+ M(
3272
+ () => !this.confirming && this.robot.trajectory.trajectoryState === "planned" && this.robot.trajectory.isPlanOutdated,
3273
+ (o) => {
3274
+ o && this.stagedPose && this.plan(this.stagedPose);
3275
+ }
3276
+ )
3277
+ );
3278
+ }
3279
+ dispose() {
3280
+ for (const t of this.disposers)
3281
+ t();
3282
+ }
3283
+ get phase() {
3284
+ return this.editing ? "editing" : this.staged ? this.staged.errorKey ? "error" : "staged" : "view";
3285
+ }
3286
+ get isJointTab() {
3287
+ return this.robot.jogging.selectedTabId === "joint";
3288
+ }
3289
+ /** The live pose as text: the joints on the joint tab, else the TCP pose */
3290
+ get liveDisplayString() {
3291
+ if (this.isJointTab)
3292
+ return gt(this.robot.state.jointPose);
3293
+ const t = this.robot.state.displayedTcpPose;
3294
+ return t ? ut(t) : "";
3295
+ }
3296
+ /** What the field shows outside of edit mode: staged value or live pose */
3297
+ get displayString() {
3298
+ var t;
3299
+ return ((t = this.staged) == null ? void 0 : t.displayString) ?? this.liveDisplayString;
3300
+ }
3301
+ /** Parsed form of the draft, or null while it is not a valid pose */
3302
+ get parsedDraft() {
3303
+ const { state: t, motionGroupId: e } = this.robot;
3304
+ if (this.isJointTab) {
3305
+ const n = Xt(this.draft, t.jointPose.length);
3306
+ return n ? { type: "joint", motionGroupId: e, joints: n } : null;
3307
+ }
3308
+ const o = te(this.draft);
3309
+ if (!o || !t.displayedTcpPose) return null;
3310
+ const s = t.displayedTcpPoseReference;
3311
+ return {
3312
+ type: "cartesian",
3313
+ motionGroupId: e,
3314
+ tcpPose: {
3315
+ pose: { position: o.position, orientation: o.orientation },
3316
+ coordSystemId: s.coordinateSystemId,
3317
+ tcpId: s.tcpId
3318
+ }
3319
+ };
3320
+ }
3321
+ get draftValid() {
3322
+ return this.parsedDraft !== null;
3323
+ }
3324
+ beginEdit() {
3325
+ this.draft = this.displayString, this.editing = !0;
3326
+ }
3327
+ setDraft(t) {
3328
+ this.draft = t;
3329
+ }
3330
+ cancelEdit() {
3331
+ this.editing = !1, this.draft = "";
3332
+ }
3333
+ /**
3334
+ * Confirms the edit: plans the pose in the draft and stages it, see
3335
+ * {@link RobotTargetPose.plan}. Does nothing while the draft is no pose.
3336
+ */
3337
+ async confirmEdit() {
3338
+ const t = this.parsedDraft;
3339
+ t && await this.plan(t);
3340
+ }
3341
+ /**
3342
+ * Stages a pose: validates it against the backend by planning a trajectory
3343
+ * to it. On success the trajectory is left initialized on the execution
3344
+ * socket, so Move to is armed immediately; on a planner rejection the pose
3345
+ * stays staged with the failure explanation, as it does when the move to
3346
+ * it fails later: planning it again is the way out. While the robot may
3347
+ * not move,
3348
+ * it plans nothing and drops the pose that was staged before: the one
3349
+ * asked for last is the one to show, and no other may stay armed behind
3350
+ * it. Does nothing while another pose is planned.
3351
+ *
3352
+ * What {@link RobotTargetPose.confirmEdit} does with the text of the
3353
+ * draft, for an app that has the pose as numbers: a cartesian pose is of
3354
+ * its own TCP and in its own coordinate system, whatever is displayed.
3355
+ */
3356
+ async plan(t) {
3357
+ var o;
3358
+ if (this.confirming) return;
3359
+ if (this.robot.notMoveableReason()) {
3360
+ await this.dropStaged();
3361
+ return;
3362
+ }
3363
+ const e = t.type === "joint" ? gt(t.joints) : ut(t.tcpPose.pose);
3364
+ this.confirming = !0;
3365
+ try {
3366
+ await ((o = this.onBeforePlan) == null ? void 0 : o.call(this));
3367
+ const s = await this.robot.trajectory.planTrajectory(
3368
+ at(t)
3369
+ );
3370
+ _(() => {
3371
+ this.staged = {
3372
+ pose: t,
3373
+ displayString: e,
3374
+ errorKey: s.ok ? null : Oe(s.errorFeedbackName)
3375
+ }, this.editing = !1, this.draft = "";
3376
+ });
3377
+ } catch (s) {
3378
+ this.logger.warn("Failed to plan trajectory to typed pose", s), _(() => {
3379
+ this.staged = {
3380
+ pose: t,
3381
+ displayString: e,
3382
+ errorKey: "Jogging.TargetPose.Error.PlanningFailed.lb"
3383
+ }, this.editing = !1, this.draft = "";
3384
+ });
3385
+ } finally {
3386
+ _(() => {
3387
+ this.confirming = !1;
3388
+ });
3389
+ }
3390
+ }
3391
+ /**
3392
+ * The Move to button is held: the robot moves to the staged pose while it
3393
+ * is, see {@link TrajectoryExecutionStore.hold}. `pose` is the pose that
3394
+ * the button's panel shows: nothing moves unless that is the staged pose,
3395
+ * so a panel that shows another one (its plan is still to come, or was
3396
+ * refused) cannot start the move to this one. Nothing moves while the
3397
+ * robot may not move either: the staged pose stays for when it may.
3398
+ * Returns whether the robot moves for this hold.
3399
+ * {@link RobotTargetPose.releaseMove} ends the hold.
3400
+ */
3401
+ holdMove(t) {
3402
+ const e = this.stagedPose;
3403
+ return !e || !De(e, t) || this.robot.notMoveableReason() ? !1 : this.robot.trajectory.hold(at(e));
3404
+ }
3405
+ /**
3406
+ * The Move to button was let go: the robot stops, see
3407
+ * {@link TrajectoryExecutionStore.release}. Safe to call without a hold.
3408
+ */
3409
+ async releaseMove() {
3410
+ await this.robot.trajectory.release();
3411
+ }
3412
+ /** Discards the staged pose and shows the live pose again */
3413
+ async resetToLive() {
3414
+ this.editing = !1, this.draft = "", await this.dropStaged();
3415
+ }
3416
+ /** Drops the staged pose and hands the trajectory that was planned to it back */
3417
+ async dropStaged() {
3418
+ const t = this.staged;
3419
+ this.staged = null, this.moveStarted = !1, t && (!t.errorKey || this.robot.trajectory.holdsExecutionSession) && await this.robot.trajectory.stopAndReset();
3420
+ }
3421
+ /**
3422
+ * Drops the staged pose and the edit without touching the trajectory: for
3423
+ * when another flow has just planned its own (RobotPad: a saved pose that
3424
+ * the user selected)
3425
+ */
3426
+ clear() {
3427
+ this.editing = !1, this.staged = null;
3428
+ }
3429
+ /** The staged pose, if it is valid to store or move to */
3430
+ get stagedPose() {
3431
+ return !this.staged || this.staged.errorKey ? null : this.staged.pose;
3432
+ }
3433
+ /** True when the robot has arrived at (or already was at) the staged pose */
3434
+ get isRobotAtStagedPose() {
3435
+ return this.stagedPose ? this.robot.state.isAt(this.stagedPose) : !1;
3436
+ }
3437
+ }
3438
+ const eo = {
3439
+ getItem: () => null,
3440
+ setItem: () => {
3441
+ }
3442
+ };
3443
+ class oo {
3444
+ /**
3445
+ * @internal Use {@link loadRobotSession}, which loads the resources and
3446
+ * makes the session
3447
+ */
3448
+ constructor(t, e, o, s = {}) {
3449
+ const n = s.logger ?? console;
3450
+ this.onError = s.onError ?? (() => {
3451
+ }), this.nova = t, this.motionGroupId = e.motionGroupId, this.controllerId = e.controllerId, this.cellId = e.cellId, this.stateSource = o.stateSource, this.motionStateSocket = o.motionStateSocket;
3452
+ const r = new Q(
3453
+ t,
3454
+ o.controllerState,
3455
+ o.motionGroupState,
3456
+ o.motionGroupDescription,
3457
+ o.initialMotionState,
3458
+ o.motionStateSocket,
3459
+ e.cellId,
3460
+ { logger: n }
3461
+ ), a = new lt(r, {
3462
+ cellId: e.cellId,
3463
+ motionGroupModel: o.motionGroupModelName,
3464
+ logger: n,
3465
+ onError: (c) => this.onError({
3466
+ kind: "jog",
3467
+ message: R(c),
3468
+ url: a.motionStream.motionStateSocket.url,
3469
+ cause: c
3470
+ })
3471
+ });
3472
+ this.jogging = z.create(
3473
+ a,
3474
+ {
3475
+ coordinateSystems: o.coordinateSystems,
3476
+ description: o.motionGroupDescription,
3477
+ kinematicModel: o.kinematicModel
3478
+ },
3479
+ {
3480
+ storage: s.storage ?? eo,
3481
+ // The store starts no jog while the robot may not move
3482
+ notMoveableReason: () => this.jogRefusedReason
3483
+ }
3484
+ ), this.description = new Ue(
3485
+ o.motionGroupDescription,
3486
+ o.controllerConfiguration,
3487
+ o.kinematicModel,
3488
+ o.motionGroupModelName,
3489
+ this.jogging.coordSystems
3490
+ );
3491
+ const d = new ve(
3492
+ o.stateSource,
3493
+ e.motionGroupId,
3494
+ o.initialControllerState,
3495
+ {
3496
+ isVirtual: this.description.isVirtual,
3497
+ onError: (c) => this.onError({ kind: "stream", ...c })
3498
+ }
3499
+ );
3500
+ this.state = new ze(d, this.description, this.jogging), this.activation = new Ve(
3501
+ t,
3502
+ e,
3503
+ this.state,
3504
+ () => this.safety,
3505
+ n,
3506
+ () => this.releaseControl()
3507
+ ), this.safety = new Ze(this.state, () => this.activation.state), this.trajectory = new Le({
3508
+ joggingStore: this.jogging,
3509
+ isLocked: s.isLocked,
3510
+ // Move to starts no move while a jog would be refused for the robot
3511
+ notMoveableReason: () => this.jogRefusedReason,
3512
+ ensureMovementOwnership: () => this.ensureMovementOwnership("trajectory"),
3513
+ logger: n
3514
+ }), this.targetPose = new to(
3515
+ {
3516
+ motionGroupId: e.motionGroupId,
3517
+ state: this.state,
3518
+ jogging: this.jogging,
3519
+ trajectory: this.trajectory,
3520
+ // A typed pose plans nothing and moves nothing while the robot may
3521
+ // not move, as jogging (also while it is activating or
3522
+ // deactivating), or while the app is locked
3523
+ notMoveableReason: () => {
3524
+ var c;
3525
+ return this.jogRefusedReason ?? ((c = s.isLocked) != null && c.call(s) ? { code: "locked" } : null);
3526
+ }
3527
+ },
3528
+ n
3529
+ ), this.jogging.onBeforeActivate = async () => {
3530
+ this.targetPose.staged && await this.targetPose.resetToLive();
3531
+ }, s.autoActivateVirtual && this.description.isVirtual && this.activation.state === "inactive" && this.activation.activate().catch((c) => {
3532
+ this.onError({
3533
+ kind: "mode",
3534
+ message: R(c),
3535
+ url: c instanceof Ut ? c.url : void 0,
3536
+ cause: c
3537
+ });
3538
+ });
3539
+ }
3540
+ /**
3541
+ * Reports what went wrong in a call that a connected component made for
3542
+ * the user, e.g. a jog: such a component has nobody to reject to, so it
3543
+ * goes to the app's `onError` like the session's own background problems
3544
+ * @internal
3545
+ */
3546
+ reportError(t) {
3547
+ this.onError(t);
3548
+ }
3549
+ /** Which motion owns the robot: jogging, a trajectory, or none ("off") */
3550
+ get movementOwner() {
3551
+ return this.jogging.jogger.mode;
3552
+ }
3553
+ /**
3554
+ * Hands the robot to jogging or to a trajectory: the controller runs only
3555
+ * one of them at a time.
3556
+ *
3557
+ * Handing it to jogging opens the jogging websocket, a movement connection
3558
+ * for which NOVA switches the controller to control mode by itself. So it
3559
+ * rejects with a `JoggingRefusedError` as a jog of {@link RobotSession.jogging}
3560
+ * does, while the robot may not move or its jogging store is locked.
3561
+ * Handing it to a trajectory opens nothing.
3562
+ */
3563
+ async ensureMovementOwnership(t) {
3564
+ if (this.movementOwner !== t) {
3565
+ if (t === "jogging") {
3566
+ await this.jogging.claimForJogging();
3567
+ return;
3568
+ }
3569
+ await this.jogging.deactivate(), await this.jogging.jogger.setJoggingMode(t);
3570
+ }
3571
+ }
3572
+ /**
3573
+ * Why the jogging store starts no jog now, and Move to plans and starts
3574
+ * no move, or null when the robot can move. While the robot is activating
3575
+ * or deactivating its safety has no reason (the robot is not
3576
+ * deactivated). But its controller is not in control mode yet, where NOVA
3577
+ * would switch it for the movement request, or is about to leave it: no
3578
+ * jog and no move then either.
3579
+ */
3580
+ get jogRefusedReason() {
3581
+ return this.safety.notMoveableReason ?? (this.safety.canBeMoved ? null : { code: "deactivated" });
3582
+ }
3583
+ /**
3584
+ * Hands back what holds the controller in control mode, before the robot
3585
+ * is deactivated: a step that runs, which is stopped and over once the
3586
+ * robot stands still (NOVA would run it to its end), and a planned move
3587
+ */
3588
+ async releaseControl() {
3589
+ await this.jogging.stopIncrementalJog({ code: "deactivated" }), await this.releasePlannedMove();
3590
+ }
3591
+ /**
3592
+ * Drops a planned move: a staged typed pose, or a trajectory the app
3593
+ * planned itself (RobotPad: to a saved pose). It holds the controller's
3594
+ * execution session, which keeps the controller in control mode: also
3595
+ * when the store has no plan any more (the robot arrived, the move
3596
+ * failed), since NOVA keeps the trajectory.
3597
+ */
3598
+ async releasePlannedMove() {
3599
+ this.targetPose.staged && await this.targetPose.resetToLive(), (this.trajectory.plannedTrajectory || this.trajectory.trajectoryState !== "idle" || this.trajectory.holdsExecutionSession) && await this.trajectory.stopAndReset();
3600
+ }
3601
+ /** Closes the session's connections and stops following the robot */
3602
+ dispose() {
3603
+ this.activation.dispose(), this.targetPose.dispose(), this.state.stream.dispose(), this.trajectory.dispose(), this.stateSource.close(), this.jogging.dispose(), this.motionStateSocket.dispose();
3604
+ }
3605
+ }
3606
+ const io = [1e3, 2e3], so = (i) => new Promise((t) => setTimeout(t, i));
3607
+ class no {
3608
+ /** @internal Use {@link loadRobotSession} */
3609
+ constructor(t, e, o, s) {
3610
+ this.nova = t, this.motionGroupId = e, this.ids = o, this.options = s, this.state = "loading", this.session = null, this.error = null, this.attempt = 0, this.disposed = !1, this.progress = new Ae(e, o.controllerId), w(
3611
+ this,
3612
+ {
3613
+ nova: !1,
3614
+ ids: !1,
3615
+ options: !1,
3616
+ attempt: !1,
3617
+ disposed: !1,
3618
+ readyPromise: !1,
3619
+ settle: !1,
3620
+ progress: !1
3621
+ },
3622
+ { autoBind: !0 }
3623
+ ), this.start();
3624
+ }
3625
+ /**
3626
+ * Resolves with the session once it is ready; rejects when the load fails
3627
+ * or is disposed. After {@link RobotSessionLoad.retry}, a new promise for the new load.
3628
+ */
3629
+ get ready() {
3630
+ return this.readyPromise;
3631
+ }
3632
+ /** Loads the robot again after a failure */
3633
+ retry() {
3634
+ this.disposed || this.state !== "failed" || this.start();
3635
+ }
3636
+ /** Stops a running load and closes the session */
3637
+ dispose() {
3638
+ var t;
3639
+ this.disposed || (this.disposed = !0, this.attempt++, (t = this.session) == null || t.dispose(), this.session = null, this.settle.reject(new Error("The robot session load was disposed")));
3640
+ }
3641
+ start() {
3642
+ this.attempt++;
3643
+ const t = this.attempt;
3644
+ this.readyPromise = new Promise((e, o) => {
3645
+ this.settle = { resolve: e, reject: o };
3646
+ }), this.readyPromise.catch(() => {
3647
+ }), _(() => {
3648
+ this.state = "loading", this.error = null;
3649
+ }), this.run(t);
3650
+ }
3651
+ isStale(t) {
3652
+ return this.disposed || t !== this.attempt;
3653
+ }
3654
+ async run(t) {
3655
+ var a, d;
3656
+ const { cellId: e, controllerId: o } = this.ids, s = this.options.retryDelaysMs ?? io, n = this.options.logger ?? console, r = this.options.stateSource ?? ((c) => Re(this.nova, c));
3657
+ for (let c = 0; ; c++)
3658
+ try {
3659
+ const l = await Ne({
3660
+ nova: this.nova,
3661
+ cellId: e,
3662
+ controllerId: o,
3663
+ motionGroupId: this.motionGroupId,
3664
+ progress: this.progress,
3665
+ createStateSource: r,
3666
+ isStale: () => this.isStale(t),
3667
+ socketTimeoutMs: this.options.socketTimeoutMs
3668
+ });
3669
+ if (!l) return;
3670
+ if (this.isStale(t)) {
3671
+ l.dispose();
3672
+ return;
3673
+ }
3674
+ let h;
3675
+ try {
3676
+ h = new oo(
3677
+ this.nova,
3678
+ { cellId: e, controllerId: o, motionGroupId: this.motionGroupId },
3679
+ l,
3680
+ this.options
3681
+ );
3682
+ } catch (g) {
3683
+ throw l.dispose(), g;
3684
+ }
3685
+ if (this.isStale(t)) {
3686
+ h.dispose();
3687
+ return;
3688
+ }
3689
+ _(() => {
3690
+ this.session = h, this.state = "ready";
3691
+ }), this.settle.resolve(h);
3692
+ return;
3693
+ } catch (l) {
3694
+ if (this.isStale(t)) return;
3695
+ const h = Z(l) ? s[c] : void 0;
3696
+ if (h === void 0) {
3697
+ _(() => {
3698
+ Z(l) ? this.progress.failStep(l.stepId, l.cause) : this.progress.failWith(l), this.state = "failed", this.error = l;
3699
+ }), (d = (a = this.options).onEvent) == null || d.call(a, {
3700
+ type: "loadFailed",
3701
+ motionGroupId: this.motionGroupId,
3702
+ step: Z(l) ? l.stepId : "unknown",
3703
+ message: R(l),
3704
+ attempts: c + 1
3705
+ }), this.settle.reject(l);
3706
+ return;
3707
+ }
3708
+ if (n.warn(
3709
+ `Retrying load of robot "${this.motionGroupId}" after: ${R(l)}`
3710
+ ), _(() => {
3711
+ this.progress.beginRetry(c + 1);
3712
+ }), await so(h), this.isStale(t)) return;
3713
+ }
3714
+ }
3715
+ }
3716
+ function yo(i, t, e = {}) {
3717
+ return ro(G(i), t, {
3718
+ ...e,
3719
+ cellId: e.cellId ?? ct(i)
3720
+ });
3721
+ }
3722
+ function ro(i, t, e = {}) {
3723
+ const o = e.cellId ?? "cell", s = e.controllerId ?? t.split("@")[1] ?? "";
3724
+ return new no(
3725
+ i,
3726
+ t,
3727
+ { cellId: o, controllerId: s },
3728
+ e
3729
+ );
3730
+ }
3731
+ export {
3732
+ ve as C,
3733
+ lt as J,
3734
+ Q as M,
3735
+ fo as O,
3736
+ ke as R,
3737
+ Le as T,
3738
+ U as a,
3739
+ z as b,
3740
+ Ve as c,
3741
+ Ue as d,
3742
+ ze as e,
3743
+ Ae as f,
3744
+ Gt as g,
3745
+ Ut as h,
3746
+ Ze as i,
3747
+ oo as j,
3748
+ no as k,
3749
+ to as l,
3750
+ St as m,
3751
+ Z as n,
3752
+ K as o,
3753
+ yo as p,
3754
+ Oe as q,
3755
+ ce as r,
3756
+ me as s,
3757
+ le as t,
3758
+ H as u,
3759
+ At as v,
3760
+ ae as w
3761
+ };