forked from Zefau/ioBroker.roomba
-
Notifications
You must be signed in to change notification settings - Fork 4
/
roomba.js
943 lines (798 loc) · 25.2 KB
/
roomba.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
'use strict';
const adapterName = require('./io-package.json').common.name;
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
let _fs = require('fs');
let _dgram = require('dgram');
let _tls = require('tls');
let _http = require('http');
let _request = require('request');
let _dorita980 = require('@karlvr/dorita980');
let _canvas;
/*
* internal libraries
*/
const Library = require(__dirname + '/lib/library.js');
const _NODES = require(__dirname + '/_NODES.js');
/*
* variables initiation
*/
let Image, Canvas, createCanvas;
let adapter;
let library;
//let encryptor = new Encryption(adapter);
let closed, unloaded;
let refreshCycle;
let _installed = false;
let _updating = false;
let robot, connected, mission, previous, icons, pathColor;
let started, endLoop;
let canvas, canvasTmp, map, mapTmp, image, img;
let mapSize = { width: 200, height: 200 };
let nPos = { x: 0, y: 0 };
let mapCenter = {h: Math.round(mapSize.width/2), v: Math.round(mapSize.height/2)};
let offset = 10;
let listeners = {};
let actions = ['start', 'stop', 'pause', 'resume', 'dock']; // states that trigger actions
let additionalListeners = ['_runCommand']; // additional states that trigger actions
const nodeConnected = {'node': 'states._connected', 'description': 'Connection state'};
/*
* ADAPTER
*
*/
function startAdapter(options)
{
options = options || {};
adapter = new utils.Adapter({ ...options, name: adapterName });
/*
* ADAPTER READY
*
*/
adapter.on('ready', function()
{
unloaded = false;
library = new Library(adapter, { updatesInLog: adapter.config.debug || false });
// Check Node.js Version
let version = parseInt(process.version.substr(1, process.version.indexOf('.')-1));
if (version <= 6) {
return library.terminate('This Adapter is not compatible with your Node.js Version ' + process.version + ' (must be >= Node.js v7).', true);
}
// check for canvas
try {
_canvas = require('canvas');
_installed = true;
Canvas = _canvas.Canvas;
Image = _canvas.Image;
createCanvas = _canvas.createCanvas;
}
catch(e) {
adapter.log.warn('Canvas not installed! Thus, no map drawings are possible. Please see installation instructions on Github (https://github.com/iobroker-community-adapters/ioBroker.roomba#installation).');
adapter.log.debug(e.message);
}
// check if settings are set
if (!adapter.config.username || !adapter.config.password || !adapter.config.ip) {
return library.terminate('Username, password and / or ip address missing!');
}
// connect to Robot
library.set(Library.CONNECTION, true);
roomba();
});
/*
* ADAPTER UNLOAD
*
*/
adapter.on('unload', function(callback)
{
try
{
adapter.log.info('Adapter stopped und unloaded.');
unloaded = true;
clearTimeout(refreshCycle);
disconnect();
callback();
}
catch(e)
{
callback();
}
});
/*
* STATE CHANGE
*
*/
adapter.on('stateChange', function(node, state)
{
adapter.log.debug('State of ' + node + ' has changed ' + JSON.stringify(state) + '.');
let action = node.substr(node.lastIndexOf('.')+1);
// action on Roomba
if (actions.indexOf(action) > -1 && state.ack !== true)
{
adapter.log.info('Triggered action -' + action + '- on Roomba.');
if (connected)
{
if (action == 'dock') robot.stop();
robot[action]();
}
else
adapter.log.warn('Roomba not online! Action not triggered.');
}
// end mission
else if (action == '_endMission' && state.ack !== true)
{
adapter.log.info('Triggered to end the current mission.');
if (mission != null)
endMission(mission);
else
adapter.log.warn('Could not save mission.');
}
// run command
else if (action == '_runCommand' && state.ack !== true)
{
// send command directly to the robot
if (state.val)
{
robot.publish('cmd', state.val, () => {
adapter.log.info('Ran command ' + state.val + '!');
});
}
}
// set schedule
else if ((action == 'cycle' || action == 'hours' || action == 'minutes') && state.ack !== true)
{
library.setDeviceState(node.replace(adapter.name + '.' + adapter.instance + '.', ''), state.val);
let week = {
'cycle': library.getDeviceState('missions.schedule.cycle').split(','),
'h': library.getDeviceState('missions.schedule.hours').split(',').map(h => parseInt(h)),
'm': library.getDeviceState('missions.schedule.minutes').split(',').map(m => parseInt(m))
};
adapter.log.warn(JSON.stringify(week));
robot.setWeek(week)
.then(res => adapter.log.info('Set Roomba cleaning schedule (to ' + JSON.stringify(week) + ').'))
.catch(err => adapter.log.warn(err.message));
}
});
/*
* HANDLE MESSAGES
*
*/
adapter.on('message', function(msg)
{
adapter.log.debug('Message: ' + JSON.stringify(msg));
switch(msg.command)
{
case 'command':
// https://github.com/koalazak/dorita980/issues/39
let command = msg.message.command;
adapter.log.debug('Sent command: ' + command + '!)');
robot.publish('cmd', JSON.stringify({command: command, time: Date.now() / 1000 | 0, initiator: 'ioBroker.roomba'}), function(err, res)
{
if (err)
adapter.log.warn(JSON.stringify(err));
else
adapter.log.debug(JSON.stringify(res));
});
break;
case 'getStates':
let states = Array.isArray(msg.message.states) ? msg.message.states : [];
states.forEach(function(state)
{
adapter.getState(state, function(err, res)
{
library.msg(msg.from, msg.command, err || !res ? {result: false, error: err.message} : {result: true, state: res}, msg.callback);
});
});
break;
case 'getIp':
_dorita980.getRobotIP(function(err, ip)
{
adapter.log.debug('Retrieved IP address: ' + ip);
library.msg(msg.from, msg.command, err ? {result: false, error: err.message} : {result: true, data: {ip: ip}}, msg.callback);
});
break;
case 'getRobotData':
getRobotData(function(res)
{
adapter.log.debug('Retrieved robot data: ' + JSON.stringify(res));
library.msg(msg.from, msg.command, res, msg.callback);
}, msg.message !== null ? msg.message.ip : undefined);
break;
case 'getPassword':
msg.message.encryption = msg.message.encryption === undefined ? true : msg.message.encryption;
getPassword(msg.message.ip, function(res)
{
adapter.log.debug(res.result === true ? 'Successfully retrieved password.' : 'Failed retrieving password.');
//if (msg.message.encryption && res.result === true) res.data.password = encryptor.encrypt(adapter.config.encryptionKey, res.data.password);
library.msg(msg.from, msg.command, res, msg.callback);
});
break;
}
});
return adapter;
};
/**
*
*
*/
function roomba()
{
// connect to Roomba
robot = connect(adapter.config.username, adapter.config.password, adapter.config.ip); // connect(adapter.config.username, decrypted, adapter.config.ip);
if (!robot)
return library.terminate('Could not connect to Roomba!');
/*
* ROBOT CONNECT
*/
robot.on('connect', function()
{
adapter.log.info('Roomba online. Connection established.');
closed = false;
connected = true;
library.set(nodeConnected, connected);
library.set(Library.CONNECTION, connected);
});
/*
* ROBOT STATE UPDATE
*/
setTimeout(() =>
{
robot.on('state', preferences => updPreferences(preferences));
}, 5*1000); // wait a bit initially, so most data is available
/*
* ROBOT ERROR
*/
robot.on('error', function(err)
{
adapter.log.error('An error occured and the adapter will be stopped! See debug for more details!');
adapter.log.debug(err.message);
adapter.log.debug(err.stack);
disconnect();
});
/*
* ROBOT CLOSE
*/
robot.on('close', function(res)
{
if (closed) return;
closed = true;
adapter.log.info('Roomba Connection closed.');
if (res && (res.code == 'ECONNREFUSED' || res.errno == 'ECONNREFUSED'))
adapter.log.warn('Connection to Roomba refused. Please close all other connections to the Roomba, e.g. Smartphone Apps!');
else if (res && (res.code == 'EPROTO' || res.errno == 'EPROTO'))
adapter.log.warn('Secure Connection to Roomba failed!');
else if (res && (res.code == 'EPIPE' || res.errno == 'EPIPE'))
;//adapter.log.warn('Secure Connection to Roomba failed!');
else
adapter.log.warn('Unknown error! Please see debug log for details.');
adapter.log.debug(JSON.stringify(res));
disconnect();
});
/*
* ROBOT OFFLINE
*/
robot.on('offline', function(res)
{
adapter.log.warn('Connection lost! Roomba offline.');
disconnect();
});
/*
* ROBOT MISSION
*/
mission = null;
endLoop = 0;
pathColor = adapter.config.pathColor || '#f00';
if (_installed)
{
icons = {roomba: getImage(__dirname + '/img/roomba.png'), home: getImage(__dirname + '/img/home.png')};
offset = icons.roomba.width;
adapter.getState('missions.current._data', function(err, state)
{
// restore last session
if (state !== null && state.val !== '')
{
mission = JSON.parse(state.val);
adapter.log.info('Restored last mission (#' + mission.id + ').');
adapter.log.debug('Restored mission: ' + state.val);
mission.restored = true;
}
// robot mission
robot.on('mission', function(res)
{
if (adapter.config.debug)
adapter.log.debug('DEBUG MISSION DATA: ' + JSON.stringify(res));
// interrupt if no position is given
if (res.pose === null || res.pose === undefined) return;
res.cleanMissionStatus.phase = getCleaningPhase(res.cleanMissionStatus.phase);
// map mission
if (['stop', 'charge', 'stuck'].indexOf(res.cleanMissionStatus.phase) === -1)
mapMission(res);
// end mission after a while, if 'hmPostMsn' was not received
else if (mission !== null && mission.time !== undefined && mission.time.ended === undefined && endLoop <= 1000)
endLoop++;
else if (mission !== null && mission.time !== undefined && mission.time.ended === undefined && endLoop > 1000)
{
endMission(mission);
endLoop = 0;
}
});
});
}
}
/**
* Translate current cleaning process.
*
* @param {string} process Current process as received from robot
* @return {string} Translation
*
*/
function getCleaningPhase(process)
{
switch(process)
{
case 'hmUsrDock': return 'docking';
case 'hmPostMsn': return 'finished';
default: return process;
}
}
/**
* Get password.
*
* @param {string} ip
* @param {function} callback
* @return {object} result
*
*/
function getPassword(ip, callback)
{
// connect
let client = _tls.connect(8883, ip, { rejectUnauthorized: false, ciphers: 'AES128-SHA256' });
client.once('secureConnect', function()
{
adapter.log.debug("Connected to Roomba!");
client.write(new Buffer('f005efcc3b2900', 'hex'));
});
// error
client.on('error', function(err)
{
callback({result: false, error: 'Connection failed!'});
});
// extract password
try
{
let sliceFrom = 13;
client.on('data', function(data)
{
if (data.length === 2)
{
sliceFrom = 9;
return;
}
if (data.length <= 7)
callback({result: false, error: 'Failed getting password! MAKE SURE TO PRESS AND HOLD --HOME-- BUTTON 2 SECONDS (not the clean button)!'});
else
{
adapter.log.debug('Extracted password.');
callback({result: true, data: {password: new Buffer(data).slice(sliceFrom).toString()}});
}
client.end();
});
client.setEncoding('utf-8');
}
catch(err)
{
adapter.log.debug('ERROR: ' + err.message);
callback({result: false, error: 'Could not retrieve password from Roomba! MAKE SURE TO PRESS AND HOLD --HOME-- BUTTON 2 SECONDS (not the clean button)!'});
}
}
/**
* Get user.
*
* @param {function} callback
* @param {string} ip (optional) IP address (otherwise broadcast will be tried)
* @return {object} result
*
*/
function getRobotData(callback, ip)
{
const server = _dgram.createSocket('udp4');
server.bind(5678, function()
{
const message = new Buffer('irobotmcs');
if (ip === undefined)
{
server.setBroadcast(true);
server.send(message, 0, message.length, 5678, '255.255.255.255');
}
else
server.send(message, 0, message.length, 5678, ip);
});
server.on('error', function(err)
{
server.close();
callback({result: false, error: err});
});
server.on('message', function(msg)
{
try
{
let parsedMsg = JSON.parse(msg);
if (parsedMsg.hostname && parsedMsg.ip && parsedMsg.hostname.split('-')[0] === 'Roomba')
{
server.close();
parsedMsg.user = parsedMsg.hostname.split('-')[1];
callback({result: true, data: parsedMsg});
}
}
catch(err) {}
});
}
/**
* Connect to Roomba.
*
*/
function connect(user, password, ip)
{
adapter.log.info('Connecting to Roomba (' + ip + ')..');
try
{
return new _dorita980.Local(user, password, ip);
}
catch(err)
{
adapter.log.error('Could not connect to Roomba! See debug for more details.');
adapter.log.debug(err.message); // this will not be trigged due to an issue in dorita980 library (see https://github.com/koalazak/dorita980/issues/75 )
return false;
}
}
/**
* Update preferences.
*
* @param {object} preferences Received preferences from robot
* @return {boolean} Indication whether preferences have been updated
*
*/
function updPreferences(preferences)
{
if (_updating)
return false;
adapter.log.silly('Retrieved preferences: ' + JSON.stringify(preferences));
_updating = true;
// save raw preferences
library.set({'node': 'device._rawData', 'description': 'Raw preferences data as json', 'role': 'json'}, JSON.stringify(preferences));
// update states
let tmp, preference, index;
_NODES.forEach(node =>
{
try
{
// action
if (node.action !== undefined && listeners[node.node] === undefined)
{
adapter.log.debug('Subscribed to states ' + node.node + '.');
library.set(node, false);
adapter.subscribeStates(node.node); // attach state listener
listeners[node.node] = node;
}
// preference
else if (node.preference !== undefined)
{
tmp = Object.assign({}, preferences);
preference = node.preference;
// go through preferences
while (preference.indexOf('.') > -1)
{
try
{
index = preference.substr(0, preference.indexOf('.'));
preference = preference.substr(preference.indexOf('.')+1);
tmp = tmp[index];
}
catch(err) {adapter.log.debug(err.message);}
}
// check value
if (tmp === undefined || tmp[preference] === undefined || tmp[preference] === null || tmp[preference] === 'aN.aN.NaN aN:aN:aN')
return;
// convert value
if (Array.isArray(tmp[preference])) {
tmp[preference] = tmp[preference].join(',');
}
if (node.kind !== undefined)
{
switch(node.kind.toLowerCase())
{
case "invert":
tmp[preference] = tmp[preference] === false;
break;
case "ip":
tmp[preference] = library.getIP(tmp[preference]);
break;
case "datetime":
if (tmp[preference].toString().indexOf('.') === -1) {
tmp[preference] = library.getDateTime(tmp[preference]*1000);
}
break;
case "timestamp":
if (tmp[preference].toString().indexOf('.') > -1) {
tmp[preference] = Math.round(new Date(tmp[preference]).getTime() / 1000);
}
break;
}
}
// write value
if (node.exception === undefined || tmp[preference] !== node.exception) // only write value if not defined as exceptional
library.set(node, node.type === 'boolean' && Number.isInteger(tmp[preference]) ? (tmp[preference] === 1) : tmp[preference]);
// subscribe to state
if (node.common && node.common.write) {
adapter.subscribeStates(node.node);
}
}
// only state creation
else
{
if (node.node !== undefined)
{
let leafnode = node.node.substr(node.node.lastIndexOf('.')+1);
adapter.log.debug('Leafnode: ' + leafnode + '.');
if ((leafnode) && (additionalListeners.indexOf(leafnode) > -1) && listeners[node.node] === undefined)
{
adapter.log.info('Subscripe Leafnode: ' + leafnode + '.');
adapter.subscribeStates(node.node); // attach state listener
listeners[node.node] = node;
}
adapter.getState(node.node, function(err, res)
{
if ((err !== null || !res) && (node.node !== undefined && node.description !== undefined))
library.set(node, '');
});
}
}
}
catch(err) {
if (node.node)
{
adapter.log.error(node.node + " --> " + JSON.stringify(err.message));
}
else
{
adapter.log.error(JSON.stringify(err.message));
}
}
});
library.set({'node': 'refreshedTimestamp', 'description': 'Timestamp of last update', 'role': 'value', 'type': 'number'}, Math.floor(Date.now()/1000));
library.set({'node': 'refreshedDateTime', 'description': 'DateTime of last update', 'role': 'text'}, library.getDateTime(Date.now()));
// refresh
if (!adapter.config.refresh)
adapter.config.refresh = 60;
else if (adapter.config.refresh > 0 && adapter.config.refresh < 10)
{
adapter.log.warn('Due to performance reasons, the refresh rate can not be set to less than 10 seconds. Using 10 seconds now.');
adapter.config.refresh = 10;
}
if (adapter.config.refresh > 0 && !unloaded)
refreshCycle = setTimeout(function() {_updating = false}, Math.round(parseInt(adapter.config.refresh)*1000));
return true;
};
/**
* Map mission.
*
*/
function mapMission(res)
{
// restore last session
if (mission !== null && mission.id === res.cleanMissionStatus.nMssn && !mission.time.ended && (!canvas || !map))
{
adapter.log.info('Roomba has resumed a previous mission (#' + mission.id + ').');
mission.pos = {
last: {theta: mission.pos.current.theta, x: mission.pos.current.x, y: mission.pos.current.y}
};
// create canvas for map
previous = getImage(mission.map.img);
canvas = previous.canvas;
map = previous.ctx;
map.beginPath();
}
// create new map once mission starts
if (mission === null || mission.id !== res.cleanMissionStatus.nMssn || !canvas)
{
mission = { id: res.cleanMissionStatus.nMssn, restored: false, home: false, time: {}, status: {}, pos: {}, map: {}, path: [] };
adapter.log.info('Roomba has started a new mission (#' + mission.id + ').');
library._setValue('missions.current.id', mission.id);
// started
mission.time.started = Math.floor(Date.now()/1000);
mission.time.startedDateTime = library.getDateTime(mission.time.started*1000);
library._setValue('missions.current.started', mission.time.started);
library._setValue('missions.current.startedDateTime', mission.time.startedDateTime);
// reset ended
library._setValue('missions.current.ended', '');
library._setValue('missions.current.endedDateTime', '');
// create canvas for map
canvas = createCanvas(mapSize.width, mapSize.height);
map = canvas.getContext('2d');
map.beginPath();
}
// last position
else
mission.pos.last = { theta: mission.pos.current.theta, x: mission.pos.current.x, y: mission.pos.current.y };
// add information to payload
mission.status = Object.assign({}, res.cleanMissionStatus, {sqm: parseFloat((res.cleanMissionStatus.sqft / 10.764).toFixed(2))});
mission.pos.current = {theta: 180-res.pose.theta, x: mapCenter.h + res.pose.point.x + nPos.x, y: mapCenter.v - res.pose.point.y + nPos.y};
//
if (!canvas || !map)
{
adapter.log.warn('Error: No map given to draw on!');
adapter.log.debug('Adapter Mission data: ' + JSON.stringify(mission));
adapter.log.debug('Roomba mission data: ' + JSON.stringify(res));
return false;
}
// place home icon
if (mission.pos && mission.pos.last && mission.pos.last.x && !mission.home)
{
map.drawImage(icons.home.canvas, mapCenter.h + mission.pos.current.x - icons.home.width/2, mapCenter.v + mission.pos.current.y - icons.home.height/2, icons.home.width, icons.home.height);
mission.home = true;
}
// draw position on map
try
{
// resize image if robot moves outside
if (mission.pos.current.x < offset || mission.pos.current.y < offset || mission.pos.current.x > mapSize.width-offset || mission.pos.current.y > mapSize.height-offset)
{
let nSize = {width: mapSize.width, height: mapSize.height};
let d = {x: 0, y: 0};
if (mission.pos.current.x > mapSize.width-offset) {nSize.width += 100}
if (mission.pos.current.y > mapSize.height-offset) {nSize.height += 100}
if (mission.pos.current.x < offset) {nSize.width += 100; d.x = 100; nPos.x += 100; mission.pos.last.x += d.x; mission.pos.current.x += d.x}
if (mission.pos.current.y < offset) {nSize.height += 100; d.y = 100; nPos.y += 100; mission.pos.last.y += d.y; mission.pos.current.y += d.y}
// resize map
canvasTmp = createCanvas(nSize.width, nSize.height);
mapTmp = canvasTmp.getContext('2d');
mapTmp.drawImage(canvas, d.x, d.y);
// remap canvas and set new size
canvas = canvasTmp;
map = mapTmp;
mapSize = {width: nSize.width, height: nSize.height};
}
// robot just started
if (mission.pos.last === undefined)
{
map.fillStyle = pathColor;
map.fillRect(mission.pos.current.x, mission.pos.current.y, 1, 1);
}
// robot moving
else
{
map.lineWidth = 2;
map.strokeStyle = pathColor;
map.moveTo(mission.pos.last.x, mission.pos.last.y);
map.lineTo(mission.pos.current.x, mission.pos.current.y);
map.stroke();
}
// copy map
image = createCanvas(canvas.width, canvas.height);
img = image.getContext('2d');
img.drawImage(canvas, 0, 0);
// add robot to copied map
img.drawImage(rotateImage(icons.roomba.canvas, mission.pos.current.theta), mission.pos.current.x - icons.roomba.width/2, mission.pos.current.y - icons.roomba.height/2, icons.roomba.width, icons.roomba.height);
mission.map = {img: image.toDataURL(), size: mapSize};
}
catch(e)
{
adapter.log.warn(e.message);
adapter.log.warn(e.stack);
}
// add to path
if (mission && mission.path)
mission.path.push(mission.pos.current);
// save map and path
library._setValue('missions.current.mapImage', mission.map.img);
library._setValue('missions.current.mapHTML', '<img src="' + mission.map.img + '" /style="width:100%;">');
library._setValue('missions.current.mapSize', JSON.stringify(mission.map.size));
library._setValue('missions.current.path', JSON.stringify(mission.path));
// additional mission status information
mission.time.runtime = Math.floor(Date.now()/1000) - mission.time.started;
library._setValue('missions.current.runtime', mission.time.runtime);
library._setValue('missions.current.sqm', mission.status.sqm);
library._setValue('missions.current.cycle', mission.status.cycle);
library._setValue('missions.current.error', !!mission.status.error);
library._setValue('missions.current.initiator', mission.status.initiator);
library._setValue('missions.current.phase', mission.status.phase);
// save data
library._setValue('missions.current._data', JSON.stringify(Object.assign(mission, {map: {img: canvas != undefined ? canvas.toDataURL() : '', size: mapSize}})));
return true;
}
/**
* Retrieve image data from file.
*
*/
function getImage(path)
{
// read as image
let img = new Image();
img.src = path.indexOf('data:image') > -1 && path.indexOf('base64') > -1 ? path : _fs.readFileSync(path);
// read as canvas
let canvas = createCanvas(img.width, img.height);
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return {
img: img,
canvas: canvas,
ctx: ctx,
width: img.width,
height: img.height
};
}
/**
* Rotate a canvas around its mapCenter.
* @see https://www.mediaevent.de/javascript/canvas-rotate.html
*
*/
function rotateImage(img, radiant)
{
let canvas = createCanvas(img.width, img.height);
let ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, img.width, img.height); // clear the canvas
ctx.translate(img.width/2, img.width/2); // move registration point to the center of the canvas
ctx.rotate(radiant * Math.PI / 180);
ctx.translate(-img.width/2, -img.width/2); // Move registration point back to the top left corner of canvas
ctx.drawImage(img, 0, 0);
return canvas;
}
/**
* Ends and saves a mission.
*
*/
function endMission(mission)
{
let history = [];
// get history
adapter.getState('missions.history', function(err, state)
{
history = state != null && state.val != '' ? JSON.parse(state.val) : history;
// add end time
mission.time.ended = Math.floor(Date.now()/1000);
mission.time.endedDateTime = library.getDateTime(mission.time.ended*1000);
library._setValue('missions.current.endedDateTime', mission.time.endedDateTime);
library._setValue('missions.current.ended', mission.time.ended);
// save data
library._setValue('missions.current._data', JSON.stringify(mission));
// check for duplicates
let duplicate = false;
history.forEach(function(entry, i)
{
if (entry.id == mission.id)
{
adapter.log.info('Mission has already been saved, but will be overwritten.');
history[i] = mission;
duplicate = true;
}
});
if (duplicate === false)
{
delete mission.path;
history.push(mission);
}
// save history
library._setValue('missions.history', JSON.stringify(history.slice(0, 199))); // only keep 200 entries
adapter.log.info('Mission #' + mission.id + ' saved.');
// reset mission
mission = null;
canvas = null;
map = null;
return true;
});
};
/**
* Disconnects a Roomba.
*
*/
function disconnect()
{
connected = false;
library.set(nodeConnected, connected);
}
/*
* COMPACT MODE
* If started as allInOne/compact mode => return function to create instance
*
*/
if (module && module.parent)
module.exports = startAdapter;
else
startAdapter(); // or start the instance directly