-- Script V1 : 26_03_30

-- Reference for PIDs: https://en.wikipedia.org/wiki/OBD-II_PIDs
-- This script reads 5 time a SAE PID from service 0x01 given the ID

local rc, currentBR = can.getCurrentBaudrate()
if (currentBR == 0) then
    --Ask the user here, since there is no current CAN baudrate set and validated
    currentBR = ui.inputValue('Set CAN Baudrate', 'u', 1, 500000, 500000)
end

if (currentBR == nil) then 
    error('No CAN Baudrate provided.')
end

rc = can.init(currentBR)
if (rc ~= 0) then
    error("CAN Init failed! Error: " .. rc .. " (Invalid BUS / Invalid CAN baudrate / Key off)")
end

local PID = 0x05 -- Engine coolant temperature

f = io.open('PIDTest.log', 'w') -- Log file will be created in the root of the SD card!

for i = 1, 5 do
    local rc, data = uds.xmit(0x7E0, 0x01, PID, "", 0x7E8, 100*3)
    local msg
    
    if rc == 0 then
        msg = string.format('rc: %d -- Hex: 0x%02X -- Value: %d', rc, data:byte(1), data:byte(1) - 40)
    else
        msg = string.format('rc: %d (Error)', rc)
    end
    
    print(msg)
    f:write(msg..'\n') 
    
end

f:close()

can.uninit()
