exmodbus.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. --[[
  2. @module exmodbus
  3. @summary exmodbus 控制Modbus RTU/ASCII/TCP主站/从站通信
  4. @version 1.0
  5. @date 2025.
  6. @author 马梦阳
  7. @usage
  8. 本文件的对外接口有 5 个:
  9. 1、exmodbus.create(config):创建 modbus 主站/从站,支持 RTU、ASCII、TCP 三种通信模式
  10. 2、modbus:read(config):主站向从站发起读取请求(仅适用于 RTU、ASCII、TCP 主站模式)
  11. 3、modbus:write(config):主站向从站发起写入请求(仅适用于 RTU、ASCII、TCP 主站模式)
  12. 4、modbus:destroy():销毁 modbus 主站/从站实例对象
  13. 5、modbus:on(callback):从站注册回调接口,用于处理主站发起的请求(仅适用于 RTU、ASCII、TCP 从站模式)
  14. ]]
  15. local exmodbus = {}
  16. -- 定义通信模式常量
  17. exmodbus.RTU_MASTER = 0 -- RTU 主站模式
  18. exmodbus.RTU_SLAVE = 1 -- RTU 从站模式
  19. exmodbus.ASCII_MASTER = 2 -- ASCII 主站模式
  20. exmodbus.ASCII_SLAVE = 3 -- ASCII 从站模式
  21. exmodbus.TCP_MASTER = 4 -- TCP 主站模式
  22. exmodbus.TCP_SLAVE = 5 -- TCP 从站模式
  23. -- 定义数据类型常量
  24. exmodbus.COIL_STATUS = 0 -- 线圈状态
  25. exmodbus.INPUT_STATUS = 1 -- 离散输入状态
  26. exmodbus.HOLDING_REGISTER = 4 -- 保持寄存器
  27. exmodbus.INPUT_REGISTER = 3 -- 输入寄存器
  28. -- 定义操作类型常量
  29. exmodbus.READ_COILS = 0x01 -- 读线圈状态
  30. exmodbus.READ_DISCRETE_INPUTS = 0x02 -- 读离散输入状态
  31. exmodbus.READ_HOLDING_REGISTERS = 0x03 -- 读保持寄存器
  32. exmodbus.READ_INPUT_REGISTERS = 0x04 -- 读输入寄存器
  33. exmodbus.WRITE_SINGLE_COIL = 0x05 -- 写单个线圈状态
  34. exmodbus.WRITE_SINGLE_HOLDING_REGISTER = 0x06 -- 写单个保持寄存器
  35. exmodbus.WRITE_MULTIPLE_HOLDING_REGISTERS = 0x10 -- 写多个保持寄存器
  36. exmodbus.WRITE_MULTIPLE_COILS = 0x0F -- 写多个线圈状态
  37. -- 定义响应结果常量
  38. exmodbus.STATUS_SUCCESS = 0 -- 收到响应数据且数据有效
  39. exmodbus.STATUS_DATA_INVALID = 1 -- 收到响应数据但数据损坏/校验失败
  40. exmodbus.STATUS_EXCEPTION = 2 -- 收到标准异常响应码
  41. exmodbus.STATUS_TIMEOUT = 3 -- 超时未收到响应
  42. -- 异常响应码常量
  43. exmodbus.ILLEGAL_FUNCTION = 0x01 -- 不支持请求的功能码
  44. exmodbus.ILLEGAL_DATA_ADDRESS = 0x02 -- 请求的数据地址无效或超出范围
  45. exmodbus.ILLEGAL_DATA_VALUE = 0x03 -- 请求的数据值无效
  46. exmodbus.SLAVE_DEVICE_FAILURE = 0x04 -- 从站在执行操作时发生内部错误
  47. exmodbus.ACKNOWLEDGE = 0x05 -- 请求已接受,但需要长时间处理
  48. exmodbus.SLAVE_DEVICE_BUSY = 0x06 -- 从站正忙,无法处理请求
  49. exmodbus.NEGATIVE_ACKNOWLEDGE = 0x07 -- 无法执行编程功能
  50. exmodbus.MEMORY_PARITY_ERROR = 0x08 -- 内存奇偶校验错误
  51. exmodbus.GATEWAY_PATH_UNAVAILABLE = 0x0A -- 网关路径不可用
  52. exmodbus.GATEWAY_TARGET_NO_RESPONSE = 0x0B -- 网关目标设备无响应
  53. -- 全局队列与调度器;
  54. local request_queue = {}
  55. local next_request_id = 1
  56. local scheduler_started = false
  57. -- 生成唯一请求 ID;
  58. local function gen_request_id()
  59. local id = next_request_id
  60. next_request_id = next_request_id + 1
  61. -- 确保请求 ID 在 32 位有符号整数范围内;
  62. if next_request_id == 0x7FFFFFFF then next_request_id = 1 end
  63. return id
  64. end
  65. -- 处理队列中的请求;
  66. local function process_request_queue()
  67. while true do
  68. if #request_queue > 0 then
  69. local req = table.remove(request_queue, 1)
  70. local instance = req.instance
  71. local config = req.config
  72. local is_read = req.is_read
  73. local req_id = req.request_id
  74. local result
  75. if is_read then
  76. result = instance:read_internal(config)
  77. else
  78. result = instance:write_internal(config)
  79. end
  80. sys.publish("exmodbus/resp/" .. req_id, result)
  81. else
  82. sys.waitUntil("start_scheduler")
  83. end
  84. end
  85. end
  86. -- 启动调度器;
  87. local function start_scheduler()
  88. if scheduler_started then return end
  89. scheduler_started = true
  90. sys.taskInit(process_request_queue)
  91. end
  92. -- 入队请求并等待响应;(内部使用)
  93. function exmodbus.enqueue_request(instance, config, is_read)
  94. -- 生成唯一请求 ID;
  95. local req_id = gen_request_id()
  96. -- 检查队列是否为空;
  97. -- 如果为空,先入队,然后发布主题告知调度器开始处理;
  98. -- 如果不为空,则直接入队,不用告知调度器;
  99. if #request_queue == 0 then
  100. -- 入队请求;
  101. table.insert(request_queue, {
  102. instance = instance,
  103. config = config,
  104. is_read = is_read,
  105. request_id = req_id
  106. })
  107. sys.publish("start_scheduler")
  108. else
  109. -- 入队请求;
  110. table.insert(request_queue, {
  111. instance = instance,
  112. config = config,
  113. is_read = is_read,
  114. request_id = req_id
  115. })
  116. end
  117. -- 启动调度器;
  118. start_scheduler()
  119. local ok, result = sys.waitUntil("exmodbus/resp/" .. req_id)
  120. return result
  121. end
  122. --[[
  123. 创建一个新的实例;
  124. @api exmodbus.create(config)
  125. @param config table 配置参数表,包含以下字段:
  126. mode number 通信模式,必须是 exmodbus 模块定义的常量(如 exmodbus.RTU_MASTER)
  127. uart_id number 串口 ID,uart0 写 0,uart1 写 1,以此类推
  128. baud_rate number 波特率
  129. data_bits number 数据位
  130. stop_bits number 停止位
  131. parity_bits number 校验位
  132. byte_order number 字节顺序
  133. rs485_dir_gpio number RS485 方向转换 GPIO 引脚
  134. rs485_dir_rx_level number RS485 接收方向电平
  135. adapter number 网卡 ID
  136. ip_address string 服务器 IP 地址
  137. port number 服务器端口号
  138. is_udp boolean 是否使用 UDP 协议
  139. is_tls boolean 是否使用加密传输
  140. keep_idle number 连接空闲多长时间后,开始发送第一个 keepalive 探针报文,单位:秒
  141. keep_interval number 发送第一个探针后,如果没收到 ACK 回复,间隔多久再发送下一个探针,单位:秒
  142. keep_cnt number 总共发送多少次探针后,如果依然没有回复,则判断连接已断开
  143. server_cert string TCP 模式下的服务器 CA 证书数据,UDP 模式下的 PSK
  144. client_cert string TCP 模式下的客户端证书数据,UDP 模式下的 PSK-ID
  145. client_key string TCP 模式下的客户端私钥加密数据
  146. client_password string TCP 模式下的客户端私钥口令数据
  147. @return table/nil 成功时返回实例对象,失败时返回 nil
  148. @usage
  149. RTU/ASCII 通信模式:
  150. local config = {
  151. mode = exmodbus.RTU_MASTER, -- 通信模式:RTU 主站
  152. uart_id = 1, -- 串口 ID:uart1
  153. baud_rate = 115200, -- 波特率:115200
  154. data_bits = 8, -- 数据位:8
  155. stop_bits = 1, -- 停止位:1
  156. parity_bits = uart.None, -- 校验位:无校验
  157. byte_order = uart.LSB, -- 字节顺序:小端序
  158. rs485_dir_gpio = 23, -- RS485 方向转换 GPIO 引脚
  159. rs485_dir_rx_level = 0 -- RS485 接收方向电平:0 为低电平,1 为高电平
  160. }
  161. local rtu_master = exmodbus.create(config)
  162. TCP 通信模式:
  163. local config = {
  164. mode = exmodbus.TCP_MASTER, -- 通信模式:TCP 主站
  165. adapter = socket.LWIP_ETH, -- 网卡 ID:LwIP 协议栈的以太网卡
  166. ip_address = "192.168.1.100", -- 服务器 IP 地址:192.168.1.100(主站:服务器 IP;从站:本地 IP,从站可以不用填此参数)
  167. port = 502, -- 服务器端口号:502(主站:服务器端口;从站:本地端口)
  168. is_udp = false, -- 是否使用 UDP 协议:不使用 UDP 协议,false/nil 表示使用 TCP 协议
  169. is_tls = false, -- 是否使用加密传输:不使用加密传输,false/nil 表示不使用加密
  170. keep_idle = 300, -- 连接空闲多长时间后,开始发送第一个 keepalive 探针报文:300 秒
  171. keep_interval = 10, -- 发送第一个探针后,如果没收到 ACK 回复,间隔多久再发送下一个探针:10 秒
  172. keep_cnt = 3, -- 总共发送多少次探针后,如果依然没有回复,则判断连接已断开:3 次
  173. server_cert = nil, -- TCP 模式下的服务器 CA 证书数据,UDP 模式下的 PSK:如果客户端不需要验证服务器证书,则设为 nil 或空着
  174. client_cert = nil, -- TCP 模式下的客户端证书数据,UDP 模式下的 PSK-ID:如果服务器不需要验证客户端证书,则设为 nil 或空着
  175. client_key = nil, -- TCP 模式下的客户端私钥加密数据:如果服务器不需要验证客户端私钥,则设为 nil 或空着
  176. client_password = nil -- TCP 模式下的客户端私钥口令数据:如果服务器不需要验证客户端私钥口令,则设为 nil 或空着
  177. }
  178. local tcp_master = exmodbus.create(config)
  179. --]]
  180. function exmodbus.create(config)
  181. -- 检查配置参数是否有效;
  182. if not config or type(config) ~= "table" then
  183. log.error("exmodbus", "配置必须是表格类型")
  184. return false
  185. end
  186. -- 根据通信模式加载对应的模块;
  187. if config.mode == exmodbus.RTU_MASTER or config.mode == exmodbus.RTU_SLAVE or
  188. config.mode == exmodbus.ASCII_MASTER or config.mode == exmodbus.ASCII_SLAVE then
  189. local result, mod = pcall(require, "exmodbus_rtu_ascii")
  190. if not result then
  191. log.error("exmodbus", "加载 RTU/ASCII 模块失败")
  192. return false
  193. end
  194. return mod.create(config, exmodbus, gen_request_id)
  195. elseif config.mode == exmodbus.TCP_MASTER or config.mode == exmodbus.TCP_SLAVE then
  196. local result, mod = pcall(require, "exmodbus_tcp")
  197. if not result then
  198. log.error("exmodbus", "加载 TCP 模块失败")
  199. return false
  200. end
  201. return mod.create(config, exmodbus, gen_request_id)
  202. else
  203. log.error("exmodbus", "通信模式不支持")
  204. return false
  205. end
  206. end
  207. --[[
  208. 主站向从站发送读取请求(仅适用于 RTU、ASCII、TCP 主站模式)
  209. @api modbus:read(config)
  210. @param config table 配置参数表,包含以下字段:
  211. slave_id number 从站 ID
  212. reg_type number 寄存器类型
  213. start_addr number 寄存器起始地址
  214. reg_count number 寄存器数量
  215. raw_request string 原始请求帧
  216. timeout number 超时时间,单位:毫秒
  217. @return table 包含以下字段:
  218. status number 响应结果状态码,参考 exmodbus 模块定义的常量(如 exmodbus.STATUS_SUCCESS)
  219. execption_code number 异常码,仅在 status 为 exmodbus.STATUS_EXCEPTION 时有效
  220. data table 寄存器数值,仅在 status 为 exmodbus.STATUS_SUCCESS 时有效,包含以下字段
  221. [start_addr] number 寄存器数值,索引为寄存器地址,值为寄存器数值
  222. ...
  223. raw_response string 原始响应帧
  224. @usage
  225. 用户在传入 config 参数时,有 原始帧 和 字段参数 两种方式
  226. 1. 原始帧方式
  227. local read_config = {
  228. raw_request = "010300000002C40B", -- 原始请求帧:01 03 00 00 00 02 C4 0B(读取保持寄存器 0x0000 开始的 2 个寄存器)
  229. timeout = 1000 -- 超时时间:1000 毫秒
  230. }
  231. local result = modbus:read(read_config)
  232. if result.status == exmodbus.STATUS_SUCCESS then
  233. log.info("exmodbus_test", "读取成功,原始响应帧: ", table.concat(result.raw_response, ", "))
  234. elseif result.status == exmodbus.STATUS_TIMEOUT then
  235. log.error("exmodbus_test", "读取请求超时")
  236. else
  237. log.error("exmodbus_test", "读取失败")
  238. end
  239. 2. 字段参数方式
  240. local read_config = {
  241. slave_id = 1, -- 从站 ID:1
  242. reg_type = exmodbus.HOLDING_REGISTER, -- 寄存器类型:保持寄存器
  243. start_addr = 0x0000, -- 寄存器起始地址:0
  244. reg_count = 0x0002, -- 寄存器数量:2
  245. timeout = 1000 -- 超时时间:1000 毫秒
  246. }
  247. local result = modbus:read(read_config)
  248. -- 根据返回状态处理结果
  249. if result.status == exmodbus.STATUS_SUCCESS then
  250. -- 数据解析:
  251. log.info("exmodbus_test", "成功读取到从站 1 保持寄存器 0-2 的值,寄存器 0 数值:", result.data[result.start_addr],
  252. ",寄存器 1 数值:", result.data[result.start_addr + 1])
  253. elseif result.status == exmodbus.STATUS_DATA_INVALID then
  254. log.info("exmodbus_test", "收到从站 1 的响应数据但数据损坏/校验失败")
  255. elseif result.status == exmodbus.STATUS_EXCEPTION then
  256. log.info("exmodbus_test", "收到从站 1 的 modbus 标准异常响应,异常码为", result.execption_code)
  257. elseif result.status == exmodbus.STATUS_TIMEOUT then
  258. log.info("exmodbus_test", "未收到从站 1 的响应(超时)")
  259. end
  260. --]]
  261. -- 该接口在各个子文件中,此处仅用作注释
  262. -- function modbus:read(config) end
  263. --[[
  264. 主站向从站发送写入请求(仅适用于 RTU、ASCII、TCP 主站模式)
  265. @api modbus:write(config)
  266. @param config table 配置参数表,包含以下字段:
  267. slave_id number 从站 ID
  268. reg_type number 寄存器类型
  269. start_addr number 寄存器起始地址
  270. reg_count number 寄存器数量
  271. data table 寄存器数值,包含以下字段:
  272. [start_addr] number 寄存器数值,索引为寄存器地址,值为寄存器数值
  273. ...
  274. force_multiple boolean 是否强制使用写多个功能码进行写入单个寄存器操作
  275. raw_request string 原始请求帧
  276. timeout number 超时时间,单位:毫秒
  277. @return table 包含以下字段:
  278. status number 响应结果状态码,参考 exmodbus 模块定义的常量(如 exmodbus.STATUS_SUCCESS)
  279. execption_code number 异常码,仅在 status 为 exmodbus.STATUS_EXCEPTION 时有效
  280. raw_response string 原始响应帧
  281. @usage
  282. 用户在传入 config 参数时,有 原始帧 和 字段参数 两种方式
  283. 1. 原始帧方式
  284. local write_config = {
  285. raw_request = "011000000002007B01592471", -- 原始请求帧:01 10 00 00 00 02 00 7B 01 59 24 71(写入保持寄存器 0x0000 开始的 2 个寄存器,值为 0x007B 和 0x0159)
  286. timeout = 1000 -- 超时时间:1000 毫秒
  287. }
  288. local result = modbus:write(write_config)
  289. if result.status == exmodbus.STATUS_SUCCESS then
  290. log.info("exmodbus_test", "写入成功,原始响应帧: ", table.concat(result.raw_response, ", "))
  291. elseif result.status == exmodbus.STATUS_TIMEOUT then
  292. log.error("exmodbus_test", "写入请求超时")
  293. else
  294. log.error("exmodbus_test", "写入失败")
  295. end
  296. 2. 字段参数方式
  297. local write_config = {
  298. slave_id = 1, -- 从站 ID:1
  299. reg_type = exmodbus.HOLDING_REGISTER, -- 寄存器类型:保持寄存器
  300. start_addr = 0x0000, -- 寄存器起始地址:0
  301. reg_count = 0x0002, -- 寄存器数量:2
  302. data = {
  303. [0x0000] = 0x007B, -- 寄存器 0 数值:0x007B
  304. [0x0001] = 0x0159, -- 寄存器 1 数值:0x0159
  305. },
  306. timeout = 1000 -- 超时时间:1000 毫秒
  307. }
  308. local result = modbus:write(write_config)
  309. -- 根据返回状态处理结果
  310. if result.status == exmodbus.STATUS_SUCCESS then
  311. log.info("exmodbus_test", "成功写入从站 1 保持寄存器 0-2 的值")
  312. elseif result.status == exmodbus.STATUS_DATA_INVALID then
  313. log.info("exmodbus_test", "收到从站 1 的响应数据但数据损坏/校验失败")
  314. elseif result.status == exmodbus.STATUS_EXCEPTION then
  315. log.info("exmodbus_test", "收到从站 1 的 modbus 标准异常响应,异常码为", result.execption_code)
  316. elseif result.status == exmodbus.STATUS_TIMEOUT then
  317. log.info("exmodbus_test", "未收到从站 1 的响应(超时)")
  318. end
  319. --]]
  320. -- 该接口在各个子文件中,此处仅用作注释
  321. -- function modbus:write(config) end
  322. --[[
  323. 销毁 modbus 主站/从站实例对象
  324. @api modbus:destroy()
  325. @return nil
  326. @usage
  327. modbus:destroy()
  328. --]]
  329. -- 该接口在各个子文件中,此处仅用作注释
  330. -- function modbus:destroy() end
  331. --[[
  332. 从站注册回调接口,用于处理主站发起的请求(仅适用于 RTU、ASCII、TCP 从站模式)
  333. @api modbus:on(callback)
  334. @param callback function 回调函数,格式为:
  335. function callback(request)
  336. -- 用户代码
  337. end
  338. 该回调函数接收 requset 一个参数,该参数为 table 类型,包含以下字段:
  339. slave_id number 从站 ID
  340. func_code number 功能码
  341. reg_type number 寄存器类型
  342. start_addr number 寄存器起始地址
  343. reg_count number 寄存器数量
  344. data table 寄存器数值,包含以下字段:
  345. [start_addr] number 寄存器数值,索引为寄存器地址,值为寄存器数值
  346. ...
  347. @return nil
  348. @usage
  349. function callback(request)
  350. -- 用户处理代码
  351. end
  352. --]]
  353. -- 该接口在各个子文件中,此处仅用作注释
  354. -- modbus:on(callback)
  355. return exmodbus