//
// Created by zx on 2019/12/9.
//

#ifndef PLC_DATA_H
#define PLC_DATA_H
#include <iostream>
#include <string>
#include <mutex>
#include <atomic>
#include "../tool/thread_condition.h"
#include <thread>
#include "../snap7_communication/s7_plc.h"
#include "unistd.h"
//#include "define.h"
#include "glog/logging.h"

#define MAX_REGIONS 6
#define ELE_FENCE_BOUNDARY_START_ADDR 3
#define ELE_FENCE_DB_NUM 95
#define ELE_FENCE_OFFSET 7
#define ELE_FENCE_COUNT 6

#define CENTRAL_CONTROLLER_DB_NUM 41
#define DOOR_STATUS_OFFSET 18


class Plc_data
{
public:
    // 获取plc通信类单例
    static Plc_data *get_instance(std::string ip = "");
    // static void Release();
    // 更新区域状态数据
    void update_data(int state_code, int border_status, int id);
    // plc更新线程
    static void plc_update_thread(Plc_data *p);
    // 获取plc实时状态
    bool get_plc_status();

public:
    std::atomic<bool> mb_is_ready; // 状态正常与否

private:
    static Plc_data *g_ins;   // 全局Plc_data实例
    static std::mutex g_lock; // 全局Plc_data实例访问互斥锁

    Thread_condition m_cond_exit;                // 系统关闭标志
    std::thread *mp_update_thread;           // plc更新线程
    S7PLC m_plc;                             // S7协议句柄
    const int m_update_interval_milli = 100; // plc更新频率

    // 有参构造函数
    Plc_data(std::string ip);

    // class CGarbo
    // {
    // public:
    // 	~CGarbo() {
    // 		if (g_ins)
    // 		{
    // 			delete g_ins;
    // 			g_ins = 0;
    // 		}
    // 	}
    // };
    // static CGarbo Garbo;	//--->1

protected:
    short m_data[MAX_REGIONS*2];
    short m_last_data[MAX_REGIONS*2];
    std::string m_ip_str;
};

#endif //PLC_DATA_H
