summaryrefslogtreecommitdiffstats
path: root/martin/door/src/main.cpp
blob: 6a6eed382ceee9c1638e6a77008078dbf900c080 (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
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
#include <Arduino.h>
#include <WiFiManager.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <ESP8266httpUpdate.h>
#include <ping.h>

#include "cc1101.h"
#include "hcs200.h"
#include "secrets.h"

// fw update
// - increment number + build
// - scp .pio/build/$ENV/firmware.bin manuel@mausz.at:public_html/coding/.firmware/martindoor.bin
#define FIRMWARE_VERSION 1
//#define FIRMWARE_URL   ""

#define _STR(s) #s
#define STR(s) _STR(s)

void http_door_open();
void serial_door_open();
void checkFirmwareUpdate();

ESP8266WebServer http_service(80);

#define RADIO_CC1101
CC1101 radio(D0 /* GDO0 */, D2 /* GDO2 */, D8 /* SS */);

#ifndef RADIO_CC1101
#define PIN_RADIO_OUT D2
#endif

#define PIN_HCS200_ENABLE D3
#define PIN_HCS200_DATA   D1
//#define HCS200_TEST
HCS200 hcs200;

const int ping_delay = 60000;
long ping_last = 0;
ping_option ping_opt;

void setup()
{
  Serial.begin(9600);

  pinMode(PIN_HCS200_ENABLE, OUTPUT);
  digitalWrite(PIN_HCS200_ENABLE, LOW);
  pinMode(PIN_HCS200_DATA, INPUT);

  if (!radio.setup())
    Serial.println("Radio not found!");
  else if (!radio.setISM(CC1101::FREQ_434MHZ))
    Serial.println("Unable to set radio frequency");
  else
  {
    Serial.println("Radio found");
    (void)radio.idle();
  }

#ifndef RADIO_CC1101
  pinMode(PIN_RADIO_OUT, OUTPUT);
  digitalWrite(PIN_RADIO_OUT, LOW);
#endif

  WiFiManager wifiManager;
  wifiManager.setConfigPortalTimeout(600);
  Serial.printf_P(PSTR("Setting up WiFi\n"));
  WiFi.hostname("door");
  if (!wifiManager.autoConnect("a-door-able"))
  {
    Serial.printf_P(PSTR("Failed to connect and hit timeout\n"));
    delay(5000);
    ESP.restart();
  }

  yield();
  checkFirmwareUpdate();
  yield();

  if (!MDNS.begin("door"))
    Serial.println("Error setting up MDNS responder!");
  MDNS.addService("http", "tcp", 80);

  http_service.on("/", HTTP_GET, []() {
    http_service.send_P(200, PSTR("text/plain"), PSTR("I'm a-door-able"));
  });
  http_service.on("/door/open", HTTP_PUT, http_door_open);
  http_service.on("/door/close", HTTP_GET, []() {
    http_service.send_P(200, PSTR("text/plain"), PSTR("OK"));
  });
  http_service.on("/door/status", HTTP_GET, []() {
    http_service.send_P(200, PSTR("text/plain"), PSTR("CLOSED"));
  });
  http_service.begin();

  memset(&ping_opt, 0, sizeof(struct ping_option));
  ping_opt.count = 1;
  ping_opt.ip = WiFi.localIP();

  Serial.println("Started listening");
}

void ICACHE_RAM_ATTR on_hcs200_isr()
{
  hcs200.on_isr(digitalRead(PIN_HCS200_DATA) == HIGH);
}

bool hcs200_get_keycode(HCS200_Keycode &keycode)
{
#if !defined(HCS200_TEST)
  hcs200.reset();
  attachInterrupt(digitalPinToInterrupt(PIN_HCS200_DATA), on_hcs200_isr, CHANGE);
  digitalWrite(PIN_HCS200_ENABLE, HIGH);
  uint8_t maxloop = 255;
  while(--maxloop)
  {
    if (hcs200.decode(keycode))
      break;
    delay(1);
    yield();
  }
  digitalWrite(PIN_HCS200_ENABLE, LOW);
  detachInterrupt(digitalPinToInterrupt(PIN_HCS200_DATA));
  return (maxloop != 0);
#else
  keycode.encrypted = 0xDEAD;
  keycode.serial    = 0xC0DE;
  keycode.buttons   = HCS200_Keycode::BM_S0;
  keycode.lowbat    = false;
  return true;
#endif
}

void http_door_open()
{
  if (!radio.register_check())
  {
    http_service.send_P(500, PSTR("text/plain"), PSTR("Radio error"));
    return;
  }

  HCS200_Keycode keycode;
  if (!hcs200_get_keycode(keycode))
  {
    http_service.send_P(500, PSTR("text/plain"), PSTR("No data from HCS200"));
    return;
  }
  keycode.lowbat = false;

  Serial.print("Got keycode: ");
  keycode.print(Serial);

#ifdef RADIO_CC1101
  if (http_service.hasArg("power"))
  {
    static const uint8_t patable_power_n30[8] = { 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_n20[8] = { 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_n15[8] = { 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_n10[8] = { 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_0[8]   = { 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_5[8]   = { 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_7[8]   = { 0x00, 0xC8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    static const uint8_t patable_power_10[8]  = { 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    int power = http_service.arg("power").toInt();
    if (power == -30)
      radio.setPatable(patable_power_n30);
    else if (power == -20)
      radio.setPatable(patable_power_n20);
    else if (power == -15)
      radio.setPatable(patable_power_n15);
    else if (power == -10)
      radio.setPatable(patable_power_n10);
    else if (power == 0)
      radio.setPatable(patable_power_0);
    else if (power == 5)
      radio.setPatable(patable_power_5);
    else if (power == 7)
      radio.setPatable(patable_power_7);
    else if (power == 10)
      radio.setPatable(patable_power_10);
    else
    {
      http_service.send_P(500, PSTR("text/plain"), PSTR("Unsupported power level"));
      return;
    }
  }

  if (!radio.transmit())
  {
    http_service.send_P(500, PSTR("text/plain"), PSTR("Unable to enable radio transmit mode"));
    return;
  }
#endif

  if (http_service.hasArg("button1"))
    keycode.buttons = HCS200_Keycode::BM_S0;
  else if (http_service.hasArg("button2"))
    keycode.buttons = HCS200_Keycode::BM_S1;
  else if (http_service.hasArg("button3"))
    keycode.buttons = HCS200_Keycode::BM_S2;
  else if (http_service.hasArg("button4"))
    keycode.buttons = HCS200_Keycode::BM_S3;

  unsigned long count = constrain(http_service.arg("count").toInt(), 2, 400);
  for (unsigned int i = 0; i < count; i++)
  {
    keycode.send([&](int value) {
#ifdef RADIO_CC1101
      radio.setGDO0(value);
#else
      digitalWrite(PIN_RADIO_OUT, value);
#endif
    });
    yield();
  }

  (void)radio.idle();
  Serial.println("Sending done");
  http_service.send_P(200, PSTR("text/plain"), PSTR("OK"));
}

void serial_door_open(Print &stream)
{
  if (!radio.register_check())
  {
    stream.println("Radio error");
    return;
  }

  HCS200_Keycode keycode;
  bool key_valid = hcs200_get_keycode(keycode);
  if (!key_valid)
    stream.println("No data from HCS200");
  stream.print("HCS200 decoder state: ");
  hcs200.print_state(stream);
  if (!key_valid)
    return;

  stream.print("Got keycode: ");
  keycode.print(stream);

#ifdef RADIO_CC1101
  if (!radio.transmit())
  {
    stream.println("Unable to enable radio transmit mode");
    return;
  }
#endif

  /* send twice */
  for (unsigned int i = 0; i < 1; i++) {
    keycode.send([&](int value) {
  #ifdef RADIO_CC1101
        radio.setGDO0(value);
  #else
        digitalWrite(PIN_RADIO_OUT, value);
  #endif
    });
  }

  (void)radio.idle();
  stream.println("Sending done");
}

void checkFirmwareUpdate()
{
  BearSSL::WiFiClientSecure update_client;
  update_client.setInsecure();

  ESPhttpUpdate.setLedPin(LED_BUILTIN, HIGH);
  ESPhttpUpdate.rebootOnUpdate(true);
  t_httpUpdate_return ret = ESPhttpUpdate.update(update_client, FIRMWARE_URL, STR(FIRMWARE_VERSION));
  switch(ret)
  {
    case HTTP_UPDATE_FAILED:
      {
        Serial.printf_P(PSTR("HTTP_UPDATE_FAILED Error (%d): %s\n"),
          ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
        String tmp = String("fwupdate error: ") + ESPhttpUpdate.getLastErrorString();
      }
      break;

    case HTTP_UPDATE_NO_UPDATES:
      Serial.printf_P(PSTR("HTTP_UPDATE_NO_UPDATES\n"));
      break;

    case HTTP_UPDATE_OK:
      Serial.printf_P(PSTR("HTTP_UPDATE_OK\n"));
      break;
  }
}

void loop()
{
  MDNS.update();
  http_service.handleClient();

  if (millis() - ping_last > ping_delay)
  {
    ping_start(&ping_opt);
    ping_last = millis();
  }

  if (Serial.available() > 0)
  {
    String command = Serial.readStringUntil('\n');
    if (command == "door" || command == "door\r")
      serial_door_open(Serial);
  }

  delay(1);
}