summaryrefslogtreecommitdiffstats
path: root/oliver/dr_desk/dr_desk.ino
blob: 0ff13e21cf808666375a341e4bdf1475be713ff9 (plain)
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
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <FastLED.h>
#include "secrets.h"

const char* autoconf_ssid  = AUTOCONF_SSID; //AP name for WiFi setup AP which your ESP will open when not able to connect to other WiFi
const char* autoconf_pwd   = AUTOCONF_PASSWORD; // AP password so noone else can connect to the ESP in case your router fails
const char* mqtt_server    = "192.168.1.2"; //MQTT Server IP, your home MQTT server eg Mosquitto on RPi, or some public MQTT
const int mqtt_port        = 1883; //MQTT Server PORT, default is 1883 but can be anything.

const char* mqtt_pingall_sub = "home/pingall";
const char* mqtt_pingall_pub = "home/pingall/response";

#define MQTT_BASE "home/diningroom/desk"
const char* mqtt_device_boot = MQTT_BASE "/device";

const char* mqtt_mode_sub = MQTT_BASE;
const char* mqtt_mode_pub = MQTT_BASE "/status";

const char* mqtt_color_sub = MQTT_BASE "/color";
const char* mqtt_color_pub = MQTT_BASE "/color/status";

const char* mqtt_brightness_sub = MQTT_BASE "/brightness";
const char* mqtt_brightness_pub = MQTT_BASE "/brightness/status";

#define RGB_PIN      2
#define RGB_NUM_LEDS 12
#define RGB_CHIPSET  WS2812B
#define RGB_COLOR_ORDER GRB
#define NUM(a) (sizeof(a) / sizeof(*a))

WiFiClient espClient;
PubSubClient client(espClient);
char convBuffer[10];
CRGB leds[RGB_NUM_LEDS];

void switchMode(struct mode *mode);
void modeOff();
void modeSolid();
void modeRainbow();
void modeRainbowFast();
void modeStrobo();

struct mode {
  const char *name;
  void (*func)();
};

struct mode modes[] = {
  { "off",         modeOff         },
  { "solid",       modeSolid       },
  { "rainbow",     modeRainbow     },
  { "rainbowfast", modeRainbowFast },
  { "strobo",      modeStrobo      },
};

struct
{
  struct mode *mode = &modes[0];
  uint32_t color = CRGB::Red;
  uint8_t brightness = 204; // 80%
} set;

struct
{
  uint8_t brightness;
  bool idle = false;
} current;

void setup()
{
  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);

  FastLED.addLeds<RGB_CHIPSET, RGB_PIN, RGB_COLOR_ORDER>(leds, RGB_NUM_LEDS);
  current.brightness = set.brightness;
  // update leds
  set.mode->func();
  FastLED.show();

  WiFiManager wifiManager;
  wifiManager.autoConnect(autoconf_ssid, autoconf_pwd);

  setup_ota();

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  digitalWrite(BUILTIN_LED, HIGH);  //Turn off led as default
}

void setup_ota()
{
  // Set OTA Password, and change it in platformio.ini
  ArduinoOTA.setPassword(OTA_PASSWORD);
  ArduinoOTA.onStart([]() {});
  ArduinoOTA.onEnd([]() {});
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {});
  ArduinoOTA.onError([](ota_error_t error)
  {
    if (error == OTA_AUTH_ERROR);          // Auth failed
    else if (error == OTA_BEGIN_ERROR);    // Begin failed
    else if (error == OTA_CONNECT_ERROR);  // Connect failed
    else if (error == OTA_RECEIVE_ERROR);  // Receive failed
    else if (error == OTA_END_ERROR);      // End failed
  });
  ArduinoOTA.begin();
}

