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

--初始化函数
--function on_init()
--end

--定时回调函数，系统每隔1秒钟自动调用。
--function on_systick()
--end

--用户通过触摸修改控件后，执行此回调函数。
--点击按钮控件，修改文本控件、修改滑动条都会触发此事件。
--function on_control_notify(screen,control,value)
--end

--当画面切换时，执行此回调函数，screen为目标画面。
--function on_screen_change(screen)
--end

local progress = 0      --进度条
local meter_value = 0   --仪表值
local meter_flag = 0    --仪表标志

local page = {  --界面页面
    button        = 3,  --按钮
    text          = 4,  --文本
    progress      = 5,  --进度条
    meter         = 6,  --仪表
    slider        = 7,  --滑块
    rtc           = 8,  --时间
    animation     = 9,  --动画
    icon          = 10, --图标
    graph         = 11, --曲线
    menu          = 12, --下拉菜单
    selector      = 13, --滚轮选择
    qrcode        = 14, --二维码
    record        = 15, --数据记录
    history_graph = 16, --历史曲线
    audio         = 17, --音频
    language      = 18, --多语言
    test          = 28, --测试
}

local control_id = {    --测试界面测试信息控件ID
    can = 16,
    usb = 12,
    sd = 14,
    uart2 = 15,
    uart2_wifi = 17,
}

local can_cmd_id = 10   --CAN ID

-- WiFi相关
local timer_id_connect_wifi = 10
local timer_id_wifi_state_scan = 11
local timer_id_wifi_init = 15
local timer_id_wifi_scan_signal = 16
wifi_config = '{"ssid":"53iq","password":"53iq53iq"}'

local heart_cnt = 0
local mcu_cmd = {}

local ProductKey = '{"p":"1lsdkyb3renfloqt","v":"1.0.0","m":0}'

local TF_State = {
    SOF        = 0,   --!< Wait for SOF
    VER        = 1,   --!< Wait for VER
    FUNC       = 2,   --!< Wait for Number Of FUNC
    DATA_LEN   = 3,
    DATA       = 4,   --!< Receive payload
    DATA_CKSUM = 5    --!< Wait for Checksum
}
local TF_SOF_BYTE = 0x55AA

local TF_VER_BYTES  = 1
local TF_FUNC_BYTES = 1
local TF_LEN_BYTES  = 2
local TF_DATA_CKSUM = 1

local tf_state = TF_State.SOF
local tf_recvTable = {}
local tf_id = 0
local tf_type = 0
local tf_cksum = 0
local tf_dataLen = 0
local tf_rxi = 0
local head = 0

--双串口检测
local cmd = {
    head_tag = 0, --检测头标识
    head     = 0, --存放头字节
    tail     = 0, --存放尾字节
    buff     = {}, --指令缓存
    len      = 0, --指令长度
    datalen  = 0  --内容长度
}


function on_init()

    local cur_lang = get_language()
    if cur_lang == 0                --当前语言为中文
    then
        set_value(page.language,1,1)

    elseif cur_lang == 0x81         --当前语言为英文
    then
        set_value(page.language,2,1)
        set_value(page.language,1,0)
    end


    set_button_notify_release() --设置按键通知

    start_timer(8,1000,0,0)     --历史曲线
    
    uart_set_baudrate2(115200)    --双串口初始化

    -- canbus_open(0,125,0,0)      --CAN初始化
end

