@robotical/webapp-types 1.1.0 → 1.1.1

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 (35) hide show
  1. package/dist-types/src/application/ApplicationManager/ApplicationManager.d.ts +13 -3
  2. package/dist-types/src/application/ApplicationManager/ApplicationManager.js +59 -26
  3. package/dist-types/src/application/RAFTs/Cog/Cog.d.ts +7 -2
  4. package/dist-types/src/application/RAFTs/Cog/Cog.js +28 -13
  5. package/dist-types/src/application/RAFTs/Cog/PublishedDataAnalyser.d.ts +64 -4
  6. package/dist-types/src/application/RAFTs/Cog/PublishedDataAnalyser.js +94 -33
  7. package/dist-types/src/application/RAFTs/Marty/Marty.js +1 -1
  8. package/dist-types/src/application/RAFTs/RAFT.d.ts +5 -4
  9. package/dist-types/src/application/RAFTs/RAFT.js +5 -5
  10. package/dist-types/src/application/communicators/SelfdestructiveMessagePromise.js +1 -1
  11. package/dist-types/src/components/modals/ConnectingLoadingSpinnerModal/index.d.ts +3 -0
  12. package/dist-types/src/components/modals/ConnectingLoadingSpinnerModal/index.js +16 -0
  13. package/dist-types/src/components/modals/DisconnectConfirmation/index.d.ts +1 -6
  14. package/dist-types/src/components/modals/DisconnectConfirmation/index.js +2 -59
  15. package/dist-types/src/components/modals/VerificationModal/index.js +1 -1
  16. package/dist-types/src/components/modals/VerificationModalPhoneApp/index.js +11 -6
  17. package/dist-types/src/services/logger/Logger.d.ts +1 -0
  18. package/dist-types/src/services/logger/Logger.js +10 -4
  19. package/dist-types/src/state-observables/modal/ModalObserver.d.ts +1 -0
  20. package/dist-types/src/state-observables/modal/ModalState.d.ts +1 -1
  21. package/dist-types/src/state-observables/modal/ModalState.js +3 -2
  22. package/dist-types/src/types/communication-between-apps/wrapper-communication.d.ts +4 -1
  23. package/dist-types/src/types/communication-between-apps/wrapper-communication.js +3 -0
  24. package/dist-types/src/wrapper-app/WrapperAppManager.d.ts +1 -1
  25. package/dist-types/src/wrapper-app/WrapperAppManager.js +2 -2
  26. package/dist-types/src/wrapper-app/communicators/WebAppCommunicator.js +1 -1
  27. package/dist-types/src/wrapper-app/connectors/CogConnector/CogConnector.d.ts +5 -0
  28. package/dist-types/src/wrapper-app/connectors/CogConnector/CogConnector.js +33 -1
  29. package/dist-types/src/wrapper-app/connectors/Connector.d.ts +4 -1
  30. package/dist-types/src/wrapper-app/connectors/Connector.js +10 -11
  31. package/dist-types/src/wrapper-app/connectors/ConnectorFactory.d.ts +1 -1
  32. package/dist-types/src/wrapper-app/connectors/ConnectorFactory.js +2 -2
  33. package/dist-types/src/wrapper-app/connectors/MartyConnector/MartyConnector.d.ts +5 -0
  34. package/dist-types/src/wrapper-app/connectors/MartyConnector/MartyConnector.js +24 -0
  35. package/package.json +1 -1
@@ -42,7 +42,7 @@ export default class ApplicationManager {
42
42
  * This method is called from various environments (connection button, blocksjr, blocks etc.)
43
43
  * Known issue: connecting to a raft from within a platform won't add the newly connected raft to the connectedRafts hook
44
44
  */
45
- connectGeneric(afterRaftConnectedCb: (raft: RAFT) => void, uuid: string): Promise<void>;
45
+ connectGeneric(afterRaftConnectedCb: (raft: RAFT) => void, uuids: string[]): Promise<void>;
46
46
  /**
47
47
  * Disconnect from RAFT generic
48
48
  * This method is called from various environments (connection button, blocksjr, blocks etc.)
@@ -52,7 +52,7 @@ export default class ApplicationManager {
52
52
  * Selects a RAFT in Phone's verification modal
53
53
  */
54
54
  selectRaft(ricToConnectTo: FOUND_RAFT_ON_DISCOVERY_RESPONSE['foundRIC'], method: RaftConnectionMethod): Promise<RAFT | null>;
55
- connectToRIC(method: RaftConnectionMethod, uuid: string): Promise<RAFT | null>;
55
+ connectToRIC(method: RaftConnectionMethod, uuids: string[]): Promise<RAFT | null>;
56
56
  /**
57
57
  * Disconnect from RAFT
58
58
  */
@@ -66,7 +66,12 @@ export default class ApplicationManager {
66
66
  * Start looking for rics to connect to
67
67
  * This is used from the Phone App only
68
68
  */
69
- startDiscovery(ricSelectedCb: (raft: RAFT) => void): Promise<void>;
69
+ startDiscovery(ricSelectedCb: (raft: RAFT) => void, uuids: string[]): Promise<void>;
70
+ /**
71
+ * Stοp discovery
72
+ * When the user cancels the discovery process without having first connected to a robot
73
+ */
74
+ stopDiscovery(): Promise<void>;
70
75
  /**
71
76
  * Stop verifying raft
72
77
  */
@@ -99,5 +104,10 @@ export default class ApplicationManager {
99
104
  * List the files from the device's local storage
100
105
  */
101
106
  listFilesFromDeviceLocalStorage(dirname: string): Promise<unknown>;
107
+ /**
108
+ * Injects JS code to the phone app
109
+ * This is used to call native functions from the web app
110
+ */
111
+ injectJS(jsCode: string): Promise<unknown>;
102
112
  getTheCurrentlySelectedDeviceOrFirstOfItsKind(deviceType: RaftTypeE): RAFT | undefined;
103
113
  }
@@ -35,7 +35,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
35
  }
36
36
  };
