

uart_free_protocol = 1  -- use custom serial protocol

-- global variables
local button_long = 0

function on_init()
  -- watchdog
  init_watchdog(1,30)  
  -- UART
  uart_setup(115200,0,1,8)
  uart_set_timeout(100, 10) 
end

function on_systick() -- triggered every second
  feed_watchdog()
end

function on_uart_recv_data(packet) -- triggered on UART packet received
  if packet[0] == 0xA0 and -- check start byte 
     #packet == 9         -- check length
  then
    -- check checksum
    local checksum = 0
    for i = 0, 8 do
      checksum = checksum + packet[i]
      checksum = checksum & 0xFF
    end
    if checksum == packet[9] -- checksum OK 
    then
      local page = packet[2]
      local pp0 = (packet[4] << 8) + packet[3]
      local pp1 = (packet[6] << 8) + packet[5]
      local pp2 = (packet[8] << 8) + packet[7]
      -- 
      print(page..', '..pp0..', '..pp1..', '..pp2)
      if page == 10 
      then
        set_value(0,3,pp0) 
      end
    end  
  end  
end

function on_control_notify(screen,control,value) -- triggered on object event
  if screen == 0 and control == 1 and value == 1 then 
    -- Button press
    send_event(10,1,1,0) -- page 10, object 1, 1=press 
  elseif screen == 0 and control == 1 and value == 0 then 
    -- Button release
    send_event(10,1,2,0) -- page 10, object 1, 2=release 
    button_long = 0 -- reset first LongPress pulse detection
  elseif screen == 0 and control == 1 and value == 2 then 
    -- Button long press
    if button_long == 0 then
      send_event(10,1,3,0) -- page 10, object 1, 3=long press
      button_long = 1 -- send long press only on first LongPress pulse
    end  
  end  
end

function send_event(event,ep0,ep1,ep2)
  local tx_buf = {}              -- tx buffer initialization
  tx_buf[0] = 0xA1               -- Start byte
  tx_buf[1] = 0                  -- device 
  tx_buf[2] = event & 0xFF       -- event 
  tx_buf[3] = (ep0 >> 0) & 0xFF  -- ep0_lo 
  tx_buf[4] = (ep0 >> 8) & 0xFF  -- ep0_hi
  tx_buf[5] = (ep1 >> 0) & 0xFF  -- ep1_lo 
  tx_buf[6] = (ep1 >> 8) & 0xFF  -- ep1_hi
  tx_buf[7] = (ep2 >> 0) & 0xFF  -- ep2_lo 
  tx_buf[8] = (ep2 >> 8) & 0xFF  -- ep3_hi
  -- checksum
  local checksum = 0
  for i = 0, 8 do
    checksum = checksum + tx_buf[i]
    checksum = checksum & 0xFF
  end
  tx_buf[9] = checksum
  -- send
  uart_send_data(tx_buf)
end