--下面列出了常用的回调函数
--更多功能请阅读<<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 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
local CatTime = 4
local screen_wifi_set = 40
local screen_search_wifi = 41
--单前选中的wifi的名称和密码
local cwifi_ssid = 0
local cwifi_pwd  = 0

local CAN_CMD_ID = 10

local recv2_buffer = {}     --串口二
local cmd_head = 0
local recv_buffer2_count = 0


--[[***************************************************************************
** Function name:  my_log
** Descriptions:   打印虚拟屏调试信息，设置 en_debug_msg = 1
                   注意：实体屏运行时， en_debug_msg 不能等于 1
***************************************************************************--]]
local en_debug_msg = 2 --0-不显示调试信息;1-虚拟屏; 2-实体屏，串口1输出
function my_log(debug_msg)
    if en_debug_msg == 1
    then
        print(debug_msg)
    elseif en_debug_msg == 2
    then
        uart_send_string(debug_msg)
        uart_send_string('\r\n')
    end
end



function on_init()
	dofile('esp32.lua')
	uart_set_baudrate2(115200)                                              --设置与4G模块通讯的串口3的波特率为115200
	air_set_callback(on_air_send_cb,on_air_resp_callback,on_air_log_cb)
	set_button_notify_release()
	start_timer(0,1000,0,0)
    
	if type(canbus_open) == nil then
        set_visiable(0,24,0) 
    end
    
    local cur_lang = get_language()
    if cur_lang == 0         --当前语言为中文
    then
        set_visiable(0,24,0)        --隐藏英文时间显示
        set_value(Languagescreen_id,1,1)
		set_value(Languagescreen_id,2,0)
    elseif cur_lang == 0x81         --当前语言为英文
    then
        set_visiable(0,9,0)        --隐藏中文时间显示
        set_value(Languagescreen_id,2,1)
		set_value(Languagescreen_id,1,0)
    end
    
	esp32_int_station()
	search_wifi_clear()
    
    start_timer(4,300,0,0)
	start_timer(8,1000,0,1)
    uart_set_baudrate3(19200)    --双串口初始化
    
    canbus_open(0,125,0,0)      --CAN初始化
end

function on_init_cb(key, value) 
    my_log('on_init_cb key:'..key..',value:'..value)
    if string.find(key,'+CWMODE=1') ~= nil and string.find(value,'OK') ~= nil 
    then
        search_wifi_clear()
        esp32_search_wifi()
        search_wifi_num = 0     
    end
end

function search_wifi_clear()
	for i=1,14 do
		set_text(screen_search_wifi,i,'')
	end
end

local search_wifi_num = 0
--+CWLAP:(4,"RD",-52,"08:9b:4b:9d:c8:ed",1,-1,-1,4,4,7,0)
function on_search_wifi_cb(key, value) 
    my_log('on_search_wifi_cb key:'..key..',value:'..value)
--local regular_e = '+ICCID: (%d*)'                       --正则表达式
--local my_iccid = string.match( value, regular_e)        --获取的值赋给 my_iccid 
    
    if string.find(key,'+CWLAP') ~= nil and string.find(value,'CWLAP:') ~= nil 
    then
        local regular_e = '.*CWLAP:[(0-9]*,"(.*)",[-0-9]*,".*",.*'                       --正则表达式
        local my_wifi_ssid = string.match( value, regular_e)        --获取的值赋给 my_iccid 
        my_log('my_wifi_ssid :'..my_wifi_ssid)
        set_text(screen_search_wifi,1+search_wifi_num,my_wifi_ssid)
        
        local regular_e2 = '.*CWLAP:[(0-9]*,".*",([-0-9]*),".*",.*'                       --正则表达式
        local my_wifi_rssi = string.match( value, regular_e2)        --获取的值赋给 my_iccid 
        my_log('my_wifi_ssid :'..my_wifi_rssi)
        --set_text(screen_search_wifi,101+search_wifi_num,my_wifi_rssi)
        
        search_wifi_num = search_wifi_num + 1
    end
    
end

function on_connect_ap_cb(key, value) 
    my_log('on_connect_ap_cb key:'..key..',value:'..value)
    if string.find(key,'+CWJAP') ~= nil and string.find(value,'OK') ~= nil 
    then
		set_text(screen_wifi_set,1,'已连接')
		set_text(screen_wifi_set,3,cwifi_ssid)
        my_log('sus:wifi connect ok')
    end
    if string.find(key,'+CWJAP') ~= nil and string.find(value,'ERROR') ~= nil 
    then
		set_text(screen_wifi_set,1,'连接失败')
        my_log('error:wifi connect error')
    end
end

