86 lines
2.8 KiB
Go
86 lines
2.8 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"bj_power_mes/ent"
|
|
"bj_power_mes/ent/plcsendlog"
|
|
)
|
|
|
|
type PlcSendReq struct {
|
|
OrderNo string `json:"orderNo"`
|
|
Sn string `json:"sn"`
|
|
StationNo int `json:"stationNo"`
|
|
ProcessCombination string `json:"processCombination"` // 如 "135"
|
|
}
|
|
|
|
// SendProcess 下发 PLC 工序码。
|
|
// 约束:上一条工序未收到完成信号,不下发下一条(模拟 S7 握手)。
|
|
func (s *Service) SendProcess(ctx context.Context, req PlcSendReq, operator string) (*ent.PlcSendLog, error) {
|
|
if req.ProcessCombination == "" {
|
|
return nil, errors.New("工序组合不能为空")
|
|
}
|
|
// 检查是否存在未完成的同工位下发
|
|
last, err := s.ctx.EntClient.PlcSendLog.Query().
|
|
Where(plcsendlog.Status("SENT")).Order(plcsendlog.ByID()).First(ctx)
|
|
if err == nil && last != nil {
|
|
done, qErr := s.ctx.PLC.Get().QueryDone(ctx)
|
|
if qErr != nil || !done {
|
|
return nil, errors.New("上一条工序尚未收到PLC完成信号,不能下发下一条")
|
|
}
|
|
// 标记上一条为完成
|
|
_, _ = s.ctx.EntClient.PlcSendLog.UpdateOneID(last.ID).
|
|
SetStatus("DONE").SetDoneTime(time.Now()).SetAck(true).Save(ctx)
|
|
}
|
|
now := time.Now()
|
|
rec, err := s.ctx.EntClient.PlcSendLog.Create().
|
|
SetOrderNo(req.OrderNo).SetSn(req.Sn).SetStationNo(req.StationNo).
|
|
SetProcessCombination(req.ProcessCombination).SetProcessCodes(parseCodes(req.ProcessCombination)).
|
|
SetStatus("SENT").SetSendTime(now).SetOperator(operator).Save(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 模拟下行下发
|
|
_, err = s.ctx.PLC.Get().SendProcessCode(ctx, req.ProcessCombination)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.ctx.EventLog.Write(ctx, "plc.send", req.OrderNo, operator, "plc_send_log", req.Sn, "PLC工序码下发", map[string]any{"combination": req.ProcessCombination})
|
|
|
|
// mock 完成信号:延时后置为完成(演示"未完成不下发下一条"握手)
|
|
go func(id int) {
|
|
time.Sleep(5 * time.Second)
|
|
s.ctx.PLC.Get().AckDone(context.Background(), true)
|
|
_, _ = s.ctx.EntClient.PlcSendLog.UpdateOneID(id).
|
|
SetStatus("DONE").SetDoneTime(time.Now()).SetAck(true).Save(context.Background())
|
|
}(rec.ID)
|
|
|
|
return rec, nil
|
|
}
|
|
|
|
func parseCodes(combination string) []int {
|
|
var out []int
|
|
for _, ch := range combination {
|
|
if ch >= '1' && ch <= '9' {
|
|
out = append(out, int(ch-'0'))
|
|
} else if ch == '1' || ch == '0' {
|
|
// 允许 "10","11","12" 两位工序
|
|
continue
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// ListPlcSendLogs 查询 PLC 下发日志
|
|
func (s *Service) ListPlcSendLogs(ctx context.Context, orderNo, status string) ([]*ent.PlcSendLog, error) {
|
|
q := s.ctx.EntClient.PlcSendLog.Query()
|
|
if orderNo != "" {
|
|
q = q.Where(plcsendlog.OrderNo(orderNo))
|
|
}
|
|
if status != "" {
|
|
q = q.Where(plcsendlog.Status(status))
|
|
}
|
|
return q.Order(ent.Desc(plcsendlog.FieldID)).All(ctx)
|
|
} |