-- UDP Server
local socket = require("socket")
require("utils")
require("globals")

-- Module Scoped Variables (or as I like to call them local-globals)
local udp

-- Startup
function love.load()
  print("load")
  udp = socket.udp()
  udp:setsockname("*", SERVER_PORT)
  udp:settimeout(0)
  print("load done")
end

-- Scheduler 
function love.update()
  -- Check for Rx packets
  local rxDataPacket, ip, port = udp:receivefrom()
  if rxDataPacket then
    -- print the packet as hex
    printStringAsHex("Rx from " .. ip .. ":" .. port .. " ", rxDataPacket)    
    -- Turn string into an array for editing
    local rxByteArray = stringToArray(rxDataPacket)
    -- Edit values
    rxByteArray[5] = 0x66 
    -- Turn back into string
    local txDataPacket = arrayToString(rxByteArray)  
    -- Reply with the result
    udp:sendto(txDataPacket, ip, port)
  end
end

-- shutdown
function love.quit()
  print("Closing connection...")
  -- done with client, close the object
  udp:close()
  print("connection close done")
end