/
bsb.cpp
554 lines (496 loc) · 14.6 KB
/
bsb.cpp
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
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "bsb.h"
#define RX_PIN 19
//#define DEBUG_LL 1
extern int bus_type;
// Constructor
BSB::BSB(uint8_t rx, uint8_t tx, uint8_t addr, uint8_t d_addr) {
if (rx == 19) {
HwSerial = true;
}
if (HwSerial == true) {
pinMode(22, OUTPUT); // provide voltage
digitalWrite(22, 1);
pinMode(23, OUTPUT); // provide voltage
digitalWrite(23, 1);
pinMode(53, OUTPUT); // provide voltage
digitalWrite(53, 1);
serial_hw = &Serial1;
serial_hw->begin(4800, SERIAL_8O1);
} else {
serial_sw = new BSBSoftwareSerial(rx, tx, true);
serial_sw->begin(4800);
serial_sw->listen();
}
myAddr=addr;
destAddr=d_addr;
}
uint8_t BSB::setBusType(uint8_t bus_type_val, uint16_t addr, uint16_t d_addr) {
bus_type = bus_type_val;
switch (bus_type) {
case 0: len_idx = 3; break;
case 1: len_idx = 1; break;
case 2: len_idx = 8; break;
default: len_idx = 3; break;
}
if (addr<=0xff) {
myAddr = addr & 0xFF;
}
if (d_addr<=0xff) {
destAddr = d_addr & 0xFF;
}
Serial.print(F("My address: "));
Serial.println(myAddr);
Serial.print(F("Destination address: "));
Serial.println(destAddr);
return bus_type;
}
uint8_t BSB::getBusType() {
return bus_type;
}
uint8_t BSB::getBusAddr() {
return myAddr;
}
uint8_t BSB::getBusDest() {
return destAddr;
}
// Dumps a message to Serial
void BSB::print(byte* msg) {
if (bus_type != 2) {
byte len = msg[len_idx];
if (len > 32) return;
byte data = 0;
for (int i=0; i<len+bus_type; i++) { // msg length counts from zero with LPB (bus_type 1) and from 1 with BSB (bus_type 0)
data = msg[i];
if (data < 16) Serial.print("0");
Serial.print(data, HEX);
Serial.print(" ");
}
Serial.println();
}
}
// Receives a message and stores it to buffer
boolean BSB::Monitor(byte* msg) {
unsigned long int ts;
byte read;
byte i=0;
if (serial_available() > 0) {
// get timestamp
ts=millis();
// output
Serial.print(ts);
Serial.print(" ");
while (serial_available() > 0) {
// Read serial data...
read = serial_read();
if (bus_type != 2) {
read = read ^ 0xFF;
}
msg[i] = read;
i++;
// output
if(read<16){
Serial.print("0");
}
Serial.print(read, HEX);
Serial.print(" ");
// if no inout available -> wait
if (serial_available() == 0) {
unsigned long timeout = millis() + 3;// > ((11/4800)*1000); // Interestingly, here the timeout is already set to 3ms... (see GetMessage() below)
while (millis() < timeout) {
delayMicroseconds(15); // ...but unclear to me (FH) why the delay is done in 15us steps when nothing else is done after each iteration...
}
}
// if still no input available telegramm has finished
if (serial_available() == 0) break;
}
Serial.println();
return true;
}
return false;
}
bool BSB::GetMessage(byte* msg) {
byte i=0,timeout;
byte read;
while (serial_available() > 0) {
// Read serial data...
read = serial_read();
if (bus_type != 2) {
read = read ^ 0xFF;
}
#if DEBUG_LL
Serial.println();
if(read<16){
Serial.print("0");
}
Serial.print(read, HEX);
Serial.print(" ");
#endif
// ... until SOF detected (= 0xDC, 0xDE bei BSB bzw. 0x78 bei LPB)
if ((bus_type == 0 && (read == 0xDC || read == 0xDE)) || (bus_type == 1 && read == 0x78) || (bus_type == 2 && (read == 0x17 || read == 0x1D || read == 0x1E))) {
// Restore otherwise dropped SOF indicator
msg[i++] = read;
if (bus_type == 2 && read == 0x17) {
uint8_t PPS_write_enabled = myAddr;
if (PPS_write_enabled == 1) {
return true; // PPS-Bus request byte 0x17 just contains one byte, so return
} else {
len_idx = 9;
}
}
// Delay for more data
if (HwSerial == true) {
delay(3); // I wonder why HardwareSerial needs longer than SoftwareSerial until a character is ready to be processed...
} else {
delay(1); // Or should I wonder why SoftwareSerial is fine with just 1ms?
// At 4800bps 8O1, one byte needs 11 Bit to be transferred. One bit takes 0.2ms transmit time. Thus, 11 bits
// take 2.2ms, and therefore, obviously, a new byte can only appear after 2.2ms.
// The question is if serial.available() reacts differently in SoftwareSerial and HardwareSerial - maybe
// SoftwareSerial reacts as soon as a new bit comes in, and HardwareSerial only notifies once a full byte is ready?
}
// read the rest of the message
while (serial_available() > 0) {
read = serial_read();
if (bus_type != 2) {
read = read ^ 0xFF;
}
msg[i++] = read;
#if DEBUG_LL
if(read<16){
Serial.print("0");
}
Serial.print(read, HEX);
Serial.print(" ");
#endif
// Break if message seems to be completely received (i==msg.length)
if (i > len_idx) {
if (bus_type == 2) {
break;
}
if ( msg[len_idx] > 32 ) // check for maximum message length
break;
if (i >= msg[len_idx]+bus_type)
break;
}
// Delay until we got next byte
if (serial_available() == 0) {
if (HwSerial == true) {
timeout = 200; // again, see above, why does HwSerial take more time to process a character? Here, timeout easily counts down 120 times 15 microseconds for a new character to be ready to process...
} else {
timeout = 30;
}
while ((timeout > 0) && (serial_available() == 0)){
delayMicroseconds(15);
timeout--;
}
}
// Break if next byte signals next message (0x23 ^ 0xFF == 0xDC)
// if((serial->peek() == 0x23)) break;
// DO NOT break because some messages contain a 0xDC
}
// We should have read the message completely. Now check and return
if (bus_type == 2) {
if (i == len_idx+1) {
len_idx = 8;
return true; // TODO: add CRC check before returning true/false
}
} else {
if (i == msg[len_idx]+bus_type) { // LPB msg length is one less than BSB
// Seems to have received all data
if (bus_type == 1) {
if (CRC_LPB(msg, i-1)-msg[i-2]*256-msg[i-1] == 0) return true;
else return false;
} else {
if (CRC(msg, i) == 0) return true;
else return false;
}
} else {
// Length error
return false;
}
}
}
}
// We got no data so:
return false;
}
// Generates CCITT XMODEM CRC from BSB message
uint16_t BSB::CRC (byte* buffer, uint8_t length) {
uint16_t crc = 0, i;
for (i = 0; i < length; i++) {
crc = _crc_xmodem_update(crc, buffer[i]);
}
// Complete message returns 0x00
// Message w/o last 2 bytes (CRC) returns last 2 bytes (CRC)
return crc;
}
// Generates checksum from LPB message
// (255 - (Telegrammlänge ohne PS - 1)) * 256 + Telegrammlänge ohne PS - 1 + Summe aller Telegrammbytes
uint16_t BSB::CRC_LPB (byte* buffer, uint8_t length) {
uint16_t crc = 0;
uint8_t i;
crc = (257-length)*256+length-2;
for (i = 0; i < length-1; i++) {
crc = crc+buffer[i];
}
return crc;
}
// Generates CRC for PPS message
uint8_t BSB::CRC_PPS (byte* buffer, uint8_t length) {
uint8_t crc = 0, i;
int sum = 0;
for (i = 0; i < length; i++) {
sum+=buffer[i];
}
sum = sum & 0xFF;
crc = 0xFF - sum + 1;
return crc;
}
uint16_t BSB::_crc_xmodem_update (uint16_t crc, uint8_t data) {
int i;
crc = crc ^ ((uint16_t)data << 8);
for (i=0; i<8; i++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ 0x1021;
} else {
crc <<= 1;
}
}
return crc;
}
// Low-Level sending of message to bus
inline bool BSB::_send(byte* msg) {
// Nun - Ein Teilnehmer will senden :
byte i;
byte data, len;
if (bus_type != 2) {
len = msg[len_idx];
} else {
len = len_idx;
}
switch (bus_type) {
case 0:
msg[0] = 0xDC;
msg[1] = myAddr | 0x80;
msg[2] = destAddr;
break;
case 1:
msg[0] = 0x78;
msg[2] = destAddr;
msg[3] = myAddr;
break;
}
{
if (bus_type == 0) {
uint16_t crc = CRC (msg, len -2);
msg[len -2] = (crc >> 8);
msg[len -1] = (crc & 0xFF);
}
if (bus_type == 1) {
uint16_t crc = CRC_LPB (msg, len);
msg[len-1] = (crc >> 8);
msg[len] = (crc & 0xFF);
}
if (bus_type == 2) {
uint8_t crc = CRC_PPS (msg, len);
msg[len] = crc;
}
}
#if DEBUG_LL
print(msg);
#endif
/*
Er wartet 11/4800 Sek ab (statt 10, Hinweis von miwi), lauscht und schaut ob der Bus in dieser Zeit von jemand anderem benutzt wird. Sprich ob der Bus in dieser Zeit mal
auf 0 runtergezogen wurde. Wenn ja - mit den warten neu anfangen.
*/
unsigned long timeoutabort = 1000; // one second timeout
unsigned long start_timer = millis();
retry:
// Select a random wait time between 60 and 79 ms
unsigned long waitfree = random(1,60) + 25; // range 26 .. 85 ms
// unsigned long waitfree = random(1,20) + 59; // range 60 .. 79 ms
{ // block begins
if(millis()-start_timer > timeoutabort){ // one second has elapsed
return false;
}
if (bus_type != 2) {
// Wait 59 ms plus a random time
unsigned long timeout = millis();
// unsigned long timeout = millis() + 3;//((1/480)*1000);
while (millis()-timeout < waitfree) {
if ((HwSerial == true && digitalRead(RX_PIN) == 0) || (HwSerial == false && serial_sw->rx_pin_read())) // Test RX pin
{
goto retry;
} // endif
} // endwhile
}
} // block ends
//Serial.println("bus free");
/*
Wenn nicht wird das erste Bit gesendet. ( Startbit )
Jedes gesendete Bit wird ( wegen Bus ) ja sofort auf der Empfangsleitung
wieder ankommen. Man schaut nach, ob das gesendete Bit mit dem
empfangenen Bit übereinstimmt.
Wenn ich eine "0" sende - also den Bus auf High lasse, dann will ich
sehen, dass der Bus weiterhin auf High ist. Sollte ein anderer
Teilnehmer in dieser Zeit eine "1" senden - also den Bus herunterziehen,
dann höre ich sofort auf mit dem Senden und fange oben wieder an.
Danach folgen nach gleichem Muster die folgenden Bits, Bit 7..0, Parity
und Stop Bit.
*/
/*
FH 27.12.2018: Wer auch immer das obige geschrieben hat, es macht bezogen auf
den nachfolgenden Code keinen Sinn:
1. Es wird hier nicht bitweise gesendet, sondern ein ganzes Byte an
BSBSoftwareSerial::write übergeben. Dort wird dann unabhängig davon, ob der
Bus frei ist oder nicht, dieses komplette Byte inkl. Start-, Stop- und Parity-
Bits gesendet.
2. BSBSoftwareSerial::write gibt immer 1 zurück, außer wenn _tx_delay == 0 ist.
Diese Variable wird aber nur einmalig bei Aufruf von BSBSoftwareSerial::begin
gesetzt und wäre nur in seltenen Ausnahmefällen == 0.
So wie es jetzt scheint, findet die Kollisionsprüfung beim Senden nicht statt.
*/
if (HwSerial == false) {
cli();
}
byte loop_len = len;
if (bus_type != 2) {
loop_len = len + bus_type - 1; // same msg length difference as above
}
for (i=0; i <= loop_len; i++) {
data = msg[i];
if (bus_type != 2) {
data = data ^ 0xFF;
}
if (HwSerial == true) {
serial_hw->write(data);
} else {
serial_sw->write(data);
}
if (HwSerial == true) {
serial_hw->flush();
serial_read(); // Read (and discard) the byte that was just sent so that it isn't processed as an incoming message
}
if ((HwSerial == true && digitalRead(RX_PIN) == 0) || (HwSerial == false && serial_sw->rx_pin_read())) { // Test RX pin
// Collision
if (HwSerial == false) {
sei();
}
goto retry;
}
}
if (HwSerial == true) {
serial_hw->flush();
} else {
sei();
}
return true;
}
bool BSB::Send(uint8_t type, uint32_t cmd, byte* rx_msg, byte* tx_msg, byte* param, byte param_len, bool wait_for_reply) {
byte i;
if (bus_type == 2) {
return _send(tx_msg);
}
if (HwSerial == true) {
while(serial_available()) {
serial_read();
}
}
// first two bytes are swapped
byte A2 = (cmd & 0xff000000) >> 24;
byte A1 = (cmd & 0x00ff0000) >> 16;
byte A3 = (cmd & 0x0000ff00) >> 8;
byte A4 = (cmd & 0x000000ff);
if (bus_type == 1) {
tx_msg[1] = param_len + 14;
tx_msg[4] = 0xC0; // some kind of sending/receiving flag?
tx_msg[5] = 0x02; // yet unknown
tx_msg[6] = 0x00; // yet unknown
tx_msg[7] = 0x14; // yet unknown
tx_msg[8] = type;
// Adress
tx_msg[9] = A1;
tx_msg[10] = A2;
tx_msg[11] = A3;
tx_msg[12] = A4;
} else {
tx_msg[3] = param_len + 11;
tx_msg[4] = type;
// Adress
tx_msg[5] = A1;
tx_msg[6] = A2;
tx_msg[7] = A3;
tx_msg[8] = A4;
}
// Value
for (i=0; i < param_len; i++) {
if (bus_type == 1) {
tx_msg[13+i] = param[i];
} else {
tx_msg[9+i] = param[i];
}
}
if(!_send(tx_msg)) return false;
if(!wait_for_reply) return true;
i=15;
unsigned long timeout = millis() + 3000;
while ((i > 0) && (millis() < timeout)) {
if (GetMessage(rx_msg)) {
#if DEBUG_LL
Serial.print(F("Duration until answer received: "));
Serial.println(3000-(timeout-millis()));
#endif
i--;
if (bus_type == 1) {
/* Activate for LPB systems with truncated error messages (no commandID in return telegram)
if (rx_msg[2] == myAddr && rx_msg[8]==0x08) { // TYPE_ERR
return false;
}
*/
if (rx_msg[2] == myAddr && rx_msg[9] == A2 && rx_msg[10] == A1 && rx_msg[11] == A3 && rx_msg[12] == A4) {
return true;
} else {
#if DEBUG_LL
Serial.println(F("Message received, but not for us:"));
print(rx_msg);
#endif
}
} else {
if ((rx_msg[2] == myAddr) && (rx_msg[5] == A2) && (rx_msg[6] == A1) && (rx_msg[7] == A3) && (rx_msg[8] == A4)) {
return true;
} else {
#if DEBUG_LL
Serial.println(F("Message received, but not for us:"));
print(rx_msg);
#endif
}
}
}
else {
delayMicroseconds(205);
}
}
#if DEBUG_LL
Serial.println(F("No answer for this send telegram:"));
#endif
print(tx_msg);
return false;
}
int BSB::serial_available() {
if (HwSerial == true) {
return serial_hw->available();
} else {
return serial_sw->available();
}
}
int BSB::serial_read() {
if (HwSerial == true) {
return serial_hw->read();
} else {
return serial_sw->read();
}
}