Skip to main content

CAN

can library implements CAN bus communication.

can.new

-- @param address string CAN device name
-- @return table
function can.new(address)
end

Creates a new CAN connection object (referred as can_conn below). It does not yet initiate an actual connection. Instead it will be initiated on a first request.

Example

can_caonn = can.new("can0")

can_conn Object

subscribe

Subscribes to handle CAN packets. can_handler will be called every time a CAN packet is received.

subscribe should be called only once for a single can_conn object.

Returns nil if performed successfully, otherwise returns error string.

-- @param can_handler function Handler of incoming CAN packets
-- @return string error
function can_conn:subscribe(can_handler)
end

-- @param msg_id number CAN message ID
-- @param data string CAN data frame, up to 8 bytes
function can_handler(msg_id, data)
end

Example

function can_handler(msg_id, data)
local bytes = { string.byte(data, 1, -1) } -- convert to array of bytes
enapter.log("CAN frame received: " .. tostring(msg_id) .. "[" .. table.concat(bytes) .. "]")
if msg_id == 0x01D0 then
local sensor = bytes[1]
enapter.log("Sensor data: " .. sensor) -- interpret first byte as a sensor value
end
end

can_conn = can.new("can0")
local err = can_conn:subscribe(can_handler)
if err ~= nil then
enapter.log("CAN subscribe failed: "..err, "error", true)
end

send

Sends CAN frame to CAN bus. Data must be a string of up to 8 bytes.

Returns nil if performed successfully, otherwise returns error string.

-- @param msg_id number CAN message ID
-- @param data string CAN data frame, up to 8 bytes
-- @return string error
function can.send(msg_id, data)
end

Example

local data = string.pack("I1I1", 58, 92) -- pack two 1 byte values

local err = can_conn.send(0x01D0, data)
if err ~= nil then
enapter.log("Sending CAN frame failed: "..err, "error", true)
end
Hardware diversity is welcome. Integrate any device into a unified energy network.
© 2024 Enapter
Developer toolkit
DocumentationReference