forked from benkuper/FlowtoysConnectBridge
-
Notifications
You must be signed in to change notification settings - Fork 2
/
StreamManager.h
101 lines (84 loc) · 2.21 KB
/
StreamManager.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
#define STREAM_MAX_COUNT 100
#define STREAM_MAX_PACKET_SIZE STREAM_MAX_COUNT*3
class StreamManager
{
public:
StreamManager() : byteIndex(0),
hasOverflowed(false),
isInit(false)
{}
~StreamManager() { stop(); }
WiFiUDP udp;
bool isInit;
//tempo
const int receiveRate = 100; //receive at 20fps max
long lastReceiveTime;
CRGB leds[STREAM_MAX_COUNT];
uint8_t streamBuffer[STREAM_MAX_PACKET_SIZE];
int byteIndex;
bool hasOverflowed;
void init()
{
start();
isInit = true;
}
bool update()
{
if(!isInit) return false;
long curTime = millis();
if (curTime > lastReceiveTime + (1000 / receiveRate))
{
lastReceiveTime = curTime;
return receiveUDP();
}
return false;
}
bool receiveUDP()
{
while (int packetSize = udp.parsePacket())
{
//DBG("Receiving !");
int numRead = udp.read(streamBuffer, STREAM_MAX_PACKET_SIZE);
if(numRead == 0) return false;
bool isFinal = streamBuffer[numRead - 1] == 255;
if(isFinal)
{
if(hasOverflowed) //if had overflowed, discard current packet and reset for next one
{
DBG("Discard overflowed packet, reset for next one");
byteIndex = 0;
hasOverflowed = false;
return false;
}
numRead--;
}
if(byteIndex + numRead > STREAM_MAX_PACKET_SIZE)
{
DBG("Stream OVERFLOW, end index would reach " +String(byteIndex+numRead));
hasOverflowed = true;
}else
{
//DBG(" > Copying at "+String(byteIndex));
memcpy((uint8_t *)leds + byteIndex, streamBuffer, numRead);
}
byteIndex += numRead;
if (isFinal)
{
byteIndex = 0;
// DBG("Received final");
return true;
}
}
return false;
}
void start()
{
udp.begin(8888);
udp.flush();
}
void stop()
{
udp.flush();
udp.stop();
}
};