-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
2586 lines (2073 loc) · 121 KB
/
main.js
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
/*
*
* ioBroker Husqvarna Automower Adapter
*
* (c) 2018-2021 Greyhound <[email protected]>
*
* MIT License
*
*/
/* jshint -W097 */ // jshint strict:false
/*jslint node: true */
"use strict";
//!V! 1.1.2.0
/*
mower.lastStartTime --> mower.statistics.mowingStartTime, alter Wert wird übernommen und lastStartTime gelöscht, ggf. in View(s) anpassen
Regenwertvergleich bei number: bei 0 oder 1 ==, sonst >=, Typ des Wertes wird aus DP des Sensors gelesen
Zähler für Anzahl WebRequests je Tag und kumulativ Monat (idnWebRequestCountXXXXX)
Workaround für Erkennung Änderung Regensensor (subscribe)
Überarbeitung Logik bei Regen/wieder trocken
*/
//!P! Beim daily-Lauf eine Kopie aller Datenpunkte erstellen und im Dateisystem speichern und dann??
//!I! in den Husqvarna-GPS-Daten fehlt Zeitstempel!
//!I! Adapter setzt voraus, dass Mower spätestens Mitternacht eingeparkt hat
//!I! Option in Cfg für automatischen Neustart nach Regen ( <0 - disabled, >= - aktiv)
/* !I! Zähler für Anzahl WebRequests je Tag
Wenn mobjMower kein valides Objekt, dann das nicht als Statusaktualisierung werten, sondern als Fehler in WebRequest, neuer DP?
!P!Ggf. bei max count == 10000 - 1000 WarnMessage und count for timer runter setzen
bei dailyAccumulation werden Werte zurückgesetzt
mnWebRequestCountDay
mnWebRequestCountDay_success
mnWebRequestCountDay_error -- beim 4. error wird auf mQueryIntervalInactive_s umgeschaltet und Nachricht/error-message gesendet, bei 10. Error wird Adapter auf rot gesetzt !?
idnWebRequestCountDay
idnWebRequestCountDay_success
idnWebRequestCountDay_error
idnWebRequestCountMonth - Month-Werte werden am ersten Tag des Monats auf 0 gesetzt oder wenn letzte Aktualisierung im letzten Monat
idnWebRequestCountMonth_success
idnWebRequestCountMonth_error
*/
//!P! ERROR_CODES_MT mehrsprachig ausfühen, dann in Konfiguration AUswahlbox für Anzeige Fehlercodes
//!P! Option in Cfg für Aktion bei Regen --> park bis auf weiters | Start mit nächster Timereinstellung | parken für 3, 6 oder 12h
//!P! auf Handy-App gibt es bei Parken 4 Möglichkeiten: " BIS AUF WEITERES" | Start mit nächster Timereinstellung | parken für "3 STUNDEN" |"6 STUNDEN" |"12 STUNDEN"
//!P! auf Handy-App gibt es bei Starten: "IM HAUPTBEREICH FORTSETZEN" | Timer aufheben für "3 STUNDEN" |"6 STUNDEN" |"12 STUNDEN"
//!P! auf Handy-App gibt es einen Befehl "Pause", dieser bewirkt das Stehenbleiben, sprich pausieren für unbestimmte Zeit oder gibt es weitere Optionen analog zu parken?
//!P! Wenn Mower in Status Pause wechselt, prüfen, ob in Ladestation (GPS + Abweichung, Druckschalter (in Arbeit), ???), Wenn nicht, dann Telegram-Nachricht und nach Zeit XXX automatisch parken lassen ?!
//!P! Prüfen. wenn Adapter neu gestartet wird, ob einige Werte falsch hochgezählt werden, z. B. Batterieladung Anzahl
//!P! Statuswerte in Variablen in Abhängigkeit vom Mähertyp laden und im Skript verwenden
//!P! updateStatus prüfen, dass Status etc. aktualisiert wird, wenn nicht bzw. http-Fehler oder sich trotz CUTTING GPS-Daten nicht ändern --> ALARM
//!P! - Status Timestamp muss sich ändern (keine Ahnung ob von Husqvarna gesetzt oder nur aktuell vom Webserver)
//!P! in Adapter-config button to test connection data and fill Combobox to select a mower, on one, fill direct
//!P! Idee, Wenn Cutting und bei den letzten 2 Statusabfragen keine Änderung des Standortes wahrscheinlich Fehler oder?
//!P! mower.isCutting scheint in HMower nicht gesetzt zu werden!?
//!P! Magnetschalter (Magnet am Mowergehäuse, Reedkontakt an Station) um zu erkennen, ob Mower in Ladestation
//!P! Wenn Magnetschalter anspricht (off) und letzter Status != LEAVING und aktueller Status != CUTTING (testen!) --> ALARM
//!P! Wenn Mower geparkt, dann Timer programmieren ermöglichen, der Mower wieder startet
//!P! "Pause"-Taste --> mower parken, startet Timer mit einstellbarer Zeit (oder jeder Pausendruck erhöht Pausenwert um X), nach Ablaus geht Mower wieder in Normalbetrieb
//!P! Es gibt wohl noch weitere Befehle ?? add_push_id, remove_push_id <-- ggf. nur für iOS/Android; get_mower_settings
//!P! die Apps können
//!P! - Timer laden/modifizieren
//!P! - Schnitthöhe abfragen/ festlegen
//!P! - Wettertimer, ECO-Modus und Spiralschnitt einstellen
//!P! - Blinkt bei Störung, Scheinwerfer ein/aus
/*
"model": "H" ==? 450X
"command": {
"park": "PARK",
"stop": "STOP",
"start": "START"
},
"status": {
"error": "ERROR",
"cutting": "OK_CUTTING",
"manualCutting": "OK_CUTTING_NOT_AUTO",
"parked": "PARKED_TIMER",
"manualParked": "PARKED_PARKED_SELECTED",
"paused": "PAUSED",
"searching": "OK_SEARCHING"
},
"model": "L" ==? 315X
"command": {
"park": "PARK",
"stop": "STOP",
"start": "START"
},
"status": {
"error": "ERROR",
"cutting": "OK_CUTTING",
"manualCutting": "OK_CUTTING_NOT_AUTO",
"parked": "PARKED_TIMER",
"manualParked": "PARKED_PARKED_SELECTED",
"paused": "PAUSED",
"searching": "OK_SEARCHING"
},
*/
/*
Handy-App
- sollte Mähdauer anzeigen und wahrscheinlichen nächsten Boxenstop
- letzte Datenaktualisierung
- Akkustatus (% Kapazität) beim Mähen anzeigen, wird seit 2018 angezeigt
- bei bestimmten Fehlern (hängt fest), sollte ein Start per App möglich sein
- Mäher hatte Netzverbindung verloren, via App nicht erkennbar, es fehlt Datum/Uhrzeit letzte Aktualisierung vom Mäher
- Datum/Uhrzeit == lokale Zeit ???
- Rückmeldung Mähen erforderlich (Mähwiderstand)
- Rückmeldung aktiver Mähbereich
- bei Statusänderung sollte der Auslöser "festgehalten" werden: mower timer, App + account, via Web-API + account
*/
/*
Actions
- Start
- Park
- Stop
*/
/*
Status
- OFF_HATCH_OPEN
- OFF_HATCH_CLOSED_DISABLED - deaktiviert, manueller Start erforderlich
- OK_CHARGING
- OK_CUTTING
- OK_CUTTING_NOT_AUTO
- OK_LEAVING
- OK_SEARCHING
- PARKED_AUTOTIMER
- OFF_DISABLED
- ERROR
- PARKED_PARKED_SELECTED
- PARKED_TIMER
- PAUSED
next start source
- MOWER_CHARGING
- NO_SOURCE
- COMPLETED_CUTTING_TODAY_AUTO --> nextStartTimestamp --> 2017-07-07 02:00:00
- WEEK_TIMER --> nextStartTimestamp --> 2017-07-07 02:00:00
OperatingMode
- Auto
- HOME --> PARKED_PARKED_SELECTED
*/
// you have to require the utils module and call adapter function
const utils = require(__dirname + '/lib/utils'); // Get common adapter utils
// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.template.0
const adapter = utils.Adapter('husq-automower');
const HusqApiRequest = require(__dirname + '/lib/HusqApiRequest');
const husqApi = new HusqApiRequest(adapter);
const husqSchedule = require('node-schedule');
const idnMowerConnected = 'info.connected',
idnMowerFirmware = 'info.firmware',
idnMowerNickname = 'info.nickname',
idnMowerID = 'info.mower_id',
idnMowerModel = 'info.model',
idnMowersIndex = 'info.mowers_index',
idnMowersJson = 'info.mowers_json',
idnHomeLocationName = 'mower.homeLocation.name',
idnHomeLocationLongitude = 'mower.homeLocation.longitude',
idnHomeLocationLatitude = 'mower.homeLocation.latitude',
idnHomeLocationLongitudeCP = 'mower.homeLocation.longitudeCP', // CP == Husqvarna central point record
idnHomeLocationLatitudeCP = 'mower.homeLocation.latitudeCP',
idnHomeLocationLongitudeOffset = 'mower.homeLocation.longitudeOffset',
idnHomeLocationLatitudeOffset = 'mower.homeLocation.latitudeOffset',
idnHomeLocationCurrentDistance = 'mower.homeLocation.currentDistance',
idnHomeLocationMaxDistance = 'mower.homeLocation.maxDistance',
idnHomeLocationSensitivityLevel = 'mower.homeLocation.sensitivityLevel',
idnHomeLocationSensitivityRadius = 'mower.homeLocation.sensitivityRadius',
idnLastLocationLatitude = 'mower.lastLocation.latitude',
idnLastLocationLongitude = 'mower.lastLocation.longitude',
idnLastLocationTimestamp = 'mower.lastLocation.timestamp',
idnBatteryChargeCycleDaily = 'mower.statistics.batteryChargeCycleDaily',
idnBatteryEfficiencyFactor = 'mower.statistics.batteryEfficiencyFactor',
idnChargingStartTime = 'mower.statistics.chargingBatteryStarttime',
idnChargingTimeBatteryCurrent = 'mower.statistics.chargingTimeBatteryCurrent',
idnChargingTimeBatteryDaily = 'mower.statistics.chargingTimeBatteryDaily',
idnChargingTimeBatteryNew = 'mower.statistics.chargingTimeBatteryNew',
idnLastChargingTimeBattery = 'mower.statistics.lastChargingTimeBattery',
idnCurrentCoveredDistance = 'mower.statistics.currentCoveredDistance',
idnCoveredDistanceDaily = 'mower.statistics.coveredDistanceDaily',
idnLastMowingTime = 'mower.statistics.lastMowingTime',
idnLastCoveredDistance = 'mower.statistics.lastCoveredDistance',
idnLastStationReturnTime = 'mower.statistics.lastStationReturnTime',
idnMowingTime = 'mower.statistics.mowingTime',
idnMowingTimeDaily = 'mower.statistics.mowingTimeDaily',
idnMowingStartTime = 'mower.statistics.mowingStartTime',
idnMowingTimeBatteryNew = 'mower.statistics.mowingTimeBatteryNew',
idnOverallBatteryChargeCycle = 'mower.statistics.overallBatteryChargeCycle',
idnOverallMowingTime = 'mower.statistics.overallMowingTime',
idnOverallCoveredDistance = 'mower.statistics.overallCoveredDistance',
idnAMAction = 'mower.action',
idnBatteryPercent = 'mower.batteryPercent',
idnCurrentErrorCode = 'mower.currentErrorCode',
idnCurrentErrorMsg = 'mower.currentErrorMsg',
idnCurrentErrorCodeTS = 'mower.currentErrorCodeTimestamp',
idnLastAction = 'mower.lastAction',
idnLastDockingTime = 'mower.lastDockingTime',
idnLastErrorCode = 'mower.lastErrorCode',
idnLastErrorMsg = 'mower.lastErrorMsg',
idnLastErrorCodeTS = 'mower.lastErrorCodeTimestamp',
idnLastHttpStatus = 'mower.lastHttpStatus',
idnLastLocations = 'mower.lastLocations',
idnLastStatus = 'mower.lastStatus',
idnLastStatusTime = 'mower.lastStatusTime',
idnLastStatusChangeTime = 'mower.lastStatusChangeTime',
idnLastDayLocations = 'mower.lastdayLocations',
idnNextStartSource = 'mower.nextStartSource',
idnNextStartTime = 'mower.nextStartTime', // --> io-package
idnNextStartWatching = 'mower.nextStartWatching', // ?????
idnOperatingMode = 'mower.operatingMode',
idnStopOnRainEnabled = 'mower.stopOnRainEnabled', // copy from config
idnStoppedDueToRain = 'mower.stoppedDueRain', // stopped due to rain
idnTimerAfterRainStartAt = 'mower.timerAfterRainStartAt',
idnWaitAfterRain = 'mower.waitAfterRain', // copy from config
idnRawSend = 'mower.rawSend',
idnRawResponse = 'mower.rawResponse',
idnRawResponseGeo = 'mower.rawResponse_geo',
idnRawResponseMowers = 'mower.rawResponse_mowers',
idnSendMessage = 'mower.sendMessage',
idnScheduleTime = 'mower.scheduleTime',
idnWebRequestCountDay = 'mower.http_request_count_day',
idnWebRequestCountDay_success = 'mower.http_request_count_day_success',
idnWebRequestCountDay_error = 'mower.http_request_count_day_error',
idnWebRequestCountMonth = 'mower.http_request_count_month',
idnWebRequestCountMonth_success = 'mower.http_request_count_month_success',
idnWebRequestCountMonth_error = 'mower.http_request_count_month_error',
UrlGoogleMaps = 'http://maps.google.com/maps?q=',
ThisIsTheEnd = 'ThisIsTheEnd';
let mobjMower = null,
mQueryIntervalActive_s = 30,
mQueryIntervalInactive_s = 300,
mCurrentStatus = 'unknown',
mLastStatus = 'unknown',
mHomeLocationLongitude = 0,
mHomeLocationLatitude = 0,
mNextStartTime = 0,
mLastStartTime = 0, // workaround, until we get the real times from API, P#03
mbStoppedDueToRain = false,
mLastErrorCode = 0,
mLastErrorCodeTimestamp = 0,
mJsonLastLocations = [],
mDist = 0,
mDistDaily = 0,
mMaxDistance = 0,
mLastLocationLongi = 0,
mLastLocationLati = 0,
mBatteryPercent = 0,
mAlarmOnBatteryPercent = false,
mMowingTime = 0,
mLastMowingTime = 0,
mMowingTimeDaily = 0,
mMowingTimeBatteryNew = 0,
mStartMowingTime = 0,
mSearchingStartTime = 0,
mChargingStartTime = 0,
mChargingTimeBatteryCurrent = 0,
mChargingTimeBatteryDaily = 0,
mChargingTimeBatteryNew = 0,
mScheduleStatus = null,
mScheduleTime = 1,
mTimeZoneOffset = new Date().getTimezoneOffset(), // offset in minutes
mWaitAfterRainTimer = null,
mWaitAutoTimer = null,
mBatteryChargeCycleDaily = 0,
mLastStatusChangeTime = 0,
mScheduleDailyAccumulation = null,
mWaitAfterRain_min = 0,
mUpdateStatusRunning = false,
mnWebRequestCountDay = 0,
mnWebRequestCountDay_success = 0,
mnWebRequestCountDay_error = 0,
mnWebRequestCountDay_error_Check = 0,
ThisIsTheEnd2;
const MSG_PRIO = {'info': 3, 'warn': 2, 'alarm': 1, 'intern': 9};
const ERROR_CODES_MT = {
'320': { // 330X
'0': {'alarm': false, 'language': {'ger': ''}},
'1': {'alarm': true, 'language': {'ger': 'Außerhalb des Arbeitsbereichs'}},
'2': {'alarm': false, 'language': {'ger': 'Kein Schleifensignal'}},
'4': {'alarm': false, 'language': {'ger': 'Problem Schleifensensor, vorne'}},
'5': {'alarm': false, 'language': {'ger': 'Problem Schleifensensor, hinten'}},
'6': {'alarm': false, 'language': {'ger': 'Problem Schleifensensor'}},
'7': {'alarm': false, 'language': {'ger': 'Problem Schleifensensor'}},
'8': {'alarm': true, 'language': {'ger': 'Falscher PIN-Code'}},
'9': {'alarm': false, 'language': {'ger': 'Eingeschlossen'}},
'10': {'alarm': false, 'language': {'ger': 'Steht auf dem Kopf'}},
'11': {'alarm': false, 'language': {'ger': 'Niedriger Batteriestand'}},
'12': {'alarm': false, 'language': {'ger': 'Batterie leer'}}, // 450X - angehoben?
'13': {'alarm': false, 'language': {'ger': 'Kein Antrieb'}},
'15': {'alarm': true, 'language': {'ger': 'Mäher angehoben'}}, // 450X - kein Schleifensignal?
'16': {'alarm': false, 'language': {'ger': 'Eingeklemmt in Ladestation'}},
'17': {'alarm': false, 'language': {'ger': 'Ladestation blockiert'}},
'18': {'alarm': false, 'language': {'ger': 'Problem Stoßsensor hinten'}},
'19': {'alarm': false, 'language': {'ger': 'Problem Stoßsensor vorne'}},
'20': {'alarm': false, 'language': {'ger': 'Radmotor rechts blockiert'}},
'21': {'alarm': false, 'language': {'ger': 'Radmotor links blockiert'}},
'22': {'alarm': false, 'language': {'ger': 'Problem Antrieb links'}},
'23': {'alarm': false, 'language': {'ger': 'Problem Antrieb rechts'}},
'24': {'alarm': false, 'language': {'ger': 'Problem Mähmotor'}},
'25': {'alarm': false, 'language': {'ger': 'Schneidsystem blockiert'}},
'26': {'alarm': false, 'language': {'ger': 'Fehlerhafte Bauteileverbindung'}},
'27': {'alarm': false, 'language': {'ger': 'Standardeinstellungen'}},
'28': {'alarm': false, 'language': {'ger': 'Speicher defekt'}},
'30': {'alarm': false, 'language': {'ger': 'Batterieproblem'}},
'31': {'alarm': false, 'language': {'ger': 'STOP-Tastenproblem'}},
'32': {'alarm': false, 'language': {'ger': 'Kippsensorproblem'}},
'33': {'alarm': true, 'language': {'ger': 'Mäher gekippt'}},
'35': {'alarm': false, 'language': {'ger': 'Rechter Radmotor überlastet'}},
'36': {'alarm': false, 'language': {'ger': 'Linker Radmotor überlastet'}},
'37': {'alarm': false, 'language': {'ger': 'Ladestrom zu hoch'}},
'38': {'alarm': false, 'language': {'ger': 'Vorübergehendes Problem'}},
'42': {'alarm': false, 'language': {'ger': 'Begrenzter Schnitthöhenbereich'}},
'43': {'alarm': false, 'language': {'ger': 'Unerwartete Schnitthöhenverstellung/Problem Antrieb Schnitthöhe'}},
'44': {'alarm': false, 'language': {'ger': 'Unerwartete Schnitthöhenverstellung/Problem Antrieb Schnitthöhe'}},
'45': {'alarm': false, 'language': {'ger': 'Unerwartete Schnitthöhenverstellung/Problem Antrieb Schnitthöhe'}},
'46': {'alarm': false, 'language': {'ger': 'Begrenzter Schnitthöhenbereich'}},
'47': {'alarm': false, 'language': {'ger': 'Unerwartete Schnitthöhenverstellung/Problem Antrieb Schnitthöhe'}},
'49': {'alarm': false, 'language': {'ger': 'unknown code 49'}},
'70': {'alarm': false, 'language': {'ger': 'Mäher/Klingen reinigen'}},
'71': {'alarm': true, 'language': {'ger': 'Mäher angehoben'}} // 430 oder 450?
}
};
//!P! abhängig vom Typ zuweisen
let ERROR_CODES = ERROR_CODES_MT['320'];
adapter.on('unload', function (callback) {
try {
husqApi.logout();
if(mScheduleStatus !== null) clearInterval(mScheduleStatus); //.cancel;
if(mScheduleDailyAccumulation !== null) husqSchedule.cancelJob(mScheduleDailyAccumulation);
//!P!if (adapter.setState) adapter.setState('info.connection', false, true);
if (adapter.setState) adapter.setState(idnMowerConnected, false, true);
adapter.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
});
// is called if a subscribed object changes
adapter.on('objectChange', function (id, obj) {
// Warning, obj can be null if it was deleted
adapter.log.info("objectChange " + id + " " + JSON.stringify(obj));
});
/**
* Function to create a state and set its value
* only if it hasn't been set to this value before
* from 'node_modules/iobroker.unifi/main.js'
*/
function createState(name, value, desc, _write, _unit) {
if(typeof(desc) === 'undefined')
desc = name;
if(typeof(_write) === 'undefined')
_write = false;
if(typeof(_write) !== 'boolean')
_write = false;
if(Array.isArray(value))
value = value.toString();
if(typeof(_unit) === 'undefined') {
adapter.setObjectNotExists(name, {
type: 'state',
common: {
name: name,
desc: desc,
type: typeof(value),
read: true,
write: _write
},
native: {id: name}
}, function(err, obj) {
if (!err && obj) {
if(typeof(value) !== 'undefined') {
adapter.setState(name, {
val: value,
ack: true
});
}
}
});
} else {
adapter.setObjectNotExists(name, {
type: 'state',
common: {
name: name,
desc: desc,
type: typeof(value),
read: true,
write: _write,
unit: _unit
},
native: {id: name}
}, function(err, obj) {
if (!err && obj) {
if(typeof(value) !== 'undefined') {
adapter.setState(name, {
val: value,
ack: true
});
}
}
});
}
} // createState()
function createChannels(adapter) {
return new Promise((resolve, reject) => {
const fctName = 'createChannels';
adapter.log.debug(fctName + ' started');
adapter.setObjectNotExists('info', {
type: 'channel',
role: 'info',
common: {
name: 'information',
},
native: {}
}, function(err) {
if (err) adapter.log.error('Cannot write object: ' + err);
reject(err);
});
adapter.setObjectNotExists('mower', {
type: 'channel',
role: 'info',
common: {
name: 'mower',
},
native: {}
}, function(err) {
if (err) adapter.log.error('Cannot write object: ' + err);
});
adapter.setObjectNotExists('mower.homeLocation', {
type: 'channel',
role: 'info',
common: {
name: 'mower.homeLocation',
},
native: {}
}, function(err) {
if (err) adapter.log.error('Cannot write object: ' + err);
});
adapter.setObjectNotExists('mower.lastLocation', {
type: 'channel',
role: 'info',
common: {
name: 'mower.lastLocation',
},
native: {}
}, function(err) {
if (err) adapter.log.error('Cannot write object: ' + err);
});
adapter.setObjectNotExists('mower.statistics', {
type: 'channel',
role: 'info',
common: {
name: 'mower.statistics',
},
native: {}
}, function(err) {
if (err) adapter.log.error('Cannot write object: ' + err);
});
adapter.log.debug(fctName + ' finished');
const successObject = {
msg: 'Success',
data: true,
};
resolve(successObject);
});
} // createChannels()
function createDPs(adapter) {
const fctName = 'createDPs';
const saveRawData = adapter.config.saveRawData;
adapter.log.debug(fctName + ' started');
createState(idnMowerConnected, false);
createState(idnMowerFirmware, '');
createState(idnMowerNickname, '');
createState(idnMowerID, '');
createState(idnMowerModel, '');
createState(idnMowersIndex, -1);
if(saveRawData) { createState(idnMowersJson, []); }
createState(idnHomeLocationName, '', idnHomeLocationName, true);
createState(idnHomeLocationLongitude, 0, idnHomeLocationLongitude, true);
createState(idnHomeLocationLatitude, 0, idnHomeLocationLatitude, true);
createState(idnHomeLocationLongitudeCP, 0);
createState(idnHomeLocationLatitudeCP, 0);
createState(idnHomeLocationLongitudeOffset, 0, idnHomeLocationLongitudeOffset, true);
createState(idnHomeLocationLatitudeOffset, 0, idnHomeLocationLatitudeOffset, true);
createState(idnHomeLocationCurrentDistance, 0, idnHomeLocationCurrentDistance, false, "m");
createState(idnHomeLocationMaxDistance, 100, idnHomeLocationMaxDistance, true, "m");
createState(idnHomeLocationSensitivityLevel, 3);
createState(idnHomeLocationSensitivityRadius, 1000);
createState(idnLastLocationLatitude, 0);
createState(idnLastLocationLongitude, 0);
createState(idnLastLocationTimestamp, 0);
createState(idnMowingTime, 0, idnMowingTime, false, "min.");
createState(idnMowingTimeDaily, 0, idnMowingTimeDaily, false, "min.");
// check for old state lastStartTime
adapter.getObject('mower.lastStartTime', function (err, oidState) {
if (err || !(oidState)) {
// not exist
createState(idnMowingStartTime, 0);
} else {
adapter.getState('mower.lastStartTime', function (err, stateLST) {
if (!err && stateLST) {
createState(idnMowingStartTime, stateLST.val);
adapter.deleteState('mower.lastStartTime');
} else {
createState(idnMowingStartTime, 0);
}
});
}
});
createState(idnMowingTimeBatteryNew, 0, idnMowingTimeBatteryNew, false, "min.");
createState(idnBatteryChargeCycleDaily, 0);
createState(idnBatteryEfficiencyFactor, 0, idnBatteryEfficiencyFactor, false, "%");
createState(idnChargingStartTime, 0);
createState(idnChargingTimeBatteryCurrent, 0, idnChargingTimeBatteryCurrent, false, "min.");
createState(idnChargingTimeBatteryDaily, 0, idnChargingTimeBatteryDaily, false, "min.");
createState(idnChargingTimeBatteryNew, 0, idnChargingTimeBatteryNew, false, "min.");
createState(idnLastChargingTimeBattery, 0, idnLastChargingTimeBattery, false, "min.");
createState(idnCurrentCoveredDistance, 0, idnCurrentCoveredDistance, false, "m");
createState(idnCoveredDistanceDaily, 0, idnCoveredDistanceDaily, false, "m");
createState(idnLastMowingTime, 0, idnLastMowingTime, false, "min.");
createState(idnLastCoveredDistance, 0, idnLastCoveredDistance, false, "m");
createState(idnLastStationReturnTime, 0, idnLastStationReturnTime, false, "min.");
createState(idnOverallBatteryChargeCycle, 0);
createState(idnOverallMowingTime, 0, idnOverallMowingTime, false, "h");
createState(idnOverallCoveredDistance, 0, idnOverallCoveredDistance, false, "km");
createState(idnAMAction, 0, idnAMAction, true);
createState(idnBatteryPercent, 0, idnBatteryPercent, false, "%");
createState(idnCurrentErrorCode, 0);
createState(idnCurrentErrorMsg, '');
createState(idnCurrentErrorCodeTS, 0);
createState(idnLastAction, 'unkonwn');
createState(idnLastDockingTime, 0);
createState(idnLastErrorCode, 0);
createState(idnLastErrorMsg, '');
createState(idnLastErrorCodeTS, 0);
createState(idnLastHttpStatus, 0);
createState(idnLastLocations, '[]');
createState(idnLastStatus, 'unkonwn');
createState(idnLastStatusTime, 0);
createState(idnLastStatusChangeTime, 0);
createState(idnLastDayLocations, '[]');
createState(idnNextStartSource, '');
createState(idnNextStartTime, 0);
createState(idnNextStartWatching, 0);
createState(idnOperatingMode, 'unkonwn');
createState(idnStopOnRainEnabled, false);
createState(idnStoppedDueToRain, false, idnStoppedDueToRain, true);
createState(idnTimerAfterRainStartAt, 0, idnTimerAfterRainStartAt, true);
createState(idnWaitAfterRain, 0, idnWaitAfterRain, false, "min.");
createState(idnSendMessage, '');
createState(idnScheduleTime, 0, idnScheduleTime, false, "s");
createState(idnWebRequestCountDay, 0);
createState(idnWebRequestCountDay_success, 0);
createState(idnWebRequestCountDay_error, 0);
createState(idnWebRequestCountMonth, 0);
createState(idnWebRequestCountMonth_success, 0);
createState(idnWebRequestCountMonth_error, 0);
//States for testing
if (saveRawData) {
createState(idnRawSend, '', 'object for sending raw messages to the mower');
createState(idnRawResponse, '', 'Display the raw message from the mower');
createState(idnRawResponseGeo, '', 'Display the raw message from the mower locations');
createState(idnRawResponseMowers, '', 'Display the raw message from get mowers');
} else { //delete Teststates
adapter.deleteState(adapter.namespace, 'mower', 'rawSend');
adapter.deleteState(adapter.namespace, 'mower', 'rawResponse');
adapter.deleteState(adapter.namespace, 'mower', 'rawResponse_geo');
adapter.deleteState(adapter.namespace, 'mower', 'rawResponse_mowers');
}
adapter.log.debug(fctName + ' finished');
} // createDPs()
function createDataStructure(adapter) {
const fctName = 'createDataStructure';
adapter.log.debug(fctName + ' started');
createChannels(adapter)
.then(result => {
adapter.log.debug(fctName + ', createChannels() finished; result: ' + JSON.stringify(result));
createDPs(adapter);
})
.catch(err => {
adapter.log.error(fctName + ', createChannels() finished; result: ' + JSON.stringify(err));
});
adapter.log.debug(fctName + ' finished');
} // createDataStructure()
function parseBool(value) {
if (typeof value === "boolean") return value;
if (typeof value === "number") {
return value === 1 ? true : value === 0 ? false : undefined;
}
if (typeof value != "string") return undefined;
return value.toLowerCase() === 'true' ? true : value.toLowerCase() === 'false' ? false : undefined;
} // parseBool()
function precisionRound(number, precision) {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
} // precisionRound()
function checkIfItsRaining() {
const fctName = 'checkIfItsRaining';
adapter.log.debug(fctName + ' started');
if(adapter.config.idRainSensor !== '' && adapter.config.stopOnRainEnabled == true) {
adapter.log.debug(fctName + ', idRainSensor: ' + adapter.config.idRainSensor); // mqtt.0.hm-rpc.0.OEQ0996420.1.STATE
// get current state
adapter.getForeignState(adapter.config.idRainSensor, function (err, idState) {
if (err) {
adapter.log.error(err);
return;
}
if (!idState) {
adapter.log.error(fctName + ', getForeignState; idRainSensor: ' + adapter.config.idRainSensor + '; object for "getForeignState(adapter.config.idRainSensor, ...)" is: ' + JSON.stringify(idState));
return;
}
adapter.log.debug(fctName + ', getForeignState; idRainSensor: ' + adapter.config.idRainSensor + '; idState: ' + JSON.stringify(idState));
// idState: {"val":0,"ack":true,"ts":1596924551829,"q":0,"from":"system.adapter.mqtt.0","user":"system.user.admin","lc":1596220067889}
adapter.getForeignObject(adapter.config.idRainSensor, function (err, oidState) {
if (err) {
adapter.log.error(err);
return;
}
const idStateType = oidState.common.type;
let bRain = false;
adapter.log.debug(fctName + ', getForeignState; adapter.config.rainSensorValue: "' + adapter.config.rainSensorValue + '"; idStateType: ' + idStateType);
switch (idStateType) {
case 'boolean':
bRain = (parseBool(idState.val) === parseBool(adapter.config.rainSensorValue));
break;
case 'number':
if (adapter.config.rainSensorValue == '0' || adapter.config.rainSensorValue == '1') {
// compare equal
bRain = (parseInt(idState.val) === parseInt(adapter.config.rainSensorValue));
} else {
// compare >=
bRain = (parseFloat(idState.val) >= parseFloat(adapter.config.rainSensorValue.replace(',', '.')));
}
break;
default:
bRain = (idState.val === adapter.config.rainSensorValue);
break;
}
if (mbStoppedDueToRain != bRain) {
if(bRain) {
adapter.setState(idnStoppedDueToRain, true, true);
adapter.log.debug(fctName + ', getForeignState; idRainSensor (it`s raining)');
} else {
adapter.setState(idnStoppedDueToRain, false, true);
adapter.log.debug(fctName + ', getForeignState; idRainSensor (no rain)');
}
}
});
});
} // if(adapter.config.idRainSensor !== '' && adapter.config.stopOnRainEnabled == true)
adapter.log.debug(fctName + ' finished');
} // checkIfItsRaining()
function handleMowerOnRain(isRaining) {
const fctName = 'handleMowerOnRain';
let sMsg = '';
adapter.log.debug(fctName + ', isRaining: ' + isRaining + '; mCurrentStatus: ' + mCurrentStatus + '; adapter.config.stopOnRainEnabled: ' + adapter.config.stopOnRainEnabled);
if(typeof isRaining !== 'boolean') {
adapter.log.debug(fctName + ' finished, isRaining has false object type: ' + typeof isRaining);
return;
}
if(adapter.config.stopOnRainEnabled === false) {
adapter.log.debug(fctName + ' finished, stopOnRainEnabled === false');
return;
}
if (isRaining === true) {
// it's raining
adapter.log.debug(fctName + ', it`s raining; mWaitAutoTimer: ' + JSON.stringify(mWaitAutoTimer) + '; mCurrentStatus: ' + mCurrentStatus);
if (mWaitAutoTimer !== null) {
clearTimeout(mWaitAutoTimer);
//!P!mWaitAutoTimer.cancel;
mWaitAutoTimer = null;
adapter.setState(idnNextStartWatching, 0, true);
}
if(mCurrentStatus === 'OK_LEAVING' || mCurrentStatus === 'OK_CUTTING' || mCurrentStatus === 'OK_CUTTING_NOT_AUTO' || mCurrentStatus === 'OK_CHARGING') { // PARKED_PARKED_SELECTED ??
//!P! beim Laden parken möglich? hat das einen Effekt
// mower is working
parkMower();
if (mWaitAfterRainTimer !== null) {
clearTimeout(mWaitAfterRainTimer);
//!P!mWaitAfterRainTimer.cancel;
mWaitAfterRainTimer = null;
adapter.setState(idnTimerAfterRainStartAt, 0, true);
}
sMsg = fctName + ' switched to rain; send mower ' + mobjMower.mower.name + ' command "park"';
adapter.setState(idnSendMessage, JSON.stringify([new Date().getTime(), sMsg, fctName, 'rain sensor', MSG_PRIO.warn]), true);
}
if(mCurrentStatus === 'PARKED_AUTOTIMER' || mCurrentStatus === 'PARKED_TIMER') { //!P! || mCurrentStatus === 'PARKED_PARKED_SELECTED' --> manueller Start zum Fortsetzen notwendig, kein Timer aktiv oder?
// mower internal timer next auto start läuft
if (mNextStartTime <= 0 && mLastStartTime <= 0) { //!P! mLastStartTime is workaround P#03
adapter.log.warn(fctName + ', mCurrentStatus === "' + mCurrentStatus + '" and mNextStartTime == ' + JSON.stringify(mNextStartTime));
} else {
// start time given
if (mNextStartTime <= 0) mNextStartTime = mLastStartTime; //!P! mLastStartTime is workaround P#03
let nTimeDiff = mNextStartTime - new Date().getTime();
adapter.log.debug(fctName + ', mCurrentStatus === "' + mCurrentStatus + '", minutes to next start: ' + (nTimeDiff / 1000 / 60));
//!P!const nNextStartLC = dateAdd(mNextStart, - mTimeZoneOffset, 'hours'); // get local time
//!P!let nextStart2 = nextStart - (1000 * 60 * mTimeZoneOffset) ;
//!P!adapter.log.debug(fctName + '; mCurrentStatus === "PARKED_AUTOTIMER", mWaitAutoTimer' + nextStart + '; nextStart2: ' + nextStart2 + '; current time:' + new Date().getTime());
if ((nTimeDiff / 1000 / 60) <= mWaitAfterRain_min) {
adapter.log.debug(fctName + ', stop autostart from parking while rain');
parkMower();
sMsg = 'mower ' + mobjMower.mower.name + ' stop autostart while rain, send mower command "park"';
adapter.setState(idnSendMessage, JSON.stringify([new Date().getTime(), sMsg, 'mower ' + mobjMower.mower.name + ' stop send', '', MSG_PRIO.warn]), true);
} else {
// Timer starten bis kurz vor Startzeit - mWaitAfterRain_min
mWaitAutoTimer = setTimeout(checkIfItKeepsRaining, mNextStartTime - (mWaitAfterRain_min * 60 * 1000) + 60000); // plant auto start - WaitAfterRain + 60s
//mWaitAutoTimer = setTimeout(startMowerAfterAutoTimerCheck, nextStart - new Date().getTime() + 60000); //plant start + 60s
adapter.setState(idnNextStartWatching, mNextStartTime - (mWaitAfterRain_min * 60 * 1000) + 60000, true);
sMsg = fctName + ' switched to rain; check mower ' + mobjMower.mower.name + ' next autostart on "' + adapter.formatDate(mNextStartTime - (mWaitAfterRain_min * 60 * 1000) + 60000, "JJJJ.MM.TT SS:mm:ss") + '"';
adapter.setState(idnSendMessage, JSON.stringify([new Date().getTime(), sMsg, fctName, 'rain sensor', MSG_PRIO.info]), true);
}
}
}
}
if (isRaining === false) {
if (mWaitAfterRain_min >= 0) {
// rain is over, wait until the grass is "dry"
adapter.log.debug(fctName + ', rain is over; mWaitAfterRainTimer: ' + JSON.stringify(mWaitAfterRainTimer) + '; mCurrentStatus: ' + mCurrentStatus);
if (mWaitAfterRainTimer !== null) {
clearTimeout(mWaitAfterRainTimer);
mWaitAfterRainTimer = null;
adapter.setState(idnTimerAfterRainStartAt, 0, true);
}
let timeout = mWaitAfterRain_min * 60 * 1000; // 10800000
mWaitAfterRainTimer = setTimeout(startMowerAfterAutoTimerCheck, timeout);
adapter.setState(idnTimerAfterRainStartAt, new Date().getTime(), true);
adapter.log.debug(fctName + '; no rain, wait for ' + mWaitAfterRain_min + ' min. for start mower.');
sMsg = fctName + ' switched to no rain; wait ' + mWaitAfterRain_min + ' min. for starting mower ' + mobjMower.mower.name ;
adapter.setState(idnSendMessage, JSON.stringify([new Date().getTime(), sMsg, fctName + ' changed', 'rain sensor', MSG_PRIO.warn]), true);
} else {
adapter.log.debug(fctName + '; no rain and no next start time known.');
}
}
adapter.log.debug(fctName + ' finished');
} // handleMowerOnRain()
function startMower() {
const fctName = 'startMower';
mobjMower.sendCommand(mobjMower.command.start, (err, msg) => {
if (err) {
adapter.log.error(msg);
} else {
adapter.log.debug(fctName + ', mower started');
}
});
} // startMower()
function stoptMower() {
const fctName = 'stoptMower';
mobjMower.sendCommand(mobjMower.command.stop, (err, msg) => {
if (err) {
adapter.log.error(msg);
} else {
adapter.log.debug(fctName + ', mower stopped');
}
});
} // stoptMower()
function parkMower() {
const fctName = 'parkMower';
mobjMower.sendCommand(mobjMower.command.park, (err, msg) => {
if (err) {
adapter.log.error(msg);
} else {
adapter.log.debug(fctName + ', mower parked');
}
});
} // parkMower()
adapter.on('stateChange', function (id, state) {
const fctName = 'subscription stateChange';
let fctNameId = '';
if (state) {
adapter.log.debug(fctName + ', id: ' + id + '; state: ' + JSON.stringify(state)); // ld: husq-automower.0.mower.lastLocation.longitude; state: {"val":11.435046666666667,"ack":false,"ts":1524829008532,"q":0,"from":"system.adapter.husq-automower.0","lc":1524829008532}
let iddp = id.substr(adapter.namespace.length + 1);
if(id !== '' && id === adapter.config.idRainSensor) {
// adapter.config.rainSensorValue - true|1|3.2|?
fctNameId = 'subscription rainsensor change';
checkIfItsRaining();
adapter.log.debug(fctNameId + ' finished');
}
// own IDs
//!P! if (!state.ack) { ?? muss/sollte ack nun true oder false sein???
switch (iddp) {
case idnAMAction:
fctNameId = 'subscription mower.action changed';
if (state.val > 0) {
if (state.val === 1) {
adapter.log.debug(fctNameId + ', start mower');
startMower();
} else if (state.val === 2) {
adapter.log.debug(fctNameId + ', stop mower');
stoptMower();
} else if (state.val === 3) {
adapter.log.debug(fctNameId + ', park mower');
parkMower();
} else if (state.val === 9) {
if(mScheduleTime === 0) {
adapter.log.debug(fctNameId + ', status mower');
updateStatus();
} else {
adapter.log.debug(fctNameId + ', execute status mower impossible, scheduler is running.');
}
} else if (state.val === 77) {
adapter.log.debug(fctNameId + ', toggle rain detected');
adapter.getState(idnStoppedDueToRain, function (err, stateSDR) {
if (!err && stateSDR) {
adapter.setState(idnStoppedDueToRain, parseBool(stateSDR.val), true);
mbStoppedDueToRain = parseBool(!stateSDR.val);
handleMowerOnRain(parseBool(!stateSDR.val)); // but not event trouhg seState !?
}
});
} else if (state.val === 91) {
adapter.log.debug(fctNameId + ', stop status scheduler');
mScheduleTime = 0;
createStatusScheduler();
} else if (state.val === 92) {
adapter.log.debug(fctNameId + ', start status scheduler');
mScheduleTime = mQueryIntervalActive_s;
createStatusScheduler();
} else if (state.val === 95) {
adapter.log.debug(fctNameId + ', pause');
// !P! ??