forked from pa-pa/AskSinPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiChannelDevice.h
588 lines (539 loc) · 18.2 KB
/
MultiChannelDevice.h
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
//- -----------------------------------------------------------------------------------------------------------------------
// AskSin++
// 2016-10-31 papa Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
//- -----------------------------------------------------------------------------------------------------------------------
#ifndef __MULTICHANNELDEVICE_H__
#define __MULTICHANNELDEVICE_H__
#include <Device.h>
#include <Defines.h>
#include <cm.h>
#include <Led.h>
#include <Activity.h>
#if ARDUINO_ARCH_AVR
#include <avr/wdt.h>
#endif
namespace as {
extern void(* resetFunc) (void);
#define REPLAY_NO 0
#define REPLAY_ACK 1
#define REPLAY_NACK 2
template <class HalType,class ChannelType,int ChannelCount,class List0Type=List0>
class ChannelDevice : public Device<HalType,List0Type> {
List0Type list0;
ChannelType* devchannels[ChannelCount];
uint8_t cfgChannel;
GenericList cfgList;
HMID lastdev; // store last fromID to evaluate a repeated message or a repeated broadcast message
uint8_t lastcnt;
public:
typedef Device<HalType,List0Type> DeviceType;
ChannelDevice (const DeviceInfo& i,uint16_t addr) : DeviceType(i,addr,list0,ChannelCount), list0(addr + this->keystore().size()), cfgChannel(0xff) {}
virtual ~ChannelDevice () {}
void registerChannel(ChannelType& ch,uint8_t num) {
if( num >= 1 && num <= ChannelCount) {
devchannels[num-1] = &ch;
}
}
void layoutChannels () {
uint16_t addr = list0.address() + list0.size();
for( uint8_t i=0; i<this->channels(); ++i ) {
devchannels[i]->setup(this,i+1,addr);
addr += devchannels[i]->size();
}
}
void channels (uint8_t num) {
DeviceType::channels(min(num,(uint8_t)ChannelCount));
}
uint8_t channels () const {
return DeviceType::channels();
}
void dumpSize () {
DPRINT(F("Address Space: "));DDEC(this->keystore().address());DPRINT(F(" - "));DDECLN(getUserStorage().getAddress());
}
// get object to access free EEPROM after device data
UserStorage getUserStorage () {
ChannelType& ch = channel(this->channels());
return UserStorage(ch.address() + ch.size());
}
uint16_t checksum () {
uint16_t crc = 0;
#ifndef NOCRC
// size of keystore data
crc = HalType::crc16(crc,DeviceType::keystore().size());
// add register of list0
for( uint8_t i=0; i<list0.size(); ++i ) {
crc = HalType::crc16(crc,list0.getRegister(i));
}
// add number of channels
for( uint8_t c=1; c<=this->channels(); ++c ) {
ChannelType& ch = channel(c);
// add register list 1
GenericList l = ch.getList1();
for( uint8_t i=0; i<l.getSize(); ++i ) {
crc = HalType::crc16(crc,l.getRegister(i));
}
// add register list 3
l = ch.getList3((uint8_t)0);
for( uint8_t i=0; i<l.getSize(); ++i ) {
crc = HalType::crc16(crc,l.getRegister(i));
}
// add register list 4
l = ch.getList4((uint8_t)0);
for( uint8_t i=0; i<l.getSize(); ++i ) {
crc = HalType::crc16(crc,l.getRegister(i));
}
// add number of peers
crc = HalType::crc16(crc,ch.peers());
}
#endif
return crc;
}
List0Type& getList0 () {
return list0;
}
bool init (HalType& hal) {
layoutChannels();
dumpSize();
// first initialize EEProm if needed
bool first = storage().setup(checksum());
if( first == true ) {
firstinit();
storage().store();
}
this->keystore().init();
this->setHal(hal);
HMID id;
this->getDeviceID(id);
hal.init(id);
hal.config(this->getConfigArea());
return first;
}
void initDone () {
// trigger initial config changed - to allow scan/caching of list data
this->hasConfigChanged(true);
this->configChanged();
for( uint8_t cdx=1; cdx<=channels(); ++cdx ) {
channel(cdx).configChanged();
}
// trigger save of storage
storage().store();
}
void firstinit () {
this->keystore().defaults(); // init aes key infrastructure
list0.defaults();
for( uint8_t i=0; i<this->channels(); ++i ) {
devchannels[i]->firstinit();
}
}
void reset () {
if( getList0().localResetDisable() == false ) {
DPRINTLN(F("RESET"));
storage().reset();
storage().store();
#if ARDUINO_ARCH_AVR
resetFunc();
#elif ARDUINO_ARCH_STM32F1
nvic_sys_reset();
#elif defined (ARDUINO_ARCH_STM32) && defined (STM32L1xx)
NVIC_SystemReset();
#elif ARDUINO_ARCH_ESP32
ESP.restart();
#elif ARDUINO_ARCH_EFM32
delay(250);
NVIC_SystemReset();
#endif
}
}
void bootloader () {
DPRINTLN(F("BOOTLOADER"));
#if ARDUINO_ARCH_AVR
wdt_enable(WDTO_250MS);
while(1);
#endif
}
void startPairing () {
this->sendDeviceInfo();
this->led().set(LedStates::pairing);
this->activity().stayAwake( seconds2ticks(20) ); // 20 seconds
}
ChannelType& channel(uint8_t ch) {
return *devchannels[ch-1];
}
bool pollRadio () {
bool worked = DeviceType::pollRadio();
for( uint8_t i=1; i<=this->channels(); ++i ) {
ChannelType& ch = channel(i);
if( ch.changed() == true ) {
bool ledEnableState = DeviceType::led().enable(); //save current enable state
DeviceType::led().enable(false); //deactivate LED when sending info message (cyclic, sabotage, ...)
this->sendInfoActuatorStatus(this->getMasterID(),this->nextcount(),ch);
DeviceType::led().enable(ledEnableState); //restore enable state
worked = true;
}
}
return worked;
}
bool aesActive () {
if( getList0().aesActive() == true ) {
return true;
}
for( uint8_t i=1; i<=this->channels(); ++i) {
if( channel(i).aesActive() == true ) {
return true;
}
}
return false;
}
bool validSignature(__attribute__((unused)) Message& msg) {
#ifdef USE_AES
if( aesActive() == true ) {
return this->requestSignature(msg);
}
#endif
return true;
}
bool validSignature(__attribute__((unused)) uint8_t ch, __attribute__((unused)) Message& msg) {
#ifdef USE_AES
if( (ch==0 && aesActive()) || (this->hasChannel(ch)==true && channel(ch).aesActive()==true) ) {
return this->requestSignature(msg);
}
#endif
return true;
}
bool process(Message& msg) {
uint8_t answer = REPLAY_NO;
ChannelType* ch = 0;
HMID devid;
this->getDeviceID(devid);
if( msg.to() == devid || this->isBroadcastMsg(msg) ) {
// we got a message - we do not answer before 100ms
this->radio().setSendTimeout(); // use default value from radio
DPRINT(F("-> "));
msg.dump();
// ignore repeated messages and store info if the last message came from same device
uint8_t samefromID = (lastdev == msg.from());
if (samefromID && lastcnt == msg.count()) {
return false;
}
lastdev = msg.from();
lastcnt = msg.count();
//is Device already paired to a master / CCU ?
bool isPaired = HMID::broadcast != this->getMasterID();
//received message is from our paired master / CCU ?
bool msgIsFromMaster = msg.from() == this->getMasterID();
// start processing the message
uint8_t mtype = msg.type();
uint8_t mcomm = msg.command();
uint8_t msubc = msg.subcommand();
if( mtype == AS_MESSAGE_CONFIG ) {
//we are already paired, but the CONFIG message does not come from master / CCU
if( isPaired == true && msgIsFromMaster == false ) {
//DPRINTLN(F("-> message for us, but from wrong master address."));
return false;
}
// PAIR_SERIAL
if( msubc == AS_CONFIG_PAIR_SERIAL && this->isDeviceSerial(msg.data())==true ) {
this->led().set(LedStates::pairing);
this->activity().stayAwake( seconds2ticks(20) ); // 20 seconds
this->sendDeviceInfo(msg.from(),msg.length());
}
// CONFIG_PEER_ADD
else if ( msubc == AS_CONFIG_PEER_ADD ) {
const ConfigPeerAddMsg& pm = msg.configPeerAdd();
bool success = false;
if( this->hasChannel(pm.channel()) == true ) {
if( validSignature(pm.channel(),msg) == true ) {
ch = &channel(pm.channel());
if( pm.peers() == 1 ) {
success = ch->peer(pm.peer1());
}
else {
success = ch->peer(pm.peer1(),pm.peer2());
}
}
}
if( success == true ) {
this->hasConfigChanged(true);
ch->configChanged();
storage().store();
answer = REPLAY_ACK;
}
else {
answer = REPLAY_NACK;
}
}
// CONFIG_PEER_REMOVE
else if ( msubc == AS_CONFIG_PEER_REMOVE ) {
const ConfigPeerRemoveMsg& pm = msg.configPeerRemove();
bool success = false;
if( this->hasChannel(pm.channel()) == true ) {
if( validSignature(pm.channel(),msg) == true ) {
ch = &channel(pm.channel());
success = ch->deletepeer(pm.peer1());
if( pm.peers() == 2 ) {
success &= ch->deletepeer(pm.peer2());
}
}
}
if( success == true ) {
this->hasConfigChanged(true);
ch->configChanged();
storage().store();
answer = REPLAY_ACK;
}
else {
answer = REPLAY_NACK;
}
}
// CONFIG_PEER_LIST_REQ
else if( msubc == AS_CONFIG_PEER_LIST_REQ ) {
const ConfigPeerListReqMsg& pm = msg.configPeerListReq();
if( this->hasChannel(pm.channel()) == true ) {
this->sendInfoPeerList(msg.from(),msg.count(),channel(pm.channel()));
}
}
// CONFIG_PARAM_REQ
else if (msubc == AS_CONFIG_PARAM_REQ ) {
const ConfigParamReqMsg& pm = msg.configParamReq();
GenericList gl = findList(pm.channel(),pm.peer(),pm.list());
if( gl.valid() == true ) {
this->sendInfoParamResponsePairs(msg.from(),msg.count(),gl);
}
else {
answer = REPLAY_NACK;
}
}
// CONFIG_STATUS_REQUEST
else if (msubc == AS_CONFIG_STATUS_REQUEST ) {
// this is an answer to a request - so we need no ack
this->sendInfoActuatorStatus(msg.from(),msg.count(),channel(msg.command()),false);
}
// CONFIG_START
else if( msubc == AS_CONFIG_START ) {
const ConfigStartMsg& pm = msg.configStart();
if( validSignature(pm.channel(),msg) == true ) {
cfgChannel = pm.channel();
cfgList = findList(cfgChannel,pm.peer(),pm.list());
// TODO setup alarm to disable after 2000ms
answer = REPLAY_ACK;
}
else {
answer = REPLAY_NACK;
}
}
// CONFIG_END
else if( msubc == AS_CONFIG_END ) {
this->hasConfigChanged(true);
if( cfgList.address() == list0.address() ) {
this->led().set(LedStates::nothing);
this->configChanged();
}
else {
// signal list update to channel
channel(cfgChannel).configChanged();
}
cfgChannel = 0xff;
storage().store();
// TODO cancel alarm
this->sendAck(msg,Message::WKMEUP);
}
else if( msubc == AS_CONFIG_WRITE_INDEX ) {
const ConfigWriteIndexMsg& pm = msg.configWriteIndex();
if( validSignature(pm.channel(),msg)==true ) {
if( cfgChannel == pm.channel() && cfgList.valid() == true ) {
this->writeList(cfgList,pm.data(),pm.datasize());
}
answer = REPLAY_ACK;
}
else {
answer = REPLAY_NACK;
}
}
else if( msubc == AS_CONFIG_SERIAL_REQ ) {
this->sendSerialInfo(msg.from(),msg.count());
}
else {
answer = REPLAY_NACK;
}
}
else if( mtype == AS_MESSAGE_ACTION ) {
//we are paired to a master / CCU, but the ACTION message does not come from master / CCU
if( isPaired==true && msgIsFromMaster==false ) {
//DPRINTLN(F("-> message for us, but from wrong master address."));
return false;
}
if ( mcomm == AS_ACTION_RESET || mcomm == AS_ACTION_ENTER_BOOTLOADER ) {
if( validSignature(msg) == true ) {
this->sendAck(msg);
if( mcomm == AS_ACTION_ENTER_BOOTLOADER ) {
bootloader();
}
else {
reset();
}
}
}
#ifndef SENSOR_ONLY
else {
const ActionMsg& pm = msg.action();
if( this->hasChannel(pm.channel())==true ) {
ch = &channel(pm.channel());
if( validSignature(pm.channel(),msg)==true ) {
switch( mcomm ) {
case AS_ACTION_INHIBIT_OFF:
ch->inhibit(false);
answer = REPLAY_ACK;
break;
case AS_ACTION_INHIBIT_ON:
ch->inhibit(true);
answer = REPLAY_ACK;
break;
case AS_ACTION_STOP_CHANGE:
ch->stop();
answer = REPLAY_ACK;
break;
case AS_ACTION_SET:
if( ch->inhibit() == false ) {
answer = ch->process(msg.actionSet()) ? REPLAY_ACK : REPLAY_NACK;
}
break;
case AS_ACTION_COMMAND:
if( ch->inhibit() == false ) {
answer = ch->process(msg.actionCommand()) ? REPLAY_ACK : REPLAY_NACK;
}
break;
}
}
}
}
#endif
}
else if( mtype == AS_MESSAGE_HAVE_DATA ) {
DPRINTLN(F("HAVE DATA"));
answer = REPLAY_ACK;
}
#ifndef SENSOR_ONLY
else if (mtype == AS_MESSAGE_SWITCH_EVENT) {
RemoteEventMsg& pm = msg.switchSim().toEventMsg();
//DPRINT(F("X> ")); pm.dump();
for (uint8_t cdx = 1; cdx <= this->channels(); ++cdx) {
ChannelType* c = &channel(cdx);
if (c->inhibit() == false && c->has(pm.peer()) == true) {
c->process(pm);
}
}
answer = REPLAY_ACK;
}
else if (mtype == AS_MESSAGE_REMOTE_EVENT || mtype == AS_MESSAGE_SENSOR_EVENT) {
static uint8_t lastcntr, lastbcst;
uint8_t cntr;
answer = REPLAY_NACK;
const RemoteEventMsg& pm = msg.remoteEvent();
uint8_t processed = 0;
for( uint8_t cdx=1; cdx<=this->channels(); ++cdx ) {
ChannelType* c = &channel(cdx);
if( c->inhibit() == false && c->has(pm.peer()) == true ) {
if( processed > 0 || validSignature(cdx,msg) == true ) {
++processed;
ch = c;
switch( mtype ) {
case AS_MESSAGE_REMOTE_EVENT:
// check if it is a repeated broadcast message addressed now to us
cntr = msg.remoteEvent().counter();
if (lastbcst && samefromID && cntr == lastcntr && !msg.remoteEvent().isLong()) {
//DPRINTLN(F("repeat broadcast"));
}
else {
ch->process(pm);
}
lastcntr = cntr;
lastbcst = msg.isBroadcast();
break;
case AS_MESSAGE_SENSOR_EVENT:
ch->process(msg.sensorEvent());
break;
}
answer = REPLAY_ACK;
}
}
}
if( processed > 1 ) {
// we had more than one channel processed
// clear channel, so we only send an ACK
ch = 0;
}
}
#endif
#ifdef USE_AES
else if (mtype == AS_MESSAGE_KEY_EXCHANGE ) {
if( isPaired==false || msgIsFromMaster==false ) { return false; }
if( validSignature(msg) == true ) {
if( this->keystore().exchange(msg.aesExchange())==true ) answer = REPLAY_ACK;
else answer = REPLAY_NACK;
}
}
#endif
// default - send Nack if answer is requested
else {
answer = REPLAY_NACK;
}
}
else {
#ifndef HIDE_IGNORE_MSG
DPRINT(F("ignore "));
msg.dump();
#endif
return false;
}
// send ack/nack
if( msg.ackRequired() == true && msg.to() == devid ) {
if( answer == REPLAY_ACK ) {
if( ch != 0 ) this->sendAck(msg, *ch);
else this->sendAck(msg);
}
else if( answer == REPLAY_NACK ) {
this->sendNack(msg);
}
}
// we always stay awake after valid communication
this->activity().stayAwake(millis2ticks(500));
return true;
}
GenericList findList(uint8_t ch,const Peer& peer,uint8_t numlist) {
if (numlist == 0) {
return list0;
} else if (this->hasChannel(ch) == true) {
ChannelType& c = channel(ch);
if (numlist == 1) {
return c.getList1();
} else if (c.hasList2() && numlist == 2) {
return c.getList2();
} else if (c.hasList3() && numlist == 3) {
return c.getList3(peer);
} else if (c.hasList4() && numlist == 4) {
return c.getList4(peer);
}
}
return GenericList();
}
void sendPeerEvent (Message& msg,const ChannelType& ch) {
// we send only to peers if there is no config message pending
if( cfgChannel != 0xff ) {
DeviceType::sendPeerEvent(msg,ch);
}
}
};
template <class HalType,class ChannelType,int ChannelCount,class List0Type=List0>
class MultiChannelDevice : public ChannelDevice<HalType,ChannelType,ChannelCount,List0Type> {
ChannelType cdata[ChannelCount];
public:
typedef ChannelDevice<HalType,ChannelType,ChannelCount,List0Type> DeviceType;
MultiChannelDevice (const DeviceInfo& i,uint16_t addr) : ChannelDevice<HalType,ChannelType,ChannelCount,List0Type>(i,addr) {
for( uint8_t i=0; i<ChannelCount; ++i ) {
this->registerChannel(cdata[i], i+1);
}
}
virtual ~MultiChannelDevice () {}
};
}
#endif