Control using both Blynk & RF Remote

I am trying to control a relay with both Blynk and an RF remote. You can see in the Loop section of the code I inserted some RF code that seems to work when Blynk is connected. The problem I am having is if Blynk isn’t connected the RF remote won’t control the dimmer.

Second problem I am having is turning the pin high or low ONLY while the RF remote is being pressed.


#include <FS.h>
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <WidgetRTC.h>
#include <TimeLib.h>

#include "WemoSwitch.h"
#include "WemoManager.h"
#include "CallbackFunction.h"

#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <RCSwitch.h>

//on/off callbacks
void DimmerOn();
void DimmerOff();

WemoManager wemoManager;
WemoSwitch *Dimmer = NULL;

RCSwitch mySwitch = RCSwitch();
BlynkTimer timer;
WidgetRTC rtc;
int timerID =1;

char blynk_token[34] = "*************************";
char name[9] ;
char currentTime[9];
bool clockSync = false;    
bool shouldSaveConfig = false;
    void saveConfigCallback () {
      Serial.println("Should save config");
      shouldSaveConfig = true;
    }
void setup(){
  Serial.begin(74880);
  Serial.println();
  mySwitch.enableReceive(12);
    snprintf(name, 15, "Dimmer_%s", blynk_token);

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          strcpy(blynk_token, json["blynk_token"]);

        } else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  
  //add all your parameters here
  wifiManager.addParameter(&custom_blynk_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 10%
  wifiManager.setMinimumSignalQuality();
  
  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect(name, "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

  //read updated parameters
  strcpy(blynk_token, custom_blynk_token.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["blynk_token"] = blynk_token;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  
  wemoManager.begin();
  // Format: Alexa invocation name, local port no, on callback, off callback
  Dimmer = new WemoSwitch("Dimmer", 81, DimmerOn, DimmerOff);
  wemoManager.addDevice(*Dimmer);

  ArduinoOTA.setHostname(name);
  ArduinoOTA.begin();
  
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  digitalWrite(4, HIGH); 
  digitalWrite(5, HIGH);

    Blynk.config(blynk_token);
    Blynk.connect();  // try to connect to server with default timeout
    rtc.begin();
    
  setSyncInterval(360);
  timer.setInterval(59000L, activetoday);  // Update Time Check every 59 seconds
}

void activetoday(){         // check if schedule #1 should run today
  if(year() != 1970){
    Blynk.syncVirtual(V1);  // sync scheduler #1  
    Blynk.syncVirtual(V2);  // sync scheduler #2  
    Blynk.syncVirtual(V9);  // sync scheduler #3  
    Blynk.syncVirtual(V10); // sync scheduler #4  
  }
}
BLYNK_WRITE(V1) {   // Scheduler #1 Time Input widget  
  TimeInputParam t(param);
int nowseconds = ((hour() * 3600) + (minute() * 60) + second());
int startseconds = (t.getStartHour() * 3600) + (t.getStartMinute() * 60);  
int stopseconds = (t.getStopHour() * 3600) + (t.getStopMinute() * 60);
  int dayadjustment = -1;  
  if(weekday() == 1){
    dayadjustment = 6; // needed for Sunday Time library is day 1 and Blynk is day 7
  }
  if(t.isWeekdaySelected((weekday() + dayadjustment))){ //Time library starts week on Sunday, Blynk on Monday  
    //Schedule is ACTIVE today 
    if(nowseconds >= startseconds - 30 && nowseconds <= startseconds + 30 ){    // 62s on 60s timer ensures 1 trigger command is sent
      Serial.println("Dimmer Opening... 1");
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, OpenDimmer);
    }               
  }
}

BLYNK_WRITE(V2) {   // Scheduler #2 Time Input widget  
  TimeInputParam t(param);
int nowseconds = ((hour() * 3600) + (minute() * 60) + second());
int startseconds = (t.getStartHour() * 3600) + (t.getStartMinute() * 60);  
int stopseconds = (t.getStopHour() * 3600) + (t.getStopMinute() * 60);
  int dayadjustment = -1;  
  if(weekday() == 1){
    dayadjustment = 6; // needed for Sunday Time library is day 1 and Blynk is day 7
  }
  if(t.isWeekdaySelected((weekday() + dayadjustment))){ //Time library starts week on Sunday, Blynk on Monday  
    //Schedule is ACTIVE today 
    if(nowseconds >= startseconds - 30 && nowseconds <= startseconds + 30 ){    // 62s on 60s timer ensures 1 trigger command is sent
      Serial.println("Dimmer Opening... 2");
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, OpenDimmer);
    }               
  }
}

