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

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

--定时回调函数，系统每隔1秒钟自动调用。

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

--当画面切换时，执行此回调函数，screen为目标画面。
--function on_screen_change(screen)
--end
--uart_free_protocol = 1
local progress = 0
local meter_value = 0
local meter_flag = 0
local Progress_screenid = 5
local Meter_screenid = 6
local Slider_screendid = 7
local RTC_screenid = 8
local Seltor_screenid = 13
local Historicalcurve_screenid = 16
local Audioscreen_id = 17
local Languagescreen_id = 18
local Bootanimation_id = 39

wifi_config = '{"ssid":"53iq","password":"53iq53iq"}'
wifi_config_tab = {}

function on_init()
	uart_set_baudrate2(115200)
	set_button_notify_release()
	start_timer(0,1000,0,0)
	local language_id = get_language()
	if language_id == 0 then
		set_value(Languagescreen_id,1,1)
		set_value(Languagescreen_id,2,0)
	end
	if language_id == 1 then
		set_value(Languagescreen_id,2,1)
		set_value(Languagescreen_id,1,0)
	end
end

function on_timer(timer_id)  
 if timer_id==1
  then
    if meter_value <=0                                                       --小于0时，数值加
  	then
  		meter_flag = 0
    end
    if meter_value >=270                                                     --大于0时，数值减
  	then
  		meter_flag = 1
    end
    if meter_flag  ==0
    then
    set_value(Meter_screenid,1,meter_value)
	set_value(Meter_screenid,5,meter_value)                                               --指针转动
	meter_value = meter_value+2                                              --数值增加
	end
	if meter_flag ==1
	then
	set_value(Meter_screenid,1,meter_value)
	set_value(Meter_screenid,5,meter_value)                                               --指针转动
	meter_value = meter_value-2                                              --数值增加
	end  
  end
	if timer_id == 0 then
		local Curve_value = math.random(1,254)
		set_history_graph_value(Historicalcurve_screenid,1,Curve_value)
	end	
	if timer_id == 30 then
		wifi_connect()
	end
end




function on_control_notify(screen,control,value)
	if screen == Meter_screenid then
		if control == 4 and value == 1 then
			start_timer(1,15,0,0)
		end
		if control == 4 and value == 0 then
			stop_timer(1)
		end
	end
	
	if screen == Seltor_screenid 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 == RTC_screenid 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 == Progress_screenid 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 == Slider_screendid 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

	if screen == 3 then
		if control == 1 then
			mcu_tatus_report(value)
		end
	end
	if screen == Bootanimation_id and control == 1 then
		change_screen(0)
	end
end
function on_video_notify(msg,v1,v2)

end
function on_audio_callback(state)
	set_value(Audioscreen_id,3,0)
	set_value(Audioscreen_id,4,0)
end


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

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)
	for i = 0, #packet, 1 do
		TF_AcceptChar(packet[i])
	end
end


local heart_cnt = 0
local mcu_cmd = {}

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

function mcu_heart_ack(flag)
	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[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[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[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[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()
		start_timer(30,100,0,1)
	end
	if tf_recvTable[4] == 0x02 then
		mcu_mode_set(0,0,0)
	end
	if tf_recvTable[4] == 0x03 then
		mcu_connect_report()
	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] == 0x24 then
		if tf_recvTable[7] == 0x00 then
			wifi_scan_signal()
		else
			local signal = tf_recvTable[7] - 256
			--print(tf_recvTable[7])
			signal = tostring(signal)
			--print(signal)
			set_text(30,13,"wifi信号强度:"..signal)
		end
	end
	if tf_recvTable[4] == 0x2C then
		--print(wifi_config.."connect->".."state")
		if tf_recvTable[7] == 0x01 then
			--print(wifi_config.."connect->".."sucess")
			set_text(30,12,"已成功连接wifi:53iq")
			wifi_scan_signal()
		elseif tf_recvTable[7] == 0x00 then
			set_text(30,12,"wifi:53iq未连接")
			wifi_connect()
		end
	end
	mcu_cmd = {}
end

function wifi_connect()
	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[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 on_systick()
	
end