~jojo/jojos-hue

ref: 6a5bfbbc145e573e6e6639805684b3dcb5336a98 jojos-hue/client/client.ino -rw-r--r-- 6.8 KiB
6a5bfbbcJoJo custom UDP protocol & offload FastLED to second core on ESP32 a month ago
                                                                                
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
#include <FastLED.h>

#define UNO_WS2812B
// #define ESP32_WS2801
// #define ESP32_WS2813

// vvvvvvv UNIT vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
#if                               defined(UNO_WS2812B)
#define LED_PINS 8
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS 48
#define MAX_MILLIAMPS 2000
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
#define CONN_ETH
#elif                             defined(ESP32_WS2801)
#define LED_PINS G33, G23
#define LED_TYPE WS2801
#define COLOR_ORDER RGB
#define NUM_LEDS 50
#define MAX_MILLIAMPS 3000
#define CONN_WIFI
#elif                             defined(ESP32_WS2813)
#define LED_PINS G33
#define LED_TYPE WS2813
#define COLOR_ORDER GRB
#define NUM_LEDS 60
#define MAX_MILLIAMPS 2000
#define DUALCORE_FASTLED
#define CONN_WIFI
#                                 else
#error No unit defined (e.g. ESP32_WS2801)
#endif
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


// vvvvvvv Connectivity vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// ---------------------------------------------------------
#if                               defined(CONN_ETH)
#include <Ethernet.h>
EthernetUDP udp;
#define NET
#elif                             defined(CONN_WIFI)
#include <WiFi.h>
#include <WiFiUdp.h>
#include "secrets.h"
WiFiUDP udp;
#define NET
#                                 else
// ...
#endif

#ifdef NET
#define SERVER_IP "192.168.0.41"
#define SERVER_PORT 7017
#define LOCAL_PORT 7711
#endif

#define READ_RETRIES 2
#define NUM_BYTES (3*NUM_LEDS)

// ESP32 seems to have a hard time keeping up with the timings of a single-wire LED strip
// like WS2812b or WS2813. This might be a result of using WiFi at the same time, with the
// WiFi code blocking us enough to throw off the timings. A workaround that seems to work
// well is to run FastLED.show() on it's own core, which we can do since ESP32 is
// dualcore.
#ifdef DUALCORE_FASTLED
#define FASTLED_SHOW_CORE 1
static TaskHandle_t showTaskHandle = 0;
static TaskHandle_t userTaskHandle = 0;
void show() {
    if (userTaskHandle == 0) {
        userTaskHandle = xTaskGetCurrentTaskHandle();
        xTaskNotifyGive(showTaskHandle);
        const TickType_t xMaxBlockTime = pdMS_TO_TICKS(200);
        ulTaskNotifyTake(pdTRUE, xMaxBlockTime);
        userTaskHandle = 0;
    }
}
void showTask(void *pvParameters) {
    for (;;) {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        FastLED.show();
        xTaskNotifyGive(userTaskHandle);
    }
}
#else
void show() {
    FastLED.show();
}
#endif


CRGB leds[NUM_LEDS];

void setAll(CRGB c) {
    for (uint16_t i = 0 ; i < NUM_LEDS; i++) {
        leds[i] = c;
    }
}

void setEach(byte* buf) {
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
        leds[i] = CRGB(buf[3*i+0], buf[3*i+1], buf[3*i+2]);
    }
}