37
37
  import { createElement } from "react";
38
- import modalState from "../../state-observables/modal/ModalState";
38
+ import modalState, { secondaryModalState } from "../../state-observables/modal/ModalState";
39
39
  import { RaftConnectionMethod, RaftTypeE } from "../../types/raft";
40
40
  import WebAppCommunicator from "../../wrapper-app/communicators/WebAppCommunicator";
41
41
  import RAFT from "../RAFTs/RAFT";
@@ -45,12 +45,13 @@ import VerificationModal from "../../components/modals/VerificationModal";
45
45
  import { raftFoundSubscriptionHelper } from "../RAFTs/raft-subscription-helpers";
46
46
  import { AppSentMessage } from "../../types/communication-between-apps/wrapper-communication";
47
47
  import VerificationModalPhoneApp from "../../components/modals/VerificationModalPhoneApp";
48
- import { RaftChannelBLE, } from "@robotical/raftjs";
49
48
  import Logger from "../../services/logger/Logger";
50
49
  import isPhoneApp from "../../utils/phone-app-communication/is-phone-app";
51
50
  import DisconnectConfirmationModal from "../../components/modals/DisconnectConfirmation";
52
51
  import Toaster from "../../utils/Toaster";
53
52
  import { AnalyticsManager } from "../../analytics/AnalyticsManager";
53
+ import { ConnManager } from "@robotical/roboticaljs";
54
+ import ConnectingLoadingSpinnerModal from "../../components/modals/ConnectingLoadingSpinnerModal";
54
55
  var SHOW_LOGS = true;
55
56
  var TAG = "ApplicationManager";
