#include "commu_task.h"

#include "semaphore_guard.h"

static  byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};

WiFiClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HASensor angle("angle");

CommuTask::CommuTask(const uint8_t task_core) : Task{"Communication", 4048, 1, task_core} {
  knob_state_queue_ = xQueueCreate(1, sizeof(KnobState));
  assert(knob_state_queue_ != NULL);
  mutex_ = xSemaphoreCreateMutex();
  assert(mutex_ != NULL);
}

CommuTask::~CommuTask()
{
  vQueueDelete(knob_state_queue_);
  vSemaphoreDelete(mutex_);
}


QueueHandle_t CommuTask::getKnobStateQueue() {
  return knob_state_queue_;
}

void CommuTask::setAngleValue(uint32_t angle)
{
  angle_ = angle;
  //log_d("setAngleCalled = %u", angle);
}

void CommuTask::run() {

  WiFi.begin("poes", "Rijnstraat214");
  while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

  KnobState state;

  device.setName("SmartKnob001");
  device.setSoftwareVersion("1.0.0");

  angle.setUnitOfMeasurement("°");
  angle.setDeviceClass("None");
  angle.setName("SmartKnob Angle");

  mqtt.begin(BROKER_ADDR, BROKER_USERNAME, BROKER_PASSWORD);

  uint32_t lastSensorUpdate = millis();
  angle.setValue(angle_);

  if(mqtt.isConnected())
  {
    printf("mqtt connected");
  }
  else{
    printf("mqtt NOT connected");

  }

  while(1)
  {
    if (xQueueReceive(knob_state_queue_, &state, portMAX_DELAY) == pdFALSE) {
      continue;
    }

    if(millis() - lastSensorUpdate > 1000)
    {
      angle.setValue(state.current_position);
      log_d("new angle=%u", state.current_position);
      lastSensorUpdate = millis();

    }

    mqtt.loop();
    delay(10);

  }
}