function on_timer(timer_id)  

    if timer_id == 1    --仪表
    then
        if meter_value <= 0     --小于0时，数值加
        then
            meter_flag = 0
        end

        if meter_value >= 260   --大于0时，数值减
        then
            meter_flag = 1
        end

        if meter_flag  == 0
        then
            set_value(page.meter, 1, meter_value)      --指针转动
            set_value(page.meter, 5, meter_value)
            meter_value = meter_value + 4   --数值增加
        end

        if meter_flag == 1
        then
            set_value(page.meter, 1, meter_value)      --指针转动
            set_value(page.meter, 5, meter_value)
            meter_value = meter_value - 4   --数值增加
        end
    end

    if timer_id == 8    --历史曲线
    then
        local Curve_value = math.random(1,254)
        set_history_graph_value(page.history_graph, 1, Curve_value)
    end

    if timer_id == 4    --串口2发送
    then
       local uart2_buffer = {0x00,0x12,0x34,0xFF,0xFC,0xFF,0xFF}
       uart2_buffer[0] = 0xEE
       uart_send_data2(uart2_buffer)
    end

    if timer_id == timer_id_connect_wifi
    then
        if heart_cnt > 0
        then
            wifi_connect()
        end
    end

    if timer_id == timer_id_wifi_state_scan
    then
        if heart_cnt > 0
        then
            wifi_state_get()
        end
    end
    if timer_id == timer_id_wifi_init
    then
        wifi_scan_testwifi()
    end
    if timer_id == timer_id_wifi_scan_signal then
		wifi_scan_signal()
	end
end


function on_audio_callback (state)  --音频结束回调
    set_value(page.audio, 3, 0)
    set_value(page.audio, 4, 0)
end


function on_control_notify(screen,control,value)

    if screen == page.meter     --仪表
    then
        if control == 4 and value == 1
        then
            start_timer(1,1,0,0)
        end

        if control == 4 and value == 0
        then
            stop_timer(1)
        end
    end

    if screen == page.selector  --滚轮
    then
        if control == 1
        then
            if value >= 0 and value <= 6
            then
                set_value(screen,3,0)
            end

            if value > 6 and value <= 12
            then
                set_value(screen,3,1)
            end

            if value > 12 and value <= 18
            then
                set_value(screen,3,2)
            end

            if value > 18 and value <= 21
            then
                set_value(screen,3,3)
            end

            if value > 21 and value <= 23
            then
                set_value(screen,3,4)
            end
        end
    end

    if screen == page.rtc   --时间
    then
        if control == 8 and value == 0
        then
            local year,mon,day,hour,min,sec,week = get_date_time()
            if week == 0 then week = "日" end
            if week == 1 then week = "一" end
            if week == 2 then week = "二" end
            if week == 3 then week = "三" end
            if week == 4 then week = "四" end
            if week == 5 then week = "五" end
            if week == 6 then week = "六" end
            set_text(screen,1,year)
            set_text(screen,2,mon)
            set_text(screen,3,day)
            set_text(screen,4,hour)
            set_text(screen,5,min)
            set_text(screen,6,sec)
            set_text(screen,7,week)
        end
    end

    if screen == page.progress  --进度条
    then
        if control == 3
        then
            if value == 0 or value == 2
            then
                progress = progress - 1
                if progress <= 0
                then
                    progress = 0
                end
                set_value(screen, 1, progress)
                set_value(screen, 2, progress)
            end

        elseif control == 1
        then
            set_value(screen, 2, value)
            progress = value

        elseif control == 4
        then
            if value == 0 or value == 2
            then
                progress = progress + 1
                if progress >= 100
                then
                    progress = 100
                end

                set_value(screen, 1, progress)
                set_value(screen, 2, progress)
            end
        end
    end

    if screen == page.slider   --滑块
    then
        if control == 2
        then
            set_value(screen, 3, value)
            set_backlight(value)
        end

        if control == 5
        then
            set_value(screen, 6, value)
        end
    end
end


function on_screen_change(screen)
    if screen == page.test      --进入测试界面
    then
        -- start_timer(4,1000,0,0)
    end
end


function CKSUM_ADD(data)
    tf_cksum = tf_cksum + data
    table.insert(tf_recvTable, data)
    
    tf_rxi = tf_rxi + 1
end

