local serialPattern = '^S%d%d%d%d%d%d%d%d$'  -- something ending in 8 numbers
local FAIL_OUTPUT = 1

-- This is called by the Keyence barcode reader each time it's triggered.
function readformatEvent()
    local barcodes = getBarcodesFromReader()
    if #barcodes == 0 then
        setReaderFailOutput()
        return 'ERROR: No barcodes found'
    end
    local result = findSerialBarcode(barcodes)
    if result == '' then
        setReaderFailOutput()
        return 'ERROR: No serial barcode found'
    end
    return result
end

function getBarcodesFromReader()
    local barcodes = {}
    for i = 1, readCount() do
        barcodes[i] = readResult(i):readData()
    end
    return barcodes
end

-- Return the first barcode that matches the serial pattern.
-- Return an empty string if no match is found.
function findSerialBarcode(barcodes)
    for _, barcode in ipairs(barcodes) do
        local match = string.match(barcode, serialPattern)
        if match then
            return match
        end
    end
    return ''
end

function setReaderFailOutput()
    outonEvent(FAIL_OUTPUT)
end

-------------------------------------------------------------------------------
-- Tests
-------------------------------------------------------------------------------

function valid_serial_is_returned()
    local expected = 'S12345678'
    local barcodes = {
        'S1234567',
        'S123456789',
        '12345678',
        'S12345678',
    }
    local result = findSerialBarcode(barcodes)
    check(expected, result)
end

function empty_string_is_returned_when_serial_is_missing()
    local expected = ''
    local barcodes = {
        'S1234567',
        'S123456789',
        '12345678',
    }
    local result = findSerialBarcode(barcodes)
    check(expected, result)
end

function empty_string_is_returned_when_no_barcodes()
    local expected = ''
    local barcodes = {}
    local result = findSerialBarcode(barcodes)
    check(expected, result)
end

function check(expected, result)
    local msg
    if result == expected then
        msg = 'Pass'
    else
        msg = 'Fail: expected "' .. expected .. '" but got "' .. result .. '".'
    end
    print(msg)
end

-- Run tests if not on Keyence hardware.
if readCount == nil then
    valid_serial_is_returned()
    empty_string_is_returned_when_serial_is_missing()
    empty_string_is_returned_when_no_barcodes()
end

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: