- MES 新增损耗台账 loss_ledger,差异确认损耗接口 ConfirmReceiveLoss(按工单归集) - 备料清单 preparation:MES 按 日计划×工单×工位×物料 实时计算,WMS 只读展示 PreparationList - 退料闭环:N5 工位托盘守卫(未完成禁止退料)、退料 AGV 自动派车(JBT21 空位判定 + 托盘回收链路)、退料参考剩余量接口(应剩余=实备-已耗-已退-已损) - 新增 AGV 车辆状态表 agv_vehicle_state 及查询 - 整合接驳台/叫料池/库存锁既有闭环,清理 sql 目录注释生成脚本与 catalog,更新文档
379 lines
14 KiB
Go
379 lines
14 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"bj_power_mes/ent"
|
||
"bj_power_mes/ent/linepoint"
|
||
"bj_power_mes/ent/plcsendlog"
|
||
"bj_power_mes/ent/workpiece"
|
||
"bj_power_mes/internal/plc"
|
||
)
|
||
|
||
// PointBit 单个点位状态(48 位之一)。
|
||
type PointBit struct {
|
||
Code string `json:"code"` // G1 / C1 / DOCK01 / JBT21
|
||
Has bool `json:"has"` // 有托盘=true
|
||
}
|
||
|
||
// BitsGroup 三组点位(工位 / 主线 / 接驳台 + 库房接驳台)。
|
||
type BitsGroup struct {
|
||
Mock bool `json:"mock"` // 当前 PLC 为模拟模式(未连接真实 PLC,页面显示「模拟数据」标注)
|
||
Station []PointBit `json:"station"`
|
||
Main []PointBit `json:"main"`
|
||
Dock []PointBit `json:"dock"`
|
||
Jbt PointBit `json:"jbt"`
|
||
}
|
||
|
||
// MWState 单个 MW 寄存器当前值 + 解析结果。
|
||
type MWState struct {
|
||
Addr int `json:"addr"`
|
||
Value int `json:"value"`
|
||
Category string `json:"category"` // A/B/C/D
|
||
InTransit bool `json:"inTransit"`
|
||
SrcCode string `json:"srcCode,omitempty"`
|
||
TgtCode string `json:"tgtCode,omitempty"`
|
||
}
|
||
|
||
// MonitorPreview 手动下发预览(MW 地址 + 写入值 + 源→目标)。
|
||
type MonitorPreview struct {
|
||
Ok bool `json:"ok"`
|
||
MW int `json:"mw"`
|
||
Value int `json:"value"`
|
||
SrcCode string `json:"srcCode"`
|
||
TgtCode string `json:"tgtCode"`
|
||
Reason string `json:"reason,omitempty"`
|
||
}
|
||
|
||
// ManualWriteReq 手动下发请求体。
|
||
type ManualWriteReq struct {
|
||
SrcType string `json:"srcType"` // G / C
|
||
Src int `json:"src"`
|
||
TgtType string `json:"tgtType"` // G / C
|
||
Tgt int `json:"tgt"`
|
||
}
|
||
|
||
// PlcMonitorBits 读取 48 位点位状态并按位置分组(工位/主线/接驳台+库房)。
|
||
func (s *Service) PlcMonitorBits(ctx context.Context) (*BitsGroup, error) {
|
||
bits, err := s.ctx.PLC.Get().ReadBits(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
g := &BitsGroup{Mock: s.ctx.PLC.IsMock()}
|
||
for i := 0; i < 12; i++ {
|
||
g.Station = append(g.Station, PointBit{Code: "G" + strconv.Itoa(i+1), Has: bitAt(bits, i)})
|
||
}
|
||
for i := 0; i < 15; i++ {
|
||
g.Main = append(g.Main, PointBit{Code: "C" + strconv.Itoa(i+1), Has: bitAt(bits, 12+i)})
|
||
}
|
||
for i := 0; i < 20; i++ {
|
||
g.Dock = append(g.Dock, PointBit{Code: "DOCK" + pad2(i+1), Has: bitAt(bits, 27+i)})
|
||
}
|
||
g.Jbt = PointBit{Code: "JBT21", Has: bitAt(bits, 47)}
|
||
return g, nil
|
||
}
|
||
|
||
func bitAt(bits []bool, i int) bool {
|
||
if i >= 0 && i < len(bits) {
|
||
return bits[i]
|
||
}
|
||
return false
|
||
}
|
||
|
||
// PlcMonitorMW 读取 §4.4 路由表全部 MW 地址当前值并解析(非0 即在途指令)。
|
||
func (s *Service) PlcMonitorMW(ctx context.Context) ([]MWState, error) {
|
||
addrs := plc.AllRouteAddrs()
|
||
out := make([]MWState, 0, len(addrs))
|
||
for _, addr := range addrs {
|
||
val, err := s.ctx.PLC.Get().ReadMW(ctx, addr)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
st := MWState{Addr: addr, Value: val, InTransit: val != 0}
|
||
if cat, ok := plc.MWCategory(addr); ok {
|
||
st.Category = string(cat)
|
||
}
|
||
if val != 0 {
|
||
if srcType, tgtType, src, tgt, ok := plc.ParseMW(addr, val); ok {
|
||
st.SrcCode = string(srcType) + strconv.Itoa(src)
|
||
st.TgtCode = string(tgtType) + strconv.Itoa(tgt)
|
||
}
|
||
}
|
||
out = append(out, st)
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// PlcMonitorManualWrite 手动下发路径指令:
|
||
// 1) 互斥:若存在在途指令(plc_send_log status=SENT),拒绝并提示,不打断自动线;
|
||
// 2) 校验组合合法性(§4.4 路由表);
|
||
// 3) 写 MW 寄存器;
|
||
// 4) 记操作日志(event_log,type=plc_manual_write)。
|
||
func (s *Service) PlcMonitorManualWrite(ctx context.Context, req ManualWriteReq, operator string) (*MonitorPreview, error) {
|
||
// 1. 互斥:在途指令(工位下发尚未收到完成信号)
|
||
inTransit, err := s.ctx.EntClient.PlcSendLog.Query().Where(plcsendlog.Status("SENT")).Exist(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if inTransit {
|
||
return nil, errors.New("存在在途指令(工位下发尚未收到完成信号),手动下发被拒绝,以免打断自动线;可在「工位下发」页撤回或人工完成后重试")
|
||
}
|
||
// 2. 校验组合
|
||
st, stok := plc.ParseSrcType(req.SrcType)
|
||
tt, ttok := plc.ParseSrcType(req.TgtType)
|
||
if !stok || !ttok {
|
||
return nil, errors.New("非法的源/目标类型")
|
||
}
|
||
mw, value, ok := plc.LookupRoute(st, req.Src, req.Tgt, tt)
|
||
if !ok {
|
||
return nil, errors.New("非法的源/目标组合(不在 §4.4 路由表内)")
|
||
}
|
||
// 2.5 多工单缓存策略(2026-11-03 定论,基础设置可配):
|
||
// strict=严格隔离——目标主线位置已被工件占用(不论哪张工单)即拒绝写入,禁共位;
|
||
// physical=物理优先(默认)——由 PLC 物理决定,MES 不额外限制。
|
||
if req.TgtType == "C" && s.CfgStr(ctx, CfgMultiOrderCachePolicy, "physical") == "strict" {
|
||
if pt, perr := s.ctx.EntClient.LinePoint.Query().
|
||
Where(linepoint.PointType("CACHE"), linepoint.PointNo(req.TgtType+strconv.Itoa(req.Tgt))).First(ctx); perr == nil && pt != nil && pt.Occupied {
|
||
return nil, fmt.Errorf("多工单缓存策略=严格隔离:%s 已被工件 %s(工单 %s)占用,禁止共位;可到「基础设置」切换为物理优先,或先清走该工件",
|
||
req.TgtType+strconv.Itoa(req.Tgt), pt.CurrentSn, pt.OrderNo)
|
||
}
|
||
}
|
||
// 3. 写 MW
|
||
if err := s.ctx.PLC.Get().WriteMW(ctx, mw, value); err != nil {
|
||
return nil, err
|
||
}
|
||
// 4. 记操作日志
|
||
srcCode := req.SrcType + strconv.Itoa(req.Src)
|
||
tgtCode := req.TgtType + strconv.Itoa(req.Tgt)
|
||
s.ctx.EventLog.Write(ctx, "plc_manual_write", "", operator, "plc", srcCode+"->"+tgtCode,
|
||
"手动下发路径指令 "+srcCode+" → "+tgtCode+"(MW"+strconv.Itoa(mw)+"="+strconv.Itoa(value)+")",
|
||
map[string]any{
|
||
"srcType": req.SrcType, "src": req.Src,
|
||
"tgtType": req.TgtType, "tgt": req.Tgt,
|
||
"mw": mw, "value": value,
|
||
})
|
||
return &MonitorPreview{Ok: true, MW: mw, Value: value, SrcCode: srcCode, TgtCode: tgtCode}, nil
|
||
}
|
||
|
||
// ---------- 在途指令强制清零(仅 §4.4 路由区 MW=0,不开放任意写) ----------
|
||
|
||
// ClearInTransitReq 在途指令强制清零请求体:仅允许 §4.4 路由表覆盖的 MW 地址,写 0。
|
||
type ClearInTransitReq struct {
|
||
Addr int `json:"addr"` // MW 地址(必须是 §4.4 路由表覆盖的 MW)
|
||
}
|
||
|
||
// ClearInTransitResult 清零结果。
|
||
type ClearInTransitResult struct {
|
||
Addr int `json:"addr"` // 被清零的 MW 地址
|
||
Before int `json:"before"` // 清零前的值(非 0 即在途指令)
|
||
}
|
||
|
||
// PlcMonitorClearInTransit 强制清零在途指令:把 §4.4 路由区某 MW 写 0。
|
||
// 仅允许路由表覆盖的 MW 地址(MWCategory 命中),越界/控制区/无关寄存器一律拒绝;不开放任意写。
|
||
// 记操作日志(event_log,type=plc_in_transit_clear)。
|
||
func (s *Service) PlcMonitorClearInTransit(ctx context.Context, req ClearInTransitReq, operator string) (*ClearInTransitResult, error) {
|
||
if req.Addr <= 0 {
|
||
return nil, errors.New("缺少 MW 地址")
|
||
}
|
||
// 仅允许 §4.4 路由表覆盖的 MW(防止误清控制区/无关寄存器)
|
||
if _, ok := plc.MWCategory(req.Addr); !ok {
|
||
return nil, errors.New("MW" + strconv.Itoa(req.Addr) + " 不在 §4.4 路由表覆盖范围内,操作已拒绝")
|
||
}
|
||
before, err := s.ctx.PLC.Get().ReadMW(ctx, req.Addr)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if err := s.ctx.PLC.Get().WriteMW(ctx, req.Addr, 0); err != nil {
|
||
return nil, err
|
||
}
|
||
obj := "MW" + strconv.Itoa(req.Addr)
|
||
desc := "强制清零在途指令:" + obj + " " + strconv.Itoa(before) + " → 0"
|
||
if srcType, tgtType, src, tgt, ok := plc.ParseMW(req.Addr, before); ok {
|
||
desc += "(" + string(srcType) + strconv.Itoa(src) + " → " + string(tgtType) + strconv.Itoa(tgt) + ")"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "plc_in_transit_clear", "", operator, "plc", obj,
|
||
desc,
|
||
map[string]any{
|
||
"object": obj,
|
||
"before": before,
|
||
"after": 0,
|
||
"operator": operator,
|
||
"clearedAt": time.Now().Format(time.RFC3339),
|
||
})
|
||
return &ClearInTransitResult{Addr: req.Addr, Before: before}, nil
|
||
}
|
||
|
||
// ---------- 工件位置纠正(块 E:产线管理页 tab4) ----------
|
||
|
||
// PositionMismatch 一处「MES 记录有、PLC 实际无」的位置不一致。
|
||
type PositionMismatch struct {
|
||
WorkpieceID int64 `json:"workpieceId"`
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
Status string `json:"status"`
|
||
AtStationNo int `json:"atStationNo"` // MES 记录的物理位置
|
||
CurStationNo int `json:"curStationNo"` // MES 记录的业务位置(最后报工工位)
|
||
}
|
||
|
||
// PositionCheck 工件位置核对结果:PLC 实际点位态 + MES 记录与实际不符的工件列表。
|
||
type PositionCheck struct {
|
||
Stations []PointBit `json:"stations"` // G1~G12 当前 PLC 点位态
|
||
Mismatches []PositionMismatch `json:"mismatches"` // 记录有、实际无(可纠正)
|
||
}
|
||
|
||
// PlcPositionCheck 核对「MES 记录的工件物理位置 vs PLC 实际托盘位」:
|
||
// MES 记 atStationNo=n(工件应在工位 n),但 PLC 该工位无托盘 ⇒ 记录过期/错位,列出待纠正。
|
||
func (s *Service) PlcPositionCheck(ctx context.Context) (*PositionCheck, error) {
|
||
bits, err := s.ctx.PLC.Get().ReadBits(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
stations := make([]PointBit, 0, 12)
|
||
for i := 0; i < 12; i++ {
|
||
stations = append(stations, PointBit{Code: "G" + strconv.Itoa(i+1), Has: bitAt(bits, i)})
|
||
}
|
||
// MES 在制工件(未完工):atStationNo>0 表示"记录说在工位 n"
|
||
list, err := s.ctx.EntClient.Workpiece.Query().
|
||
Where(workpiece.AtStationNoGT(0), workpiece.StatusNEQ("DONE")).
|
||
Order(ent.Desc(workpiece.FieldID)).Limit(200).All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
mismatches := make([]PositionMismatch, 0)
|
||
for _, wp := range list {
|
||
n := wp.AtStationNo
|
||
if n < 1 || n > 12 {
|
||
continue
|
||
}
|
||
if bitAt(bits, n-1) {
|
||
continue // PLC 也说有件:一致
|
||
}
|
||
mismatches = append(mismatches, PositionMismatch{
|
||
WorkpieceID: int64(wp.ID),
|
||
Sn: wp.Sn,
|
||
OrderNo: wp.OrderNo,
|
||
Status: wp.Status,
|
||
AtStationNo: n,
|
||
CurStationNo: wp.CurrentStationNo,
|
||
})
|
||
}
|
||
return &PositionCheck{Stations: stations, Mismatches: mismatches}, nil
|
||
}
|
||
|
||
// CorrectPositionReq 工件位置纠正请求体。
|
||
type CorrectPositionReq struct {
|
||
WorkpieceID int64 `json:"workpieceId"`
|
||
}// PlcPositionCorrect 纠正工件位置:把"记录在工位、实际 PLC 无托盘"的工件清为不在工位(atStationNo=0)。
|
||
// 记操作日志(event_log,type=plc_position_correct),含工件 SN、纠正前/后位置、操作人。
|
||
func (s *Service) PlcPositionCorrect(ctx context.Context, req CorrectPositionReq, operator string) error {
|
||
if req.WorkpieceID <= 0 {
|
||
return errors.New("缺少工件 ID")
|
||
}
|
||
wp, err := s.ctx.EntClient.Workpiece.Get(ctx, int(req.WorkpieceID))
|
||
if err != nil {
|
||
return errors.New("工件不存在或已删除")
|
||
}
|
||
before := wp.AtStationNo
|
||
if before <= 0 {
|
||
return errors.New("该工件当前未记录工位位置,无需纠正")
|
||
}
|
||
if _, err := s.ctx.EntClient.Workpiece.UpdateOneID(int(req.WorkpieceID)).
|
||
SetAtStationNo(0).Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
obj := "工件 " + wp.Sn
|
||
s.ctx.EventLog.Write(ctx, "plc_position_correct", wp.OrderNo, operator, "workpiece", wp.Sn,
|
||
"纠正工件位置:"+wp.Sn+" 工位 "+strconv.Itoa(before)+" → 不在工位(PLC 该工位无托盘,记录已过期)",
|
||
map[string]any{
|
||
"object": obj,
|
||
"sn": wp.Sn,
|
||
"before": before,
|
||
"after": 0,
|
||
"operator": operator,
|
||
})
|
||
return nil
|
||
}
|
||
|
||
// ---------- 末端取件释放(块 H 收尾:G11/G12 无 PLC 传感器,取件必须人工确认) ----------
|
||
|
||
// EndPointOccupied 末端下料检测位(END-U=G11 上排 / END-D=G12 下排)的一条占用记录。
|
||
type EndPointOccupied struct {
|
||
PointNo string `json:"pointNo"` // 点位编号 END-U / END-D
|
||
Label string `json:"label"` // 点位名称
|
||
StationNo int `json:"stationNo"` // 对应工位 11/12
|
||
Sn string `json:"sn"` // 占用工件的 SN
|
||
OrderNo string `json:"orderNo"` // 来源:所属工单(占用记账时写入)
|
||
UpdatedAt int64 `json:"updatedAt"` // 占用时间(点位台账最后更新时间)
|
||
}
|
||
|
||
// ListEndPointOccupied 列出末端下料检测位(G11/G12)当前被占用的记录。
|
||
// G11/G12 无 PLC 传感器,工件被物理取走后点位台账不会自动清,必须人工确认释放。
|
||
func (s *Service) ListEndPointOccupied(ctx context.Context) ([]EndPointOccupied, error) {
|
||
pts, err := s.ctx.EntClient.LinePoint.Query().
|
||
Where(linepoint.PointType("END"), linepoint.Occupied(true)).
|
||
Order(ent.Asc(linepoint.FieldSeq)).All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
out := make([]EndPointOccupied, 0, len(pts))
|
||
for _, p := range pts {
|
||
out = append(out, EndPointOccupied{
|
||
PointNo: p.PointNo,
|
||
Label: p.Label,
|
||
StationNo: p.StationNo,
|
||
Sn: p.CurrentSn,
|
||
OrderNo: p.OrderNo,
|
||
UpdatedAt: p.UpdatedAt.Unix(),
|
||
})
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ReleaseEndPointReq 末端取件释放请求体。
|
||
type ReleaseEndPointReq struct {
|
||
PointNo string `json:"pointNo"`
|
||
}
|
||
|
||
// ReleaseEndPoint 人工确认末端取件:释放 G11/G12 点位占用(OccupyPoint OUT)并写操作日志。
|
||
// 记 event_log(type=point_release_manual),含 SN、点位、操作人、释放时间、说明「人工确认末端取件」。
|
||
func (s *Service) ReleaseEndPoint(ctx context.Context, req ReleaseEndPointReq, operator string) error {
|
||
pointNo := strings.TrimSpace(req.PointNo)
|
||
if pointNo == "" {
|
||
return errors.New("缺少点位编号")
|
||
}
|
||
pt, err := s.ctx.EntClient.LinePoint.Query().Where(linepoint.PointNo(pointNo)).First(ctx)
|
||
if err != nil {
|
||
return errors.New("点位不存在:" + pointNo)
|
||
}
|
||
if pt.PointType != "END" {
|
||
return errors.New("仅支持释放末端下料检测位(G11/G12)")
|
||
}
|
||
if !pt.Occupied {
|
||
return errors.New("该点位当前未被占用,无需释放")
|
||
}
|
||
sn, orderNo := pt.CurrentSn, pt.OrderNo
|
||
// 释放点位(唯一事实源维护入口,内部写 line.point.out 流水)
|
||
if err := s.OccupyPoint(ctx, pointNo, sn, orderNo, operator, "OUT"); err != nil {
|
||
return err
|
||
}
|
||
now := time.Now().Unix()
|
||
s.ctx.EventLog.Write(ctx, "point_release_manual", orderNo, operator, "line_point", pointNo,
|
||
"人工确认末端取件:"+pointNo+"("+pt.Label+")",
|
||
map[string]any{
|
||
"object": "点位 " + pointNo,
|
||
"pointNo": pointNo,
|
||
"pointLabel": pt.Label,
|
||
"sn": sn,
|
||
"orderNo": orderNo,
|
||
"operator": operator,
|
||
"releasedAt": now,
|
||
"note": "人工确认末端取件",
|
||
})
|
||
return nil
|
||
}
|