require "log"
require "sys"
require "utils"
require "patch"
require "pack"
require "bit"
local siganl = require 'posix.signal'
local syswait = require 'posix.sys.wait'
local unistd = require 'posix.unistd'
local lpack=require("lua_pack")
local internal_api=require("internal_api")

LOG_LEVEL = log.LOGLEVEL_DEBUG



local sub_nodes = {
    {
        sn_suffix = "_DI",
        grp_idx =nil,
        ident_list = {"DIRead"}
    }
    
}
local gw_sn
local nodes_info --SN:object
local g_nodes --全局node_cfg
local g_grp = {--[[{data={},ctrl={},status={},protect={},warn={}}]]}
local g_total = {data={},ctrl={},status={},protect={},warn_type={},warn={}}
local auto = 1
local range = 1
--local TAG_5DD_pre=0;
--local TAG_579_pre=0--water
--local TAG_4C6_pre=0--smoke
--local TAG_519_pre=0--extinguish
--local TAG_4C8_pre=0--gas
local Sig_DO3=2 --DO3 recover signal

--local nodes_cfg =
  --  '[{"connect_port":"VINTF_TCP","depth":0,"product_key":"206627059","sn":"21881E000056_DI","template_id":"206627059"}]'


-- 数据采集
local function pp_msg(topic,payload)
      
    local currTime = os.time()
    --print("DOfire1",topic,payload)
    local obj = cjson.decode(payload)   
    local tags = obj.tag_node and cjson.decode(obj.tag_node) or nil
    
    ---- 先对数据做汇聚
    if not obj.sn then
        log.error(nil,"Invalid device sn")
        return
    end
    local node_info = nodes_info[obj.sn]
    if not node_info then return end
    local found
    for _,ident in ipairs(node_info.ident_list) do
        if obj.identifier == ident then
            found = true
            log.info("DO2 found",obj.identifier)
            break
        end
    end
    if not found then 
        log.error(nil,string.format("Invalid identifier:%s in sn:%s",obj.identifier,obj.sn))
    end

    local grp_idx = node_info.grp_idx
    local data_space
    if grp_idx then         data_space = g_grp[grp_idx]
    else                    data_space = g_total
    end
    if data_space then
    -- 更新数据
        for msg_field,msg_value in pairs (tags)do -- 遍历上来的变量
            local data = data_space.data
            data[msg_field] = msg_value
            -- log.debug(nil,msg_field,msg_value)
            log.info("DO2 msg_field",msg_field)

        end
    -- 更新状态
        node_info.recv_time = os.time()
        sys.publish("REAL_DATA_UPDATE",grp_idx)
    end
    -- log.debug(nil,cjson.encode(g_grp[1]))
end
local function DO2_3(Onoff)
    
    local dev_sn = string.format("%s_DI",gw_sn)  
    log.info("DO2 TAG_579",g_total.data.TAG_579)
    log.info("DO2 TAG_4C6",g_total.data.TAG_4C6)
    log.info("DO2 TAG_519",g_total.data.TAG_519)
    log.info("DO2 TAG_4C8",g_total.data.TAG_4C8)
    log.info("DO2 gw_sn dev_sn Pulse sending",gw_sn,dev_sn)
    if Onoff == 1 then
        internal_api.call_dev_service(gw_sn,dev_sn,"NULL","DO2",{DO_2 = 65280},0)
        internal_api.call_dev_service(gw_sn,dev_sn,"NULL","DO3",{DO_3 = 65280},0)
        sys.wait(200) 
        internal_api.call_dev_service(gw_sn,dev_sn,"NULL","DO2",{DO_2 = 0},0)
        Sig_DO3=1
    elseif Onoff == 0 then
        internal_api.call_dev_service(gw_sn,dev_sn,"NULL","DO3",{DO_3 = 0},0)
        Sig_DO3=0
    else
        internal_api.call_dev_service(gw_sn,dev_sn,"NULL","DO3",{DO_3 = 65280},0)
        Sig_DO3=1
    end      

    
    
end

