-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy pathmain.cpp
557 lines (458 loc) · 14.7 KB
/
main.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
555
556
557
#ifndef UNIT_TEST
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <cstdlib>
#include <FS.h>
#include <IntParsing.h>
#include <LinkedList.h>
#include <LEDStatus.h>
#include <GroupStateStore.h>
#include <MiLightRadioConfig.h>
#include <MiLightRemoteConfig.h>
#include <MiLightHttpServer.h>
#include <Settings.h>
#include <MiLightUdpServer.h>
#include <MqttClient.h>
#include <MiLightDiscoveryServer.h>
#include <MiLightClient.h>
#include <BulbStateUpdater.h>
#include <RadioSwitchboard.h>
#include <PacketSender.h>
#include <HomeAssistantDiscoveryClient.h>
#include <TransitionController.h>
#include <ProjectWifi.h>
#include <ESPId.h>
#ifdef ESP8266
#include <ESP8266mDNS.h>
#include <ESP8266SSDP.h>
#elif ESP32
#include "ESP32SSDP.h"
#include <esp_wifi.h>
#include <SPIFFS.h>
#include <ESPmDNS.h>
#endif
#include <vector>
#include <memory>
#include "ProjectFS.h"
WiFiManager* wifiManager;
// because of callbacks, these need to be in the higher scope :(
WiFiManagerParameter* wifiStaticIP = NULL;
WiFiManagerParameter* wifiStaticIPNetmask = NULL;
WiFiManagerParameter* wifiStaticIPGateway = NULL;
WiFiManagerParameter* wifiMode = NULL;
static LEDStatus *ledStatus;
Settings settings;
MiLightClient* milightClient = NULL;
RadioSwitchboard* radios = nullptr;
PacketSender* packetSender = nullptr;
std::shared_ptr<MiLightRadioFactory> radioFactory;
MiLightHttpServer *httpServer = NULL;
MqttClient* mqttClient = NULL;
MiLightDiscoveryServer* discoveryServer = NULL;
uint8_t currentRadioType = 0;
// For tracking and managing group state
GroupStateStore* stateStore = NULL;
BulbStateUpdater* bulbStateUpdater = NULL;
TransitionController transitions;
std::vector<std::shared_ptr<MiLightUdpServer>> udpServers;
/**
* Set up UDP servers (both v5 and v6). Clean up old ones if necessary.
*/
void initMilightUdpServers() {
if (! WiFi.isConnected()) {
return;
}
udpServers.clear();
for (size_t i = 0; i < settings.gatewayConfigs.size(); ++i) {
const GatewayConfig& config = *settings.gatewayConfigs[i];
std::shared_ptr<MiLightUdpServer> server = MiLightUdpServer::fromVersion(
config.protocolVersion,
milightClient,
config.port,
config.deviceId
);
if (server == NULL) {
Serial.print(F("Error creating UDP server with protocol version: "));
Serial.println(config.protocolVersion);
} else {
udpServers.push_back(std::move(server));
udpServers[i]->begin();
}
}
if (discoveryServer) {
delete discoveryServer;
discoveryServer = NULL;
}
if (settings.discoveryPort != 0) {
discoveryServer = new MiLightDiscoveryServer(settings);
discoveryServer->begin();
}
}
/**
* Milight RF packet handler.
*
* Called both when a packet is sent locally, and when an intercepted packet
* is read.
*/
void onPacketSentHandler(uint8_t* packet, const MiLightRemoteConfig& config) {
StaticJsonDocument<200> buffer;
JsonObject result = buffer.to<JsonObject>();
BulbId bulbId = config.packetFormatter->parsePacket(packet, result);
// set LED mode for a packet movement
ledStatus->oneshot(settings.ledModePacket, settings.ledModePacketCount);
if (bulbId == DEFAULT_BULB_ID) {
Serial.println(F("Skipping packet handler because packet was not decoded"));
return;
}
const MiLightRemoteConfig& remoteConfig =
*MiLightRemoteConfig::fromType(bulbId.deviceType);
// update state to reflect changes from this packet
GroupState* groupState = stateStore->get(bulbId);
// pass in previous scratch state as well
const GroupState stateUpdates(groupState, result);
if (groupState != NULL) {
groupState->patch(stateUpdates);
// Copy state before setting it to avoid group 0 re-initialization clobbering it
stateStore->set(bulbId, stateUpdates);
}
if (mqttClient) {
// Sends the state delta derived from the raw packet
char output[200];
serializeJson(result, output);
mqttClient->sendUpdate(remoteConfig, bulbId.deviceId, bulbId.groupId, output);
// Sends the entire state
if (groupState != NULL) {
bulbStateUpdater->enqueueUpdate(bulbId, *groupState);
}
}
httpServer->handlePacketSent(packet, remoteConfig, bulbId, result);
}
/**
* Listen for packets on one radio config. Cycles through all configs as its
* called.
*/
void handleListen() {
// Do not handle listens while there are packets enqueued to be sent
// Doing so causes the radio module to need to be reinitialized inbetween
// repeats, which slows things down.
if (! settings.listenRepeats || packetSender->isSending()) {
return;
}
std::shared_ptr<MiLightRadio> radio = radios->switchRadio(currentRadioType++ % radios->getNumRadios());
for (size_t i = 0; i < settings.listenRepeats; i++) {
if (radios->available()) {
uint8_t readPacket[MILIGHT_MAX_PACKET_LENGTH];
size_t packetLen = radios->read(readPacket);
const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
radio->config(),
readPacket,
packetLen
);
if (remoteConfig == NULL) {
// This can happen under normal circumstances, so not an error condition
#ifdef DEBUG_PRINTF
Serial.println(F("WARNING: Couldn't find remote for received packet"));
#endif
return;
}
// update state to reflect this packet
onPacketSentHandler(readPacket, *remoteConfig);
}
}
}
/**
* Called when MqttClient#update is first being processed. Stop sending updates
* and aggregate state changes until the update is finished.
*/
void onUpdateBegin() {
if (bulbStateUpdater) {
bulbStateUpdater->disable();
}
}
/**
* Called when MqttClient#update is finished processing. Re-enable state
* updates, which will flush accumulated state changes.
*/
void onUpdateEnd() {
if (bulbStateUpdater) {
bulbStateUpdater->enable();
}
}
/**
* Apply what's in the Settings object.
*/
void applySettings() {
if (milightClient) {
delete milightClient;
}
if (mqttClient) {
delete mqttClient;
delete bulbStateUpdater;
mqttClient = NULL;
bulbStateUpdater = NULL;
}
if (stateStore) {
delete stateStore;
}
if (packetSender) {
delete packetSender;
}
if (radios) {
delete radios;
}
transitions.setDefaultPeriod(settings.defaultTransitionPeriod);
radioFactory = MiLightRadioFactory::fromSettings(settings);
if (radioFactory == NULL) {
Serial.println(F("ERROR: unable to construct radio factory"));
}
stateStore = new GroupStateStore(MILIGHT_MAX_STATE_ITEMS, settings.stateFlushInterval);
radios = new RadioSwitchboard(radioFactory, stateStore, settings);
packetSender = new PacketSender(*radios, settings, onPacketSentHandler);
milightClient = new MiLightClient(
*radios,
*packetSender,
stateStore,
settings,
transitions
);
milightClient->onUpdateBegin(onUpdateBegin);
milightClient->onUpdateEnd(onUpdateEnd);
if (settings.mqttServer().length() > 0) {
mqttClient = new MqttClient(settings, milightClient);
mqttClient->begin();
mqttClient->onConnect([]() {
if (settings.homeAssistantDiscoveryPrefix.length() > 0) {
HomeAssistantDiscoveryClient discoveryClient(settings, mqttClient);
discoveryClient.sendDiscoverableDevices(settings.groupIdAliases);
discoveryClient.removeOldDevices(settings.deletedGroupIdAliases);
settings.deletedGroupIdAliases.clear();
}
});
bulbStateUpdater = new BulbStateUpdater(settings, *mqttClient, *stateStore);
}
initMilightUdpServers();
// update LED pin and operating mode
if (ledStatus) {
ledStatus->changePin(settings.ledPin);
ledStatus->continuous(settings.ledModeOperating);
}
WiFi.hostname(settings.hostname);
#ifdef ESP8266
WiFiPhyMode_t wifiPhyMode;
switch (settings.wifiMode) {
case WifiMode::B:
wifiPhyMode = WIFI_PHY_MODE_11B;
break;
case WifiMode::G:
wifiPhyMode = WIFI_PHY_MODE_11G;
break;
default:
case WifiMode::N:
wifiPhyMode = WIFI_PHY_MODE_11N;
break;
}
WiFi.setPhyMode(wifiPhyMode);
#elif ESP32
switch (settings.wifiMode) {
case WifiMode::B:
esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_11B);
break;
case WifiMode::G:
esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_11G);
break;
default:
case WifiMode::N:
esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_11N);
break;
}
esp_wifi_set_bandwidth(WIFI_IF_STA, WIFI_BW_HT20);
#endif
}
/**
*
*/
bool shouldRestart() {
if (! settings.isAutoRestartEnabled()) {
return false;
}
return settings.getAutoRestartPeriod()*60*1000 < millis();
}
void wifiExtraSettingsChange() {
settings.wifiStaticIP = wifiStaticIP->getValue();
settings.wifiStaticIPNetmask = wifiStaticIPNetmask->getValue();
settings.wifiStaticIPGateway = wifiStaticIPGateway->getValue();
settings.wifiMode = Settings::wifiModeFromString(wifiMode->getValue());
settings.save();
// Restart the device
delay(1000);
ESP.restart();
}
void aboutHandler(JsonDocument& json) {
JsonObject mqtt = json.createNestedObject(FPSTR("mqtt"));
mqtt[FPSTR("configured")] = (mqttClient != nullptr);
if (mqttClient) {
mqtt[FPSTR("connected")] = mqttClient->isConnected();
mqtt[FPSTR("status")] = mqttClient->getConnectionStatusString();
}
}
// Called when a group is deleted via the REST API. Will publish an empty message to
// the MQTT topic to delete retained state
void onGroupDeleted(const BulbId& id) {
if (mqttClient != NULL) {
mqttClient->sendState(
*MiLightRemoteConfig::fromType(id.deviceType),
id.deviceId,
id.groupId,
""
);
}
}
bool initialized = false;
void postConnectSetup() {
if (initialized) return;
initialized = true;
delete wifiManager;
wifiManager = NULL;
MDNS.addService("http", "tcp", 80);
SSDP.setSchemaURL("description.xml");
SSDP.setHTTPPort(80);
SSDP.setName("ESP8266 MiLight Gateway");
SSDP.setSerialNumber(getESPId());
SSDP.setURL("/");
SSDP.setDeviceType("upnp:rootdevice");
SSDP.begin();
httpServer = new MiLightHttpServer(settings, milightClient, stateStore, packetSender, radios, transitions);
httpServer->onSettingsSaved(applySettings);
httpServer->onGroupDeleted(onGroupDeleted);
httpServer->onAbout(aboutHandler);
httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); });
httpServer->begin();
transitions.addListener(
[](const BulbId& bulbId, GroupStateField field, uint16_t value) {
StaticJsonDocument<100> buffer;
const char* fieldName = GroupStateFieldHelpers::getFieldName(field);
buffer[fieldName] = value;
milightClient->prepare(bulbId.deviceType, bulbId.deviceId, bulbId.groupId);
milightClient->update(buffer.as<JsonObject>());
}
);
initMilightUdpServers();
Serial.printf_P(PSTR("Setup complete (version %s)\n"), QUOTE(MILIGHT_HUB_VERSION));
}
void setup() {
Serial.begin(9600);
String ssid = "ESP" + String(getESPId());
// load up our persistent settings from the file system
// ESP8266 doesn't support the formatOnFail parameter
#ifdef ESP8266
if (! ProjectFS.begin()) {
Serial.println(F("Failed to mount file system"));
}
#else
if (! ProjectFS.begin(true)) {
Serial.println(F("Failed to mount file system"));
}
#endif
Settings::load(settings);
ESPMH_SETUP_WIFI(settings);
applySettings();
// set up the LED status for wifi configuration
ledStatus = new LEDStatus(settings.ledPin);
ledStatus->continuous(settings.ledModeWifiConfig);
// start up the wifi manager
if (! MDNS.begin("milight-hub")) {
Serial.println(F("Error setting up MDNS responder"));
}
// Allows us to have static IP config in the captive portal. Yucky pointers to pointers, just to have the settings carry through
wifiManager = new WiFiManager();
// Setting breakAfterConfig to true causes wifiExtraSettingsChange to be called whenever config params are changed
// (even when connection fails or user is just changing settings and not network)
wifiManager->setBreakAfterConfig(true);
wifiManager->setSaveConfigCallback(wifiExtraSettingsChange);
wifiManager->setConfigPortalBlocking(false);
wifiManager->setConnectTimeout(20);
wifiManager->setConnectRetries(5);
wifiStaticIP = new WiFiManagerParameter(
"staticIP",
"Static IP (Leave blank for dhcp)",
settings.wifiStaticIP.c_str(),
MAX_IP_ADDR_LEN
);
wifiManager->addParameter(wifiStaticIP);
wifiStaticIPNetmask = new WiFiManagerParameter(
"netmask",
"Netmask (required if IP given)",
settings.wifiStaticIPNetmask.c_str(),
MAX_IP_ADDR_LEN
);
wifiManager->addParameter(wifiStaticIPNetmask);
wifiStaticIPGateway = new WiFiManagerParameter(
"gateway",
"Default Gateway (optional, only used if static IP)",
settings.wifiStaticIPGateway.c_str(),
MAX_IP_ADDR_LEN
);
wifiManager->addParameter(wifiStaticIPGateway);
wifiMode = new WiFiManagerParameter(
"wifiMode",
"WiFi Mode (b/g/n)",
settings.wifiMode == WifiMode::B ? "b" : settings.wifiMode == WifiMode::G ? "g" : "n",
1
);
wifiManager->addParameter(wifiMode);
// We have a saved static IP, let's try and use it.
if (settings.wifiStaticIP.length() > 0) {
Serial.printf_P(PSTR("We have a static IP: %s\n"), settings.wifiStaticIP.c_str());
IPAddress _ip, _subnet, _gw;
_ip.fromString(settings.wifiStaticIP);
_subnet.fromString(settings.wifiStaticIPNetmask);
_gw.fromString(settings.wifiStaticIPGateway);
wifiManager->setSTAStaticIPConfig(_ip,_gw,_subnet);
}
wifiManager->setConfigPortalTimeout(180);
wifiManager->setConfigPortalTimeoutCallback([]() {
ledStatus->continuous(settings.ledModeWifiFailed);
Serial.println(F("Wifi config portal timed out. Restarting..."));
delay(10000);
ESP.restart();
});
if (wifiManager->autoConnect(ssid.c_str(), "milightHub")) {
// set LED mode for successful operation
ledStatus->continuous(settings.ledModeOperating);
Serial.println(F("Wifi connected succesfully\n"));
// if the config portal was started, make sure to turn off the config AP
WiFi.mode(WIFI_STA);
postConnectSetup();
}
}
size_t i = 0;
void loop() {
// update LED with status
ledStatus->handle();
if (shouldRestart()) {
Serial.println(F("Auto-restart triggered. Restarting..."));
ESP.restart();
}
if (wifiManager) {
wifiManager->process();
}
if (WiFi.getMode() == WIFI_STA && WiFi.isConnected()) {
postConnectSetup();
httpServer->handleClient();
if (mqttClient) {
mqttClient->handleClient();
bulbStateUpdater->loop();
}
for (auto & udpServer : udpServers) {
udpServer->handleClient();
}
if (discoveryServer) {
discoveryServer->handleClient();
}
handleListen();
stateStore->limitedFlush();
packetSender->loop();
transitions.loop();
}
}
#endif