This commit is contained in:
2021-02-17 22:54:53 -05:00
parent bc316375e0
commit 68f57a0807
20 changed files with 3554 additions and 23 deletions

View File

@@ -16,7 +16,7 @@ platform = atmelavr
framework = arduino
board = attiny85
upload_protocol = custom
upload_port = /dev/ttyACM1
upload_port = /dev/ttyACM0
upload_speed = 19200
upload_flags =
-C

View File

@@ -36,7 +36,6 @@ void AttinyDebounce::update(unsigned long millisNow) {
break;
case TRIGGERED:
// TODO: Debounce this part too
if (!assertedNow) {
state = IDLE;
}

View File

@@ -29,13 +29,14 @@ constexpr uint8_t BUTTON_PIN = 1; // Button press
constexpr uint8_t RTC_PIN = 4; // RTC alarm (currently, from the ESP8266 RTC)
constexpr uint8_t AUX_PIN = 5; // Another wakeup source. May be used for other sensors in the future.
constexpr uint8_t DEBUG_LED = RTC_PIN;
// constexpr uint8_t DEBUG_LED = RTC_PIN;
constexpr unsigned long CMD_TIMEOUT_MILLIS = 1000; // After this period of with no commands, the device will sleep
constexpr unsigned long WAKE_PULSE_MILLIS = 100; // Length of pulse sent to wake the main MCU
constexpr unsigned long LONG_PRESS_MILLIS = 5000;
constexpr unsigned long I2C_WATCHDOG_PERIOD_MILLIS = 2000; // If we don't get a request from the Main MCU in this time, just go to sleep.
constexpr unsigned long DEBOUNCE_MILLIS = 100;
constexpr unsigned long I2C_WATCHDOG_PERIOD_MILLIS = 1000; // If we don't get a request from the Main MCU in this time, just go to sleep.
constexpr unsigned long DEBOUNCE_MILLIS = 1;
constexpr unsigned long NO_WAKEUP_SRC_TIMEOUT_MILLIS = DEBOUNCE_MILLIS + 5;
constexpr uint8_t I2C_DEVICE_ADDR = 0x4F; // Chosen arbitrarily
@@ -78,6 +79,7 @@ static unsigned long startWakeMillis, i2cWatchDogTime;
static I2cReq i2c_cmd_byte;
static volatile WakeSource wakeSource;
static volatile unsigned long endButtonMillis;
static unsigned long wakeupMillis = 0;
static void i2cReceiveHook(int numBytes) {
while (numBytes > 0) {
@@ -96,8 +98,6 @@ static void i2cRequestHook() {
}
}
static void enablePinChangeInterrupt() {
GIMSK |= _BV(PCIE);
PCMSK |= _BV(BUTTON_PIN);
@@ -123,15 +123,15 @@ static void resetState() {
void setup() {
// Init pin states
pinMode(MAIN_MCU_NRESET_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
pinMode(RTC_PIN, INPUT);
pinMode(AUX_PIN, INPUT);
pinMode(DEBUG_LED, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(RTC_PIN, INPUT_PULLUP);
pinMode(AUX_PIN, INPUT_PULLUP);
// pinMode(DEBUG_LED, OUTPUT);
// On first run, reset the main MCU to get in sync.
digitalWrite(MAIN_MCU_NRESET_PIN, HIGH);
delay(WAKE_PULSE_MILLIS);
digitalWrite(MAIN_MCU_NRESET_PIN, LOW);
delay(WAKE_PULSE_MILLIS);
digitalWrite(MAIN_MCU_NRESET_PIN, HIGH);
appState = AppState::SLEEP;
@@ -151,21 +151,19 @@ static void buttonCallback(int index) {
}
ISR(PCINT0_vect) {
unsigned long millisNow = millis();
ButtonDebounce.update(millisNow);
ButtonDebounce.update(millis());
}
void loop() {
unsigned long millisNow = millis();
ButtonDebounce.update(millisNow);
ButtonDebounce.update(millis());
switch (appState) {
case AppState::SLEEP:
resetState();
//digitalWrite(DEBUG_LED, HIGH);
// digitalWrite(DEBUG_LED, LOW);
sleepUntilPinChange();
//digitalWrite(DEBUG_LED, LOW);
wakeupMillis = millis();
// digitalWrite(DEBUG_LED, HIGH);
appState = AppState::WATCHING_INPUT;
break;
case AppState::WATCHING_INPUT:
@@ -173,21 +171,24 @@ void loop() {
// Keep waiting. For example, waiting to see if long or short button press.
// TODO: Not yet implemented
} else if (wakeSource == WakeSource::NONE) {
// appState = AppState::SLEEP;
if (millis() > wakeupMillis + NO_WAKEUP_SRC_TIMEOUT_MILLIS) {
appState = AppState::SLEEP;
break;
}
} else {
// We know the wakeup source. Time to inform the main MCU.
appState = AppState::START_WAKE_MAIN_MCU;
}
break;
case AppState::START_WAKE_MAIN_MCU:
digitalWrite(MAIN_MCU_NRESET_PIN, HIGH);
digitalWrite(MAIN_MCU_NRESET_PIN, LOW);
startWakeMillis = millis();
appState = AppState::WAKING_MAIN_MCU;
break;
case AppState::WAKING_MAIN_MCU:
if (millis() > startWakeMillis + WAKE_PULSE_MILLIS) {
appState = AppState::WAITING_FOR_I2C;
digitalWrite(MAIN_MCU_NRESET_PIN, LOW);
digitalWrite(MAIN_MCU_NRESET_PIN, HIGH);
}
break;
case AppState::WAITING_FOR_I2C:

2
firmware/main_mcu/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.pio
src/config.h

View File

@@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View File

@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View File

@@ -0,0 +1,26 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env]
platform = espressif8266
framework = arduino
board = esp12e
lib_deps =
knolleary/PubSubClient@^2.8.0
bblanchon/ArduinoJson@^6.17.2
upload_speed = 115200
[env:button-release]
[env:button-timing]
build_flags = -D DEBUG_SKETCH_TIMING
[env:button-debug]
build_flags = -D DEBUG_SKETCH

View File

@@ -0,0 +1,114 @@
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "config.h"
#include "mqtt.h"
#include "util.h"
#define BTN_PIN D0
#define RED_LED_PIN 4
#define GREEN_LED_PIN 5
#define BLUE_LED_PIN 12
#define LONG_PRESS_MILLIS 1000
static WiFiClient wifiClient;
static PubSubClient mqttClient;
void blink(int pin, int times, int onMillis, int offMillis) {
// for (int i = 0; i < times; i++) {
// digitalWrite(pin, HIGH);
// delay(onMillis);
// digitalWrite(pin, LOW);
// delay(offMillis);
// }
}
void fail(const char *message) {
PRINT(message);
blink(RED_LED_PIN, 3, 50, 50);
// TODO: go back to sleep
}
void success() {
blink(GREEN_LED_PIN, 1, 50, 0);
}
static void initConnection() {
initWifi(wifiClient);
initMqtt(mqttClient, wifiClient);
}
void handleShortButtonWakeup() {
initConnection();
if (!publishTriggerMessage(mqttClient, String("short_press"))) {
fail("failed to publish trigger message\n");
}
if (!publishBatteryMessage(mqttClient, 100)) {
fail("Failed to publish battery message\n");
}
}
void handleLongButtonWakeup() {
initConnection();
if (!publishHABatteryDiscoveryConfig(mqttClient)) {
fail("Failed to publish battery config\n");
}
if (!publishHATriggerDiscoveryConfig(mqttClient)) {
fail("Failed to publish trigger config\n");
}
if (!publishBatteryMessage(mqttClient, 100)) {
fail("Failed to publish trigger message\n");
}
success();
}
void setup() {
// Sample the input button ASAP.
// pinMode(BTN_PIN, INPUT);
// bool btn_value = digitalRead(BTN_PIN);
unsigned long startTimingMillis = millis();
pinMode(RED_LED_PIN, OUTPUT);
pinMode(BLUE_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
#if defined(DEBUG_SKETCH) || defined(DEBUG_SKETCH_TIMING)
Serial.begin(9600);
#endif
PRINTLN("\nBeginning setup\n");
PRINT("Device name:");
PRINTLN(getDeviceHumanName());
handleShortButtonWakeup();
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(BLUE_LED_PIN, LOW);
// We've done our work- back to sleep.
PRINT("Going to sleep...\n");
#if defined(DEBUG_SKETCH_TIMING)
unsigned long endTimeMillis = millis();
Serial.print("Ran for " + String(endTimeMillis - startTimingMillis) + " milliseconds\n");
#endif
// Drain all of our pending requests
mqttClient.disconnect();
wifiClient.flush();
while (mqttClient.state() != -1) {
yield();
}
ESP.deepSleep(0, RFMode::RF_NO_CAL);
}
void loop() {
}

View File

@@ -0,0 +1,146 @@
#include "mqtt.h"
#include <ArduinoJson.h>
#include "config.h"
#include "util.h"
#define MAX_PACKET_SIZE 1024
#define TIMEOUT_MILLIS 1000
#define TRIGGER_KEY "event"
#define VALUE_TEMPLATE(key) ("{{ value_json." key " }}")
// TODO: This should really be a class, this is kinda busted
static bool isDone = true;
void initMqtt(PubSubClient &mqttClient, WiFiClient &wifiClient) {
mqttClient.setServer(CONFIG_MQTT_SERVER, CONFIG_MQTT_SERVER_PORT);
mqttClient.setClient(wifiClient);
mqttClient.setBufferSize(MAX_PACKET_SIZE);
mqttClient.setCallback([](char *, unsigned char*, unsigned int){
PRINTLN("Message sent!");
isDone = true;
});
PRINT("Connecting to MQTT broker...");
while (!mqttClient.connected()) {
PRINT(".");
mqttClient.connect(getDeviceMachineName().c_str());
}
PRINTLN("\nConnected!");
}
static bool waitTilDone(PubSubClient &mqttClient) {
mqttClient.loop();
return true;
// unsigned long startTime = millis();
// do {
// mqttClient.loop();
// } while (!isDone && startTime + TIMEOUT_MILLIS > millis());
// return isDone;
}
static String getHATriggerConfigTopic() {
return String(CONFIG_HOMEASSISTANT_MQTT_PREFIX "device_automation/") + getDeviceMachineName() + "/config";
}
static String getHASensorConfigTopic() {
return String(CONFIG_HOMEASSISTANT_MQTT_PREFIX "sensor/") + getDeviceMachineName() + "/config";
}
static String getButtonTopicBase(bool abbrev) {
if (abbrev) {
return String("~");
} else {
return String(CONFIG_BUTTON_EVENT_TOPIC_PREFIX) + getDeviceMachineName();
}
}
static String getButtonStateTopic(bool abbrev) {
return getButtonTopicBase(abbrev) + "/" CONFIG_BUTTON_STATE_TOPIC_NAME;
}
static String getButtonTriggerTopic(bool abbrev) {
return getButtonTopicBase(abbrev) + "/" CONFIG_BUTTON_TRIGGER_TOPIC_NAME;
}
static bool publishJsonDocument(PubSubClient &mqttClient, String topic, JsonDocument &message, bool retain) {
char str[MAX_PACKET_SIZE];
size_t len = serializeJson(message, str, MAX_PACKET_SIZE);
PRINT(topic);
PRINT(":");
PRINTLN(str);
isDone = false;
if (!mqttClient.publish(topic.c_str(), (uint8_t *) str, len, retain)) {
return false;
}
return waitTilDone(mqttClient);
}
static void addDeviceJson(JsonDocument &doc) {
JsonObject device = doc.createNestedObject("device");
device["name"] = getDeviceHumanName();
device["mf"] = "DIY"; // manufacturer
device["mdl"] = "IoT Button - ESP8266"; // model
device["sw"] = "1.0"; // sw_version
JsonArray ids = device.createNestedArray("ids");
ids.add(getDeviceId());
}
bool publishBatteryMessage(PubSubClient &mqttClient, int percentage) {
StaticJsonDocument<MAX_PACKET_SIZE> json;
json["battery"] = percentage;
isDone = false;
PRINTLN("Publishing battery message");
return publishJsonDocument(mqttClient, getButtonStateTopic(false), json, true);
}
bool publishTriggerMessage(PubSubClient &mqttClient, String message) {
isDone = false;
PRINTLN("Publishing trigger message");
if (!mqttClient.publish(getButtonTriggerTopic(false).c_str(), message.c_str(), false)) {
return false;
}
return waitTilDone(mqttClient);
}
bool publishHABatteryDiscoveryConfig(PubSubClient &mqttClient) {
StaticJsonDocument<MAX_PACKET_SIZE> json;
bool abbrev = true;
json["~"] = getButtonTopicBase(false);
json["stat_t"] = getButtonStateTopic(abbrev); // state_topic
json["val_tpl"] = VALUE_TEMPLATE("battery"); // state_value_template
json["uniq_id"] = getDeviceMachineName() + "-battery"; // unique_id
json["dev_cla"] = "battery"; // device_class
json["name"] = getDeviceHumanName() + ": Battery";
addDeviceJson(json);
PRINTLN("Publishing device sensor config");
return publishJsonDocument(mqttClient, getHASensorConfigTopic(), json, true);
}
bool publishHATriggerDiscoveryConfig(PubSubClient &mqttClient) {
StaticJsonDocument<MAX_PACKET_SIZE> json;
bool abbrev = true;
// json["name"] = getDeviceHumanName();
json["atype"] = "trigger"; // automation_type
json["type"] = "button_short_press";
json["stype"] = "button_1"; // subtype
json["~"] = getButtonTopicBase(false);
json["t"] = getButtonTriggerTopic(abbrev); // topic
addDeviceJson(json);
PRINTLN("Publishing device trigger discovery");
return publishJsonDocument(mqttClient, getHATriggerConfigTopic(), json, true);
}

View File

@@ -0,0 +1,16 @@
#ifndef __MQTT_H_
#define __MQTT_H_
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
void initMqtt(PubSubClient& client, WiFiClient &wifiClient);
bool publishHABatteryDiscoveryConfig(PubSubClient &client);
bool publishHATriggerDiscoveryConfig(PubSubClient &client);
bool publishTriggerMessage(PubSubClient &client, String message);
bool publishBatteryMessage(PubSubClient &client, int percent);
#endif // __MQTT_H_

View File

@@ -0,0 +1,41 @@
#include "util.h"
#include "config.h"
#define DEVICE_NAME_PREFIX "button-"
#define PRINT_DELAY_MILLIS 500
String getDeviceId() {
return String(ESP.getChipId(), HEX);
}
String getDeviceMachineName() {
return String(DEVICE_NAME_PREFIX) + getDeviceId();
}
String getDeviceHumanName() {
return "IoT Button (" + getDeviceId() + ")";
}
void initWifi(WiFiClient &wifi) {
PRINT("Connecting to WiFi using MAC: ");
PRINTLN(WiFi.macAddress());
WiFi.hostname(getDeviceMachineName().c_str());
WiFi.begin(CONFIG_SSID, CONFIG_PSK);
long last_time = millis();
while (WiFi.status() != WL_CONNECTED) {
yield();
long time = millis();
if (time >= last_time + PRINT_DELAY_MILLIS) {
PRINT(".");
last_time = time;
}
}
PRINTLN("\nConnected!");
PRINT("IP Address: ");
PRINTLN(WiFi.localIP());
}

View File

@@ -0,0 +1,21 @@
#ifndef __UTIL_H_
#define __UTIL_H_
#include <Arduino.h>
#include <ESP8266WiFi.h>
#ifdef DEBUG_SKETCH
#define PRINT(x) { Serial.print(x); } while (0)
#define PRINTLN(x) { Serial.println(x); } while (0)
#else
#define PRINT(x)
#define PRINTLN(x)
#endif
String getDeviceHumanName();
String getDeviceMachineName();
String getDeviceId();
void initWifi(WiFiClient &wifi);
#endif // __UTIL_H_

View File

@@ -0,0 +1,11 @@
This directory is intended for PlatformIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html