feat(mes): AGV挂起动作引擎 + 智能跟车流转 + PLC快照缓存(2026-11-19 主控拍板)
一、AGV 挂起动作引擎(弃显式任务队列、弃并发硬拒) - 新增 internal/logic/agv_pending.go:待发动作直接挂任务(pending_action + pending_since), CONTINUE_LIFT(举升完成→continueTask#1)/ WAIT_DROP_CONFIRM(人工确认放下→continueTask#2) / FREE_ROBOT(末组完成→freeRobot);系统动作超 60s 未触发转预警人工重试,绝不自动重发 - Client 新增 ContinueTask(RCS 2.1.2) / FreeRobot(3.1.2),仅点名释放指定车,禁止释放全部 - agv_task 增 pending_action/pending_since 字段,ent 重生成 + db.go 幂等迁移补丁 + migrateonce - 回调按 B01/B02/C01 模板编排:业务流转到位即自动放行放下、回调自动放车; 仅人工派车(MANUAL)挂 WAIT_DROP_CONFIRM;新增 /agv/confirm-drop、/agv/pending/retry - 前端 AgvManual/Agv 确认放下、挂起重试按钮与等待提示联动 二、智能跟车 + 动态目标截断流转引擎 - 新增 internal/logic/flow_engine.go:事件驱动(报工/扫码),读 48 位物理快照,从下游往上游算, 前方占用则动态截断到最近空闲缓存位;IN_TRANSIT 在途闭锁防重复下发,MW=0 才确认到位落台账; 主线占用=台账 OR 传感器,工位 G 位只认台账;在途超 5s 落预警 - workpiece 增 flow_transit_mw/target/at 字段,ent 重生成 + 迁移补丁 三、PLC 读取优化与诊断 - 新增 internal/plc/snapshot_cache.go:2s TTL + singleflight + 写失效,合并 SSE/PLC监控/流转引擎 的重复点位读取;tcp.go 读块重构、localip.go 多网卡、plcdiag 诊断工具、plc_monitor/logging 配套 四、文档与前端 - help.js 重写「工位下发」帮助:明确报工自动驱动流转 vs 下发路线码的定位、缺料/握手/撤回边界 - 案例.md 补充定稿说明;public/index.html 构建指纹更新
This commit is contained in:
@@ -12,21 +12,33 @@ import (
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
||||
var commTag = netutil.Tag()
|
||||
|
||||
// logClient 日志装饰器:inner 为真实实现(s7Real / tcpClient / mock)。
|
||||
type logClient struct{ inner Client }
|
||||
// tag 为"[host=本机出口IP]",按实际连接 PLC 的目标地址做路由探测得出——多网卡机器上
|
||||
// 它精确指出"连 PLC 走的是哪块网卡的 IP",断网排查时不再被 APIPA 虚拟地址误导。
|
||||
type logClient struct {
|
||||
inner Client
|
||||
tag string
|
||||
}
|
||||
|
||||
func newLogClient(inner Client) *logClient { return &logClient{inner: inner} }
|
||||
// newLogClient 按 PLC 目标地址解析本机出口 IP。target 形如 "192.168.22.20:102";
|
||||
// 探测不到(如纯 mock 无目标)时回退到通用 netutil.Tag()。进程构造期算一次,不逐请求枚举。
|
||||
func newLogClient(inner Client, target string) *logClient {
|
||||
tag := netutil.Tag()
|
||||
if target != "" {
|
||||
if ip := netutil.LocalIPFor(target); ip != "" {
|
||||
tag = "[host=" + ip + "]"
|
||||
}
|
||||
}
|
||||
return &logClient{inner: inner, tag: tag}
|
||||
}
|
||||
|
||||
func (l *logClient) SendProcessCode(ctx context.Context, combination string) ([]int, error) {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" --> SendProcessCode combination=%s", combination)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" --> SendProcessCode combination=%s", combination)
|
||||
codes, err := l.inner.SendProcessCode(ctx, combination)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- SendProcessCode err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- SendProcessCode err=%v", err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- SendProcessCode codes=%v", codes)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- SendProcessCode codes=%v", codes)
|
||||
}
|
||||
return codes, err
|
||||
}
|
||||
@@ -34,24 +46,24 @@ func (l *logClient) SendProcessCode(ctx context.Context, combination string) ([]
|
||||
func (l *logClient) QueryDone(ctx context.Context) (bool, error) {
|
||||
done, err := l.inner.QueryDone(ctx)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryDone err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- QueryDone err=%v", err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryDone done=%v", done)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- QueryDone done=%v", done)
|
||||
}
|
||||
return done, err
|
||||
}
|
||||
|
||||
func (l *logClient) AckDone(ctx context.Context, ok bool) {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" AckDone ok=%v", ok)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" AckDone ok=%v", ok)
|
||||
l.inner.AckDone(ctx, ok)
|
||||
}
|
||||
|
||||
func (l *logClient) QueryDockPallet(ctx context.Context, dockCode string) (bool, error) {
|
||||
has, err := l.inner.QueryDockPallet(ctx, dockCode)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryDockPallet dock=%s err=%v", dockCode, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- QueryDockPallet dock=%s err=%v", dockCode, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryDockPallet dock=%s hasPallet=%v", dockCode, has)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- QueryDockPallet dock=%s hasPallet=%v", dockCode, has)
|
||||
}
|
||||
return has, err
|
||||
}
|
||||
@@ -59,9 +71,9 @@ func (l *logClient) QueryDockPallet(ctx context.Context, dockCode string) (bool,
|
||||
func (l *logClient) QueryStationPallet(ctx context.Context, stationNo int) (bool, error) {
|
||||
has, err := l.inner.QueryStationPallet(ctx, stationNo)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryStationPallet station=%d err=%v", stationNo, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- QueryStationPallet station=%d err=%v", stationNo, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryStationPallet station=%d hasPallet=%v", stationNo, has)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- QueryStationPallet station=%d hasPallet=%v", stationNo, has)
|
||||
}
|
||||
return has, err
|
||||
}
|
||||
@@ -69,7 +81,7 @@ func (l *logClient) QueryStationPallet(ctx context.Context, stationNo int) (bool
|
||||
func (l *logClient) ReadBits(ctx context.Context) ([]bool, error) {
|
||||
bits, err := l.inner.ReadBits(ctx)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadBits err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- ReadBits err=%v", err)
|
||||
} else {
|
||||
// 48 位压成 0/1 字符串,一行可读
|
||||
s := make([]byte, len(bits))
|
||||
@@ -80,7 +92,7 @@ func (l *logClient) ReadBits(ctx context.Context) ([]bool, error) {
|
||||
s[i] = '0'
|
||||
}
|
||||
}
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- ReadBits bits=%s", string(s))
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- ReadBits bits=%s", string(s))
|
||||
}
|
||||
return bits, err
|
||||
}
|
||||
@@ -88,9 +100,9 @@ func (l *logClient) ReadBits(ctx context.Context) ([]bool, error) {
|
||||
func (l *logClient) ReadMW(ctx context.Context, addr int) (int, error) {
|
||||
v, err := l.inner.ReadMW(ctx, addr)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadMW MW%d err=%v", addr, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- ReadMW MW%d err=%v", addr, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- ReadMW MW%d=%d", addr, v)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- ReadMW MW%d=%d", addr, v)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
@@ -98,18 +110,18 @@ func (l *logClient) ReadMW(ctx context.Context, addr int) (int, error) {
|
||||
func (l *logClient) ReadMWBlock(ctx context.Context, start, count int) ([]int, error) {
|
||||
vals, err := l.inner.ReadMWBlock(ctx, start, count)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadMWBlock MW%d..MW%d err=%v", start, start+count-1, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- ReadMWBlock MW%d..MW%d err=%v", start, start+count-1, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- ReadMWBlock MW%d..MW%d vals=%v", start, start+count-1, vals)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" <-- ReadMWBlock MW%d..MW%d vals=%v", start, start+count-1, vals)
|
||||
}
|
||||
return vals, err
|
||||
}
|
||||
|
||||
func (l *logClient) WriteMW(ctx context.Context, addr, value int) error {
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" --> WriteMW MW%d=%d", addr, value)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+l.tag+" --> WriteMW MW%d=%d", addr, value)
|
||||
err := l.inner.WriteMW(ctx, addr, value)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- WriteMW MW%d=%d err=%v", addr, value, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+l.tag+" <-- WriteMW MW%d=%d err=%v", addr, value, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package plc
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -46,6 +47,10 @@ type Client interface {
|
||||
WriteMW(ctx context.Context, addr, value int) error
|
||||
}
|
||||
|
||||
// plcSnapshotTTL 48 位快照缓存有效期(2026-11-19 智能跟车):
|
||||
// 2 秒内对 PLC 的多次全量读合并为一次;写 MW 后立即失效重建,兼顾负载与实时性。
|
||||
const plcSnapshotTTL = 2 * time.Second
|
||||
|
||||
// Manager 管理 PLC 客户端实例
|
||||
type Manager struct {
|
||||
client Client
|
||||
@@ -54,15 +59,18 @@ type Manager struct {
|
||||
onFail func(ctx context.Context, err error) // 2026-11-16:连续失败首次沿触发(通信异常预警),恢复后重置
|
||||
mu sync.Mutex
|
||||
consecFails int
|
||||
mockOffline bool // mock 模式:模拟 PLC 离线(拍板2 联调/自测用,真实 PLC 忽略)
|
||||
mockOffline bool // mock 模式:模拟 PLC 离线(拍板2 联调/自测用,真实 PLC 忽略)
|
||||
snap *snapshotCache // 48 位快照缓存(读合并 + 写失效)
|
||||
}
|
||||
|
||||
func NewManager(c config.PlcConf, mock bool) (*Manager, error) {
|
||||
m := &Manager{mock: mock}
|
||||
m := &Manager{mock: mock, snap: newSnapshotCache(plcSnapshotTTL)}
|
||||
// 日志前缀按实际连接目标做路由探测,精确显示连 PLC 走的是哪块网卡的 IP。
|
||||
target := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
if mock {
|
||||
m.client = newLogClient(newMockClient())
|
||||
m.client = newLogClient(newMockClient(), target)
|
||||
} else {
|
||||
m.client = newLogClient(newTcpClient(c))
|
||||
m.client = newLogClient(newTcpClient(c), target)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -103,13 +111,20 @@ func (m *Manager) QueryStationPallet(ctx context.Context, stationNo int) (bool,
|
||||
return v, err
|
||||
}
|
||||
|
||||
// ReadBits 读 48 位点位信号(带恢复检测)。
|
||||
// ReadBits 读 48 位点位信号(带恢复检测,穿透缓存,实时)。
|
||||
func (m *Manager) ReadBits(ctx context.Context) ([]bool, error) {
|
||||
v, err := m.client.ReadBits(ctx)
|
||||
m.track(err)
|
||||
return v, err
|
||||
}
|
||||
|
||||
// ReadBitsCached 读 48 位快照(2 秒 TTL + singleflight 合并 + 写失效)。
|
||||
// 看板/监控/流转引擎的"看一眼全量点位"走这里,避免高频轮询打死 PLC;
|
||||
// 进站、到位等精细业务确认必须走 ReadBits/ReadMW 穿透,拿实时值。
|
||||
func (m *Manager) ReadBitsCached(ctx context.Context) ([]bool, error) {
|
||||
return m.snap.get(ctx, m.ReadBits)
|
||||
}
|
||||
|
||||
// ReadMW 读 16 位寄存器(带恢复检测)。
|
||||
func (m *Manager) ReadMW(ctx context.Context, addr int) (int, error) {
|
||||
v, err := m.client.ReadMW(ctx, addr)
|
||||
@@ -125,8 +140,13 @@ func (m *Manager) ReadMWBlock(ctx context.Context, start, count int) ([]int, err
|
||||
}
|
||||
|
||||
// WriteMW 写 16 位寄存器(带恢复检测)。
|
||||
// 2026-11-19:写入成功后立即失效 48 位快照——下一条指令/判定读到的是下发后的真实物理状态,
|
||||
// 杜绝"下发了却仍吃 2 秒前旧缓存"造成误判(用户拍板的写即失效兜底)。写失败不失效(状态未变)。
|
||||
func (m *Manager) WriteMW(ctx context.Context, addr, value int) error {
|
||||
err := m.client.WriteMW(ctx, addr, value)
|
||||
if err == nil {
|
||||
m.snap.invalidate()
|
||||
}
|
||||
m.track(err)
|
||||
return err
|
||||
}
|
||||
@@ -203,4 +223,4 @@ func parseCombination(s string) []int {
|
||||
// Sleep 简化轮询间隔(供 logic 使用)
|
||||
func Sleep(d time.Duration) {
|
||||
time.Sleep(d)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package plc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// bitsSnapshot 一次 48 位点位快照(MB895~MB902)。
|
||||
// 全程只存副本,调用方改动不影响缓存。
|
||||
type bitsSnapshot struct {
|
||||
bits []bool
|
||||
at time.Time
|
||||
}
|
||||
|
||||
// snapshotCache 全局单例的 PLC 48 位快照缓存(2026-11-19 智能跟车)。
|
||||
//
|
||||
// 目的:看板 SSE / PLC 监控 WS / 流转引擎 每轮都要读一次全量点位。多网卡、高频轮询
|
||||
// 叠加时若不合并,会在 2 秒内对同一条 S7 连接打多次读事务。这里做两件事:
|
||||
// 1. TTL:snapshotTTL 内的重复读直接返回同一份快照,不碰 PLC;
|
||||
// 2. singleflight:TTL 过期瞬间并发的 N 个读,只放 1 个真读打 PLC,其余等结果;
|
||||
// 3. 写失效:任何 WriteMW 后调用 Invalidate(),立即丢弃旧快照,下次读强制重建——
|
||||
// 保证"下发指令 → 再读点位"不会因为吃了 2 秒旧缓存而误判(用户拍板的兜底)。
|
||||
//
|
||||
// 业务精细确认(进站判定读单个 MW / 到位确认)不走本缓存,直接穿透PLC,实时取值。
|
||||
type snapshotCache struct {
|
||||
mu sync.Mutex
|
||||
ttl time.Duration
|
||||
snap *bitsSnapshot
|
||||
loading bool
|
||||
waiters []chan struct{}
|
||||
}
|
||||
|
||||
func newSnapshotCache(ttl time.Duration) *snapshotCache {
|
||||
return &snapshotCache{ttl: ttl}
|
||||
}
|
||||
|
||||
// get 取快照:命中 TTL 直接返回;并发只放一个真读(load),其余等待共享结果。
|
||||
func (c *snapshotCache) get(ctx context.Context, load func(context.Context) ([]bool, error)) ([]bool, error) {
|
||||
c.mu.Lock()
|
||||
if c.snap != nil && time.Since(c.snap.at) < c.ttl {
|
||||
bits := append([]bool(nil), c.snap.bits...)
|
||||
c.mu.Unlock()
|
||||
return bits, nil
|
||||
}
|
||||
if c.loading {
|
||||
ch := make(chan struct{})
|
||||
c.waiters = append(c.waiters, ch)
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
c.mu.Lock()
|
||||
if c.snap != nil {
|
||||
bits := append([]bool(nil), c.snap.bits...)
|
||||
c.mu.Unlock()
|
||||
return bits, nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
// 真读失败导致无快照,等待者各自穿透重试(不把错误缓存)。
|
||||
return load(ctx)
|
||||
}
|
||||
c.loading = true
|
||||
c.mu.Unlock()
|
||||
|
||||
bits, err := load(ctx)
|
||||
|
||||
c.mu.Lock()
|
||||
if err == nil {
|
||||
c.snap = &bitsSnapshot{bits: append([]bool(nil), bits...), at: time.Now()}
|
||||
}
|
||||
c.loading = false
|
||||
waiters := c.waiters
|
||||
c.waiters = nil
|
||||
c.mu.Unlock()
|
||||
for _, ch := range waiters {
|
||||
close(ch)
|
||||
}
|
||||
return bits, err
|
||||
}
|
||||
|
||||
// invalidate 让缓存立即过期(写 MW 后调用):丢弃快照,下次 get 强制真读重建。
|
||||
func (c *snapshotCache) invalidate() {
|
||||
c.mu.Lock()
|
||||
c.snap = nil
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -27,64 +27,76 @@ import (
|
||||
const (
|
||||
plcBlockStartByte = 895
|
||||
plcBlockBytes = 8
|
||||
plcReadTimeout = 30 * time.Second
|
||||
// plcOpTimeout 单次 S7 网络操作的硬上限(拨号 + 一次读/写事务的收尾)。
|
||||
// 2026-11-19 修正:原值 30s 与上层 plcHardCut 2.5s 严重错配——gos7 的 Send 用
|
||||
// conn.SetDeadline(lastActivity+Timeout) 做读超时,30s 内不返回的读会把事务层
|
||||
// 的串行闸一直占住;上层虽已 2.5s 硬切返回,底层 goroutine 仍在拨号/读,后续
|
||||
// 每轮轮询全部堵在闸上 → 日志里成片 context deadline exceeded。现场实测正常
|
||||
// 单次读 <50ms(诊断工具 17ms 建连),1.5s 已是极宽裕的容错,断电时也能Quick fail。
|
||||
plcOpTimeout = 1500 * time.Millisecond
|
||||
)
|
||||
|
||||
// s7Real 真实西门子 S7 客户端(gos7),持有一条长连接,断线惰性重连。
|
||||
//
|
||||
// 并发模型(2026-11-19 重构,修复 PLC 强制断链 / 重连风暴):
|
||||
// - gos7 的 Client 用同一个 TCPClientHandler/conn + 自增事务号收发,并非并发安全:
|
||||
// 两个 goroutine 同时在一条连接上做 AGReadMB,会出现请求-响应错配、读到半包、
|
||||
// PLC 协议栈拒绝报文并主动 RST(日志里 "forcibly closed by the remote host")。
|
||||
// - 因此连接建立 + 每一次读/写事务全程在 opMu 内串行执行,任何时刻只有一条 S7 事务在途。
|
||||
// - 串行化后单事务耗时可控(<50ms),不会拖垮 3s 一轮的监控页快照 / 看板 SSE。
|
||||
type s7Real struct {
|
||||
c config.PlcConf
|
||||
handler *gos7.TCPClientHandler
|
||||
client gos7.Client
|
||||
mu sync.Mutex
|
||||
opMu sync.Mutex // 串行闸:连接 + 单次事务全程持有,保证 gos7 单连接不被并发访问
|
||||
}
|
||||
|
||||
func newS7Real(c config.PlcConf) *s7Real {
|
||||
h := gos7.NewTCPClientHandler(c.Host, c.Rack, c.Slot)
|
||||
h.Timeout = plcReadTimeout
|
||||
h.Timeout = plcOpTimeout
|
||||
return &s7Real{c: c, handler: h}
|
||||
}
|
||||
|
||||
// ensure 惰性连接 + 断线重连。
|
||||
func (s *s7Real) ensure() error {
|
||||
// ensure 惰性连接 + 断线重连。调用方必须已持有 s.opMu。
|
||||
// 用 ConnectContext 而非 Connect:gos7 的 Connect() 内部走 context.Background(),
|
||||
// 拨号不可打断;带 ctx 后上层 plcHardCut 硬切能真正取消拨号,不留后台 goroutine。
|
||||
func (s *s7Real) ensure(ctx context.Context) error {
|
||||
if s.client != nil {
|
||||
return nil
|
||||
}
|
||||
if err := s.handler.Connect(); err != nil {
|
||||
if err := s.handler.ConnectContext(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
s.client = gos7.NewClient(s.handler)
|
||||
return nil
|
||||
}
|
||||
|
||||
// readBlock 读取 48 位块(MB895..MB900)原始 6 字节。
|
||||
// run 在串行闸内执行一条 S7 事务:确保连接 → 执行 fn → 出错即断链(下轮惰性重连)。
|
||||
// 拨号阶段认 ctx(可被上层硬切取消);读/写事务阶段由 gos7 的 plcOpTimeout 兜底。
|
||||
func (s *s7Real) run(ctx context.Context, fn func(gos7.Client) error) error {
|
||||
s.opMu.Lock()
|
||||
defer s.opMu.Unlock()
|
||||
if err := s.ensure(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fn(s.client); err != nil {
|
||||
_ = s.handler.Close()
|
||||
s.client = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readBlock 读取 48 位块(MB895..MB902)原始 8 字节。
|
||||
func (s *s7Real) readBlock(ctx context.Context) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
cl := s.client
|
||||
need := cl == nil
|
||||
if need {
|
||||
if err := s.ensure(); err != nil {
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
cl = s.client
|
||||
}
|
||||
s.mu.Unlock()
|
||||
buf := make([]byte, plcBlockBytes)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cl.AGReadMB(plcBlockStartByte, plcBlockBytes, buf) }()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
_ = s.handler.Close()
|
||||
s.client = nil
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
err := s.run(ctx, func(cl gos7.Client) error {
|
||||
return cl.AGReadMB(plcBlockStartByte, plcBlockBytes, buf)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// readByte 读取单个 Merker 字节(用于 48 位块之外的完成信号位等)。
|
||||
@@ -96,34 +108,19 @@ func (s *s7Real) readByte(ctx context.Context, byteOffset int) (byte, error) {
|
||||
return buf[0], nil
|
||||
}
|
||||
|
||||
// readBytes 读任意 Merker 字节区间(带惰性连接与断线重连),供 ReadMWBlock 等批量读使用。
|
||||
// readBytes 读任意 Merker 字节区间(串行闸内一次事务),供 ReadMWBlock 等批量读使用。
|
||||
func (s *s7Real) readBytes(ctx context.Context, byteOffset, length int) ([]byte, error) {
|
||||
if byteOffset < 0 || length <= 0 {
|
||||
return nil, fmt.Errorf("非法读区间: offset=%d len=%d", byteOffset, length)
|
||||
}
|
||||
s.mu.Lock()
|
||||
if err := s.ensure(); err != nil {
|
||||
s.mu.Unlock()
|
||||
buf := make([]byte, length)
|
||||
err := s.run(ctx, func(cl gos7.Client) error {
|
||||
return cl.AGReadMB(byteOffset, length, buf)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cl := s.client
|
||||
s.mu.Unlock()
|
||||
buf := make([]byte, length)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cl.AGReadMB(byteOffset, length, buf) }()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
_ = s.handler.Close()
|
||||
s.client = nil
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// bit 取块内某位(bitOffset 0..47)。
|
||||
@@ -275,28 +272,9 @@ func (t *tcpClient) WriteMW(ctx context.Context, addr, value int) error {
|
||||
return t.real.writeBuffer(ctx, addr, buf)
|
||||
}
|
||||
|
||||
// writeBuffer 写任意 Merker 字节区间(供 WriteMW 调用),带惰性连接与断线重连。
|
||||
// writeBuffer 写任意 Merker 字节区间(供 WriteMW 调用),与读共用同一串行闸。
|
||||
func (s *s7Real) writeBuffer(ctx context.Context, byteOffset int, data []byte) error {
|
||||
s.mu.Lock()
|
||||
if err := s.ensure(); err != nil {
|
||||
s.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
cl := s.client
|
||||
s.mu.Unlock()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cl.AGWriteMB(byteOffset, len(data), data) }()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
_ = s.handler.Close()
|
||||
s.client = nil
|
||||
s.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return s.run(ctx, func(cl gos7.Client) error {
|
||||
return cl.AGWriteMB(byteOffset, len(data), data)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user