56
57
  var ApplicationManager = /** @class */ (function () {
@@ -113,14 +114,14 @@ var ApplicationManager = /** @class */ (function () {
113
114
  ApplicationManager.prototype.connectGenericMarty = function (afterRaftConnectedCb) {
114
115
  return __awaiter(this, void 0, void 0, function () {
115
116
  return __generator(this, function (_a) {
116
- return [2 /*return*/, this.connectGeneric(afterRaftConnectedCb, RaftChannelBLE.RICServiceUUID)];
117
+ return [2 /*return*/, this.connectGeneric(afterRaftConnectedCb, [ConnManager.RICUUID])];
117
118
  });
118
119
  });
119
120
  };
120
121
  ApplicationManager.prototype.connectGenericCog = function (afterRaftConnectedCb) {
121
122
  return __awaiter(this, void 0, void 0, function () {
122
123
  return __generator(this, function (_a) {
123
- return [2 /*return*/, this.connectGeneric(afterRaftConnectedCb, RaftChannelBLE.CogServiceUUID)];
124
+ return [2 /*return*/, this.connectGeneric(afterRaftConnectedCb, [ConnManager.COGUUID])];
124
125
  });
125
126
  });
126
127
  };
@@ -129,7 +130,7 @@ var ApplicationManager = /** @class */ (function () {
129
130
  * This method is called from various environments (connection button, blocksjr, blocks etc.)
130
131
  * Known issue: connecting to a raft from within a platform won't add the newly connected raft to the connectedRafts hook
131
132
  */
132
- ApplicationManager.prototype.connectGeneric = function (afterRaftConnectedCb, uuid) {
133
+ ApplicationManager.prototype.connectGeneric = function (afterRaftConnectedCb, uuids) {
133
134
  return __awaiter(this, void 0, void 0, function () {
134
135
  var e_1, newRaft, e_2;
135
136
  var _this = this;
@@ -143,7 +144,7 @@ var ApplicationManager = /** @class */ (function () {
143
144
  return [4 /*yield*/, window.applicationManager.startDiscovery(function (newRaft) {
144
145
  _this.connectedRaftContextMethods.addConnectedRaft({ id: newRaft.id, type: newRaft.type, name: newRaft.getFriendlyName() || "", isSelected: true });
145
146
  afterRaftConnectedCb(newRaft);
146
- })];
147
+ }, uuids)];
147
148
  case 2:
148
149
  _a.sent();
149
150
  return [3 /*break*/, 4];
@@ -151,22 +152,28 @@ var ApplicationManager = /** @class */ (function () {
151
152
  e_1 = _a.sent();
152
153
  Logger.error(SHOW_LOGS, TAG, "Failed to start discovery: ".concat(e_1));
153
154
  return [3 /*break*/, 4];
154
- case 4: return [3 /*break*/, 8];
155
+ case 4: return [3 /*break*/, 10];
155
156
  case 5:
156
- _a.trys.push([5, 7, , 8]);
157
- return [4 /*yield*/, window.applicationManager.connectToRIC(RaftConnectionMethod.WEB_BLE, uuid)];
157
+ secondaryModalState.setModal(createElement(ConnectingLoadingSpinnerModal, {}), "Connecting...", false);
158
+ _a.label = 6;
158
159
  case 6:
160
+ _a.trys.push([6, 8, , 9]);
161
+ return [4 /*yield*/, window.applicationManager.connectToRIC(RaftConnectionMethod.WEB_BLE, uuids)];
162
+ case 7:
159
163
  newRaft = _a.sent();
160
164
  if (newRaft) {
161
165
  this.connectedRaftContextMethods.addConnectedRaft({ id: newRaft.id, type: newRaft.type, name: newRaft.getFriendlyName() || "", isSelected: true });
162
166
  afterRaftConnectedCb(newRaft);
163
167
  }
164
- return [3 /*break*/, 8];
165
- case 7:
168
+ return [3 /*break*/, 9];
169
+ case 8:
166
170
  e_2 = _a.sent();
167
171
  Logger.error(SHOW_LOGS, TAG, "Failed to connect to new robot: ".concat(e_2));
168
- return [3 /*break*/, 8];
169
- case 8: return [2 /*return*/];
172
+ return [3 /*break*/, 9];
173
+ case 9:
174
+ secondaryModalState.closeModal();
175
+ _a.label = 10;
176
+ case 10: return [2 /*return*/];
170
177
  }
171
178
  });
172
179
  });
@@ -182,7 +189,7 @@ var ApplicationManager = /** @class */ (function () {
182
189
  switch (_a.label) {
183
190
  case 0:
184
191
  _a.trys.push([0, 3, , 4]);
185
- return [4 /*yield*/, modalState.setModal(createElement(DisconnectConfirmationModal, { connectedRaft: window.applicationManager.connectedRafts[raft.id] }), "Are you sure you want to disconnect from your ".concat(raft.getFriendlyName(), "?"))];
192
+ return [4 /*yield*/, modalState.setModal(createElement(DisconnectConfirmationModal), "Are you sure you want to disconnect from your ".concat(raft.getFriendlyName(), "?"))];
186
193
  case 1:
187
194
  confirmDisconnect = _a.sent();
188
195
  if (!confirmDisconnect) {
@@ -213,7 +220,7 @@ var ApplicationManager = /** @class */ (function () {
213
220
  var selectResults, raftId, raftType, raft;
214
221
  return __generator(this, function (_c) {
215
222
  switch (_c.label) {
216
- case 0: return [4 /*yield*/, window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.RAFT_SELECT, { discoveredRIC: ricToConnectTo, method: method })];
223
+ case 0: return [4 /*yield*/, window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.RAFT_SELECT, { discoveredDevice: ricToConnectTo, method: method })];
217
224
  case 1:
218
225
  selectResults = _c.sent();
219
226
  if (!selectResults.success) return [3 /*break*/, 3];
@@ -253,13 +260,13 @@ var ApplicationManager = /** @class */ (function () {
253
260
  });
254
261
  });
255
262
  };
256
- ApplicationManager.prototype.connectToRIC = function (method, uuid) {
263
+ ApplicationManager.prototype.connectToRIC = function (method, uuids) {
257
264
  var _a, _b;
258
265
  return __awaiter(this, void 0, void 0, function () {
259
266
  var wasConnectedObj, raftId, raftType, raft;
260
267
  return __generator(this, function (_c) {
261
268
  switch (_c.label) {
262
- case 0: return [4 /*yield*/, RAFT.connect(method, uuid)];
269
+ case 0: return [4 /*yield*/, RAFT.connect(method, uuids)];
263
270
  case 1:
264
271
  wasConnectedObj = _c.sent();
265
272
  if (!wasConnectedObj.success) return [3 /*break*/, 3];
@@ -331,7 +338,7 @@ var ApplicationManager = /** @class */ (function () {
331
338
  * Start looking for rics to connect to
332
339
  * This is used from the Phone App only
333
340
  */
334
- ApplicationManager.prototype.startDiscovery = function (ricSelectedCb) {
341
+ ApplicationManager.prototype.startDiscovery = function (ricSelectedCb, uuids) {
335
342
  return __awaiter(this, void 0, void 0, function () {
336
343
  var foundRICs, wasDiscoveryStarted;
337
344
  return __generator(this, function (_a) {
@@ -340,33 +347,52 @@ var ApplicationManager = /** @class */ (function () {
340
347
  this.ricSelectedCb = ricSelectedCb;
341
348
  foundRICs = [];
342
349
  raftFoundSubscriptionHelper().subscribe(function (_a) {
343
- var discoveredRIC = _a.discoveredRIC;
350
+ var discoveredDevice = _a.discoveredDevice;
344
351
  // if the discovered RAFT is already in the list, don't add it, just update the rssi
345
- var foundRICIdx = foundRICs.findIndex(function (ric_) { return ric_._id === discoveredRIC._id; });
352
+ var foundRICIdx = foundRICs.findIndex(function (ric_) { return ric_._id === discoveredDevice._id; });
346
353
  if (foundRICIdx !== -1) {
347
- foundRICs[foundRICIdx] = discoveredRIC;
354
+ foundRICs[foundRICIdx] = discoveredDevice;
348
355
  }
349
356
  else {
350
- foundRICs.push(discoveredRIC);
357
+ foundRICs.push(discoveredDevice);
351
358
  }
352
359
  // foundRICs.sort((a, b) => b._rssi - a._rssi);
353
360
  modalState.setModal(createElement(VerificationModalPhoneApp, { foundRICs: foundRICs }), "Looking for RAFT");
354
361
  });
355
- return [4 /*yield*/, window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.RAFT_START_DISCOVERY)];
362
+ modalState.setModal(createElement(VerificationModalPhoneApp, { foundRICs: [] }), "Looking for RAFT");
363
+ return [4 /*yield*/, window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.RAFT_START_DISCOVERY, { uuids: uuids })];
356
364
  case 1:
357
365
  wasDiscoveryStarted = _a.sent();
358
- if (!wasDiscoveryStarted) {
359
- return [2 /*return*/, raftFoundSubscriptionHelper().unsubscribe()];
360
- }
361
366
  return [4 /*yield*/, modalState.setModal(createElement(VerificationModalPhoneApp, { foundRICs: [] }), "Looking for RAFT")];
362
367
  case 2:
363
368
  _a.sent();
369
+ if (!wasDiscoveryStarted) {
370
+ return [2 /*return*/, raftFoundSubscriptionHelper().unsubscribe()];
371
+ }
364
372
  raftFoundSubscriptionHelper().unsubscribe();
365
373
  return [2 /*return*/];
366
374
  }
367
375
  });
368
376
  });
369
377
  };
378
+ /**
379
+ * Stοp discovery
380
+ * When the user cancels the discovery process without having first connected to a robot
381
+ */
382
+ ApplicationManager.prototype.stopDiscovery = function () {
383
+ return __awaiter(this, void 0, void 0, function () {
384
+ var wasDiscoveryStopped;
385
+ return __generator(this, function (_a) {
386
+ switch (_a.label) {
387
+ case 0: return [4 /*yield*/, window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.RAFT_STOP_DISCOVERY)];
388
+ case 1:
389
+ wasDiscoveryStopped = _a.sent();
390
+ Logger.phoneAppLog(SHOW_LOGS, TAG, "Was discovery stopped: " + wasDiscoveryStopped);
391
+ return [2 /*return*/];
392
+ }
393
+ });
394
+ });
395
+ };
370
396
  /**
371
397
  * Stop verifying raft
372
398
  */
@@ -479,6 +505,13 @@ var ApplicationManager = /** @class */ (function () {
479
505
  });
480
506
  });
481
507
  };
508
+ /**
509
+ * Injects JS code to the phone app
510
+ * This is used to call native functions from the web app
511
+ */
512
+ ApplicationManager.prototype.injectJS = function (jsCode) {
513
+ return window.wrapperCommunicator.sendMessageAndWait(AppSentMessage.INJECT_JS, { jsCode: jsCode });
514
+ };
482
515
  /*======== END OF NATIVE COMMANDS ONLY ========*/
483
516
  //======================//
484
517
  /* UI */
@@ -1,7 +1,8 @@
1
1
  import RAFT from "../RAFT";
2
2
  import RICInterface from "../RAFTInterface";
3
3
  import { RaftTypeE } from "../../../types/raft";
4
- import { CogStateInfo, RICLedLcdColours } from "@robotical/roboticaljs";
4
+ import { RICLedLcdColours } from "@robotical/roboticaljs";
5
+ import { SimplifiedCogStateInfo } from "@robotical/roboticaljs/dist/SystemTypeCog/CogTypes";
5
6
  import { RaftConnEvent, RaftPublishEvent, RaftUpdateEvent } from "@robotical/raftjs";
6
7
  import { RaftInfoEvents } from "../../../types/events/raft-info";
7
8
  import PublishedDataAnalyser from "./PublishedDataAnalyser";
@@ -9,7 +10,7 @@ export declare class Cog extends RAFT implements RICInterface {
9
10
  id: string;
10
11
  type: RaftTypeE;
11
12
  _ledLcdColours: RICLedLcdColours;
12
- raftStateInfo: CogStateInfo | null;
13
+ raftStateInfo: SimplifiedCogStateInfo | null;
13
14
  publishedDataAnalyser: PublishedDataAnalyser;
14
15
  constructor(id: string);
15
16
  get ledLcdColours(): RICLedLcdColours;
@@ -17,6 +18,10 @@ export declare class Cog extends RAFT implements RICInterface {
17
18
  * Gets the RSSI of the RAFT
18
19
  */
19
20
  getRSSI(): number;
21
+ /**
22
+ * Helper function to calculate battery strength based on voltage
23
+ */
24
+ calculateBatteryStrength(voltage: number): number;
20
25
  /**
21
26
  * Gets the battery strength of the RAFT
22
27
  */
@@ -51,9 +51,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
51
51
  };
52
52
  import RAFT from "../RAFT";
53
53
  import { RaftTypeE } from "../../../types/raft";
54
- import { deviceAttrGetLatestFormatted, RaftConnEvent, RaftPublishEvent } from "@robotical/raftjs";
54
+ import { RaftConnEvent, RaftPublishEvent } from "@robotical/raftjs";
55
55
  import { RaftInfoEvents } from "../../../types/events/raft-info";
56
- import PublishedDataAnalyser from "./PublishedDataAnalyser";
56
+ import PublishedDataAnalyser, { setButtonThresholdsUtil } from "./PublishedDataAnalyser";
57
57
  var Cog = /** @class */ (function (_super) {
58
58
  __extends(Cog, _super);
59
59
  function Cog(id) {
@@ -87,25 +87,36 @@ var Cog = /** @class */ (function (_super) {
87
87
  var possibleValues = [126, 127];
88
88
  return possibleValues[Math.floor(Math.random() * possibleValues.length)];
89
89
  };
90
+ /**
91
+ * Helper function to calculate battery strength based on voltage
92
+ */
93
+ Cog.prototype.calculateBatteryStrength = function (voltage) {
94
+ if (voltage >= 2.7) {
95
+ return 100;
96
+ }
97
+ else if (voltage >= 2.3) {
98
+ return ((voltage - 2.3) / 0.4) * 80 + 20;
99
+ }
100
+ else if (voltage >= 2.0) {
101
+ return ((voltage - 2.0) / 0.3) * 20;
102
+ }
103
+ else {
104
+ return 0;
105
+ }
106
+ };
90
107
  /**
91
108
  * Gets the battery strength of the RAFT
92
109
  */
93
110
  Cog.prototype.getBatteryStrength = function () {
94
- var _a, _b, _c, _d;
95
111
  /* check if usb is connected */
96
- var usbAttr = (_b = (_a = this.raftStateInfo) === null || _a === void 0 ? void 0 : _a.deviceManager.getDeviceState('RoboCogPowerV1_00')) === null || _b === void 0 ? void 0 : _b.deviceAttributes['USB'];
97
- if (!usbAttr)
112
+ if (!this.raftStateInfo)
98
113
  return 0.1;
99
- var usb = deviceAttrGetLatestFormatted(usbAttr);
100
- if (usb === 'yes')
114
+ if (this.raftStateInfo.power.usb === 'yes')
101
115
  return 0; // 0 indicates USB is connected
102
116
  /* if usb is not connected, check battery voltage */
103
- var battVAttr = (_d = (_c = this.raftStateInfo) === null || _c === void 0 ? void 0 : _c.deviceManager.getDeviceState('RoboCogPowerV1_00')) === null || _d === void 0 ? void 0 : _d.deviceAttributes['battV'];
104
- if (!battVAttr)
105
- return 0.1;
106
- var battV = deviceAttrGetLatestFormatted(battVAttr);
117
+ var battV = this.raftStateInfo.power.battV;
107
118
  if (!isNaN(+battV)) {
108
- return Math.round(+battV * 100);
119
+ return Math.round(this.calculateBatteryStrength(+battV));
109
120
  }
110
121
  return 0;
111
122
  };
@@ -135,6 +146,10 @@ var Cog = /** @class */ (function (_super) {
135
146
  return __awaiter(this, void 0, void 0, function () {
136
147
  return __generator(this, function (_a) {
137
148
  switch (eventEnum) {
149
+ case RaftConnEvent.CONN_VERIFIED_CORRECT:
150
+ // set up cog thresholds
151
+ setButtonThresholdsUtil(this);
152
+ break;
138
153
  case RaftConnEvent.CONN_DISCONNECTED:
139
154
  // this.publishedDataAnalyser.unsubscribeFromPublishedData();
140
155
  break;
@@ -193,7 +208,7 @@ var Cog = /** @class */ (function (_super) {
193
208
  return __generator(this, function (_a) {
194
209
  switch (eventEnum) {
195
210
  case RaftInfoEvents.STATE_INFO:
196
- this.raftStateInfo = data.stateInfo;
211
+ this.raftStateInfo = data;
197
212
  break;
198
213
  default:
199
214
  break;
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
- import { CogStateInfo } from "@robotical/roboticaljs";
3
2
  import RAFT from "../RAFT";
4
- import PublishedDataGetter from "./PublishedDataGetter";
5
3
  import EventEmitter from "events";
4
+ import Cog from "./Cog";
5
+ import { SimplifiedCogStateInfo } from "@robotical/roboticaljs/dist/SystemTypeCog/CogTypes";
6
6
  interface CogState {
7
7
  tilt: "none" | "forward" | "backward" | "left" | "right";
8
8
  movementType: "none" | "shake" | "move";
@@ -15,6 +15,12 @@ declare class PublishedDataAnalyser extends EventEmitter {
15
15
  private cog;
16
16
  cogState: CogState;
17
17
  private pubSub;
18
+ rotationDetection: RotationDetection;
19
+ shakeDetector: ShakeDetector;
20
+ buttonClickDetection: ButtonClickDetection;
21
+ tiltDetection: TiltDetection;
22
+ objectSenseDetection: ObjectSenseDetection;
23
+ lightSenseDetection: LightSenseDetection;
18
24
  eventsMap: {
19
25
  tilt: {
20
26
  [key in CogState["tilt"]]: string;
@@ -36,11 +42,10 @@ declare class PublishedDataAnalyser extends EventEmitter {
36
42
  };
37
43
  };
38
44
  TiltDetection: typeof TiltDetection;
39
- PublishedDataGetter: typeof PublishedDataGetter;
40
45
  constructor(cog: RAFT);
41
46
  subscribeToPublishedData(): void;
42
47
  unsubscribeFromPublishedData(): void;
43
- analyse(data: CogStateInfo): void;
48
+ analyse(data: SimplifiedCogStateInfo): void;
44
49
  setTilt(tilt: CogState["tilt"]): void;
45
50
  setMovementType(movementType: CogState["movementType"]): void;
46
51
  setRotation(rotation: CogState["rotation"]): void;
@@ -57,4 +62,59 @@ declare class TiltDetection {
57
62
  };
58
63
  detectTilt(ax: number, ay: number, az: number, isMoving: boolean | undefined, analyser: PublishedDataAnalyser, cogVersion: string): void;
59
64
  }
65
+ declare class RotationDetection {
66
+ private dataBuffer;
67
+ private bufferSize;
68
+ private DELAY_FOR_ROTATION;
69
+ private ROTATION_THRESHOLD;
70
+ private rotationDetected;
71
+ private lastRotationDetectionTime;
72
+ private rotationTimer;
73
+ constructor();
74
+ addToBuffer(data: number): void;
75
+ detectRotation(gz: number, isMoving: boolean | undefined, analyser: PublishedDataAnalyser): void;
76
+ calculateMetric(): number;
77
+ }
78
+ declare class ShakeDetector {
79
+ private thresholdAccelerationMove;
80
+ private thresholdAcceleration;
81
+ private thresholdShakeNumber;
82
+ private interval;
83
+ private maxShakeDuration;
84
+ private coolOffPeriod;
85
+ private lastTime;
86
+ private lastTimeShakeDetected;
87
+ private sensorBundles;
88
+ private gravityVector;
89
+ private lastVector;
90
+ private shakeInProgress;
91
+ private moveInProgress;
92
+ constructor();
93
+ detectShake(xAcc: number, yAcc: number, zAcc: number, timestamp: number, analyser: PublishedDataAnalyser): boolean;
94
+ performCheck(analyser: PublishedDataAnalyser): void;
95
+ updateAxis(index: number, acceleration: number, matrix: number[][], adjustment?: number): void;
96
+ }
97
+ export declare class ButtonClickDetection {
98
+ clickThreshold: number;
99
+ releaseThreshold: number;
100
+ lastTime: number;
101
+ buttonClicked: boolean;
102
+ constructor();
103
+ detectButtonClick(buttonValue: number, analyser: PublishedDataAnalyser, cogVersion: string): void;
104
+ }
105
+ declare class ObjectSenseDetection {
106
+ private objectSensed0Threshold;
107
+ private objectSensed1Threshold;
108
+ private objectSensed2Threshold;
109
+ constructor();
110
+ detectObjectSense(objectSenseValue: number[], analyser: PublishedDataAnalyser): void;
111
+ }
112
+ declare class LightSenseDetection {
113
+ private lowLightThreshold;
114
+ private midLightThreshold;
115
+ private highLightThreshold;
116
+ constructor();
117
+ detectLightSense(lightSenseValue: number, analyser: PublishedDataAnalyser): void;
118
+ }
119
+ export declare const setButtonThresholdsUtil: (connectedCog: Cog) => Promise<void>;
60
120
  export default PublishedDataAnalyser;
@@ -13,15 +13,59 @@ var __extends = (this && this.__extends) || (function () {
13
13
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
14
  };
15
15
  })();
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ var __generator = (this && this.__generator) || function (thisArg, body) {
26
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
27
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
28
+ function verb(n) { return function (v) { return step([n, v]); }; }
29
+ function step(op) {
30
+ if (f) throw new TypeError("Generator is already executing.");
31
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
32
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
33
+ if (y = 0, t) op = [op[0] & 2, t.value];
34
+ switch (op[0]) {
35
+ case 0: case 1: t = op; break;
36
+ case 4: _.label++; return { value: op[1], done: false };
37
+ case 5: _.label++; y = op[1]; op = [0]; continue;
38
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
39
+ default:
40
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
41
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
42
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
43
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
44
+ if (t[2]) _.ops.pop();
45
+ _.trys.pop(); continue;
46
+ }
47
+ op = body.call(thisArg, _);
48
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
49
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
50
+ }
51
+ };
16
52
  import { raftPubSubscriptionHelper } from "../raft-subscription-helpers";
17
53
  import { isVersionGreater_errorCatching } from "../../../utils/helpers/compare-version";
18
- import PublishedDataGetter from "./PublishedDataGetter";
19
54
  import EventEmitter from "events";
55
+ import Logger from "../../../services/logger/Logger";
56
+ var SHOW_LOGS = true;
57
+ var TAG = "PublishedDataAnalyser";
20
58
  var PublishedDataAnalyser = /** @class */ (function (_super) {
21
59
  __extends(PublishedDataAnalyser, _super);
22
60
  function PublishedDataAnalyser(cog) {
23
61
  var _this = _super.call(this) || this;
24
62
  _this.cog = cog;
63
+ _this.rotationDetection = new RotationDetection();
64
+ _this.shakeDetector = new ShakeDetector();
65
+ _this.buttonClickDetection = new ButtonClickDetection();
66
+ _this.tiltDetection = new TiltDetection();
67
+ _this.objectSenseDetection = new ObjectSenseDetection();
68
+ _this.lightSenseDetection = new LightSenseDetection();
25
69
  _this.eventsMap = {
26
70
  tilt: {
27
71
  forward: "tiltForward",
@@ -58,7 +102,6 @@ var PublishedDataAnalyser = /** @class */ (function (_super) {
58
102
  },
59
103
  };
60
104
  _this.TiltDetection = TiltDetection;
61
- _this.PublishedDataGetter = PublishedDataGetter;
62
105
  _this.cog = cog;
63
106
  _this.cogState = {
64
107
  tilt: "none",
@@ -76,7 +119,7 @@ var PublishedDataAnalyser = /** @class */ (function (_super) {
76
119
  var _this = this;
77
120
  this.pubSub = raftPubSubscriptionHelper(this.cog);
78
121
  this.pubSub.subscribe(function (data) {
79
- _this.analyse(data.stateInfo);
122
+ _this.analyse(data);
80
123
  });
81
124
  };
82
125
  PublishedDataAnalyser.prototype.unsubscribeFromPublishedData = function () {
@@ -84,20 +127,19 @@ var PublishedDataAnalyser = /** @class */ (function (_super) {
84
127
  (_a = this.pubSub) === null || _a === void 0 ? void 0 : _a.unsubscribe();
85
128
  };
86
129
  PublishedDataAnalyser.prototype.analyse = function (data) {
87
- //@ts-ignore
88
- var accelData = PublishedDataGetter.getAccelerometerData(data.deviceManager);
89
- //@ts-ignore
90
- var gyroData = PublishedDataGetter.getGyroscopeData(data.deviceManager);
91
- //@ts-ignore
92
- var lightData = PublishedDataGetter.getLightData(data.deviceManager);
130
+ if (!data)
131
+ return;
132
+ var accelData = data.accelerometer;
133
+ var gyroData = data.gyroscope;
134
+ var lightData = data.light;
93
135
  var isMoving;
94
136
  if (accelData)
95
- isMoving = shakeDetector.detectShake(accelData.ax, accelData.ay, accelData.az, Date.now(), this);
96
- accelData && tiltDetection.detectTilt(accelData.ax, accelData.ay, accelData.az, isMoving, this, this.cog.getRaftVersion());
97
- gyroData && rotationDetection.detectRotation(gyroData.gz, isMoving, this);
98
- lightData && buttonClickDetection.detectButtonClick(lightData.ir2, this, this.cog.getRaftVersion());
99
- lightData && objectSenseDetection.detectObjectSense([lightData.ir0, lightData.ir1], this);
100
- lightData && lightSenseDetection.detectLightSense(lightData.amb0, this);
137
+ isMoving = this.shakeDetector.detectShake(accelData.ax, accelData.ay, accelData.az, Date.now(), this);
138
+ accelData && this.tiltDetection.detectTilt(accelData.ax, accelData.ay, accelData.az, isMoving, this, this.cog.getRaftVersion());
139
+ gyroData && this.rotationDetection.detectRotation(gyroData.gz, isMoving, this);
140
+ lightData && this.buttonClickDetection.detectButtonClick(lightData.ir2, this, this.cog.getRaftVersion());
141
+ lightData && this.objectSenseDetection.detectObjectSense([lightData.ir0, lightData.ir1], this);
142
+ lightData && this.lightSenseDetection.detectLightSense(lightData.amb0, this);
101
143
  };
102
144
  PublishedDataAnalyser.prototype.setTilt = function (tilt) {
103
145
  this.cogState.tilt = tilt;
@@ -157,7 +199,7 @@ var TiltDetection = /** @class */ (function () {
157
199
  if (isVersionGreater_errorCatching(cogVersion, correctionCutOffVersion)) {
158
200
  tiltCorrection = tiltCorrectionForNewerCog;
159
201
  }
160
- var _a = TiltDetection.rotateAccelData(ax, ay, az, tiltCorrection), x = _a.x, y = _a.y, z = _a.z;
202
+ var _a = TiltDetection.rotateAccelData(ax, ay, az * -1, tiltCorrection), x = _a.x, y = _a.y, z = _a.z;
161
203
  var pitch = Math.atan2(x, this.distance(y, z));
162
204
  var roll = Math.atan2(y, this.distance(x, z));
163
205
  var yaw = Math.atan2(z, this.distance(x, y));
@@ -392,27 +434,18 @@ var ButtonClickDetection = /** @class */ (function () {
392
434
  this.buttonClicked = false;
393
435
  }
394
436
  ButtonClickDetection.prototype.detectButtonClick = function (buttonValue, analyser, cogVersion) {
395
- var correctionCutOffVersion = "1.2.0";
396
- var clickThreshold = 1600;
397
- if (isVersionGreater_errorCatching(cogVersion, correctionCutOffVersion)) {
398
- clickThreshold = 1500;
399
- }
400
- var releaseThreshold = 1590;
401
- if (isVersionGreater_errorCatching(cogVersion, correctionCutOffVersion)) {
402
- releaseThreshold = 1490;
403
- }
404
- this.clickThreshold = clickThreshold;
405
- this.releaseThreshold = releaseThreshold;
406
437
  var currentTime = Date.now();
407
438
  if (buttonValue > this.clickThreshold && !this.buttonClicked) {
408
439
  // console.log("Button clicked", buttonValue);
409
440
  this.buttonClicked = true;
410
441
  this.lastTime = currentTime;
442
+ Logger.info(SHOW_LOGS, TAG, "Button clicked");
411
443
  analyser.setButtonClick("click");
412
444
  }
413
445
  else if (buttonValue < this.releaseThreshold && this.buttonClicked) {
414
446
  // console.log("Button released", buttonValue);
415
447
  this.buttonClicked = false;
448
+ Logger.info(SHOW_LOGS, TAG, "Button released");
416
449
  analyser.setButtonClick("release");
417
450
  }
418
451
  // } else {
@@ -422,6 +455,7 @@ var ButtonClickDetection = /** @class */ (function () {
422
455
  };
423
456
  return ButtonClickDetection;
424
457
  }());
458
+ export { ButtonClickDetection };
425
459
  var ObjectSenseDetection = /** @class */ (function () {
426
460
  function ObjectSenseDetection() {
427
461
  this.objectSensed0Threshold = 2500; // left of the arrow
@@ -463,10 +497,37 @@ var LightSenseDetection = /** @class */ (function () {
463
497
  };
464
498
  return LightSenseDetection;
465
499
  }());
466
- var rotationDetection = new RotationDetection();
467
- var shakeDetector = new ShakeDetector();
468
- var buttonClickDetection = new ButtonClickDetection();
469
- var tiltDetection = new TiltDetection();
470
- var objectSenseDetection = new ObjectSenseDetection();
471
- var lightSenseDetection = new LightSenseDetection();
500
+ export var setButtonThresholdsUtil = function (connectedCog) { return __awaiter(void 0, void 0, void 0, function () {
501
+ var lightResponse, irMin, irMax, buttonClickDetection, error_1;
502
+ return __generator(this, function (_a) {
503
+ switch (_a.label) {
504
+ case 0:
505
+ Logger.info(SHOW_LOGS, TAG, "Setting button thresholds");
506
+ _a.label = 1;
507
+ case 1:
508
+ _a.trys.push([1, 3, , 4]);
509
+ return [4 /*yield*/, connectedCog.sendRestMessage('light')];
510
+ case 2:
511
+ lightResponse = _a.sent();
512
+ if (lightResponse && lightResponse.rslt === "ok" && lightResponse.light.irMax4) {
513
+ irMin = lightResponse.light.irMin4;
514
+ irMax = lightResponse.light.irMax4;
515
+ Logger.info(SHOW_LOGS, TAG, "Got button thresholds: irMin: ".concat(irMin, ", irMax: ").concat(irMax));
516
+ buttonClickDetection = connectedCog.publishedDataAnalyser.buttonClickDetection;
517
+ buttonClickDetection.clickThreshold = irMin + (irMax - irMin) / 2;
518
+ buttonClickDetection.releaseThreshold = buttonClickDetection.clickThreshold - 10;
519
+ Logger.info(SHOW_LOGS, TAG, "Set button thresholds: clickThreshold: ".concat(buttonClickDetection.clickThreshold, ", releaseThreshold: ").concat(buttonClickDetection.releaseThreshold));
520
+ }
521
+ else {
522
+ Logger.warn(SHOW_LOGS, TAG, "Couldn't get button thresholds, probably older fw version");
523
+ }
524
+ return [3 /*break*/, 4];
525
+ case 3:
526
+ error_1 = _a.sent();
527
+ Logger.warn(SHOW_LOGS, TAG, "Couldn't get button thresholds, probably older fw version");
528
+ return [3 /*break*/, 4];
529
+ case 4: return [2 /*return*/];
530
+ }
531
+ });
532
+ }); };
472
533
  export default PublishedDataAnalyser;