add : USB CDC虚拟串口通讯

This commit is contained in:
2026-04-03 12:14:43 +08:00
parent da4e944bca
commit dc518cefed
59 changed files with 13943 additions and 673 deletions

View File

@@ -0,0 +1,83 @@
require "socket"
require "log"
local ip, port = "121.43.69.62", "8767"
local clientCount = 1
local clients = {}
for i = 1, clientCount do
local client = {
id = i,
socket = nil,
connected = false
}
sys.taskInit(function()
while true do
while not socket.isReady() do sys.wait(1000) end
client.socket = socket.tcp()
log.debug("Client " .. client.id .. ": Connecting to " .. ip .. ":" .. port)
while not client.socket:connect(ip, port) do
log.warn("Client " .. client.id .. ": Connection failed, retrying...")
sys.wait(2000)
end
client.connected = true
log.debug("Client " .. client.id .. ": Connected successfully")
uart.write(1, "Socket " .. client.id .. " connected\r\n")
while client.socket:asyncSelect(60, "ping") do end
client.connected = false
client.socket:close()
log.error("Client " .. client.id .. ": Disconnected")
end
end)
clients[i] = client
end
local function toHexcode(str)
local hexcode = ""
for i = 1, #str do
hexcode = hexcode .. string.format("%02X", str:byte(i))
end
return hexcode
end
sys.subscribe("SOCKET_RECV", function(id)
for i, client in ipairs(clients) do
if client.socket and client.socket.id == id then
local data = client.socket:asyncRecv()
log.info("Client " .. client.id .. ": Received data: " .. toHexcode(data))
local frame = string.char(0x55) .. string.char(0xAA) .. string.char(0x01) .. string.char(i) .. string.char(#data) .. data .. string.char(0xAA) .. string.char(0x55)
uart.write(1, frame)
break
end
end
end)
function sendToSocket(id_byte, msg)
if clients[id_byte] and clients[id_byte].socket and clients[id_byte].connected then
clients[id_byte].socket:asyncSend(msg)
else
log.error("Socket " .. id_byte .. " not connected or does not exist")
end
end