feat: AGV状态实时推送与受控异常处置 + rcs-dps状态接口独立配置与日志落盘修复
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
// Package agv 海康 AGV 调度系统(RCS-Lite V1.5) 对接客户端(2026-10-17 由 RCS-2000 改为 RCS-Lite 1.5)。
|
||||
// 能力:生成搬运任务(genAgvSchedulingTask)、查询任务状态(queryTaskStatus)、取消任务(cancelTask)。
|
||||
// 协议详见《AGV海康litev1.5.md》:无签名;所有参数统一字符串;成功 code=="0"。
|
||||
// 完整请求路径 = BaseURL(已含 /rCMS/services/rest/hikRpcService) + 业务路径。
|
||||
// 完整请求路径 = BaseURL(已含 /rcms/services/rest/hikRpcService,小写) + 业务路径;
|
||||
// 车辆状态查询例外:走 AgvStatusURL(rcms-dps/rest 独立服务) + /queryAgvStatus。
|
||||
// 未配置真实 RCS(BaseURL 为空) 或 EnableMock=true 时走 Mock 客户端。
|
||||
package agv
|
||||
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -19,8 +21,12 @@ import (
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
|
||||
"bj_power_mes/internal/config"
|
||||
"bj_power_mes/internal/netutil"
|
||||
)
|
||||
|
||||
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
||||
var commTag = netutil.Tag()
|
||||
|
||||
// Client AGV 调度客户端抽象
|
||||
type Client interface {
|
||||
// SubmitTask 下发搬运任务 fromDock -> toDock。taskCode 为我方任务单号(透传给 RCS 便于回查)。
|
||||
@@ -65,34 +71,91 @@ func New(cfg config.AgvConf) Client {
|
||||
// ---------- 请求与响应(真实海康 RCS-Lite) ----------
|
||||
|
||||
type realClient struct {
|
||||
cfg config.AgvConf
|
||||
hc *http.Client
|
||||
carrier string
|
||||
cfg config.AgvConf
|
||||
hc *http.Client
|
||||
carrier string
|
||||
statusBase string // 车辆状态(rcms-dps/rest)独立服务地址
|
||||
}
|
||||
|
||||
func newRealClient(cfg config.AgvConf) *realClient {
|
||||
return &realClient{
|
||||
cfg: cfg,
|
||||
hc: &http.Client{Timeout: 15 * time.Second},
|
||||
carrier: cfg.CarrierCode,
|
||||
cfg: cfg,
|
||||
hc: &http.Client{Timeout: 15 * time.Second},
|
||||
carrier: cfg.CarrierCode,
|
||||
statusBase: resolveStatusBase(cfg),
|
||||
}
|
||||
}
|
||||
|
||||
// url 拼接 RCS-Lite 基础地址 + 业务路径(BaseURL 已含 /rCMS/services/rest/hikRpcService)。
|
||||
// resolveStatusBase 车辆状态(rcms-dps/rest)地址:优先显式配置;留空则从 BaseURL 取 scheme://host 推导。
|
||||
// 推导用 net/url 解析(非正则),如 http://IP:8182/rcms/services/... → http://IP:8182/rcms-dps/rest。
|
||||
func resolveStatusBase(cfg config.AgvConf) string {
|
||||
if s := strings.TrimSpace(cfg.AgvStatusURL); s != "" {
|
||||
return strings.TrimRight(s, "/")
|
||||
}
|
||||
u, err := url.Parse(cfg.BaseURL)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return ""
|
||||
}
|
||||
return u.Scheme + "://" + u.Host + "/rcms-dps/rest"
|
||||
}
|
||||
|
||||
// url 拼接 RCS-Lite 任务接口地址 + 业务路径(BaseURL 已含 /rcms/services/rest/hikRpcService,小写)。
|
||||
func (c *realClient) url(path string) string {
|
||||
return strings.TrimRight(c.cfg.BaseURL, "/") + path
|
||||
}
|
||||
|
||||
// statusURL 拼接车辆状态地址 + 业务路径(rcms-dps/rest 独立服务)。
|
||||
func (c *realClient) statusURL(path string) string {
|
||||
return strings.TrimRight(c.statusBase, "/") + path
|
||||
}
|
||||
|
||||
// flexString 兼容 RCS 字段「有时返回 JSON 字符串、有时返回数字」的情况。
|
||||
// 协议文档写"参数统一字符串",但实测响应 code 返回数字 1006/-1、status 也可能是数字,
|
||||
// 用 string 直接反序列化会报 cannot unmarshal number into Go struct field ... of type string。
|
||||
// 本类型把字符串/数字/布尔/null 统一收成字符串,下游按字符串比较即可。不使用正则。
|
||||
type flexString string
|
||||
|
||||
func (f *flexString) UnmarshalJSON(b []byte) error {
|
||||
if len(b) == 0 {
|
||||
*f = ""
|
||||
return nil
|
||||
}
|
||||
if b[0] == '"' { // JSON 字符串
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = flexString(s)
|
||||
return nil
|
||||
}
|
||||
var v any // 数字/布尔/null 按字面量收
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
if v == nil {
|
||||
*f = ""
|
||||
return nil
|
||||
}
|
||||
*f = flexString(fmt.Sprint(v))
|
||||
return nil
|
||||
}
|
||||
|
||||
// envelope RCS-Lite 统一响应信封(§1.4):code 必填、message 必填、reqCode 回传、data 选填。
|
||||
type envelope struct {
|
||||
Code string `json:"code"`
|
||||
Code flexString `json:"code"`
|
||||
Message string `json:"message"`
|
||||
ReqCode string `json:"reqCode"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// call POST 到 RCS-Lite 并解析信封。成功判定 code=="0";out 非空时把 data 反序列化进去。
|
||||
// call POST 到 RCS-Lite 任务接口(BaseURL)并解析信封。
|
||||
func (c *realClient) call(ctx context.Context, path string, payload map[string]any, out any) error {
|
||||
return c.callAt(ctx, c.url(path), payload, out)
|
||||
}
|
||||
|
||||
// callAt POST 到完整 URL 并解析信封。成功判定 code=="0";out 非空时把 data 反序列化进去。
|
||||
// 车辆状态(rcms-dps)等独立服务接口用本方法,避免误挂到任务接口 BaseURL 下。
|
||||
func (c *realClient) callAt(ctx context.Context, reqURL string, payload map[string]any, out any) error {
|
||||
if payload == nil {
|
||||
payload = map[string]any{}
|
||||
}
|
||||
@@ -107,29 +170,28 @@ func (c *realClient) call(ctx context.Context, path string, payload map[string]a
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reqURL := c.url(path)
|
||||
// 2026-11-16 联调:AGV 全量 HTTP 交互落日志(请求 URL/报文 + 响应状态/响应体),grep "[AGV]" 可见。
|
||||
logx.WithContext(ctx).Infof("[AGV] --> POST %s payload=%s", reqURL, string(body))
|
||||
logx.WithContext(ctx).Infof("[AGV]"+commTag+" --> POST %s payload=%s", reqURL, string(body))
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[AGV] <-- build request error url=%s err=%v", reqURL, err)
|
||||
logx.WithContext(ctx).Errorf("[AGV]"+commTag+" <-- build request error url=%s err=%v", reqURL, err)
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
|
||||
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[AGV] <-- transport error url=%s err=%v", reqURL, err)
|
||||
logx.WithContext(ctx).Errorf("[AGV]"+commTag+" <-- transport error url=%s err=%v", reqURL, err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[AGV] <-- read body error url=%s httpStatus=%d err=%v", reqURL, resp.StatusCode, err)
|
||||
logx.WithContext(ctx).Errorf("[AGV]"+commTag+" <-- read body error url=%s httpStatus=%d err=%v", reqURL, resp.StatusCode, err)
|
||||
return err
|
||||
}
|
||||
logx.WithContext(ctx).Infof("[AGV] <-- HTTP %d url=%s body=%s", resp.StatusCode, reqURL, string(raw))
|
||||
logx.WithContext(ctx).Infof("[AGV]"+commTag+" <-- HTTP %d url=%s body=%s", resp.StatusCode, reqURL, string(raw))
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("agv http %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
@@ -139,7 +201,7 @@ func (c *realClient) call(ctx context.Context, path string, payload map[string]a
|
||||
}
|
||||
// 成功码固定字符串 "0"(§1.5 结果码定义)
|
||||
if env.Code != "0" {
|
||||
logx.WithContext(ctx).Errorf("[AGV] <-- biz error url=%s code=%s message=%s reqCode=%v", reqURL, env.Code, env.Message, payload["reqCode"])
|
||||
logx.WithContext(ctx).Errorf("[AGV]"+commTag+" <-- biz error url=%s code=%s message=%s reqCode=%v", reqURL, env.Code, env.Message, payload["reqCode"])
|
||||
return fmt.Errorf("agv code=%s message=%s", env.Code, env.Message)
|
||||
}
|
||||
if out != nil && len(env.Data) > 0 {
|
||||
@@ -203,12 +265,12 @@ func (c *realClient) SubmitTask(ctx context.Context, taskCode, fromDock, toDock,
|
||||
return taskCode, nil
|
||||
}
|
||||
|
||||
// queryTaskData queryTaskStatus 的 data 列表项
|
||||
// queryTaskData queryTaskStatus 的 data 列表项(字段兼容字符串/数字)
|
||||
type queryTaskData struct {
|
||||
TaskCode string `json:"taskCode"`
|
||||
TaskStatus string `json:"taskStatus"`
|
||||
AgvCode string `json:"agvCode"`
|
||||
TaskTyp string `json:"taskTyp"`
|
||||
TaskCode flexString `json:"taskCode"`
|
||||
TaskStatus flexString `json:"taskStatus"`
|
||||
AgvCode flexString `json:"agvCode"`
|
||||
TaskTyp flexString `json:"taskTyp"`
|
||||
}
|
||||
|
||||
// QueryTask 实现 Client:查询任务状态(queryTaskStatus)。
|
||||
@@ -225,8 +287,8 @@ func (c *realClient) QueryTask(ctx context.Context, taskCode string) (string, st
|
||||
return "", "", err
|
||||
}
|
||||
for _, d := range out.Data {
|
||||
if d.TaskCode == taskCode && d.TaskStatus != "" {
|
||||
return d.TaskStatus, d.AgvCode, nil
|
||||
if string(d.TaskCode) == taskCode && d.TaskStatus != "" {
|
||||
return string(d.TaskStatus), string(d.AgvCode), nil
|
||||
}
|
||||
}
|
||||
return "1", "", nil
|
||||
@@ -245,18 +307,20 @@ func (c *realClient) CancelTask(ctx context.Context, taskCode, reason string) er
|
||||
return c.call(ctx, "/cancelTask", payload, nil)
|
||||
}
|
||||
|
||||
// queryAgvStatusData 3.1.7 单条车辆状态 data 项
|
||||
// queryAgvStatusData 3.1.7 单条车辆状态 data 项(字段兼容字符串/数字)
|
||||
type queryAgvStatusData struct {
|
||||
RobotCode string `json:"robotCode"`
|
||||
Battery string `json:"battery"`
|
||||
Status string `json:"status"`
|
||||
PodCode string `json:"podCode"`
|
||||
PosX string `json:"posX"`
|
||||
PosY string `json:"posY"`
|
||||
Stop string `json:"stop"`
|
||||
RobotCode flexString `json:"robotCode"`
|
||||
Battery flexString `json:"battery"`
|
||||
Status flexString `json:"status"`
|
||||
PodCode flexString `json:"podCode"`
|
||||
PosX flexString `json:"posX"`
|
||||
PosY flexString `json:"posY"`
|
||||
Stop flexString `json:"stop"`
|
||||
}
|
||||
|
||||
// QueryAgvStatus 实现 Client:3.1.7 只读获取全部车辆状态。
|
||||
// 走 rcs-dps/rest 独立服务(§3.1.7 调用路径 http://IP:8182/rcms-dps/rest/queryAgvStatus),
|
||||
// 不是 hikRpcService 任务接口——此前挂到任务 BaseURL 下导致 404。
|
||||
// mapShortName 取配置 MapCode(多地图场景必填;单地图可空,RCS 侧默认)。
|
||||
func (c *realClient) QueryAgvStatus(ctx context.Context) ([]AgvVehicle, error) {
|
||||
payload := map[string]any{
|
||||
@@ -265,19 +329,19 @@ func (c *realClient) QueryAgvStatus(ctx context.Context) ([]AgvVehicle, error) {
|
||||
var out struct {
|
||||
Data []queryAgvStatusData `json:"data"`
|
||||
}
|
||||
if err := c.call(ctx, "/queryAgvStatus", payload, &out); err != nil {
|
||||
if err := c.callAt(ctx, c.statusURL("/queryAgvStatus"), payload, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vs := make([]AgvVehicle, 0, len(out.Data))
|
||||
for _, d := range out.Data {
|
||||
vs = append(vs, AgvVehicle{
|
||||
RobotCode: d.RobotCode,
|
||||
Battery: atof(d.Battery),
|
||||
Status: d.Status,
|
||||
PodCode: d.PodCode,
|
||||
PosX: atof(d.PosX),
|
||||
PosY: atof(d.PosY),
|
||||
Stop: d.Stop == "1",
|
||||
RobotCode: string(d.RobotCode),
|
||||
Battery: atof(string(d.Battery)),
|
||||
Status: string(d.Status),
|
||||
PodCode: string(d.PodCode),
|
||||
PosX: atof(string(d.PosX)),
|
||||
PosY: atof(string(d.PosY)),
|
||||
Stop: d.Stop == "1" || d.Stop == "true",
|
||||
})
|
||||
}
|
||||
return vs, nil
|
||||
@@ -300,24 +364,24 @@ func newMockClient() *mockClient { return &mockClient{} }
|
||||
|
||||
func (m *mockClient) SubmitTask(ctx context.Context, taskCode, fromDock, toDock, carrierCode, templateType, agvCode string) (string, error) {
|
||||
// 模拟立即成功下发,返回我方 taskCode(与真实客户端一致,HikTaskCode=taskNo)
|
||||
logx.WithContext(ctx).Infof("[AGV][MOCK] SubmitTask taskCode=%s %s->%s template=%s agvCode=%s(模拟下发成功,未发真实 HTTP)", taskCode, fromDock, toDock, templateType, agvCode)
|
||||
logx.WithContext(ctx).Infof("[AGV]"+commTag+"[MOCK] SubmitTask taskCode=%s %s->%s template=%s agvCode=%s(模拟下发成功,未发真实 HTTP)", taskCode, fromDock, toDock, templateType, agvCode)
|
||||
return taskCode, nil
|
||||
}
|
||||
|
||||
func (m *mockClient) QueryTask(ctx context.Context, taskCode string) (string, string, error) {
|
||||
// 模拟:MOCK 任务一律视为已结束,便于离线联调观察"待搬运→已到位";模拟模式无真实分车,agvCode 为空
|
||||
logx.WithContext(ctx).Infof("[AGV][MOCK] QueryTask taskCode=%s(模拟返回已结束)", taskCode)
|
||||
logx.WithContext(ctx).Infof("[AGV]"+commTag+"[MOCK] QueryTask taskCode=%s(模拟返回已结束)", taskCode)
|
||||
return "9", "", nil
|
||||
}
|
||||
|
||||
func (m *mockClient) CancelTask(ctx context.Context, taskCode, reason string) error {
|
||||
logx.WithContext(ctx).Infof("[AGV][MOCK] CancelTask taskCode=%s reason=%s(模拟取消成功)", taskCode, reason)
|
||||
logx.WithContext(ctx).Infof("[AGV]"+commTag+"[MOCK] CancelTask taskCode=%s reason=%s(模拟取消成功)", taskCode, reason)
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryAgvStatus Mock:返回两台示例车(一台空闲、一台执行中),便于联调展示。
|
||||
func (m *mockClient) QueryAgvStatus(ctx context.Context) ([]AgvVehicle, error) {
|
||||
logx.WithContext(ctx).Infof("[AGV][MOCK] QueryAgvStatus(模拟返回样例车 9001/9002)")
|
||||
logx.WithContext(ctx).Infof("[AGV]" + commTag + "[MOCK] QueryAgvStatus(模拟返回样例车 9001/9002)")
|
||||
return []AgvVehicle{
|
||||
{RobotCode: "9001", Battery: 99, Status: "4", PodCode: "0", PosX: 20000, PosY: 20000, Stop: false},
|
||||
{RobotCode: "9002", Battery: 78, Status: "2", PodCode: "100001", PosX: 35000, PosY: 12000, Stop: false},
|
||||
|
||||
@@ -61,8 +61,8 @@ type PlcConf struct {
|
||||
Enable bool `json:",default=false"`
|
||||
Host string `json:",default=127.0.0.1"`
|
||||
Port int `json:",default=102"`
|
||||
Rack int `json:",default=0"` // S7 机架号(1200=0,300=0)
|
||||
Slot int `json:",default=1"` // S7 槽号(1200=1,300=2)
|
||||
Rack int `json:",default=0"` // S7 机架号(1200=0,300=0)
|
||||
Slot int `json:",default=1"` // S7 槽号(1200=1,300=2)
|
||||
// DoneByte/DoneBit 工艺完成信号位(PLC 完成上一条下发后置位,MES 读此位决定是否下发下一条)。
|
||||
// 待现场 PLC 点位表确认;未配置时 QueryDone 安全返回 false(不下发下一条,不误进)。
|
||||
DoneByte int `json:",default=-1"`
|
||||
@@ -72,11 +72,12 @@ type PlcConf struct {
|
||||
// AgvConf 海康 AGV(RCS-Lite V1.5) 调度系统对接(2026-10-17 由 RCS-2000 改为 RCS-Lite 1.5)。
|
||||
// RCS-Lite 无签名鉴权;未配置 BaseURL 或 EnableMock=true 时,使用 mock 客户端(模拟下发成功/到位),便于离线联调。
|
||||
type AgvConf struct {
|
||||
EnableMock bool `json:",default=true"` // 是否模拟(未接真实 RCS-Lite 前保持 true)
|
||||
BaseURL string `json:",default=http://127.0.0.1:8182/rCMS/services/rest/hikRpcService"` // RCS-Lite 服务地址(含 /rCMS/services/rest/hikRpcService,默认端口 8182)
|
||||
CarrierCode string `json:",default=DEFAULT"` // 默认载具/托盘编号(选填,下发时作为 podCode)
|
||||
MapCode string `json:",default="` // 地图编号(选填,RCS-Lite 多地图场景使用)
|
||||
Priority string `json:",default=1"` // 任务优先级(字符串 1-127,默认 1)
|
||||
EnableMock bool `json:",default=true"` // 是否模拟(未接真实 RCS-Lite 前保持 true)
|
||||
BaseURL string `json:",default=http://127.0.0.1:8182/rcms/services/rest/hikRpcService"` // RCS-Lite 任务接口地址(含 /rcms/services/rest/hikRpcService,小写 rcms,客户 postman 实测大写会 404)
|
||||
AgvStatusURL string `json:",optional"` // 车辆状态接口地址(rcs-dps 独立服务,如 http://IP:8182/rcms-dps/rest;留空则由 BaseURL 推导)
|
||||
CarrierCode string `json:",default=DEFAULT"` // 默认载具/托盘编号(选填,下发时作为 podCode)
|
||||
MapCode string `json:",default="` // 地图编号(选填,RCS-Lite 多地图场景使用)
|
||||
Priority string `json:",default=1"` // 任务优先级(字符串 1-127,默认 1)
|
||||
// 任务类型编号 = RCS-Lite 任务模板载体(接口文档 2.1.1 taskTyp:与 RCS 端配置的主任务类型编号一致,
|
||||
// 模板绑定在该编号上,错误码 1005/1044 即模板读取/配置失败)。
|
||||
// 2026-11-13 拍板:现场模板 B01=举升(目标点为 JBT21 或工位接驳台)、B02=移动(A1-A4/XW/XT/KF1/GW1Z 等无接驳台点位)。
|
||||
|
||||
@@ -305,6 +305,31 @@ func AgvChainEndHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// AgvChainForceEndHandler POST /agv/chain/force-end 强制结束安全阀:
|
||||
// 人工确认现场实物已处置后,仅清系统死锁状态(段置终态+释放点位锁+留痕),
|
||||
// 不调用海康任何接口、不下发任何物理动作。风险由前端确认弹窗告知。
|
||||
func AgvChainForceEndHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
ChainNo string `json:"chainNo"`
|
||||
Reason string `json:"reason"` // 现场实际处置情况(受控入口必选),仅用于留痕
|
||||
}
|
||||
if err := httpx.ParseJSON(r, &req); err != nil || req.ChainNo == "" {
|
||||
httpx.BadRequest(w, "缺少任务链号(chainNo)")
|
||||
return
|
||||
}
|
||||
operator := r.Header.Get("X-Username")
|
||||
if operator == "" {
|
||||
operator = "dispatcher"
|
||||
}
|
||||
if err := logic.New(svcCtx).AgvChainForceEnd(r.Context(), req.ChainNo, operator, req.Reason); err != nil {
|
||||
httpx.Fail(w, 3315, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "已强制结束,系统状态已解除;请确认现场实物已处理", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// AgvChainListHandler GET /agv/chain/list 手动链列表(任务进行中面板:链号/锁定车/节点/进行中)。
|
||||
func AgvChainListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -319,9 +344,11 @@ func AgvChainListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
|
||||
// AgvPointLockHandler POST /agv/points/:id/lock —— 点位锁定管理(派车锁 2026-11-06 拍板):
|
||||
// body {locked bool, reason string, clearForcePick bool}
|
||||
// locked=true → 人工锁定(reason 必填,locked_by=manual,仅人工解锁);
|
||||
// locked=false → 人工解锁(含 JBT21 手动解锁、系统锁人工释放);
|
||||
// clearForcePick=true → 清除强提风险标记(人工确认现场安全后)。
|
||||
//
|
||||
// locked=true → 人工锁定(reason 必填,locked_by=manual,仅人工解锁);
|
||||
// locked=false → 人工解锁(含 JBT21 手动解锁、系统锁人工释放);
|
||||
// clearForcePick=true → 清除强提风险标记(人工确认现场安全后)。
|
||||
//
|
||||
// 全部操作 event_log 留痕。
|
||||
func AgvPointLockHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
tokenx "bj_power_mes/common/token"
|
||||
"bj_power_mes/internal/svc"
|
||||
"bj_power_mes/internal/ws"
|
||||
)
|
||||
|
||||
var (
|
||||
agvHubOnce sync.Once
|
||||
agvHub *ws.AgvHub
|
||||
)
|
||||
|
||||
func globalAgvHub(svcCtx *svc.ServiceContext) *ws.AgvHub {
|
||||
agvHubOnce.Do(func() {
|
||||
agvHub = ws.NewAgvHub(svcCtx)
|
||||
})
|
||||
return agvHub
|
||||
}
|
||||
|
||||
// AgvWsHandler GET /api/v1/agv/ws?token=<JWT> 人工派车状态推送。
|
||||
// 浏览器 WebSocket 无法带 Authorization 头,token 走 query;校验复用 tokenx.Parse(签名+过期),
|
||||
// 通过后交由 AgvHub 升级管理。状态来源:AgvHub 定时拉海康 RCS 写回本地库后对比快照变化即推。
|
||||
func AgvWsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
tok := strings.TrimSpace(r.URL.Query().Get("token"))
|
||||
if tok == "" {
|
||||
httpx.Unauthorized(w, "缺少登录凭证,请重新登录")
|
||||
return
|
||||
}
|
||||
claims, err := tokenx.Parse(svcCtx.Config.Auth.AccessSecret, tok)
|
||||
if err != nil || claims == nil || claims.ExpiresAt == nil || time.Until(claims.ExpiresAt.Time) <= 0 {
|
||||
httpx.Unauthorized(w, "登录凭证无效或已过期,请重新登录")
|
||||
return
|
||||
}
|
||||
globalAgvHub(svcCtx).Handle(w, r)
|
||||
}
|
||||
}
|
||||
@@ -449,6 +449,7 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
|
||||
// 手动多段链(2026-11-06 拍板):逐节点人工推进,全程锁同一台车
|
||||
{Method: http.MethodPost, Path: "/agv/chain/next", Handler: production.AgvChainNextHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/agv/chain/end", Handler: production.AgvChainEndHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/agv/chain/force-end", Handler: production.AgvChainForceEndHandler(serverCtx)},
|
||||
{Method: http.MethodGet, Path: "/agv/chain/list", Handler: production.AgvChainListHandler(serverCtx)},
|
||||
{Method: http.MethodGet, Path: "/agv/mode", Handler: production.AgvModeHandler(serverCtx)},
|
||||
// AGV 点位管理(独立点位表:硬件映射编码/接驳台绑定不可改,仅名称/启用可改)
|
||||
@@ -652,6 +653,12 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
|
||||
Method: http.MethodGet, Path: "/api/v1/todos/ws", Handler: production.TodoWsHandler(serverCtx),
|
||||
}, rest.WithTimeout(3600_000_000_000))
|
||||
|
||||
// ---------- 人工派车状态 WebSocket:长连接推送 AGV 到位/失败,免手动刷新 ----------
|
||||
// token 走 query 由 AgvWsHandler 自校验(同 TodoWs),不挂 WithJwt;放宽超时避免 5s 断连。
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodGet, Path: "/api/v1/agv/ws", Handler: production.AgvWsHandler(serverCtx),
|
||||
}, rest.WithTimeout(3600_000_000_000))
|
||||
|
||||
// ---------- 海康 RCS-Lite SPI 主动回调(文档 2.2.1 任务执行通知 agvCallback) ----------
|
||||
// 注意:RCS 回调不携带我方鉴权头;生产环境必须以防火墙 / IP 白名单隔离该端点(待与 RCS 方确认鉴权方式)。
|
||||
// RCS-Lite 后台需将上层回调地址配置为本端点(路径遵循文档 /xxx/agv/agvCallbackService/agvCallback)。
|
||||
|
||||
@@ -55,7 +55,7 @@ type AgvPointView struct {
|
||||
LockedBy string `json:"lockedBy"` // system / manual
|
||||
LockedReason string `json:"lockedReason"` // 任务号或人工原因
|
||||
LockedAt int64 `json:"lockedAt"`
|
||||
ForcePick bool `json:"forcePick"` // 强提风险标记(派车需人工二次确认)
|
||||
ForcePick bool `json:"forcePick"` // 强提风险标记(派车需人工二次确认)
|
||||
ForcePickAt int64 `json:"forcePickAt"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
}
|
||||
@@ -297,7 +297,7 @@ func (s *Service) agvRcsCommFail(ctx context.Context, where string, err error) {
|
||||
// DispatchAgvForCall 业务配送单派车(2026-11-13 拍板:独立「手动派车/叫料派车」入口下线,
|
||||
// 只由仓库备料完成等业务配送链路触发;前端不再有可直调的手动派车路由):
|
||||
// 由库管在 WMS 叫料队列点「送货」(DispatchCallAgv)调用——生成「空车前往装货点(JBT21)」段
|
||||
//(kind=GO_LOAD)并下发。AGV 到位后 status=ARRIVED(到位待令),库管点「确认装车并送货」
|
||||
// (kind=GO_LOAD)并下发。AGV 到位后 status=ARRIVED(到位待令),库管点「确认装车并送货」
|
||||
// 才生成重载运输段(TRANSPORT)发往工位接驳台;卸货点再经「卸货完成并放行」后空车回充。
|
||||
// 失败仅记日志/预警(best-effort),不阻断调用方响应。
|
||||
func (s *Service) DispatchAgvForCall(ctx context.Context, mr *ent.MaterialRequest, operator string) error {
|
||||
@@ -680,7 +680,7 @@ func (s *Service) ApplyAgvCallback(ctx context.Context, taskCode, method, robotC
|
||||
|
||||
// notifyDeliveredOnArrival AGV 到位 → 关联出库单回写「已送达」(2026-11-03 断头路补全:
|
||||
// 出库单状态机「已出库/已送达」此前无写者)。任务关联叫料单 → 叫料单上回写的 WMS 出库单号
|
||||
//(可多个逗号分隔)→ 通知 WMS 置已送达。best-effort:WMS 不可达只记日志,不阻断到位链路。
|
||||
// (可多个逗号分隔)→ 通知 WMS 置已送达。best-effort:WMS 不可达只记日志,不阻断到位链路。
|
||||
func (s *Service) notifyDeliveredOnArrival(ctx context.Context, t *ent.AgvTask) {
|
||||
if t == nil || t.RelatedRequestNo == "" || s.ctx.Wms == nil {
|
||||
return
|
||||
@@ -721,8 +721,8 @@ func (s *Service) notifyDeliveredOnArrival(ctx context.Context, t *ent.AgvTask)
|
||||
// 确认装车(车背托盘离开装货点)→ 装货点 hasPallet=false;确认卸货(托盘上台)→ 卸货点 hasPallet=true。
|
||||
|
||||
const (
|
||||
dockStoreCode = "JBT21" // 库房接驳台(装货点/空托盘回收终点;T7 2026-11-03 统一 JBT21)
|
||||
agvChargePoint = "AGV-CHARGE01" // 充电位(seed 纯点位,is_dock=false)
|
||||
dockStoreCode = "JBT21" // 库房接驳台(装货点/空托盘回收终点;T7 2026-11-03 统一 JBT21)
|
||||
agvChargePoint = "AGV-CHARGE01" // 充电位(seed 纯点位,is_dock=false)
|
||||
)
|
||||
|
||||
// agvSegInput 单段任务入参
|
||||
@@ -742,9 +742,11 @@ type agvSegInput struct {
|
||||
}
|
||||
|
||||
// agvTemplateType 模板推导唯一入口(2026-11-14 用户终版改为【按点位码硬编码】):
|
||||
// 目标点为 JBT21 或 GW*(工位接驳台)→ LIFT → B01 举升任务模板;
|
||||
// 目标点为 7 个虚拟点位(A1-A4 / XW / XT / KF1)→ NONE → B02 移动任务模板。
|
||||
// 历史 DOCK* 业务点位不在 28 个点位内,按库内 is_dock 兜底,保证存量派车链路不被改动。
|
||||
//
|
||||
// 目标点为 JBT21 或 GW*(工位接驳台)→ LIFT → B01 举升任务模板;
|
||||
// 目标点为 7 个虚拟点位(A1-A4 / XW / XT / KF1)→ NONE → B02 移动任务模板。
|
||||
// 历史 DOCK* 业务点位不在 28 个点位内,按库内 is_dock 兜底,保证存量派车链路不被改动。
|
||||
//
|
||||
// 规则真源 logic.AgvTemplateOf;举升模板编号仍取「基础设置」可配值(默认 B01/B02)。
|
||||
// 原实现「起点或终点任一为接驳台就举升」已废止;模板内部动作序列由 RCS 预置,MES 不控制动作。
|
||||
// 点位查询失败返回错误阻断下发(宁可不下发)。
|
||||
@@ -816,7 +818,11 @@ func (s *Service) dispatchAgvSegment(ctx context.Context, in agvSegInput) (strin
|
||||
return "", err
|
||||
}
|
||||
submitTmpl := tmpl
|
||||
if tmpl == "LIFT" { submitTmpl = s.CfgStr(ctx, CfgAgvTaskTypLift, "B01") } else { submitTmpl = s.CfgStr(ctx, CfgAgvTaskTypPlain, "B02") }
|
||||
if tmpl == "LIFT" {
|
||||
submitTmpl = s.CfgStr(ctx, CfgAgvTaskTypLift, "B01")
|
||||
} else {
|
||||
submitTmpl = s.CfgStr(ctx, CfgAgvTaskTypPlain, "B02")
|
||||
}
|
||||
_, aerr := s.ctx.Agv.SubmitTask(ctx, taskNo, in.Source, in.Target, "", submitTmpl, in.AgvCode)
|
||||
if aerr != nil {
|
||||
s.agvRcsCommFail(ctx, "下发 "+in.Source+"→"+in.Target, aerr)
|
||||
@@ -971,9 +977,9 @@ func (s *Service) FinishFreeReturn(ctx context.Context, taskNo, operator string)
|
||||
// AgvChainInfo 手动链视图(任务进行中面板)。
|
||||
type AgvChainInfo struct {
|
||||
ChainNo string `json:"chainNo"`
|
||||
AgvCode string `json:"agvCode"` // 锁定车(最新回写的 agv_code;空=RCS 尚未分车)
|
||||
Active bool `json:"active"` // 是否进行中(最新段未终态)
|
||||
Segments []AgvTaskView `json:"segments"` // 已走节点(按段创建顺序)
|
||||
AgvCode string `json:"agvCode"` // 锁定车(最新回写的 agv_code;空=RCS 尚未分车)
|
||||
Active bool `json:"active"` // 是否进行中(最新段未终态)
|
||||
Segments []AgvTaskView `json:"segments"` // 已走节点(按段创建顺序)
|
||||
}
|
||||
|
||||
// agvChainSegments 取链内全部段(按创建顺序);不存在返回空。
|
||||
@@ -1012,7 +1018,7 @@ func agvChainGuardManual(segs []*ent.AgvTask) error {
|
||||
}
|
||||
|
||||
// AgvChainNextNode 手动链「下一个节点」:当前段必须已到位(ARRIVED);取链锁定车
|
||||
//(最新段 agv_code,未回写则拒绝)注入下发;当前段置 9,新段挂同一链号。
|
||||
// (最新段 agv_code,未回写则拒绝)注入下发;当前段置 9,新段挂同一链号。
|
||||
// source 空=沿用上一节点落点;target 必填(用户自选下一段去哪)。
|
||||
// confirmForcePick="1" 表示用户已对强提风险目标点位完成人工二次确认。
|
||||
func (s *Service) AgvChainNextNode(ctx context.Context, chainNo, source, target, operator, confirmForcePick string) (string, error) {
|
||||
@@ -1072,7 +1078,7 @@ func (s *Service) AgvChainNextNode(ctx context.Context, chainNo, source, target,
|
||||
}
|
||||
|
||||
// AgvChainEndTask 手动链「结束任务」:当前段必须已到位(ARRIVED);先校验 AGV 上无托盘
|
||||
//(载货台账硬校验 + RCS 实时车载货架校验),通过后当前段置 9,下发空车回充段(不指定车)。
|
||||
// (载货台账硬校验 + RCS 实时车载货架校验),通过后当前段置 9,下发空车回充段(不指定车)。
|
||||
// force=人工确认无托盘强制结束:仅在 RCS 状态查询失败(超时/报错)时放行,操作留痕;
|
||||
// 台账判定有托盘时无论是否 force 一律拒绝(台账是系统权威,人工勾选不覆盖)。
|
||||
func (s *Service) AgvChainEndTask(ctx context.Context, chainNo, operator string, force bool) error {
|
||||
@@ -1132,6 +1138,44 @@ func (s *Service) AgvChainEndTask(ctx context.Context, chainNo, operator string,
|
||||
return nil
|
||||
}
|
||||
|
||||
// AgvChainForceEnd 手动链「强制结束」安全阀(2026-11-16 主控定案):
|
||||
// 用途=解开「AGV 未到位却无法结束、也无法继续」的系统死锁。当现场实物已人工处置
|
||||
// (货已卸/车已停),但 RCS 状态未回、回调丢失或断网导致本地段卡在 1/2/FAILED 时,
|
||||
// 人工确认后调用。本方法【只清系统状态】:当前段置终态 9 + 释放目标点位系统锁 + 留痕;
|
||||
// 【绝不调用海康任何接口】——尤其不调 cancelTask(forceCancel=0 会把车上的货直接扔在路上,
|
||||
// 见《AGV海康litev1.5.md》§2.1.3)。下发空车回充也不做:现场车辆处置由人负责,系统不再遥控。
|
||||
// 风险由前端确认弹窗明确告知,后端这里只保证本地状态机一致、不产生任何物理动作。
|
||||
func (s *Service) AgvChainForceEnd(ctx context.Context, chainNo, operator, reason string) error {
|
||||
if chainNo == "" {
|
||||
return errors.New("缺少任务链号")
|
||||
}
|
||||
segs := s.agvChainSegments(ctx, chainNo)
|
||||
if err := agvChainGuardManual(segs); err != nil {
|
||||
return err
|
||||
}
|
||||
cur := agvChainCurrent(segs)
|
||||
if cur == nil {
|
||||
return errors.New("任务链已结束,无需强制结束")
|
||||
}
|
||||
oldStatus := cur.Status
|
||||
oldDock := cur.TargetDock
|
||||
oldTaskNo := cur.TaskNo
|
||||
// 1) 仅本地:当前段置终态(9=完成,与正常结束同口径,让链从 agvChainCurrent 消失)
|
||||
if err := s.ctx.EntClient.AgvTask.UpdateOneID(cur.ID).SetStatus("9").Exec(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
// 2) 仅本地:释放该任务占用的点位系统锁(避免后续派车被幽灵锁挡住)
|
||||
s.unlockAgvPointByTask(ctx, oldDock, oldTaskNo)
|
||||
// 3) 留痕:明确标注「仅清系统状态、未通知 RCS、实物需人工已处置」
|
||||
if reason == "" {
|
||||
reason = "未填写(受控入口应强制选择)"
|
||||
}
|
||||
s.ctx.EventLog.Write(ctx, "agv.chain_force_end", operator, "", "agv_task", chainNo,
|
||||
"强制结束(仅解系统死锁,未通知RCS):段 "+oldTaskNo+" 状态 "+oldStatus+"→9,点位 "+oldDock+" 系统锁已释放;现场处置="+reason,
|
||||
map[string]any{"taskNo": oldTaskNo, "oldStatus": oldStatus, "targetDock": oldDock, "reason": reason})
|
||||
return nil
|
||||
}
|
||||
|
||||
// AgvChainList 手动链列表(任务进行中面板):全部 kind=MANUAL 段按链号分组,
|
||||
// AgvCode 取链内最新回写值,Active=链内存在非终态段。按链起始时间倒序。
|
||||
func (s *Service) AgvChainList(ctx context.Context) ([]AgvChainInfo, error) {
|
||||
@@ -1142,7 +1186,7 @@ func (s *Service) AgvChainList(ctx context.Context) ([]AgvChainInfo, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
order := []string{} // 链号首次出现顺序(id 升序=创建顺序)
|
||||
order := []string{} // 链号首次出现顺序(id 升序=创建顺序)
|
||||
byChain := map[string][]*ent.AgvTask{}
|
||||
for _, seg := range segs {
|
||||
cn := seg.ChainNo
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package netutil 提供本机 IP 缓存,供跨系统通信日志前缀使用(断网排查时能一眼看到是哪台机器发的日志)。
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
tagValue string
|
||||
)
|
||||
|
||||
// Tag 返回日志前缀片段,形如 [host=192.168.1.10];取不到非环回 IPv4 时返回 [host=?]。
|
||||
// 进程内只解析一次(sync.Once),不每次请求都枚举网卡;不使用正则,纯标准库。
|
||||
func Tag() string {
|
||||
once.Do(func() {
|
||||
ip := firstNonLoopbackIPv4()
|
||||
if ip == "" {
|
||||
ip = "?"
|
||||
}
|
||||
tagValue = "[host=" + ip + "]"
|
||||
})
|
||||
return tagValue
|
||||
}
|
||||
|
||||
// LocalIP 返回缓存的本机非环回 IPv4(取不到返回空串)。
|
||||
func LocalIP() string {
|
||||
Tag()
|
||||
ip := tagValue
|
||||
const p, s = "[host=", "]"
|
||||
if len(ip) > len(p)+len(s) {
|
||||
return ip[len(p) : len(ip)-len(s)]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstNonLoopbackIPv4() string {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, a := range addrs {
|
||||
ipnet, ok := a.(*net.IPNet)
|
||||
if !ok || ipnet.IP.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
v4 := ipnet.IP.To4()
|
||||
if v4 != nil {
|
||||
return v4.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -8,21 +8,25 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"bj_power_mes/internal/netutil"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
||||
var commTag = netutil.Tag()
|
||||
|
||||
// logClient 日志装饰器:inner 为真实实现(s7Real / tcpClient / mock)。
|
||||
type logClient struct{ inner Client }
|
||||
|
||||
func newLogClient(inner Client) *logClient { return &logClient{inner: inner} }
|
||||
|
||||
func (l *logClient) SendProcessCode(ctx context.Context, combination string) ([]int, error) {
|
||||
logx.WithContext(ctx).Infof("[PLC] --> SendProcessCode combination=%s", combination)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" --> SendProcessCode combination=%s", combination)
|
||||
codes, err := l.inner.SendProcessCode(ctx, combination)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC] <-- SendProcessCode err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- SendProcessCode err=%v", err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- SendProcessCode codes=%v", codes)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- SendProcessCode codes=%v", codes)
|
||||
}
|
||||
return codes, err
|
||||
}
|
||||
@@ -30,24 +34,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] <-- QueryDone err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryDone err=%v", err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- QueryDone done=%v", done)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryDone done=%v", done)
|
||||
}
|
||||
return done, err
|
||||
}
|
||||
|
||||
func (l *logClient) AckDone(ctx context.Context, ok bool) {
|
||||
logx.WithContext(ctx).Infof("[PLC] AckDone ok=%v", ok)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" 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] <-- QueryDockPallet dock=%s err=%v", dockCode, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryDockPallet dock=%s err=%v", dockCode, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- QueryDockPallet dock=%s hasPallet=%v", dockCode, has)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryDockPallet dock=%s hasPallet=%v", dockCode, has)
|
||||
}
|
||||
return has, err
|
||||
}
|
||||
@@ -55,9 +59,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] <-- QueryStationPallet station=%d err=%v", stationNo, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- QueryStationPallet station=%d err=%v", stationNo, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- QueryStationPallet station=%d hasPallet=%v", stationNo, has)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- QueryStationPallet station=%d hasPallet=%v", stationNo, has)
|
||||
}
|
||||
return has, err
|
||||
}
|
||||
@@ -65,7 +69,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] <-- ReadBits err=%v", err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadBits err=%v", err)
|
||||
} else {
|
||||
// 48 位压成 0/1 字符串,一行可读
|
||||
s := make([]byte, len(bits))
|
||||
@@ -76,7 +80,7 @@ func (l *logClient) ReadBits(ctx context.Context) ([]bool, error) {
|
||||
s[i] = '0'
|
||||
}
|
||||
}
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- ReadBits bits=%s", string(s))
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- ReadBits bits=%s", string(s))
|
||||
}
|
||||
return bits, err
|
||||
}
|
||||
@@ -84,9 +88,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] <-- ReadMW MW%d err=%v", addr, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadMW MW%d err=%v", addr, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- ReadMW MW%d=%d", addr, v)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- ReadMW MW%d=%d", addr, v)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
@@ -94,18 +98,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] <-- ReadMWBlock MW%d..MW%d err=%v", start, start+count-1, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- ReadMWBlock MW%d..MW%d err=%v", start, start+count-1, err)
|
||||
} else {
|
||||
logx.WithContext(ctx).Infof("[PLC] <-- ReadMWBlock MW%d..MW%d vals=%v", start, start+count-1, vals)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" <-- 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] --> WriteMW MW%d=%d", addr, value)
|
||||
logx.WithContext(ctx).Infof("[PLC]"+commTag+" --> WriteMW MW%d=%d", addr, value)
|
||||
err := l.inner.WriteMW(ctx, addr, value)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorf("[PLC] <-- WriteMW MW%d=%d err=%v", addr, value, err)
|
||||
logx.WithContext(ctx).Errorf("[PLC]"+commTag+" <-- WriteMW MW%d=%d err=%v", addr, value, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -11,9 +11,13 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"bj_power_mes/internal/netutil"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
||||
var commTag = netutil.Tag()
|
||||
|
||||
// loggingTransport 日志装饰 transport。
|
||||
type loggingTransport struct{ base http.RoundTripper }
|
||||
|
||||
@@ -34,11 +38,11 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
_ = req.Body.Close()
|
||||
req.Body = io.NopCloser(bytes.NewReader(reqBody))
|
||||
}
|
||||
logx.WithContext(req.Context()).Infof("[MES→WMS] --> %s %s body=%s", req.Method, u, truncateLogBytes(reqBody))
|
||||
logx.WithContext(req.Context()).Infof("[MES→WMS]"+commTag+"--> %s %s body=%s", req.Method, u, truncateLogBytes(reqBody))
|
||||
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
if err != nil {
|
||||
logx.WithContext(req.Context()).Errorf("[MES→WMS] <-- transport error %s err=%v", u, err)
|
||||
logx.WithContext(req.Context()).Errorf("[MES→WMS]"+commTag+"<-- transport error %s err=%v", u, err)
|
||||
if FailHook != nil {
|
||||
FailHook(req.Context(), req.Method, u, err)
|
||||
}
|
||||
@@ -47,10 +51,10 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
raw, rerr := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if rerr != nil {
|
||||
logx.WithContext(req.Context()).Errorf("[MES→WMS] <-- read body error %s status=%d err=%v", u, resp.StatusCode, rerr)
|
||||
logx.WithContext(req.Context()).Errorf("[MES→WMS]"+commTag+"<-- read body error %s status=%d err=%v", u, resp.StatusCode, rerr)
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(raw))
|
||||
logx.WithContext(req.Context()).Infof("[MES→WMS] <-- HTTP %d %s body=%s", resp.StatusCode, u, truncateLogBytes(raw))
|
||||
logx.WithContext(req.Context()).Infof("[MES→WMS]"+commTag+"<-- HTTP %d %s body=%s", resp.StatusCode, u, truncateLogBytes(raw))
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bj_power_mes/internal/logic"
|
||||
"bj_power_mes/internal/svc"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
// AGV 人工派车状态推送参数:轮询间隔 / 写读超时 / ping 间隔。
|
||||
const (
|
||||
agvPollInterval = 3 * time.Second // AGV 状态要求秒级感知,3s 拉一次 RCS
|
||||
agvWriteTimeout = 5 * time.Second
|
||||
agvReadTimeout = 90 * time.Second
|
||||
agvPingInterval = 30 * time.Second
|
||||
)
|
||||
|
||||
// agvClient 单个 WebSocket 连接;send 由 writePump 独占写,避免并发写冲突。
|
||||
type agvClient struct {
|
||||
conn *websocket.Conn
|
||||
send chan []byte
|
||||
}
|
||||
|
||||
// AgvHub 人工派车 WebSocket 推送中心:
|
||||
// - 首个连接建立时懒启动轮询:每 agvPollInterval 先 RefreshAgvTasks(拉海康 RCS → 写回本地库),
|
||||
// 再取手动链快照 AgvChainList,与上次不一致才广播 —— 兼顾「断网恢复后自动同步」与「状态变化秒级推送」。
|
||||
// - RCS 回调(ApplyAgvCallback)改库后也调 BroadcastNow 主动推一帧,不等下一个轮询周期。
|
||||
type AgvHub struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
upgrader websocket.Upgrader
|
||||
mu sync.Mutex
|
||||
clients map[*agvClient]struct{}
|
||||
last string
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func NewAgvHub(svcCtx *svc.ServiceContext) *AgvHub {
|
||||
h := &AgvHub{
|
||||
svcCtx: svcCtx,
|
||||
clients: map[*agvClient]struct{}{},
|
||||
}
|
||||
h.upgrader = websocket.Upgrader{CheckOrigin: sameOrigin}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *AgvHub) add(c *agvClient) {
|
||||
h.mu.Lock()
|
||||
h.clients[c] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *AgvHub) remove(c *agvClient) {
|
||||
h.mu.Lock()
|
||||
delete(h.clients, c)
|
||||
h.mu.Unlock()
|
||||
_ = c.conn.Close()
|
||||
}
|
||||
|
||||
// snapshot 取一次手动链快照(仅 MANUAL 段,即人工派车页面消费的数据)。
|
||||
func (h *AgvHub) snapshot(ctx context.Context) []byte {
|
||||
list, err := logic.New(h.svcCtx).AgvChainList(ctx)
|
||||
if err != nil {
|
||||
logx.Errorf("AGV 链快照失败:%v", err)
|
||||
list = []logic.AgvChainInfo{}
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"chains": list})
|
||||
return b
|
||||
}
|
||||
|
||||
// publishIfChanged 先拉 RCS 更新本地库,再取快照对比,变化才广播。
|
||||
func (h *AgvHub) publishIfChanged(ctx context.Context) {
|
||||
if _, err := logic.New(h.svcCtx).RefreshAgvTasks(ctx); err != nil {
|
||||
logx.Errorf("AGV RCS 状态刷新失败:%v", err)
|
||||
}
|
||||
h.BroadcastNow(ctx)
|
||||
}
|
||||
|
||||
// BroadcastNow 立即取快照并在变化时广播(RCS 回调改库后调用,秒级推送)。
|
||||
func (h *AgvHub) BroadcastNow(ctx context.Context) {
|
||||
payload := h.snapshot(ctx)
|
||||
h.mu.Lock()
|
||||
if string(payload) == h.last {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
h.last = string(payload)
|
||||
h.mu.Unlock()
|
||||
h.broadcast(payload)
|
||||
}
|
||||
|
||||
func (h *AgvHub) broadcast(payload []byte) {
|
||||
h.mu.Lock()
|
||||
for c := range h.clients {
|
||||
select {
|
||||
case c.send <- payload:
|
||||
default: // 慢客户端丢弃当前帧,不阻塞其它连接(下一个周期会推最新全量)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// startPolling 首个连接建立时懒启动轮询。
|
||||
func (h *AgvHub) startPolling() {
|
||||
h.once.Do(func() {
|
||||
go func() {
|
||||
ticker := time.NewTicker(agvPollInterval)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
h.publishIfChanged(context.Background())
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
// Handle 升级为 WebSocket:先推一次全量并对齐 last,再由 writePump 串行写广播帧与 ping。
|
||||
// token 校验在 handler 层完成。
|
||||
func (h *AgvHub) Handle(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logx.Errorf("AGV WebSocket 升级失败:%v", err)
|
||||
return
|
||||
}
|
||||
c := &agvClient{conn: conn, send: make(chan []byte, 16)}
|
||||
h.add(c)
|
||||
h.startPolling()
|
||||
|
||||
payload := h.snapshot(r.Context())
|
||||
h.mu.Lock()
|
||||
h.last = string(payload)
|
||||
h.mu.Unlock()
|
||||
c.send <- payload
|
||||
|
||||
go h.writePump(c)
|
||||
h.readPump(c)
|
||||
}
|
||||
|
||||
func (h *AgvHub) readPump(c *agvClient) {
|
||||
defer h.remove(c)
|
||||
c.conn.SetReadLimit(1024)
|
||||
_ = c.conn.SetReadDeadline(time.Now().Add(agvReadTimeout))
|
||||
c.conn.SetPongHandler(func(string) error {
|
||||
return c.conn.SetReadDeadline(time.Now().Add(agvReadTimeout))
|
||||
})
|
||||
for {
|
||||
if _, _, err := c.conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AgvHub) writePump(c *agvClient) {
|
||||
ticker := time.NewTicker(agvPingInterval)
|
||||
defer func() {
|
||||
ticker.Stop()
|
||||
_ = c.conn.Close()
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case msg := <-c.send:
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(agvWriteTimeout))
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(agvWriteTimeout))
|
||||
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user