--/** Handle a received char - here's the main state machine */
function TF_AcceptChar(data)
    --超时判断
    --table.insert()
    local switch = {
        [TF_State.SOF] = function(data)
            head = (head << 8 | data)&0xFFFF
            if head == TF_SOF_BYTE then
                CKSUM_ADD((head >>8) & 0xFF)
                CKSUM_ADD((head >>0) & 0xFF)
                tf_state = TF_State.VER
                tf_rxi = 0
				--print('head...')
            else
                -- 如果帧头出错 不处理
            end
        end,

        [TF_State.VER] = function(data)
            CKSUM_ADD(data)
            if tf_rxi == TF_VER_BYTES then
                tf_state = TF_State.FUNC
                tf_rxi = 0
				--print('ver...')
            end
        end,

        [TF_State.FUNC] = function(data)
            CKSUM_ADD(data)
            if tf_rxi == TF_FUNC_BYTES then
                tf_state = TF_State.DATA_LEN
                tf_rxi = 0
				--print('func...')
            end
        end,

        [TF_State.DATA_LEN] = function(data)
            CKSUM_ADD(data)
            if tf_rxi == TF_LEN_BYTES then

                tf_dataLen = tf_recvTable[5] << 8 | tf_recvTable[6]
				--print('deta_len...'..tf_dataLen)
				if tf_dataLen > 0
				then
					tf_state = TF_State.DATA
				else
					tf_state = TF_State.DATA_CKSUM
				end
				tf_rxi = 0
            end
        end,

        [TF_State.DATA] = function(data)
            CKSUM_ADD(data)
            if tf_rxi == tf_dataLen then
				--print('data...')
                tf_state = TF_State.DATA_CKSUM
                tf_rxi = 0
            end    
        end,
        [TF_State.DATA_CKSUM] = function(data)
			--print('sun...')
            if (tf_cksum % 0x100) == data then
				table.insert(tf_recvTable, data)
                __protocolParse()
            end
			head = 0
            tf_cksum = 0
            for i=1, #tf_recvTable do
                table.remove(tf_recvTable)
            end
            tf_state = TF_State.SOF
        end
    }
    
    if switch[tf_state] then
        switch[tf_state](data)
    end
end

function on_uart_recv_data2(packet)     --串口2

    for i = 0, #packet, 1 do
		TF_AcceptChar(packet[i])
	end
        
end

function on_canbus_recv (index,identifier,dlc,rtr,ide,data)     --CAN通讯

    if can_cmd_id == identifier
    then
        if data[0] == 0xA0
        then
            canbus_write(0, can_cmd_id, 8, 0, 0, {[0] = (data[1] + 1),0x55,0x00,0x08,0xF2,0x01,0xCC,0xCC})
        elseif data[0] == 0xA2
        then
            set_text(page.test, control_id.can, "CAN通信:正常")
        end
    end
end


function on_usb_inserted(driver)    --U盘插入
    set_text(page.test, control_id.usb, 'U盘检测：成功')
end


function on_sd_inserted(dir)    --SD卡插入
    set_text(page.test, control_id.sd, 'SD卡检测：成功')
end


-- MCU心跳包回复，flag=0表示第一次回复，flag=1表示非第一次回复
function mcu_heart_ack(flag)
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x00
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x01
	mcu_cmd[6] = flag
	local sum = 0
	for i = 0, 6, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[7] = sum % 0x100
	uart_send_data2(mcu_cmd)
end