void reconnect()
{
  // Loop until we're reconnected
  while (!client.connected())
  {
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);

    // Attempt to connect
    if (client.connect(clientId.c_str()))
    {
      // Once connected, publish an announcement...
      client.publish(mqtt_device_boot, "connected");
      // ... and resubscribe
      client.subscribe(mqtt_pingall_sub);

      // publish states
      Serial.println(mqtt_mode_sub);
      client.subscribe(mqtt_mode_sub);
      client.publish(mqtt_mode_pub, set.mode->name, true);

      Serial.println(mqtt_color_sub);
      client.subscribe(mqtt_color_sub);
      itoa(set.color, convBuffer, 10);
      client.publish(mqtt_color_pub, convBuffer, true);

      Serial.println(mqtt_brightness_sub);
      client.subscribe(mqtt_brightness_sub);
      itoa(map(set.brightness, 0, 255, 0, 100), convBuffer, 10);
      client.publish(mqtt_brightness_pub, convBuffer, true);
    }
    else
    {
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char *topic, uint8_t *payload, unsigned int length)
{
  uint8_t c_payload[length];
  memcpy(c_payload, payload, length);
  c_payload[length] = '\0';

  if (strcmp(topic, mqtt_pingall_sub) == 0)
  {
    blink();
    client.publish(mqtt_pingall_pub,
      "{\"diningroom_desk\":\"connected\"}");
  }
  else if (strcmp(topic, mqtt_mode_sub) == 0)
  {
    for (uint8_t i = 0; i < NUM(modes); ++i)
    {
      if (strcmp(modes[i].name, (char *)c_payload) != 0)
        continue;
      switchMode(&modes[i]);
      break;
    }
  }
  else if (strcmp(topic, mqtt_color_sub) == 0)
  {
    // switch from OFF to SOLID
    if (set.mode == &modes[0])
      switchMode(&modes[1]);

    set.color = atoi((char *)c_payload);
    current.idle = false;
    itoa(set.color, convBuffer, 10);
    client.publish(mqtt_color_pub, convBuffer, true);
  }
  else if (strcmp(topic, mqtt_brightness_sub) == 0)
  {
    set.brightness = map(atoi((char *)c_payload), 0, 100, 0, 255);
    current.idle = false;
    itoa(map(set.brightness, 0, 255, 0, 100), convBuffer, 10);
    client.publish(mqtt_brightness_pub, convBuffer, true);
  }
}

void blink()
{
  //Blink on received MQTT message
  digitalWrite(BUILTIN_LED, LOW);
  delay(25);
  digitalWrite(BUILTIN_LED, HIGH);
}

void calcBrightness()
{
  #define FADE_STEP 10
  if (current.brightness == set.brightness)
    return;
  int fadeAmount = set.brightness - current.brightness;
  if (abs(fadeAmount) > FADE_STEP)
    fadeAmount = (fadeAmount > 0) ? FADE_STEP : -FADE_STEP;
  current.brightness += fadeAmount;
}

void switchMode(struct mode *mode)
{
  if (set.mode == mode)
    return;
  Serial.print("Switching mode to ");
  Serial.println(mode->name);
  set.mode = mode;
  current.idle = false;
  client.publish(mqtt_mode_pub, set.mode->name, true);
}

void modeOff()
{
  fill_solid(leds, RGB_NUM_LEDS, CRGB::Black);
  current.idle = true;
}

void modeSolid()
{
  fill_solid(leds, RGB_NUM_LEDS, set.color);
  calcBrightness();
  nscale8_video(leds, RGB_NUM_LEDS, current.brightness);
  current.idle = (current.brightness == set.brightness);
}

void modeRainbow()
{
  static CRGBPalette16 palette = RainbowColors_p;
  static uint8_t hue = 0;
  calcBrightness();
  for (int i = 0; i < RGB_NUM_LEDS; ++i)
    leds[i] = ColorFromPalette(palette, hue, current.brightness);
  hue++;
}

void modeRainbowFast()
{
  static CRGBPalette16 palette = RainbowColors_p;
  static uint8_t hue = 0;
  calcBrightness();
  for (int i = 0; i < RGB_NUM_LEDS; ++i)
    leds[i] = ColorFromPalette(palette, hue, current.brightness);
  hue+=5;
}

void modeStrobo()
{
  static bool state = 0;
  if (set.color == CRGB::Black)
    return;
  fill_solid(leds, RGB_NUM_LEDS, (state) ? set.color : CRGB::Black);
  calcBrightness();
  nscale8_video(leds, RGB_NUM_LEDS, current.brightness);
  state = !state;
}

void loop()
{
  if (!client.connected())
    reconnect();
  client.loop();
  ArduinoOTA.handle();

  EVERY_N_MILLISECONDS(100)
  {
    if (!current.idle)
    {
      set.mode->func();
      FastLED.show();
    }
    if (!current.idle && current.brightness == 0)
      current.idle = true;
  }
}