conn.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package modbus
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "math"
  8. "net"
  9. "strings"
  10. "sync"
  11. "time"
  12. "git.simanc.com/software/golib/v4/gio"
  13. "git.simanc.com/software/golib/v4/gnet"
  14. "git.simanc.com/software/golib/v4/log"
  15. )
  16. type PLC interface {
  17. gnet.ConnStat
  18. gnet.DataAccess
  19. io.Closer
  20. }
  21. var (
  22. ErrReadError = errors.New("modbus: read error")
  23. ErrWriteError = errors.New("modbus: write error")
  24. ErrReadTimeout = errors.New("modbus: read timeout")
  25. ErrWriteTimeout = errors.New("modbus: write timeout")
  26. ErrConnError = errors.New("modbus: connection error")
  27. ErrParamError = errors.New("modbus: parameter error")
  28. )
  29. const (
  30. MaxReadBuffSize = 1024
  31. )
  32. // 一次连续读取寄存器的最大数量
  33. const maxReadRegister = 30
  34. type modbusConn struct {
  35. conn net.Conn
  36. buf gnet.Bytes
  37. logger log.Logger
  38. mu sync.Mutex
  39. }
  40. func (w *modbusConn) IsConnected() bool {
  41. if w.conn == nil {
  42. return false
  43. }
  44. if conn, ok := w.conn.(gnet.ConnStat); ok {
  45. return conn.IsConnected()
  46. }
  47. return true
  48. }
  49. func (w *modbusConn) IsClosed() bool {
  50. if w.conn == nil {
  51. return true
  52. }
  53. if conn, ok := w.conn.(gnet.ConnStat); ok {
  54. return conn.IsClosed()
  55. }
  56. return false
  57. }
  58. // ReadData 读取原始数据, 当 count 过大时会自动分段读取
  59. // 规则:
  60. //
  61. // blockId == Code3, 表示读取保持寄存器, 每个寄存器大小为 2 个字节, count 为寄存器数量, 返回数据大小为 count*2
  62. func (w *modbusConn) ReadData(ctx context.Context, blockId, address, count int) ([]byte, error) {
  63. if !w.IsConnected() || w.IsClosed() {
  64. return nil, gnet.ErrUnconnected
  65. }
  66. w.mu.Lock()
  67. defer w.mu.Unlock()
  68. switch blockId {
  69. case Code3:
  70. if !w.checkCode3(address, count) {
  71. return nil, ErrParamError
  72. }
  73. default:
  74. // TODO 目前仅支持 4x(Code03) 地址
  75. return nil, fmt.Errorf("modbus: ReadData: unsupported funCode: %d", blockId)
  76. }
  77. pduGroup := gnet.SplitNumber(count, maxReadRegister)
  78. aduList := make([]ADU, len(pduGroup))
  79. for i, length := range pduGroup { //
  80. curAddr := address + i*maxReadRegister
  81. pdu := NewPDUReadRegisters(byte(blockId), uint16(curAddr), uint16(length))
  82. aduList[i] = NewADU(uint16(i), Protocol, 0, pdu)
  83. }
  84. buf := make([]byte, count*2)
  85. for i, adu := range aduList {
  86. b, err := w.call(ctx, adu.Serialize())
  87. if err != nil {
  88. return nil, fmt.Errorf("modbus: ReadData: %s", err)
  89. }
  90. resp, err := ParseADU(b)
  91. if err != nil {
  92. return nil, fmt.Errorf("modbus: ReadData: ParseADU: %s", err)
  93. }
  94. if err = CheckADU(adu, resp); err != nil {
  95. return nil, fmt.Errorf("modbus: ReadData: CheckADU: %s", err)
  96. }
  97. copy(buf[maxReadRegister*2*i:], resp.PDU.Data)
  98. }
  99. return buf, nil
  100. }
  101. func (w *modbusConn) WriteData(ctx context.Context, blockId, address, count int, buf []byte) error {
  102. if !w.IsConnected() || w.IsClosed() {
  103. return gnet.ErrUnconnected
  104. }
  105. w.mu.Lock()
  106. defer w.mu.Unlock()
  107. switch blockId {
  108. case Code6, Code16:
  109. if !w.checkCode6(address, count, buf) {
  110. return ErrParamError
  111. }
  112. default:
  113. return fmt.Errorf("modbus: WriteData: unsupported funCode: %d", blockId)
  114. }
  115. var (
  116. pdu PDU
  117. err error
  118. )
  119. if count == 1 {
  120. pdu, err = NewPDUWriterSingleRegisterFromBuff(uint16(address), buf)
  121. } else {
  122. pdu, err = NewPDUWriterMultipleRegistersFromBuff(uint16(address), uint16(count), buf)
  123. }
  124. if err != nil {
  125. return errors.Join(ErrParamError, err)
  126. }
  127. adu := NewADU(uint16(address), Protocol, 0, pdu)
  128. b, err := w.call(ctx, adu.Serialize())
  129. if err != nil {
  130. return fmt.Errorf("modbus: WriteData: : %s", err)
  131. }
  132. resp, err := ParseADU(b)
  133. if err != nil {
  134. return fmt.Errorf("modbus: WriteData: ParseADU: %s", err)
  135. }
  136. if resp.TransactionID != adu.TransactionID {
  137. return fmt.Errorf("modbus: WriteData: transactionID mismatch: want %d, got %d", adu.TransactionID, resp.TransactionID)
  138. }
  139. return nil
  140. }
  141. func (w *modbusConn) GetProtocolName() string {
  142. return ProtocolName
  143. }
  144. func (w *modbusConn) checkCode3(address, count int) bool {
  145. return (address >= 0 && address <= math.MaxUint16) && (count > 0 && count <= math.MaxUint16)
  146. }
  147. func (w *modbusConn) checkCode6(address, count int, buf []byte) bool {
  148. return (address >= 0 && address <= math.MaxUint16) && (count > 0 && count <= math.MaxUint16) && (len(buf)/2 == count)
  149. }
  150. func (w *modbusConn) call(ctx context.Context, b gnet.Bytes) ([]byte, error) {
  151. ctx, cancel := context.WithCancel(ctx)
  152. if _, ok := ctx.Deadline(); !ok {
  153. ctx, cancel = context.WithTimeout(ctx, gnet.ClientReadTimeout)
  154. }
  155. defer cancel()
  156. if _, err := gnet.WriteWithContext(ctx, w.conn, b); err != nil {
  157. w.logger.Error("modbus: call: failed to write response: %s", err)
  158. if isNetTimeout(err) {
  159. return nil, errors.Join(ErrWriteTimeout, err)
  160. }
  161. return nil, errors.Join(ErrWriteError, err)
  162. }
  163. w.logger.Debug("modbus: Write: %s", b.HexTo())
  164. clear(w.buf)
  165. n, err := gnet.ReadWithContext(ctx, w.conn, w.buf)
  166. if err != nil {
  167. w.logger.Error("modbus: call: failed to read response: %s", err)
  168. if isNetTimeout(err) {
  169. return nil, errors.Join(ErrReadTimeout, err)
  170. }
  171. return nil, errors.Join(ErrReadError, err)
  172. }
  173. data := w.buf[:n]
  174. w.logger.Debug("modbus: Read: %s", data.HexTo())
  175. return data, nil
  176. }
  177. func (w *modbusConn) Close() error {
  178. if w.conn == nil {
  179. return nil
  180. }
  181. return w.conn.Close()
  182. }
  183. func New(conn net.Conn, logger log.Logger) PLC {
  184. c := &modbusConn{
  185. conn: conn,
  186. buf: make([]byte, MaxReadBuffSize),
  187. logger: logger,
  188. }
  189. return c
  190. }
  191. // Conn PLC 主控连接
  192. // Deprecated, 请使用 New
  193. type Conn interface {
  194. // ConnStat 连接状态
  195. gnet.ConnStat
  196. // IsLocked 表示当前有其他线程正在与 PLC 交互
  197. IsLocked() bool
  198. // WriteResponse 向 PLC 发送数据并等待 PLC 响应
  199. WriteResponse(b []byte) ([]byte, error)
  200. // Closer 关闭与 PLC 主控的连接
  201. io.Closer
  202. }
  203. // Dialer
  204. // Deprecated, 请使用 New
  205. type Dialer struct {
  206. conn net.Conn
  207. buf []byte
  208. logger log.Logger
  209. mu sync.Mutex
  210. lock bool
  211. }
  212. func (w *Dialer) IsConnected() bool {
  213. if w.conn == nil {
  214. return false
  215. }
  216. return w.conn.(gnet.ConnStat).IsConnected()
  217. }
  218. func (w *Dialer) IsClosed() bool {
  219. if w.conn == nil {
  220. return true
  221. }
  222. return w.conn.(gnet.ConnStat).IsClosed()
  223. }
  224. func (w *Dialer) IsLocked() bool {
  225. return w.lock
  226. }
  227. // WriteResponse 写入并读取下一次的数据
  228. func (w *Dialer) WriteResponse(b []byte) ([]byte, error) {
  229. if w.conn == nil {
  230. return nil, gnet.ErrConnNotFound
  231. }
  232. w.mu.Lock()
  233. defer w.mu.Unlock()
  234. w.lock = true
  235. defer func() {
  236. w.lock = false
  237. }()
  238. w.logger.Debug("Write: %s", gnet.Bytes(b).HexTo())
  239. if i, err := w.conn.Write(b); err != nil {
  240. w.logger.Error("Write err: %d->%d %s", len(b), i, err)
  241. if isNetTimeout(err) {
  242. return nil, errors.Join(ErrWriteTimeout, err)
  243. }
  244. return nil, err
  245. }
  246. clear(w.buf)
  247. n, err := w.conn.Read(w.buf)
  248. if err != nil {
  249. w.logger.Error("Read err: %s", err)
  250. if isNetTimeout(err) {
  251. return nil, errors.Join(ErrReadTimeout, err)
  252. }
  253. return nil, err
  254. }
  255. w.logger.Debug("Read: %s", gnet.Bytes(w.buf[:n]).HexTo())
  256. return w.buf[:n], nil
  257. }
  258. func (w *Dialer) Close() error {
  259. if w.conn == nil {
  260. return nil
  261. }
  262. return w.conn.Close()
  263. }
  264. func (w *Dialer) CloseWith(ctx context.Context) {
  265. <-ctx.Done()
  266. w.logger.Warn("DialContext: %s", ctx.Err())
  267. _ = w.Close()
  268. }
  269. func (w *Dialer) DialContext(ctx context.Context, address string, logger log.Logger) (Conn, error) {
  270. config := &gnet.Config{ // 由于现场网络环境比较差, 因此加大超时时间以防止频繁掉线重连
  271. Timeout: 60 * time.Second,
  272. DialTimeout: 10 * time.Second,
  273. Reconnect: true,
  274. }
  275. return w.DialConfig(ctx, address, config, logger)
  276. }
  277. func (w *Dialer) DialConfig(ctx context.Context, address string, config *gnet.Config, logger log.Logger) (Conn, error) {
  278. deadline := time.Now().Add(config.DialTimeout)
  279. if conn, err := gnet.DialTCPConfig(address, config); err == nil {
  280. w.conn = conn
  281. } else {
  282. if timeout := deadline.Sub(time.Now()); timeout > 0 {
  283. gio.RandSleep(0, timeout)
  284. }
  285. logger.Debug("DialContext: %s", err)
  286. return nil, err
  287. }
  288. go func() {
  289. w.CloseWith(ctx)
  290. }()
  291. w.buf = make([]byte, MaxReadBuffSize)
  292. w.logger = log.Part(logger, "conn", strings.ReplaceAll(address, ":", "_"))
  293. return w, nil
  294. }
  295. func isNetTimeout(err error) bool {
  296. var ne *gnet.Timeout
  297. if errors.As(err, &ne) && ne.Timeout() {
  298. return true
  299. }
  300. return false
  301. }
  302. // DialContext
  303. // Deprecated, 请使用 New
  304. func DialContext(ctx context.Context, address string, logger log.Logger) (Conn, error) {
  305. var dialer Dialer
  306. return dialer.DialContext(ctx, address, logger)
  307. }
  308. // DialConfig
  309. // Deprecated, 请使用 New
  310. func DialConfig(ctx context.Context, address string, config *gnet.Config, logger log.Logger) (Conn, error) {
  311. var dialer Dialer
  312. return dialer.DialConfig(ctx, address, config, logger)
  313. }
  314. // Dial
  315. // Deprecated, 请使用 New
  316. func Dial(address string, logger log.Logger) (Conn, error) {
  317. return DialContext(context.Background(), address, logger)
  318. }