function mcu_productkey_ack()
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x01
	local datalen = string.len(ProductKey)
	mcu_cmd[4] = (datalen >> 8) & 0xFF
	mcu_cmd[5] = datalen & 0xFF
	for i = 1, string.len(ProductKey) do
		table.insert(mcu_cmd,i+5,string.byte(string.sub(ProductKey,i,i)))
	end
	local sum = 0
	for i = 0, (datalen+5), 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[datalen+6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end


function mcu_mode_set(mode,led_io,reset_io)
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x02
	if mode == 0 then
		mcu_cmd[4] = 0x00
		mcu_cmd[5] = 0x00
		local sum = 0
		for i = 0, 5, 1 do
			sum = sum + mcu_cmd[i]
			mcu_cmd[6] = sum % 0x100
			uart_send_data2(mcu_cmd)
		end
	end
	if mode == 2 then
		mcu_cmd[4] = 0x00
		mcu_cmd[5] = 0x02
		mcu_cmd[6] = led_io
		mcu_cmd[7] = reset_io
		local sum = 0
		for i = 0, 7, 1 do
			sum = sum + mcu_cmd[i]
			mcu_cmd[8] = sum % 0x100
			uart_send_data2(mcu_cmd)
		end
	end
end

function mcu_connect_report()
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x03
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x00
	local sum = 0
	for i = 0, 5, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end

function mcu_tatus_report(value)
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x07
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x05
	mcu_cmd[6] = 0x14
	mcu_cmd[7] = 0x01
	mcu_cmd[8] = 0x00
	mcu_cmd[9] = 0x01
	mcu_cmd[10] = value
	local sum = 0
	for i = 0, 10, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[11] = sum % 0x100
	uart_send_data2(mcu_cmd)
end

local dpid = 0
local button_flag = 0
function __protocolParse()
	if tf_recvTable[4] == 0x00 then
		heart_cnt = heart_cnt + 1
		print("检测到WBR3心跳包")
		if heart_cnt == 1 then
			mcu_heart_ack(0)
		else
			mcu_heart_ack(1)
		end
	end
	if tf_recvTable[4] == 0x01 then
		mcu_productkey_ack()
	end
	if tf_recvTable[4] == 0x02 then
		mcu_mode_set(0,0,0)
		print('0x02')
		start_timer(timer_id_wifi_init,5000,0,2)
		set_text(page.test, control_id.uart2, "wifi未连接")
	    set_text(page.test, control_id.uart2_wifi, "")
	end
	if tf_recvTable[4] == 0x03 then
		mcu_connect_report()
        print('0x03')
		print("tf_recvTable[7]   :"..tf_recvTable[7])
		if tf_recvTable[7] >= 0x03 and tf_recvTable[7] <= 0x05  then
           set_text(page.test, control_id.uart2, "wifi已连接")
			wifi_scan_signal()
		elseif tf_recvTable[7] >= 0x01 and tf_recvTable[7] <= 0x02  then
			--set_text(page.test, control_id.wifi, "wifi已配置")
			--wifi_scan_signal()
		end
	end
	if tf_recvTable[4] == 0x06 then
	
		dpid = tf_recvTable[7]
		if dpid == 20 then
			button_flag = (button_flag+1) % 2
			mcu_tatus_report(button_flag)
			set_value(3,1,button_flag)
		end
	end
    if tf_recvTable[4] == 0x0e then
		
		if tf_recvTable[7] == 1 then
		set_text(page.test, control_id.uart2, "扫描WIFI成功")
	    set_text(page.test, control_id.uart2_wifi, "信号:"..tf_recvTable[8])
		end
	end	

	if tf_recvTable[4] == 0x24 then
		if tf_recvTable[7] == 0x00 then
			--start_timer(timer_id_wifi_scan_signal,1000,0,0)
		else
			set_text(page.test, control_id.uart2_wifi, "信号强度："..tostring(tf_recvTable[7] - 256))
		end
	end
	if tf_recvTable[4] == 0x2C then

	end
	if tf_recvTable[4] == 0x2b then

	end
	mcu_cmd = {}
end

function wifi_connect()
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x2C
	mcu_cmd[4] = (string.len(wifi_config)>>8) & 0xFF
	mcu_cmd[5] = string.len(wifi_config) & 0xFF
	for i = 1,string.len(wifi_config)
	do
		table.insert(mcu_cmd,i+5,string.byte(string.sub(wifi_config,i,i)))
	end
	local sum = 0
	for i = 0, 5+string.len(wifi_config), 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[string.len(wifi_config)+6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end


function wifi_scan_signal()
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x24
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x00
	local sum = 0
	for i = 0, 5, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end

function wifi_state_get()
    mcu_cmd = {}
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x2b
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x00
	local sum = 0
	for i = 0, 5, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end

--涂鸦产测扫描指定WiFi SSID：tuya_mdev_test
function wifi_scan_testwifi()
	mcu_cmd[0] = 0x55
	mcu_cmd[1] = 0xAA
	mcu_cmd[2] = 0x03
	mcu_cmd[3] = 0x0e
	mcu_cmd[4] = 0x00
	mcu_cmd[5] = 0x00
	local sum = 0
	for i = 0, 5, 1 do
		sum = sum + mcu_cmd[i]
	end
	mcu_cmd[6] = sum % 0x100
	uart_send_data2(mcu_cmd)
end
