-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBelWattmeter.cpp
More file actions
105 lines (100 loc) · 2.49 KB
/
Copy pathBelWattmeter.cpp
File metadata and controls
105 lines (100 loc) · 2.49 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
103
104
105
#include "BelWattmeter.h"
void BelWattmeter::ProcessByte(int dataIndex, uint8_t data)
{
if(dataIndex == 1) this->dataLength = data;
if(dataIndex == 4) this->voltageTmp = data;
if(dataIndex == 5) this->voltageTmp |= data << 8;
if(dataIndex == 6) this->currentTmp = data;
if(dataIndex == 7) this->currentTmp |= data << 8;
if(dataIndex == 8) this->consumptionTmp = data;
if(dataIndex == 9) this->consumptionTmp |= data << 8;
if(dataIndex == 21) this->powerTmp = data;
if(dataIndex == 22) this->powerTmp |= data << 8;
if(dataIndex == 28)
{
crcOk = crc == data;
return;
}
crc += data;
}
void BelWattmeter::Loop()
{
while(Serial2.available())
{
int raw = Serial2.read();
if(raw < 0)
{
continue;
}
byte read = (byte)raw;
switch(state)
{
case WAIT_FOR_START:
if(read == 0xFC)
{
state = IN_FRAME;
crc = 0;
feCount = 0;
dataIndex = 0;
dataLength = 0;
this->voltageTmp = 0;
this->currentTmp = 0;
this->consumptionTmp = 0;
this->powerTmp = 0;
crcOk = false;
}
break;
case IN_FRAME:
if(read == 0xFD)
{
state = ESCAPE_NEXT;
}
else if (read == 0xFE)
{
feCount++;
if(feCount == 2)
{
if(crcOk && voltageTmp < 360 && currentTmp < 1600 && powerTmp < 4000)
{
data.voltage = ((unsigned long)data.voltage * counter + voltageTmp) / (counter + 1);
data.current = ((unsigned long)data.current * counter + currentTmp) / (counter + 1);
data.power = ((unsigned long)data.power * counter + powerTmp) / (counter + 1);
data.consumption = consumptionTmp;
counter++;
}
state = WAIT_FOR_START;
}
}
else
{
if(dataIndex > 1 && (dataIndex > this->dataLength + 1 || this->dataLength != 28))
{
state = WAIT_FOR_START;
break;
}
ProcessByte(dataIndex, read);
feCount = 0;
dataIndex++;
}
break;
case ESCAPE_NEXT:
ProcessByte(dataIndex, read);
state = IN_FRAME;
feCount = 0;
dataIndex++;
break;
}
}
}
BelData BelWattmeter::GetBelData()
{
return data;
}
void BelWattmeter::Reset()
{
data.voltage = 0;
data.current = 0;
data.power = 0;
data.consumption = 0;
counter = 0;
}