#include <Arduino.h>
#include <ittiot.h>
#include <ClickEncoder.h>
 
#define WIFI_NAME "TalTech"
#define WIFI_PASSWORD ""
 
#define ENC_PINA 12
#define ENC_PINB 13
#define ENC_BTN   0
#define ENC_STEPS_PER_NOTCH 4
 
ClickEncoder encoder = ClickEncoder(ENC_PINA, ENC_PINB, ENC_BTN, ENC_STEPS_PER_NOTCH);
 
#define LEVEL_MIN 0
#define LEVEL_MAX 255
#define LEVEL_DEFAULT 127
#define LEVEL_STEP 4
int32_t level = LEVEL_DEFAULT;
 
void iot_connected()
{
  Serial.println("MQTT connected callback");
}
 
void setup()
{
  // Initialize serial port and send message
  Serial.begin(115200); // setting up serial connection parameter
  Serial.println("Booting");
 
  iot.setConfig("wname", WIFI_NAME);
  iot.setConfig("wpass", WIFI_PASSWORD);
  iot.setConfig("msrv", "193.40.245.72");
  iot.setConfig("mport", "1883");
  iot.setConfig("muser", "test");
  iot.setConfig("mpass", "test");
  iot.printConfig(); // print IoT json config to serial
  iot.setup(); // Initialize IoT library
}

void loop()
{
  iot.handle(); // IoT behind the plan work, it should be periodically called
  delay(5);
  encoder.service();
 
  static int16_t oldPosition, newPosition;
  newPosition += encoder.getValue(); // Read encoder value
 
  char StrBuf[16];
  if(newPosition > oldPosition)
  {
    if(level != LEVEL_MAX) 
    {
      level += LEVEL_STEP;
      if(level > LEVEL_MAX) level = LEVEL_MAX;
      sprintf(StrBuf, "%d", level);
      iot.publishMsg("light_level", StrBuf);
    }
  }
  else if (newPosition < oldPosition)
  {
    if(level != LEVEL_MIN)
    {
      level -= LEVEL_STEP;
      if(level < LEVEL_MIN) level = LEVEL_MIN;
      sprintf(StrBuf, "%d", level);
      iot.publishMsg("light_level", StrBuf);
    }
  }
  oldPosition = newPosition;
}