Skip to content

Commit

Permalink
implemented WPS button and status LED; refactored NetManager class; i…
Browse files Browse the repository at this point in the history
…mplemented WiFiManager class
  • Loading branch information
genemars committed Feb 16, 2019
1 parent 3c97038 commit aab1183
Show file tree
Hide file tree
Showing 18 changed files with 256 additions and 143 deletions.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Expand Up @@ -51,7 +51,7 @@ add_custom_target(
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)

add_executable(${PROJECT_NAME} ${SRC_LIST} src/io/IOManager.cpp src/io/IOManager.h src/net/HTTPServer.cpp src/net/HTTPServer.h src/net/NetManager.cpp src/net/NetManager.h src/io/Logger.cpp src/io/Logger.h src/scripting/ProgramEngine.cpp src/scripting/ProgramEngine.h src/io/env/LightSensor.cpp src/io/env/LightSensor.h src/io/env/DS18B20.cpp src/io/env/DS18B20.h src/service/api/APIRequest.cpp src/service/api/APIRequest.h src/TaskManager.cpp src/TaskManager.h src/Task.cpp src/Task.h src/net/MQTTServer.cpp src/net/MQTTServer.h src/net/mqtt/MQTTBrokerConfig.cpp src/net/mqtt/MQTTBrokerConfig.h src/io/rf/x10/X10Message.cpp src/io/rf/x10/X10Message.h src/io/sys/Diagnostics.cpp src/io/sys/Diagnostics.h src/io/IOEvent.h src/io/IOEventDomains.h src/io/IOEventPaths.h src/service/EventRouter.cpp src/service/EventRouter.h src/service/api/APIHandler.h src/service/api/X10Handler.cpp src/service/api/X10Handler.h src/Utility.cpp src/Utility.h src/service/api/HomeGenieHandler.cpp src/service/api/HomeGenieHandler.h src/service/defs.h src/io/gpio/P1Port.cpp src/io/gpio/P1Port.h src/io/IOModule.cpp src/io/IOModule.h)
add_executable(${PROJECT_NAME} ${SRC_LIST} src/io/IOManager.cpp src/io/IOManager.h src/net/HTTPServer.cpp src/net/HTTPServer.h src/net/NetManager.cpp src/net/NetManager.h src/io/Logger.cpp src/io/Logger.h src/scripting/ProgramEngine.cpp src/scripting/ProgramEngine.h src/io/env/LightSensor.cpp src/io/env/LightSensor.h src/io/env/DS18B20.cpp src/io/env/DS18B20.h src/service/api/APIRequest.cpp src/service/api/APIRequest.h src/TaskManager.cpp src/TaskManager.h src/Task.cpp src/Task.h src/net/MQTTServer.cpp src/net/MQTTServer.h src/net/mqtt/MQTTBrokerConfig.cpp src/net/mqtt/MQTTBrokerConfig.h src/io/rf/x10/X10Message.cpp src/io/rf/x10/X10Message.h src/io/sys/Diagnostics.cpp src/io/sys/Diagnostics.h src/io/IOEvent.h src/io/IOEventDomains.h src/io/IOEventPaths.h src/service/EventRouter.cpp src/service/EventRouter.h src/service/api/APIHandler.h src/service/api/X10Handler.cpp src/service/api/X10Handler.h src/Utility.cpp src/Utility.h src/service/api/HomeGenieHandler.cpp src/service/api/HomeGenieHandler.h src/service/defs.h src/io/gpio/P1Port.cpp src/io/gpio/P1Port.h src/io/IOModule.cpp src/io/IOModule.h src/net/WiFiManager.cpp src/net/WiFiManager.h src/Config.h)

include_directories(./.piolibdeps/ArduinoJson_ID64)
include_directories(./.piolibdeps/ArduinoLog_ID1532)
Expand Down
18 changes: 18 additions & 0 deletions src/Config.h
@@ -0,0 +1,18 @@
//
// Created by gene on 16/02/19.
//

#ifndef HOMEGENIE_MINI_CONFIG_H
#define HOMEGENIE_MINI_CONFIG_H

#include <Arduino.h>

class Config {
public:
const static uint8_t ServiceButtonPin = D4;
const static uint8_t StatusLedPin = D0;
const static uint16_t WpsModePushInterval = 2500;
const static bool X10RFReceiverEnabled = false;
};