BLYNK_WRITE(V9) {   // Scheduler #3 Time Input widget  
  TimeInputParam t(param);
int nowseconds = ((hour() * 3600) + (minute() * 60) + second());
int startseconds = (t.getStartHour() * 3600) + (t.getStartMinute() * 60);  
int stopseconds = (t.getStopHour() * 3600) + (t.getStopMinute() * 60);
  int dayadjustment = -1;  
  if(weekday() == 1){
    dayadjustment = 6; // needed for Sunday Time library is day 1 and Blynk is day 7
  }
  if(t.isWeekdaySelected((weekday() + dayadjustment))){ //Time library starts week on Sunday, Blynk on Monday  
    //Schedule is ACTIVE today 
    if(nowseconds >= startseconds - 30 && nowseconds <= startseconds + 30 ){    // 62s on 60s timer ensures 1 trigger command is sent
  Serial.println("Dimmer Closing... 3");
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, CloseDimmer);
    }               
  }
}

BLYNK_WRITE(V10) {   // Scheduler #4 Time Input widget  
  TimeInputParam t(param);
int nowseconds = ((hour() * 3600) + (minute() * 60) + second());
int startseconds = (t.getStartHour() * 3600) + (t.getStartMinute() * 60);  
int stopseconds = (t.getStopHour() * 3600) + (t.getStopMinute() * 60);
  int dayadjustment = -1; 
      Serial.println(String("Time zone: ") + t.getTZ()); // Timezone is already added to start/stop time 
    Serial.println(String("Time zone offset: ") + t.getTZ_Offset()); // Get timezone offset (in seconds) 
  if(weekday() == 1){
    dayadjustment = 6; // needed for Sunday Time library is day 1 and Blynk is day 7
  }
  if(t.isWeekdaySelected((weekday() + dayadjustment))){ //Time library starts week on Sunday, Blynk on Monday  
    //Schedule is ACTIVE today 
    if(nowseconds >= startseconds - 30 && nowseconds <= startseconds + 30 ){    // 62s on 60s timer ensures 1 trigger command is sent
  Serial.println("Dimmer Closing... 4");
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, CloseDimmer);
    }               
  }
}

BLYNK_WRITE(V4) { // Open Dimmer
    digitalWrite(5, HIGH);
    digitalWrite(4, LOW);
     if (param.asInt() == 0) {
      digitalWrite(4, HIGH);
    };
}

BLYNK_WRITE(V5) { // Close Dimmer
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
     if (param.asInt() == 0) {
      digitalWrite(5, HIGH);
    };
}

BLYNK_WRITE(V6) { 
  Serial.println("Dimmer Closing...");
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, CloseDimmer);
}

void CloseDimmer() {
    digitalWrite(5, HIGH);
    Blynk.virtualWrite(V6, HIGH);
    Serial.println("Dimmer Closed");
}

BLYNK_WRITE(V7) { 
  Serial.println("Dimmer Opening...");
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, OpenDimmer);
}

void OpenDimmer() {
    digitalWrite(4, HIGH);
    Blynk.virtualWrite(V7, HIGH);
    Serial.println("Dimmer Opened");
}

void DimmerOn() {    // alexa open command
    Serial.print("Alexa Dimmer Opening...");
  digitalWrite(5, HIGH);
  digitalWrite(4, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, OpenDimmer);
}

void DimmerOff() {    // alexa close command
    Serial.print("Alexa Dimmer Closing...");
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  timer.deleteTimer(timerID);
  timerID = timer.setTimeout(16000, CloseDimmer);
}

int start = 0;
BLYNK_WRITE(V20)  {
    if (param.asInt()) {
       //button pressed
        start = millis();
    } else {
       //button released
          if (millis() - start > 5000) {
                Serial.println("Reset WiFi...");
                WiFi.disconnect(true);
                delay(5000);
                ESP.reset();
          }
    }
    
}

void loop() {
    if (mySwitch.available()) {
    int value = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 8354) {
DimmerOff();}
    mySwitch.resetAvailable();
    }
    ArduinoOTA.handle();
    Blynk.run();
    timer.run();
    wemoManager.serverLoop();
}