void setup() {
    Serial.begin(115200);
    Serial.println("hello!");
#if defined(CONN_ETH)
    Ethernet.init(SS);
    Ethernet.begin(mymac);
    Serial.println("online");
    Serial.print("IP address: ");
    Serial.println(Ethernet.localIP());
    udp.begin(LOCAL_PORT);
#elif defined(CONN_WIFI)
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(300);
        Serial.print(".");
    }
    Serial.print("\nConnected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    // if (MDNS.begin("esp32")) {
    //     Serial.println("MDNS responder started");
    // }
    udp.begin(LOCAL_PORT);
#endif

    FastLED.addLeds<LED_TYPE, LED_PINS, COLOR_ORDER>(leds, NUM_LEDS)
        .setCorrection(TypicalLEDStrip);
    FastLED.setMaxPowerInVoltsAndMilliamps(5, MAX_MILLIAMPS);
#ifdef DUALCORE_FASTLED
    xTaskCreatePinnedToCore(showTask, "showTask", 2048, NULL, 2, &showTaskHandle, FASTLED_SHOW_CORE);
#endif
    CRGB initCols[] = {
        CRGB(255, 0, 0),
        CRGB(0, 255, 0),
        CRGB(0, 0, 255),
        CRGB(255, 255, 255),
        CRGB(0, 0, 0)
    };
    for (uint8_t i = 0; i < sizeof(initCols)/sizeof(CRGB); i++) {
        setAll(initCols[i]);
        show();
        delay(1000);
    }
    Serial.println("setup finished");
}

#ifdef NET
uint16_t readMax(uint16_t n, byte* buf) {
    if (udp.available() <= 0) {
        udp.parsePacket();
    }
    int r = udp.read(buf, n);
    return max(0, r);
}

void sendHeartbeat() {
    udp.beginPacket(SERVER_IP, SERVER_PORT);
    udp.write((const uint8_t*)"heart<", 6);
    const uint16_t n = NUM_LEDS;
    udp.write((const byte*)&n, 2);
    udp.write((const uint8_t*)">beat", 5);
    udp.endPacket();
}
void keepConnectionAlive() {
    const uint16_t interval = 500 / READ_RETRIES;
    static uint16_t n = interval;
    n += 1;
    if (n > interval) {
        sendHeartbeat();
        n = 0;
    }
}
#endif

// Returns false on timeout
bool readExact(uint16_t n, byte* buf) {
    uint16_t retry = 0;
    while (n > 0) {
        uint16_t m = readMax(n, buf);
        if (m == 0) {
            retry += 1;
            if (retry > READ_RETRIES) {
                return false;
            }
            delay(1);
        } else {
            n -= m;
            buf += m;
        }
    }
    return true;
}

// Blocks until one byte read. Returns -1 on timeout
int readSingle() {
    byte x;
    return readExact(1, &x) ? x : -1;
}

#define MAGIC_COOKIE_LEN 5
const byte magicCookie[MAGIC_COOKIE_LEN] = {'s','a','t','a','n'};

bool isMagicCookie(byte* buf) {
    for (uint16_t i = 0; i < MAGIC_COOKIE_LEN; i++) {
        if (magicCookie[i] != buf[i]) {
            return false;
        }
    }
    return true;
}

// Blockingly skips until synced. Returns false if timeout reached.
bool synchronize() {
    byte buf[MAGIC_COOKIE_LEN];
    if (!readExact(MAGIC_COOKIE_LEN, buf)) {
        return false;
    }
    if (isMagicCookie(buf)) {
        return true;
    }
    Serial.println("out of sync");
    while (!isMagicCookie(buf)) {
        uint16_t i = 0;
        for (; i < MAGIC_COOKIE_LEN-1; i++) {
            buf[i] = buf[i+1];
        }
        int b = readSingle();
        if (b < 0) {
            return false;
        } else {
            buf[i] = (byte)b;
        }
    }
    return true;
}

byte frame[NUM_BYTES];

void readFrame() {
    // Max number of timed out reads before we turn the lights off
    const uint16_t maxFails = 80000 / READ_RETRIES;
    static uint16_t fails = 0;
    // Blocks until we got sync and all data, unless timeout
    if (synchronize() && readExact(NUM_BYTES, frame)) {
        if (fails > maxFails) {
            Serial.println("we're back!");
        }
        fails = 0;
        setEach(frame);
    } else {
        fails += 1;
        if (fails == maxFails) {
            fails = maxFails + 1;
            Serial.println("server seems dead. lights off!");
            setAll(CRGB(0, 0, 0));
        }
    }
}

void loop() {
#ifdef NET
    keepConnectionAlive();
#endif
    readFrame();
    show();
}