print("###lua This is camyu lua script.")
--C++ 提供的函数接口
--1、io_write          写入数据到物理层
--2、update_register   通知应用层更新数据
--3、CRC8_Table
data_buf=""
g_readreg=0x00

STATUS_WAITHEAD  = (1<<0)
STATUS_READWAITSTATUS  = (1<<1)
STATUS_WAITLEN   = (1<<2)
STATUS_WAITDATA  = (1<<3)
STATUS_WRITEWAITSTATUS = (1<<31)
prase_data       = "";
parase_status    = STATUS_WAITHEAD
dlength          = 0;               -- 后续数据长度(数据+校验和+命令+应答位)
parase_len       = 0;               -- 预接收长度
function process_data(pd)
    print("###lua process_data:",(string.gsub(pd,"(.)",function (x) return string.format("%02X ",string.byte(x)) end)))
    --print("")
    for i=1,#pd do
        d = string.byte(pd,i)
        if parase_status==STATUS_READWAITSTATUS then
            if d == 0x06 then
                --print("in 1")
                parase_status = STATUS_WAITDATA;
                parase_len    = 4
                dlength       = 0
                prase_data = ""
                --prase_data = prase_data..string.char(indata);
            end
        elseif parase_status == STATUS_WRITEWAITSTATUS then
            if d == 0x06 then
                update_register(g_readreg,"1234")
            end
        elseif parase_status == STATUS_WAITDATA then
            --print("in 2")
            if (dlength + 1) >= parase_len then
                print("complet")
                dlength = dlength+1
                prase_data = prase_data..string.char(d)
                parase_status = STATUS_WAITHEAD
                update_register(g_readreg,string.char(string.byte(prase_data,4),string.byte(prase_data,3),string.byte(prase_data,2),string.byte(prase_data,1)))
            else
                dlength = dlength+1
                prase_data = prase_data..string.char(d)
            end
        end
    end
    return 4;
end;
--发起连接将调用该函数，可以在这个函数处理连接协议
function connect_device(pd)
    print("###lua connect_device",pd)
    --io_write(0x001,"123")
    return 0;
end;
--发起写寄存器将调用该函数，可以在这个函数处理寄存器写操作
--reg 寄存器
--tp 写入参数类型
--pd 写入参数缓存
function write_register(reg,tp,pd)
    --print("###lua write_register",reg,pd,#pd)
    --head
    g_readreg = reg
    parase_status = STATUS_WRITEWAITSTATUS
    local sh = string.char(0x57,(reg>>8)&0xFF,(reg>>0)&0xFF,string.byte(pd,4),string.byte(pd,3),string.byte(pd,2),string.byte(pd,1))
    --print("#############################################################dasdasdasa")
    print("###lua write_register:",(string.gsub(sh,"(.)",function (x) return string.format("%02X ",string.byte(x)) end)))
    io_write(sh)
    return 0;
end;
--发起读寄存器将调用该函数，可以在这个函数处理寄存器读操作
--reg 寄存器
--tp 读取参数类型
--pd 读取参数缓存
function read_register(reg,tp,pd)
    --print("###lua read_register",reg,pd)
    --head
    parase_status = STATUS_READWAITSTATUS
    g_readreg = reg
    local sh = string.char(0x52,(reg>>8)&0xFF,(reg>>0)&0xFF);
    print("###lua write_register:",(string.gsub(sh,"(.)",function (x) return string.format("%02X ",string.byte(x)) end)))
    io_write(sh)
    return 0;
end;






