forked from ice987987/ioBroker.husqvarna-automower
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
3098 lines (2983 loc) · 117 KB
/
Copy pathmain.js
File metadata and controls
3098 lines (2983 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/*
* Created with @iobroker/create-adapter v2.3.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here, e.g.:
const axios = require('axios');
const WebSocket = require('ws');
// variables
const isValidApplicationCredential = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/; // format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (anchored: without ^/$ any string merely *containing* this pattern would pass)
class HusqvarnaAutomower extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'husqvarna-automower-connect',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.wss = null;
this.access_token = null;
this.mowerData = null;
this.firstStart = true;
this.statisticsPollInProgress = false;
this.autoRestartTimeout = null;
this.ping = null;
// exponential backoff for WebSocket reconnects (autoRestart()) - reset to the base delay on every
// successful (re-)connection, see the 'open' handler in connectToWS()
this.wsReconnectDelay = 5000;
this.statisticsInterval = null;
this.numberOfSchedules = 0;
this.capabilities = [];
}
/**
* Is called when databases are connected and adapter received configuration.
*/
// One-time (well, cheap-and-idempotent-every-startup) fix for a set of known role/type mistakes
// present in objects created by older versions (see CHANGELOG). setObjectNotExistsAsync() never
// touches an object that already exists, so simply updating the adapter does not correct objects
// an already-running installation had already created - this actively force-corrects them via
// extendObjectAsync() instead. Only touches an object if it STILL holds one of the known-bad
// role/type values, so it never clobbers anything a user might have customized in the meantime.
// Role and type are checked independently (not "both must still be wrong"), so an object that
// was already partially corrected by an earlier version of this migration (e.g. role fixed but
// type still wrong) gets fully corrected instead of being skipped.
async migrateObjectRoles() {
try {
const objects = await this.getAdapterObjectsAsync();
const fixes = [
{ suffix: /\.ACTIONS\.HEADLIGHT$/, badRole: 'value', common: { role: 'state' } },
{ suffix: /\.ACTIONS\.schedule\.\d+\.(start|duration)$/, badRole: 'value', common: { role: 'level' } },
{ suffix: /\.ACTIONS\.schedule\.\d+\.(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/, badRole: 'value', common: { role: 'switch' } },
{ suffix: /\.messages\.messages$/, badType: 'array', common: { type: 'string' } },
{ suffix: /\.system\.id$/, badRole: 'info.id', common: { role: 'text' } },
{ suffix: /\.system\.type$/, badRole: 'info.type', common: { role: 'text' } },
{ suffix: /\.system\.serialNumber$/, badRole: 'info.serialnumber', badType: 'number', common: { role: 'info.serial', type: 'string' } },
{ suffix: /\.positions\.latlong$/, badRole: 'value.gps', common: { role: 'text' } },
];
let fixedCount = 0;
for (const id of Object.keys(objects)) {
const obj = objects[id];
if (!obj || obj.type !== 'state' || !obj.common) {
continue;
}
for (const fix of fixes) {
if (!fix.suffix.test(id)) {
continue;
}
const roleStillBad = fix.badRole !== undefined && obj.common.role === fix.badRole;
const typeStillBad = fix.badType !== undefined && obj.common.type === fix.badType;
if (roleStillBad || typeStillBad) {
await this.extendObjectAsync(id, { common: fix.common });
fixedCount++;
}
break; // each id matches at most one fix pattern (suffixes are mutually exclusive)
}
}
if (fixedCount > 0) {
this.log.info(`Migration: corrected role/type on ${fixedCount} existing object(s) created by an older version.`);
}
} catch (e) {
// Never let a migration failure block adapter startup - worst case the objects stay
// as they were, which is the same situation as before this migration existed.
this.log.warn(`Migration of object roles/types failed (non-fatal, adapter will continue starting): ${e}`);
}
}
async onReady() {
// Initialize your adapter here
this.log.info('starting adapter "husqvarna-automower"...');
// One-time migration: setObjectNotExistsAsync() (used throughout this adapter to create
// states) only creates an object if it does NOT already exist yet - it never updates an
// already-existing object. Installations that were running before 1.0.3 therefore kept the
// incorrect roles/types fixed in that release (see CHANGELOG) forever, even after updating,
// since the objects already existed. This forces those specific, known-bad objects to the
// corrected values on every startup (extendObjectAsync is cheap/idempotent once corrected).
await this.migrateObjectRoles();
// Reset the connection indicator during startup
this.setState('info.connection', false, true);
// The adapters config (in the instance object everything under the attribute "native") is accessible via this.config:
// NOTE: never log the actual applicationKey/applicationSecret values, even at debug level - this adapter's
// own README tells users to enable debug logging and attach the logfile when filing a GitHub issue, and
// the Application Secret in particular is a credential, not just an identifier.
this.log.debug(`config.applicationKey: ${this.config.applicationKey ? '[set]' : '[missing]'}`);
this.log.debug(`config.applicationSecret: ${this.config.applicationSecret ? '[set]' : '[missing]'}`);
this.log.debug(`config.statisticsInterval: ${this.config.statisticsInterval}`);
// check applicationKey
if (!isValidApplicationCredential.test(this.config.applicationKey)) {
this.log.error('"Application Key" is not valid (allowed format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (ERR_#001)');
return;
}
// check applicationSecret
if (!isValidApplicationCredential.test(this.config.applicationSecret)) {
this.log.error('"Application Secret" is not valid (allowed format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (ERR_#002)');
return;
}
// check statisticsInterval
// NOTE: this used "&&" instead of "||", which made the check permanently unreachable (a number can never be
// both < 5 and > 10080 at the same time) - any configured value, including 0 or negative, silently passed.
if (Number(this.config.statisticsInterval) < 5 || Number(this.config.statisticsInterval) > 10080) {
this.log.error('"Time interval to retrieve statistical values" is not valid (5 <= t <= 10080 minutes) (ERR_#003)');
return;
}
this.log.debug('The configuration has been checked successfully. Trying to connect "Automower Connect API"...');
try {
// get Husqvarna access_token
await this.getAccessToken();
// get data from husqvarna API
await this.getMowerData();
// create objects
await this.createObjects(this.mowerData);
// fill in states
await this.fillObjects(this.mowerData);
// get message/error history (non-fatal if it fails, see getAndFillMowerMessages())
await this.getAndFillMowerMessages();
// establish WebSocket connection
await this.connectToWS();
// get statistics
this.statisticsInterval = this.setInterval(async () => {
// guard against overlapping runs: with a short statisticsInterval and a slow/degraded connection,
// a cycle could still be in flight when the next one is due to start, which risked concurrent
// getMowerData()/fillObjects() calls racing each other on the same state tree.
if (this.statisticsPollInProgress) {
this.log.debug('[statisticsInterval]: previous poll still in progress, skipping this tick.');
return;
}
this.statisticsPollInProgress = true;
try {
await this.getMowerData();
await this.fillObjects(this.mowerData);
// NOTE: message history is deliberately NOT re-fetched here on every tick. New messages already
// arrive live via the WebSocket "message" push event (see connectToWS()); polling the full
// GET .../messages list on every statistics cycle would double the request volume against
// Husqvarna's 10 000 requests/month budget for anyone using a short statisticsInterval, for a
// list that in the steady state rarely changes between polls anyway. It is still refreshed on
// adapter startup and on-demand via ACTIONS.REFRESHSTATISTICS.
} catch (error) {
this.log.debug(`${error} (ERR_#015)`);
} finally {
this.statisticsPollInProgress = false;
}
}, this.config.statisticsInterval * 60000); // max. 10000 requests/month; (31d*24h*60min*60s*1000ms)/10000requests/month = 267840ms = 4.46min
} catch (error) {
this.log.error(`${error} (ERR_#004)`);
}
}
/**
* Returns a deep copy of the given value with known-sensitive fields masked. Used everywhere before a value is
* passed to this.log.debug(). This matters because this adapter's own README explicitly tells users to enable
* debug logging and attach the logfile when filing a GitHub issue - without redaction, the Application Secret,
* Application Key and the live OAuth access token would end up in plaintext in every debug log line that logs
* an axios request/response, and very likely in a publicly posted bug report sooner or later.
*
* @param {unknown} value
* @returns {unknown} a deep copy of value with sensitive fields replaced by '***redacted***'
*/
redact(value) {
const SENSITIVE_KEYS = new Set(['authorization', 'x-api-key', 'access_token', 'refresh_token', 'client_secret', 'client_id', 'applicationkey', 'applicationsecret']);
const seen = new WeakSet();
const walk = input => {
if (input === null || typeof input !== 'object') {
return input;
}
if (seen.has(input)) {
return '[circular]';
}
seen.add(input);
if (Array.isArray(input)) {
return input.map(walk);
}
const out = {};
for (const [key, val] of Object.entries(input)) {
if (SENSITIVE_KEYS.has(key.toLowerCase())) {
out[key] = '***redacted***';
} else if (key === 'data' && typeof val === 'string' && (val.includes('client_secret') || val.includes('client_id'))) {
// axios request body for the "get access token" call is a raw x-www-form-urlencoded string,
// not an object, so the key-based masking above does not apply to it - mask it explicitly.
out[key] = val.replace(/client_secret=[^&]*/i, 'client_secret=***redacted***').replace(/client_id=[^&]*/i, 'client_id=***redacted***');
} else {
out[key] = walk(val);
}
}
return out;
};
return walk(value);
}
/**
* Consistent, redacted debug logging for a failed axios request. Factored out because five call sites each had
* a hand-written, near-identical copy of this block - which had already drifted out of sync at least once (a
* copy-pasted context label pointing at the wrong function name, see git history).
*
* @param {string} context - short label identifying the calling function, e.g. 'getMowerData'
* @param {unknown} error - the error caught from a failed axios request
*/
logAxiosError(context, error) {
if (error.response) {
// The request was made and the server responded with a status code that falls out of the range of 2xx
this.log.debug(`[${context}]: HTTP status response: ${error.response.status}; headers: ${JSON.stringify(this.redact(error.response.headers))}; data: ${JSON.stringify(this.redact(error.response.data))}`);
} else if (error.request) {
// The request was made but no response was received - error.request is an instance of XMLHttpRequest in
// the browser and an instance of http.ClientRequest in node.js
this.log.debug(`[${context}]: error request: ${error}`);
} else {
// Something happened in setting up the request that triggered an Error
this.log.debug(`[${context}]: error message: ${error.message}`);
}
this.log.debug(`[${context}]: error.config: ${JSON.stringify(this.redact(error.config))}`);
}
// https://developer.husqvarnagroup.cloud/apis/authentication-api#readme
async getAccessToken() {
await axios({
method: 'POST',
url: 'https://api.authentication.husqvarnagroup.dev/v1/oauth2/token',
data: `grant_type=client_credentials&client_id=${this.config.applicationKey}&client_secret=${this.config.applicationSecret}`,
})
.then(response => {
this.log.debug(`[getAccessToken]: HTTP status response: ${response.status} ${response.statusText}; config: ${JSON.stringify(this.redact(response.config))}; headers: ${JSON.stringify(this.redact(response.headers))}; data: ${JSON.stringify(this.redact(response.data))}`);
this.access_token = response.data.access_token;
if (this.firstStart === true) {
this.log.info('"Husqvarna Authentication API Access token" received.');
} else {
this.log.debug('"Husqvarna Authentication API Access token" received.');
}
})
.catch(error => {
this.logAxiosError('getAccessToken', error);
throw new Error('"Automower Connect API" not reachable. (ERR_#005)');
});
}
// https://developer.husqvarnagroup.cloud/apis/automower-connect-api#readme
async getMowerData() {
await axios({
method: 'GET',
url: 'https://api.amc.husqvarna.dev/v1/mowers',
headers: {
Authorization: `Bearer ${this.access_token}`,
'X-Api-Key': this.config.applicationKey,
'Authorization-Provider': 'husqvarna',
},
})
.then(async response => {
this.log.debug(`[getMowerData]: HTTP status response: ${response.status} ${response.statusText}; config: ${JSON.stringify(this.redact(response.config))}; headers: ${JSON.stringify(this.redact(response.headers))}; data: ${JSON.stringify(response.data)}`);
this.mowerData = response.data;
this.log.debug(`[getMowerData]: response.data: ${JSON.stringify(response.data)}`);
})
.catch(error => {
this.logAxiosError('getMowerData', error);
throw new Error('"Automower Connect API" not reachable. (ERR_#006)');
});
}
// https://developer.husqvarnagroup.cloud/apis/automower-connect-api#readme (GET .../messages)
// Fetches and stores the diagnostic/error message history for every known mower. Non-fatal on error:
// message history is supplementary information and must never block the core status update cycle.
async getAndFillMowerMessages() {
if (!this.mowerData || !Array.isArray(this.mowerData.data)) {
return;
}
for (const mower of this.mowerData.data) {
if (mower.type !== 'mower') {
continue;
}
await axios({
method: 'GET',
url: `https://api.amc.husqvarna.dev/v1/mowers/${mower.id}/messages`,
headers: {
Authorization: `Bearer ${this.access_token}`,
'X-Api-Key': this.config.applicationKey,
'Authorization-Provider': 'husqvarna',
},
})
.then(response => {
this.log.debug(`[getAndFillMowerMessages]: HTTP status response: ${response.status} ${response.statusText}; data: ${JSON.stringify(response.data)}`);
const messages = (response.data && response.data.data && response.data.data.attributes && response.data.data.attributes.messages) || [];
this.setState(`${mower.id}.messages.messages`, { val: JSON.stringify(messages), ack: true });
if (messages.length > 0) {
this.setState(`${mower.id}.messages.lastTime`, { val: messages[0].time, ack: true });
this.setState(`${mower.id}.messages.lastCode`, { val: messages[0].code, ack: true });
this.setState(`${mower.id}.messages.lastSeverity`, { val: messages[0].severity, ack: true });
this.setState(`${mower.id}.messages.lastLatitude`, { val: messages[0].latitude, ack: true });
this.setState(`${mower.id}.messages.lastLongitude`, { val: messages[0].longitude, ack: true });
}
})
.catch(error => {
this.logAxiosError('getAndFillMowerMessages', error);
// intentionally not re-thrown: message history is supplementary and must not block core status updates
});
}
}
// https://github.com/ioBroker/ioBroker.docs/blob/master/docs/en/dev/objectsschema.md
// https://github.com/ioBroker/ioBroker/blob/master/doc/STATE_ROLES.md#state-roles
async createObjects(mowerData) {
// this.log.debug(`[createObjects]: listMowers: ${JSON.stringify(listMowers)}`);
this.log.debug(`[createObjects]: start objects creation for ${Object.keys(mowerData.data).length} device${Object.keys(mowerData.data).length > 1 ? 's' : ''}...`);
if (Object.keys(mowerData.data).length !== 0) {
for (let i = 0; i < Object.keys(mowerData.data).length; i++) {
if (mowerData.data[i].type === 'mower') {
// create device
await this.setObjectNotExistsAsync(mowerData.data[i].id, {
type: 'device',
common: {
name: mowerData.data[i].attributes.system.model,
// icon: deviceIcon
},
native: {},
});
// create channel "system"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system`, {
type: 'channel',
common: {
name: 'System information about an Automower',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system.type`, {
type: 'state',
common: {
name: 'Device type',
type: 'string',
role: 'text',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system.id`, {
type: 'state',
common: {
name: 'Device ID',
type: 'string',
role: 'text',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system.name`, {
type: 'state',
common: {
name: 'The name given to the Automower by the user when pairing the Automower',
type: 'string',
role: 'info.name',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system.model`, {
type: 'state',
common: {
name: 'The model name of the Automower',
type: 'string',
role: 'info.model',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.system.serialNumber`, {
type: 'state',
common: {
name: 'The serial number for the Automower',
type: 'string',
role: 'info.serial',
read: true,
write: false,
},
native: {},
});
// create channel "battery"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.battery`, {
type: 'channel',
common: {
name: 'Information about the battery in the Automower',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.battery.batteryPercent`, {
type: 'state',
common: {
name: 'The current battery level percentage',
type: 'number',
role: 'value.battery',
min: 0,
max: 100,
unit: '%',
read: true,
write: false,
},
native: {},
});
// create channel "capabilities"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities`, {
type: 'channel',
common: {
name: 'Information about what capabilities the Automower has',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities.canConfirmError`, {
type: 'state',
common: {
name: 'If the Automower supports the command confirm error. The error also needs to be confirmable.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities.headlights`, {
type: 'state',
common: {
name: 'If the Automower supports headlights. If false, no headlights are available.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities.position`, {
type: 'state',
common: {
name: 'If the Automower supports GPS position. If false, no positions are available.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities.stayOutZones`, {
type: 'state',
common: {
name: 'If the Automower supports stay-out zones. If false, no stay-out zones are available.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.capabilities.workAreas`, {
type: 'state',
common: {
name: 'If the Automower supports work areas. If false, no work areas are avalilable.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
// create channel "mower", see https://developer.husqvarnagroup.cloud/apis/Automower+Connect+API#/status%20description%20and%20error%20codes for descriptions of status and error codes
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower`, {
type: 'channel',
common: {
name: 'Information about the mowers current status.',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.mode`, {
type: 'state',
common: {
name: 'Information about the mowers current mode.',
type: 'string',
role: 'state',
states: {
MAIN_AREA: 'Mower will mow until low battery. Go home and charge. Leave and continue mowing.',
DEMO: 'Same as main area, but shorter times. (No blade operation)',
SECONDARY_AREA: 'Mower will mow until empty battery, or a limited time. When done, it stops in the garden.',
HOME: 'Mower goes home and parks forever.',
UNKNOWN: 'Unknown mode.',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.activity`, {
type: 'state',
common: {
name: 'Information about the mowers current activity',
type: 'string',
role: 'state',
states: {
UNKNOWN: 'Unknown activity.',
NOT_APPLICABLE: 'Manual start required in mower.',
MOWING: 'Mower is mowing lawn. If in demo mode the blades are not in operation.',
GOING_HOME: 'Mower is going home to the charging station.',
CHARGING: 'Mower is charging in station due to low battery.',
LEAVING: 'Mower is leaving the charging station.',
PARKED_IN_CS: 'Mower is parked in charging station.',
STOPPED_IN_GARDEN: 'Mower has stopped. Needs manual action to resume.',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.inactiveReason`, {
type: 'state',
common: {
name: 'Inactive reason',
type: 'string',
role: 'state',
states: {
NONE: 'No inactive reason.',
PLANNING: 'The mower is planning a path or a work area.',
SEARCHING_FOR_SATELLITES: 'Waiting for fix when using EPOS.',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.state`, {
type: 'state',
common: {
name: 'Information about the mowers current state',
type: 'string',
role: 'state',
states: {
UNKNOWN: 'Unknown state.',
NOT_APPLICABLE: 'Not applicable.',
PAUSED: 'Mower has been paused by user.',
IN_OPERATION: 'Mower is operating according to selected mode. The activity gives information about what it is currently up to.',
WAIT_UPDATING: 'Mower is in wait state when updating.',
WAIT_POWER_UP: 'Mower is in wait state when powering up.',
RESTRICTED: 'The mower is currently restricted from mowing for some reason. It will continue mowing when the restriction is removed. The activity gives information about what the mower is currently up to.',
OFF: 'Mower is turned off.',
STOPPED: 'Mower is stopped, and cannot be started remotely. Start requirements (safety or other) are not fulfilled.',
ERROR: 'A temporary error has occured. If the error is resolved, the mower will resume operation without user interaction. Typically, this happens when the loop signal is lost. When it comes back, the operation is resumed.',
FATAL_ERROR: 'A fatal error has occured. Error has to be fixed confirmed to leave this state.',
ERROR_AT_POWER_UP: 'An error at power up.',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.workAreaId`, {
type: 'state',
common: {
name: 'Current work area id. If the mower supports work areas and the mower is working on a work area. If no current work area is selected this attribute is not set.',
type: 'number',
role: 'state',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.errorCode`, {
type: 'state',
common: {
name: 'Information about the mowers current error status',
type: 'number',
role: 'state',
states: {
0: 'Unexpected error',
1: 'Outside working area',
2: 'No loop signal',
3: 'Wrong loop signal',
4: 'Loop sensor problem, front',
5: 'Loop sensor problem, rear',
6: 'Loop sensor problem, left',
7: 'Loop sensor problem, right',
8: 'Wrong PIN code',
9: 'Trapped',
10: 'Upside down',
11: 'Low battery',
12: 'Empty battery',
13: 'No drive',
14: 'Mower lifted',
15: 'Lifted',
16: 'Stuck in charging station',
17: 'Charging station blocked',
18: 'Collision sensor problem, rear',
19: 'Collision sensor problem, front',
20: 'Wheel motor blocked, right',
21: 'Wheel motor blocked, left',
22: 'Wheel drive problem, right',
23: 'Wheel drive problem, left',
24: 'Cutting system blocked',
25: 'Cutting system blocked',
26: 'Invalid sub-device combination',
27: 'Settings restored',
28: 'Memory circuit problem',
29: 'Slope too steep',
30: 'Charging system problem',
31: 'STOP button problem',
32: 'Tilt sensor problem',
33: 'Mower tilted',
34: 'Cutting stopped - slope too steep',
35: 'Wheel motor overloaded, right',
36: 'Wheel motor overloaded, left',
37: 'Charging current too high',
38: 'Electronic problem',
39: 'Cutting motor problem',
40: 'Limited cutting height range',
41: 'Unexpected cutting height adj',
42: 'Limited cutting height range',
43: 'Cutting height problem, drive',
44: 'Cutting height problem, curr',
45: 'Cutting height problem, dir',
46: 'Cutting height blocked',
47: 'Cutting height problem',
48: 'No response from charger',
49: 'Ultrasonic problem',
50: 'Guide 1 not found',
51: 'Guide 2 not found',
52: 'Guide 3 not found',
53: 'GPS navigation problem',
54: 'Weak GPS signal',
55: 'Difficult finding home',
56: 'Guide calibration accomplished',
57: 'Guide calibration failed',
58: 'Temporary battery problem',
59: 'Temporary battery problem',
60: 'Temporary battery problem',
61: 'Temporary battery problem',
62: 'Temporary battery problem',
63: 'Temporary battery problem',
64: 'Temporary battery problem',
65: 'Temporary battery problem',
66: 'Battery problem',
67: 'Battery problem',
68: 'Temporary battery problem',
69: 'Alarm! Mower switched off',
70: 'Alarm! Mower stopped',
71: 'Alarm! Mower lifted',
72: 'Alarm! Mower tilted',
73: 'Alarm! Mower in motion',
74: 'Alarm! Outside geofence',
75: 'Connection changed',
76: 'Connection NOT changed',
77: 'Com board not available',
78: 'Slipped - Mower has Slipped. Situation not solved with moving pattern',
79: 'Invalid battery combination - Invalid combination of different battery types',
80: 'Cutting system imbalance --Warning--',
81: 'Safety function faulty',
82: 'Wheel motor blocked, rear right',
83: 'Wheel motor blocked, rear left',
84: 'Wheel drive problem, rear right',
85: 'Wheel drive problem, rear left',
86: 'Wheel motor overloaded, rear right',
87: 'Wheel motor overloaded, rear left',
88: 'Angular sensor problem',
89: 'Invalid system configuration',
90: 'No power in charging station',
91: 'Switch cord problem',
92: 'Work area not valid',
93: 'No accurate position from satellites',
94: 'Reference station communication problem',
95: 'Folding sensor activated',
96: 'Right brush motor overloaded',
97: 'Left brush motor overloaded',
98: 'Ultrasonic Sensor 1 defect',
99: 'Ultrasonic Sensor 2 defect',
100: 'Ultrasonic Sensor 3 defect',
101: 'Ultrasonic Sensor 4 defect',
102: 'Cutting drive motor 1 defect',
103: 'Cutting drive motor 2 defect',
104: 'Cutting drive motor 3 defect',
105: 'Lift Sensor defect',
106: 'Collision sensor defect',
107: 'Docking sensor defect',
108: 'Folding cutting deck sensor defect',
109: 'Loop sensor defect',
110: 'Collision sensor error',
111: 'No confirmed position',
112: 'Cutting system major imbalance',
113: 'Complex working area',
114: 'Too high discharge current',
115: 'Too high internal current',
116: 'High charging power loss',
117: 'High internal power loss',
118: 'Charging system problem',
119: 'Zone generator problem',
120: 'Internal voltage error',
121: 'High internal temerature',
122: 'CAN error',
123: 'Destination not reachable',
124: 'Destination blocked',
125: 'Battery needs replacement',
126: 'Battery near end of life',
127: 'Battery problem',
128: 'Multiple reference stations detected',
129: 'Auxiliary cutting means blocked',
130: 'Imbalanced auxiliary cutting disc detected',
131: 'Lifted in link arm',
132: 'EPOS accessory missing',
133: 'Bluetooth com with CS failed',
134: 'Invalid SW configuration',
135: 'Radar problem',
136: 'Work area tampered',
137: 'High temperature in cutting motor, right',
138: 'High temperature in cutting motor, center',
139: 'High temperature in cutting motor, left',
141: 'Wheel brush motor problem',
143: 'Accessory power problem',
144: 'Boundary wire problem',
701: 'Connectivity problem',
702: 'Connectivity settings restored',
703: 'Connectivity problem',
704: 'Connectivity problem',
705: 'Connectivity problem',
706: 'Poor signal quality',
707: 'SIM card requires PIN',
708: 'SIM card locked',
709: 'SIM card not found',
710: 'SIM card locked',
711: 'SIM card locked',
712: 'SIM card locked',
713: 'Geofence problem',
714: 'Geofence problem',
715: 'Connectivity problem',
716: 'Connectivity problem',
717: 'SMS could not be sent',
724: 'Communication circuit board SW must be updated',
},
min: 0,
max: 724,
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.errorCodeTimestamp`, {
type: 'state',
common: {
name: 'Timestamp for the last error code in milliseconds since 1970-01-01T00:00:00 in local time. NOTE! This timestamp is in local time for the mower and is coming directly from the mower.',
type: 'number',
role: 'value.time',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.mower.isErrorConfirmable`, {
type: 'state',
common: {
name: 'If the mower has an errorCode this attribute state if the error is confirmable.',
type: 'boolean',
role: 'state',
read: true,
write: false,
},
native: {},
});
// create channel "planner"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.planner`, {
type: 'channel',
common: {
name: 'Information about the planner. The planner tells when the mower should work.',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.planner.nextStartTimestamp`, {
type: 'state',
common: {
name: 'Timestamp for the next auto start in milliseconds since 1970-01-01T00:00:00 in local time. If the mower is charging then the value is the estimated time when it will be leaving the charging station. If the value is 0 then the mower should start now. NOTE! This timestamp is in local time for the mower and is coming directly from the mower.',
type: 'number',
role: 'value.time',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.planner.override`, {
type: 'state',
common: {
name: 'The Planner has an override feature, which can be used to override the operation decided by the Calendar. There is room for one override at a time, and it occurs from now and for a duration of time.',
type: 'string',
role: 'state',
states: {
NOT_ACTIVE: 'Not active',
FORCE_PARK: 'Force park until next start means that no more mowing will be done within the current task. Operation will be resumed at the start of the next task instead',
FORCE_MOW: 'Force the mower to mow for the specified amount of time. When the time has elapsed, the override is removed and the Planner reverts to the Calendar instead',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.planner.restrictedReason`, {
type: 'state',
common: {
name: 'Restricted reason',
type: 'string',
role: 'state',
states: {
NONE: 'No restricted reason.',
WEEK_SCHEDULE: 'There is no task in the Calendar right now, nothing to do.',
PARK_OVERRIDE: 'The restriction is because someone forced us to park, using the override feature.',
SENSOR: 'The sensor has decided that the grass is short enough, so there is no need to wear it down even more.',
DAILY_LIMIT: 'If a model has a maximum allowed mowing time per day, this restriction will apply when that time has run out.',
FOTA: 'When a Fota update is being transferred to the mower, we want to remain in the charging station to ensure that the transfer is successful. The restriction is removed when the transfer is done.',
FROST: 'The frost sensor thinks it is too cold to mow.',
ALL_WORK_AREAS_COMPLETED: 'All work areas are completed.',
EXTERNAL: 'An external reason set by an external tool. Can be IFTTT, Google Assistant or Amazon Alexa. See externalReason for more information.',
},
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.planner.externalReason`, {
type: 'state',
common: {
name: 'External reason set by i.e. IFTTT, Google Assistant or Amazon Alexa.',
type: 'number',
role: 'state',
min: 1000,
max: 300000,
read: true,
write: false,
},
native: {},
});
// create channel "metadata"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.metadata`, {
type: 'channel',
common: {
name: 'Information if the mower is connected to the cloud and when last status was reported by the mower to the cloud.',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.metadata.connected`, {
type: 'state',
common: {
name: 'Is the mower currently connected to the cloud. The mower needs to be connected to send command to the mower.',
type: 'boolean',
role: 'indicator.connected',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.metadata.statusTimestamp`, {
type: 'state',
common: {
name: 'Timestamp for the last status update in milliseconds since 1970-01-01T00:00:00 in UTC time. NOTE! This timestamp is generated in the backend and not from the Mower.',
type: 'number',
role: 'value.time',
read: true,
write: false,
},
native: {},
});
// create channel GPS-"positions" if supported
// if (mowerData.data[i].attributes.capabilities.position) {
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.positions`, {
type: 'channel',
common: {
name: 'List of the GPS positions. Latest registered position is first in the array and the oldest last in the array. Max number of positions is 50 after that the latest position is removed from the array.',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.positions.latitude`, {
type: 'state',
common: {
name: 'Position latitude',
type: 'number',
role: 'value.gps.latitude',
unit: '°',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.positions.longitude`, {
type: 'state',
common: {
name: 'Position longitude',
type: 'number',
role: 'value.gps.longitude',
unit: '°',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.positions.latlong`, {
type: 'state',
common: {
name: 'Position "latitude;longitude"',
type: 'string',
role: 'text',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.positions.positions`, {
type: 'state',
common: {
name: 'Positions',
type: 'string',
role: 'state',
read: true,
write: false,
},
native: {},
});
// }
// create channel "statistics"
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.statistics`, {
type: 'channel',
common: {
name: 'Information about the statistics. If a value is missing the mower does not support the value.',
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.statistics.cuttingBladeUsageTime`, {
type: 'state',
common: {
name: 'The number of seconds since the last reset of the cutting blade usage counter.',
type: 'number',
role: 'state',
unit: 's',
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync(`${mowerData.data[i].id}.statistics.numberOfChargingCycles`, {
type: 'state',
common: {
name: 'Numbers of charging cycles.',
type: 'number',