#include "MainDevice.h"

MainDevice::MainDevice(/* args */)
{
}

MainDevice::~MainDevice()
{
}

ArduinoQueue<String> MyQueue(MAXITEMS, MAXMEMORY);

void TaskMqttPublish(void *pvParameters)
{
    while (true)
    {
        while (MyQueue.itemCount() > 0)
        {
            String res = MyQueue.dequeue();
            myJson.ParseJson(res);
            _mqttHelper.publish(myJson.StatusDataReport());
            _mqttHelper.Loop();
            vTaskDelay(1);
        }
        _mqttHelper.Loop();
        vTaskDelay(10);
    }
}

void MainDevice::Init()
{
    Serial2.begin(115200); // lora 模块通讯串口
    Serial.begin(115200);  //消息日志串口
    pinMode(2, OUTPUT);
    _mqttHelper.Init();
    digitalWrite(2, 1);
    xTaskCreatePinnedToCore(TaskMqttPublish, "MqttHelt", 4096, NULL, 1, &MqttTest, 0);
}

void MainDevice::Start()
{
    digitalWrite(2, 0);
    String res;
    Delay mydelay;
    bool StartRevice = false;
    while (true)
    {
        if (Serial2.available() > 0)
        {
            char resRead = (char)Serial2.read();
            if (StartRevice && resRead == 'B')
            {
                MyQueue.enqueue(res);
                digitalWrite(2, 1);
                return;
            }
            if (StartRevice)
                res += resRead;
            if (resRead == 'A')
                StartRevice = true;
        }
        if (mydelay.Start(true, 2))
        {
            return;
        }
    }
}

MainDevice _mainDevice;