--下面列出了常用的回调函数
--更多功能请阅读<<物联型LUA脚本API.pdf>>


local sc_check = 0

local Temp = {0, 0, 0, 0, 0}
Temp[0] = 0


--calculate CRC16
--@data : t, data to be verified
--@n    : number of verified
--@return : check result
function add_crc16(data, n)

    local  i, j, carry_flag, a = 0
    local result = 0xffff
   
    for i = 0, n
    do
        result = result ~ data[i]
        for j = 0, 7
        do
            a = result
            carry_flag = a & 0x0001
            result = result >> 1
            if carry_flag == 1
            then
                 result = result ~ 0xa001
            end
        end
    end
    
    print('> crc16 = '.. string.format('%04X', result))
    
    return result
end

function on_control_notify(screen,control,value)
    
    if screen == sc_check
    then
        if control >= 1 and control <= 6
        then
            local cur_Input = get_text(sc_check, control) 
            
            if cur_Input == ''
            then
                cur_Input = 0
            end
            Temp[control - 1] = math.ceil(tonumber(cur_Input))
            set_text(sc_check, control, string.format('%02X',cur_Input))
            
        elseif control == 7 and value == 0
        then
            local Check_Data = {}
            for i = 0, 5
            do
                Check_Data[i] =  Temp[i]
                print('> Check_Data['..i..'] = '..string.format('%02X', Check_Data[i]))
            end

            local result = add_crc16(Check_Data, #(Check_Data))
            Check_Data[6] =  (result >> 8) & 0xFF
            Check_Data[7] =  (result >> 0) & 0xFF
            set_text(sc_check, 8, string.format('%02X',Check_Data[6])..'  '..string.format('%02X',Check_Data[7]))
            uart_send_data(Check_Data)
        end
    end
end
