forked from pedrocastelani/SoftIBus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSoftIBus.cpp
More file actions
102 lines (93 loc) · 1.95 KB
/
SoftIBus.cpp
File metadata and controls
102 lines (93 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <Arduino.h>
#include "SoftIBus.h"
#include "SoftwareSerial.h"
SIBus IBus;
void SIBus::begin(SoftwareSerial& serial)
{
begin((Stream&)serial);
}
void SIBus::begin(Stream& stream)
{
this->stream = &stream;
this->state = DISCARD;
this->last = millis();
this->ptr = 0;
this->len = 0;
this->chksum = 0;
this->lchksum = 0;
}
void SIBus::loop(void)
{
while (stream->available() > 0)
{
uint32_t now = millis();
if (now - last >= PROTOCOL_TIMEGAP)
{
state = GET_LENGTH;
}
last = now;
uint8_t v = stream->read();
switch (state)
{
case GET_LENGTH:
if (v <= PROTOCOL_LENGTH)
{
ptr = 0;
len = v - PROTOCOL_OVERHEAD;
chksum = 0xFFFF - v;
state = GET_DATA;
}
else
{
state = DISCARD;
}
break;
case GET_DATA:
buffer[ptr++] = v;
chksum -= v;
if (ptr == len)
{
state = GET_CHKSUML;
}
break;
case GET_CHKSUML:
lchksum = v;
state = GET_CHKSUMH;
break;
case GET_CHKSUMH:
// Validate checksum
if (chksum == static_cast<uint16_t>(v << 8) + lchksum) // было if (chksum == (v << 8) + lchksum)
{
// Execute command - we only know command 0x40
switch (buffer[0])
{
case PROTOCOL_COMMAND40:
// Valid - extract channel data
for (uint8_t i = 1; i < PROTOCOL_CHANNELS * 2 + 1; i += 2)
{
channel[i / 2] = buffer[i] | (buffer[i + 1] << 8);
}
break;
default:
break;
}
}
state = DISCARD;
break;
case DISCARD:
default:
break;
}
}
}
uint16_t SIBus::readChannel(uint8_t channelNr)
{
if (channelNr < PROTOCOL_CHANNELS)
{
return channel[channelNr];
}
else
{
return 0;
}
}