function on_timer(timer_id)
	on_esp_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==4      --双串口测试
    then
        local uart1_buffer= {0x04,0xff,0xfc,0xff,0xff}
        uart1_buffer[0] = 0xee

        uart_send_data3(uart1_buffer)
       
    elseif timer_id==8 
    then
        set_text(28,15,"")
    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 == 28
    then
        if control == 13
        then
            local uart1_buffer= {0xAA,0x55,0x00 ,0x08 ,0xF2 ,0x01 ,0x00 ,0x01 ,0x00 ,0x00 ,0xCC ,0xCC}
            canbus_write(0,CAN_CMD_ID,2,0,0,uart1_buffer)
        end
    end
    
	if screen == screen_wifi_set then
		if control == 6 then
            search_wifi_clear()
            esp32_search_wifi()
            search_wifi_num = 0
		end	
        if control == 7 then
            cwifi_pwd = get_text(screen_wifi_set,5)
            esp32_connect_ap(cwifi_ssid,cwifi_pwd)
        end
	end
	if screen == screen_search_wifi then
		if control==15 then
			search_wifi_clear()
			esp32_search_wifi()
			search_wifi_num = 0
		end
		if control > 15 and control <30 then
            cwifi_ssid = get_text(screen_search_wifi,control-15)
            print(cwifi_ssid)
            set_text(screen_wifi_set,4,cwifi_ssid)
        end
	end
end




function on_video_notify(msg,v1,v2)
	local anim_id = get_current_screen()
	if anim_id == Bootanimation_id and msg == 0 then
		change_screen(0)
	end
end
function on_audio_callback(state)
	set_value(Audioscreen_id,3,0)
	set_value(Audioscreen_id,4,0)
end



--[[***************************************************************************
** Function name:  on_air_log_cb
** Descriptions:   4G模块-调试信息输出
***************************************************************************--]]
function on_air_log_cb(msg)
  --数据打印到记录控件
  --record_add(0,4,string.sub(msg,1,100))
end


--[[***************************************************************************
** Function name:  on_air_send_cb
** Descriptions:   4G模块-发送数据
***************************************************************************--]]
function on_air_send_cb(msg)
    if air_debug_mode==1  
    then
        uart_send_string(msg)                       -- air_debug_mode==1 ，使用虚拟屏调试，通过串口1发送数据
        my_log(msg)
    else
        uart_send_string2(msg)                      -- air_debug_mode==0 ，使用实体屏调试，通过串口3发送数据
        --my_log('out: '..msg..'\r\n')
    end
end


--[[***************************************************************************
** Function name:  on_air_resp_callback
** Descriptions :  4G模块-数据回调接口
** @key         :  屏幕->4G模块的发送请求
** @value       :  4G模块->返回的数据
***************************************************************************--]]
function on_air_resp_callback(key, value)  
    
    my_log('on_air_resp_callback()')
    
    if value == nil
    then 
        return              --value为空时退出
    end
   
    --***************************************************************************
    --功能：    判断 key
    --          如果 key 为空，则退出函数。
    --          因为 key 为空时，下方 string.find( key , ) 是不正确的使用。
    --          以下key的处理必须不为空，
    --***************************************************************************
    if key == nil 
    then
        return
    end  
end


--[[***************************************************************************
** Function name : on_uart_recv_data
** Descriptions  : 接收串口1的数据的回调函数。串口1是普通串口。
**                 虚拟屏调试时, air_debug_mode = 1，处理串口1的数据。
** @packet       : 接收的数据包
** @return       : nil,无返回值
***************************************************************************--]]
function on_uart_recv_data(packet)
    --4G模块直接PC串口
    if air_debug_mode == 1 
    then
        on_esp_recv_data(packet)
    end
    if air_debug_mode == 0
    then
        uart_send_data2(packet)
    end
end

--[[***************************************************************************
** Function name:  on_uart_recv_data3
** Descriptions:   接收串口3的数据的回调函数。串口3是连接4G模块。
***************************************************************************--]]
function on_uart_recv_data2(packet)
    on_esp_recv_data(packet)
end

function on_uart_recv_data3(packet)     --串口2

	for i = 0,(#(packet)) do
		cmd_head = packet[i]
		cmd_head = cmd_head&0xff
		
		if cmd_head==0XEE then  
			
			recv2_buffer = {}
			recv_buffer2_count = 1
			
			recv2_buffer[0] = 0xee

		else
			recv2_buffer[recv_buffer2_count] = packet[i]
			recv_buffer2_count = recv_buffer2_count+1
		end

		if recv_buffer2_count >= 6 then                --指令长度判定
			if recv2_buffer[0] == 0xee then
				set_text(28,15,"串口2通信成功")
				stop_timer(8)
				start_timer(8,1000,0,1)
			end
		end
		
	end
end

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

	if CAN_CMD_ID == identifier then
		if data[1] ~= nil then
			local show_value = (data[1]<<8) + data[2] 
			set_text(28,16,"CAN 通信正常")
			canbus_write(0,CAN_CMD_ID,2,0,0,data)
			
		end
	end
	
end

function on_usb_inserted(driver)    --U盘插入
    set_text(28,12,'U盘插入')
end

function on_usb_removed()           --U盘拔出
    set_text(28,12,'U盘拔出')
end