local function linkage_Pulse()
    
    
    while true do
        local ret, grp_idx = sys.waitUntil("REAL_DATA_UPDATE", 2000)
        local dev_sn = string.format("%s_DI",gw_sn)  
        log.info("DO2 TAG_579",g_total.data.TAG_579)
        log.info("DO2 TAG_4C6",g_total.data.TAG_4C6)
        log.info("DO2 TAG_519",g_total.data.TAG_519)
        log.info("DO2 TAG_4C8",g_total.data.TAG_4C8)
        log.info("DO2 TAG_6A5",g_total.data.TAG_6A5)
        log.info("DO2 TAG_5DD",g_total.data.TAG_5DD)
               
        -- if g_total.data.TAG_579==1 then --and TAG_579_pre==0 then
        --     log.info("DO2 gw_sn dev_sn TAG_579 Pulse sending",gw_sn,dev_sn)
        --     DO2_3(1)
        -- end        
        -- --TAG_579_pre=g_total.data.TAG_579

        -- if g_total.data.TAG_4C6==1 then --and TAG_4C6_pre==0 then
        --     log.info("DO2 gw_sn dev_sn TAG_4C6 Pulse sending",gw_sn,dev_sn)
        --     DO2_3(1)           
        -- end
        -- --TAG_4C6_pre=g_total.data.TAG_4C6

        if g_total.data.TAG_519 == 1 then --and TAG_519_pre==0 then
            log.info("DO2 gw_sn dev_sn TAG_519 Pulse sending",gw_sn,dev_sn)
            DO2_3(1)           
        end
        --TAG_519_pre=g_total.data.TAG_519

        -- if g_total.data.TAG_4C8==1 then --and TAG_4C8_pre==0 then
        --     log.info("DO2 gw_sn dev_sn TAG_4C8 Pulse sending",gw_sn,dev_sn)
        --     DO2_3(1)           
        -- end
        -- --TAG_4C8_pre=g_total.data.TAG_4C8
        -- if g_total.data.TAG_6A5==1 then
        --     log.info("DO2 TAG_6A5 Pulse sending",gw_sn,dev_sn)
        --     DO2_3(2)   
        -- end
        -- if g_total.data.TAG_5DD==1 then
        --     log.info("DO2 TAG_5DD Pulse sending",gw_sn,dev_sn)
        --     DO2_3(2)   
        -- end

        if  g_total.data.TAG_579 == 0 and g_total.data.TAG_4C6 == 0 and g_total.data.TAG_519 == 0 
        and g_total.data.TAG_4C8 == 0 and g_total.data.TAG_6A5 == 0 and g_total.data.TAG_5DD == 0 
        and (Sig_DO3 == 1 or Sig_DO3 == 2) then
            DO2_3(0)   

        end  


        sys.wait(500)
    end

end




function main(nodes_cfg,sn)
    log.info("main_loop", "=============== Guard System of EMS 1.0.0 ============")
    gw_sn = sn
    if not gw_sn then
        gw_sn = io.getGatewayID()
    end

    g_nodes = cjson.decode(nodes_cfg or "{}")
    

    if not internal_api.update_nodes_info then log.error(nil, "Please upgrade package:internal_api version to 2.0.7 or higher") return end
    nodes_info = internal_api.update_nodes_info(gw_sn,sub_nodes)

    log.info("DO2pulse",  string.format("DO2pulse\nsn='%s'\nnodes='%s'\nmain_loop(nodes,sn)",gw_sn or "NOT SN",nodes_cfg or ""))

    siganl.signal(siganl.SIGKILL,handler)
    siganl.signal(siganl.SIGHUP,handler)

    local subscribe = internal_api.get_subscribes(gw_sn,sub_nodes,g_nodes)

    internal_api.mqtt_session("localhost", 1883, nil, nil, subscribe, function (topic,payload)
        if string.find(topic,"/data/service/") then  pp_msg(topic,payload) --如果是原始数据一定是南向数据
       -- elseif string.find(topic,"/data/Set_Rglt") then iot_msg(topic,payload)
        end
    end)

    sys.taskInit(linkage_Pulse)
    
    sys.init(0, 0)
    sys.run()
end

main(arg[1],arg[2])
--main(nodes_cfg,'21881E000056')
