Initial commit

This commit is contained in:
Adam Bissen 2021-05-22 19:55:17 -05:00
parent 3785675c9f
commit 1988b2957b
8 changed files with 363 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}

39
include/README Normal file
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

46
lib/README Normal file
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

18
platformio.ini Normal file
View File

@ -0,0 +1,18 @@
; 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:esp32dev]
platform = espressif32
board = nodemcu-32s
framework = arduino
lib_deps =
knolleary/PubSubClient@^2.8
bblanchon/ArduinoJson@^6.18.0
fastled/FastLED@^3.4.0

235
src/main.cpp Normal file
View File

@ -0,0 +1,235 @@
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <FastLED.h>
#include <SPI.h>
#include <SD.h>
char* config_filename = "/config.txt";
struct wifi_config_struct
{
char ssid[32];
char password[16];
char ip[16];
char mask[16];
char gateway[16];
char dns1[16];
char dns2[16];
};
wifi_config_struct wifi_config;
// Load configuration file from SD card
void loadconfig(const char* filename) {
Serial.println(F("Loading configuration file."));
File file = SD.open(filename);
StaticJsonDocument<512> jsonBuffer;
DeserializationError error = deserializeJson(jsonBuffer, file);
if (error) {
Serial.print(F("Unable to deserialize JSON config file."));
Serial.println(error.f_str());
} else {
strcpy(wifi_config.ssid, jsonBuffer["wifi"]["ssid"] | "defualtSSID");
strcpy(wifi_config.password, jsonBuffer["wifi"]["password"] | "");
strcpy(wifi_config.ip, jsonBuffer["wifi"]["ip"] | "");
strcpy(wifi_config.mask, jsonBuffer["wifi"]["mask"] | "");
strcpy(wifi_config.gateway, jsonBuffer["wifi"]["gateway"] | "");
strcpy(wifi_config.dns1, jsonBuffer["wifi"]["dns1"] | "");
strcpy(wifi_config.dns2, jsonBuffer["wifi"]["dns2"] | "");
}
file.close();
}
// Setup for addressable RGB LED's
#define num_leds 9
#define data_pin 4
CRGB leds[num_leds];
//Initialize WiFi Function
void initWiFi() {
// Set Static IP address
IPAddress local_IP;
local_IP.fromString(wifi_config.ip);
// Set Gateway IP address
IPAddress gateway;
gateway.fromString(wifi_config.gateway);
IPAddress subnet;
subnet.fromString(wifi_config.mask);
IPAddress primaryDNS; // optional
primaryDNS.fromString(wifi_config.dns1);
IPAddress secondaryDNS; // optional
secondaryDNS.fromString(wifi_config.dns2);
// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println(F("STA Failed to configure"));
}
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_config.ssid, wifi_config.password);
Serial.print(F("Connecting to WiFi .."));
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println();
Serial.print(F("IP Address: "));
Serial.println(WiFi.localIP());
}
// Variable for Power Usage
char mqtt_topic[64] = "";
float mqtt_payload_value = 0;
void printBuffers() {
Serial.print("MQTT_Topic: ");
Serial.println(mqtt_topic);
Serial.print("Value: ");
Serial.println(mqtt_payload_value);
}
// Callback to process MQTT payload
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived!");
StaticJsonDocument<64> doc;
DeserializationError error = deserializeJson(doc, payload, length);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
} else {
mqtt_payload_value = doc["value"];
Serial.println(mqtt_payload_value);
strcpy(mqtt_topic, topic);
}
printBuffers();
}
//Configure MQTT
WiFiClient wifi_client;
IPAddress mqtt_server(192, 168, 1, 10);
PubSubClient mqtt_client(mqtt_server, 1883, callback, wifi_client);
// Connect to MQTT Server and subscrib to topics
void reconnect_mqtt() {
while (!mqtt_client.connected()) {
Serial.println(F("Attempting MQTT connection"));
if (mqtt_client.connect("ESP32")) {
Serial.println("MQTT Connected!");
mqtt_client.subscribe("zwave/nodeID_7/50/0/value/66049");
} else {
Serial.println(F("MQTT Connection Failed. Trying again."));
delay(250);
}
}
}
void setup() {
// Configure Serial
Serial.begin(9600);
delay(1000);
//Initialize SD card. Pin 5 is slave select for SD card
Serial.println(F("Initializing SD card"));
if (!SD.begin(5)) {
Serial.println(F("Initialization failed!"));
while (1);
}
Serial.println(F("SD card Initialization success!"));
loadconfig(config_filename);
SD.end();
// Setup LED's
FastLED.addLeds<NEOPIXEL, data_pin>(leds, num_leds);
// Configure Pins
pinMode(2, OUTPUT);
// Connect to WiFi
initWiFi();
//Connect to MQTT Server
if (!mqtt_client.connected()) {
reconnect_mqtt();
}
// Create initial LED Pattern
for (int i = 0; i < sizeof(leds); i++) {
int mod = i % 7;
if ( mod == 0) {
leds[i] = CRGB::Red;
} else if (i == 1) {
leds[i] = CRGB::Orange;
} else if (i == 2) {
leds[i] = CRGB::Yellow;
} else if (i == 3) {
leds[i] = CRGB::Green;
} else if (i == 4) {
leds[i] = CRGB::Blue;
} else if (i == 5) {
leds[i] = CRGB::Indigo;
} else if (i == 6) {
leds[i] = CRGB::Violet;
}
}
FastLED.show();
}
void ESP_LED_flash() {
static boolean LED_flag = true;
static unsigned long LED_timer = millis();
// Change LED state every 250ms
if (millis() - LED_timer >= 250) {
LED_timer = millis();
if (LED_flag) {
digitalWrite(2, HIGH);
} else {
digitalWrite(2, LOW);
}
LED_flag = !LED_flag;
}
}
void loop() {
static unsigned int initial_hue = 0;
const unsigned int hue_diff = 12;
ESP_LED_flash();
static unsigned long fastled_timer = millis();
if (millis() - fastled_timer >= 20) {
fastled_timer = millis();
fill_rainbow(leds, num_leds, initial_hue, hue_diff);
initial_hue += hue_diff;
Serial.println("Updating LED Strip");
FastLED.show();
}
//Connect to MQTT Server
if (!mqtt_client.connected()) {
reconnect_mqtt();
}
// Process MQTT packets
mqtt_client.loop();
}

11
test/README Normal file
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