#endif //HOMEGENIE_MINI_CONFIG_H
15 changes: 14 additions & 1 deletion src/Task.h
Expand Up @@ -37,11 +37,24 @@
class Task {
public:
Task();
/**
* Task loop() entry point. This is called by the TaskManager when the task is scheduled.
*/
virtual void loop() = 0;
/**
* If the task loop() is scheduled.
* @return `true` if scheduled, `false` otherwise.
*/
bool willLoop();
void setLoopInterval(uint64_t interval) { loopInterval = interval; };
/**
* Set task loop() schedule interval.
* @param interval_ms schedule interval in milliseconds.
*/
void setLoopInterval(uint64_t interval_ms) { loopInterval = interval_ms; };

/// Pointer to the next task
Task* nextTask = NULL;
/// Pointer to the previous task
Task* previousTask = NULL;

void loopExit();
Expand Down
8 changes: 4 additions & 4 deletions src/io/IOManager.cpp
Expand Up @@ -36,9 +36,9 @@ namespace IO {
systemDiagnostics = new System::Diagnostics();
systemDiagnostics->setEventReceiver(this);
// Instantiate the X10 RFReceiver Class
// RFReceiverConfig x10ReceiverConfig = RFReceiverConfig(CONFIG_RF_RX_PIN);
// x10Receiver = new RFReceiver(&x10ReceiverConfig);
// x10Receiver->setEventReceiver(this);
RFReceiverConfig x10ReceiverConfig = RFReceiverConfig(CONFIG_RF_RX_PIN);
x10Receiver = new RFReceiver(&x10ReceiverConfig);
x10Receiver->setEventReceiver(this);
// X10 RF RFReceiver and RFTransmitter objects
RFTransmitterConfig x10TransmitterConfig = RFTransmitterConfig(CONFIG_RF_TX_PIN);
x10Transmitter = new RFTransmitter(&x10TransmitterConfig);
Expand All @@ -54,7 +54,7 @@ namespace IO {
}

void IOManager::begin() {
// x10Receiver->begin();
x10Receiver->begin();
x10Transmitter->begin();
temperatureSensor->begin();
lightSensor->begin();
Expand Down
2 changes: 1 addition & 1 deletion src/io/env/DS18B20.cpp
Expand Up @@ -97,7 +97,7 @@ namespace IO { namespace Env {
byte MSB = data[1];
byte LSB = data[0];

return ((MSB << 8) | LSB) / 16.0f;
return (((MSB << 8) | LSB) / 16.0f) + DS18B20_MEASURE_OFFSET;
}

void DS18B20::setInputPin(const uint8_t pinNumber) {
Expand Down
2 changes: 2 additions & 0 deletions src/io/env/DS18B20.h
Expand Up @@ -43,6 +43,8 @@
#define DS18B20_NS_PREFIX "IO::Env::DS18B10"
#define DS18B20_SAMPLING_RATE 60000L
#define DS18B20_READ_ERROR -1000
// TODO: maybe put this as a configurable parameter through API
#define DS18B20_MEASURE_OFFSET (float_t)-7.0

namespace IO { namespace Env {

Expand Down
15 changes: 8 additions & 7 deletions src/io/rf/x10/RFReceiver.cpp
Expand Up @@ -28,6 +28,7 @@
*/

#include <service/defs.h>
#include <Config.h>
#include "RFReceiver.h"

namespace IO { namespace X10 {
Expand All @@ -54,15 +55,15 @@ namespace IO { namespace X10 {
//////////////////////////////

void RFReceiver::begin() {
Logger::info("| - %s (PIN=%d INT=%d)", X10_RFRECEIVER_NS_PREFIX, configuration->getPin(), configuration->getInterrupt());
pinMode(configuration->getPin(), INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(configuration->getInterrupt()), receiverInstance_wrapper, RISING);
Logger::info("| ✔ %s", X10_RFRECEIVER_NS_PREFIX);
if (Config::X10RFReceiverEnabled) {
Logger::info("| - %s (PIN=%d INT=%d)", X10_RFRECEIVER_NS_PREFIX, configuration->getPin(),
configuration->getInterrupt());
pinMode(configuration->getPin(), INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(configuration->getInterrupt()), receiverInstance_wrapper, RISING);
Logger::info("| ✔ %s", X10_RFRECEIVER_NS_PREFIX);
}
}

uint8_t messageType = 0x00;
uint8_t byteBuffer[4];

void RFReceiver::receive() {
//if (!isEnabled()) return;

Expand Down
2 changes: 2 additions & 0 deletions src/io/rf/x10/RFReceiver.h
Expand Up @@ -55,6 +55,8 @@ namespace IO { namespace X10 {
private:
RFReceiverConfig *configuration;
// 32-bit RF message decoding
volatile uint8_t messageType = 0x00;
volatile uint8_t byteBuffer[4];
volatile uint32_t riseUs;
volatile int8_t receivedCount;
volatile uint32_t receiveBuffer;
Expand Down
2 changes: 0 additions & 2 deletions src/io/rf/x10/RFTransmitter.cpp
Expand Up @@ -92,10 +92,8 @@ namespace IO { namespace X10 {
}

void RFTransmitter::sendByte(uint8_t data) {
//Serial.println("\n");
for (int i = 7; i >= 0; i--) { // send bits from byte
sendBit(bitRead(data, i) == 1);
//Serial.print(bitRead(data,i));
}
}

Expand Down
14 changes: 7 additions & 7 deletions src/io/rf/x10/RFTransmitterConfig.cpp
Expand Up @@ -48,14 +48,14 @@ namespace IO { namespace X10 {
{
this->pin = pin;
}
uint8_t RFTransmitterConfig::getPin() { return this->pin; };
uint8_t RFTransmitterConfig::getSendRepeat() { return this->sendRepeat; };
uint16_t RFTransmitterConfig::getStartBustLong() { return this->startBustLong; };
uint16_t RFTransmitterConfig::getStartBustShort() { return this->startBustShort; };
uint8_t RFTransmitterConfig::getPin() { return pin; };
uint8_t RFTransmitterConfig::getSendRepeat() { return sendRepeat; };
uint16_t RFTransmitterConfig::getStartBustLong() { return startBustLong; };
uint16_t RFTransmitterConfig::getStartBustShort() { return startBustShort; };

uint16_t RFTransmitterConfig::getBitLong() { return this->bitLong; };
uint16_t RFTransmitterConfig::getBitShort() { return this->bitShort; };
uint16_t RFTransmitterConfig::getBitLong() { return bitLong; };
uint16_t RFTransmitterConfig::getBitShort() { return bitShort; };

uint16_t RFTransmitterConfig::getPacketGap() { return this->packetGap; };
uint16_t RFTransmitterConfig::getPacketGap() { return packetGap; };

}} // ns
46 changes: 42 additions & 4 deletions src/main.cpp
Expand Up @@ -29,11 +29,13 @@

#include <Arduino.h>

#include <net/WiFiManager.h>
#include <net/NetManager.h>
#include <io/Logger.h>
#include <scripting/ProgramEngine.h>

#include "service/HomeGenie.h"
#include "Config.h"
#include <TaskManager.h>

#define HOMEGENIE_MINI_VERSION "1.0"
Expand All @@ -44,12 +46,46 @@ using namespace Service;

HomeGenie homeGenie;

volatile int64_t buttonPressStart = -1;
volatile bool buttonPressed = false;
void buttonChange() {
buttonPressed = (digitalRead(Config::ServiceButtonPin) == LOW);
if (buttonPressed) {
buttonPressStart = millis();
}
}
void checkServiceButton() {
int64_t elapsed = 0;
if (buttonPressed) {
// released
elapsed = millis() - buttonPressStart;
if (elapsed > Config::WpsModePushInterval) {
homeGenie.getNetManager().getWiFiManager().startWPS();
}
}
}
bool statusLedOn = false;
uint64_t statusLedTs = 0;
void statusLedLoop() {
if (millis() - statusLedTs > 950 && !statusLedOn) {
statusLedOn = true;
digitalWrite(Config::StatusLedPin, HIGH);
statusLedTs = millis();
} else if (statusLedOn && millis() - statusLedTs > 50) {
statusLedOn = false;
digitalWrite(Config::StatusLedPin, LOW);
statusLedTs = millis();
}
}

/// This gets called just before the main application loop()
void setup() {

// Turn off built-in LED
pinMode(D4, OUTPUT);
digitalWrite(D4, HIGH);
// Setup status led
pinMode(Config::StatusLedPin, OUTPUT);
// Setup button
pinMode(Config::ServiceButtonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(Config::ServiceButtonPin), buttonChange, CHANGE);

// Logger initialization
Logger::begin(LOG_LEVEL_TRACE);
Expand All @@ -68,7 +104,9 @@ void setup() {
/// Main application loop
void loop()
{
// TODO: sort of Load index could be obtained by measuring time elapsed for `TaskManager::loop()` method
statusLedLoop();
checkServiceButton();
// TODO: sort of system load index could be obtained by measuring time elapsed for `TaskManager::loop()` method
TaskManager::loop();
}

Expand Down
79 changes: 18 additions & 61 deletions src/net/NetManager.cpp
Expand Up @@ -27,15 +27,13 @@
*
*/

#include <service/HomeGenie.h>
#include <Config.h>
#include "NetManager.h"

namespace Net {

using namespace IO;

HTTPServer httpServer;

// Time sync
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
Expand All @@ -48,55 +46,8 @@ namespace Net {

Logger::info("+ Starting NetManager");

// WI-FI will not boot without this delay!!!
delay(2000);

Logger::infoN("| - Connecting to WI-FI .");
// WPS works in STA (Station mode) only -> not working in WIFI_AP_STA !!!
WiFi.mode(WIFI_STA);
delay(1000); // TODO: is this delay necessary?

// WiFi.begin("foobar",""); // make a failed connection
WiFi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str());
while (WiFi.status() == WL_DISCONNECTED) {
delay(2000);
Serial.print(".");
}
Serial.println();

bool wpsSuccess;
wl_status_t status = WiFi.status();
if (status == WL_CONNECTED) {
Logger::info("| ✔ Connected to '%s'", WiFi.SSID().c_str());
wpsSuccess = true;
} else {
Logger::error("| ! Not connected to WiFi (state='%d')", status);
Logger::info ("| >> Press WPS button on your router <<");
//while(!Serial.available()) { ; }
//if(!startWPSPBC()) {
// Serial.println("Failed to connect with WPS :-(");
//}
wpsSuccess = WiFi.beginWPSConfig();
if (wpsSuccess) {
// Well this means not always success :-/ in case of a timeout we have an empty ssid
String newSSID = WiFi.SSID();
if (newSSID.length() > 0) {
// WPSConfig has already connected in STA mode successfully to the new station.
Logger::info("| ✔ Successfully connected to '%s'", newSSID.c_str());
// save to config and use next time or just use - WiFi.begin(WiFi.SSID().c_str(),WiFi.psk().c_str());
//qConfig.wifiSSID = newSSID;
//qConfig.wifiPWD = WiFi.psk();
//saveConfig();
} else {
wpsSuccess = false;
}
}

}

if (wpsSuccess) {
Logger::info("| ✔ IP: %s", WiFi.localIP().toString().c_str());
}
wiFiManager = new WiFiManager();
bool wpsSuccess = wiFiManager->checkWiFiStatus();

httpServer = new HTTPServer();
httpServer->begin();
Expand Down Expand Up @@ -142,31 +93,37 @@ namespace Net {
webSocket->loop();

if (WiFi.isConnected() && !timeClient.update()) {
digitalWrite(Config::StatusLedPin, HIGH);
timeClient.forceUpdate();
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
formattedDate = timeClient.getFormattedDate();
Logger::info("NTP Time: %s", formattedDate.c_str());
digitalWrite(Config::StatusLedPin, LOW);
}

Logger::verbose("%s loop() << END", NETMANAGER_LOG_PREFIX);
}

HTTPServer* NetManager::getHttpServer() {
return httpServer;
WiFiManager& NetManager::getWiFiManager() {
return *wiFiManager;
}

MQTTServer* NetManager::getMQTTServer() {
return mqttServer;
HTTPServer& NetManager::getHttpServer() {
return *httpServer;
}

WebSocketsServer* NetManager::getWebSocketServer() {
return webSocket;
MQTTServer& NetManager::getMQTTServer() {
return *mqttServer;
}

NetManager::NetManager() {
WebSocketsServer& NetManager::getWebSocketServer() {
return *webSocket;
}

NetManager::NetManager() {
// TODO: ...
}
NetManager::~NetManager() {
// TODO: !!!! IMPLEMENT DESTRUCTOR AS WELL FOR HttpServer and MQTTServer classes
Expand All @@ -175,8 +132,8 @@ namespace Net {
delete webSocket;
}

NTPClient NetManager::getTimeClient() {
NTPClient& NetManager::getTimeClient() {
return timeClient;
}

}
}

0 comments on commit aab1183

Please sign in to comment.