package v1
|
|
import (
|
"apsClient/conf"
|
"apsClient/constvar"
|
"apsClient/model"
|
"apsClient/model/common"
|
"apsClient/model/response"
|
"apsClient/nsq"
|
"apsClient/pkg/contextx"
|
"apsClient/pkg/convertx"
|
"apsClient/pkg/ecode"
|
"apsClient/pkg/logx"
|
"apsClient/pkg/plc"
|
"apsClient/service"
|
"apsClient/service/plc_address"
|
"encoding/json"
|
"errors"
|
"fmt"
|
"github.com/gin-gonic/gin"
|
"gorm.io/gorm"
|
"time"
|
)
|
|
type TaskApi struct{}
|
|
// TaskCountdown
|
// @Tags Task
|
// @Summary 新任务倒计时
|
// @Produce application/json
|
// @Success 200 {object} contextx.Response{data=response.TaskCountdown} "成功"
|
// @Router /v1/task/countdown [get]
|
func (slf *TaskApi) TaskCountdown(c *gin.Context) {
|
ctx, ok := contextx.NewContext(c, nil)
|
if !ok {
|
return
|
}
|
var resp response.TaskCountdown
|
workOrder, err := service.NewTaskService().GetCurrentTask()
|
if err == nil {
|
seconds := workOrder.StartTime - time.Now().Unix()
|
resp.CountDownHour = seconds / 3600
|
resp.CountDownMinute = seconds % 3600 / 60
|
resp.ShowCountDown = true
|
}
|
ctx.OkWithDetailed(resp)
|
}
|
|
// TaskGet
|
// @Tags Task
|
// @Summary 获取任务
|
// @Produce application/json
|
// @Success 200 {object} contextx.Response{data=response.TaskData} "成功"
|
// @Router /v1/task/get [get]
|
func (slf *TaskApi) TaskGet(c *gin.Context) {
|
ctx, ok := contextx.NewContext(c, nil)
|
if !ok {
|
return
|
}
|
|
taskData, code := service.NewTaskService().GetTask()
|
if code != ecode.OK {
|
ctx.Fail(code)
|
return
|
}
|
ctx.OkWithDetailed(taskData)
|
}
|
|
// GetProcessParams
|
// @Tags Task
|
// @Summary 任务开始(获取工艺参数)
|
// @Produce application/json
|
// @Param id path int true "工序id"
|
// @Success 200 {object} contextx.Response{data=response.ProcessParamsResponse} "成功"
|
// @Router /v1/task/start/{id} [get]
|
func (slf *TaskApi) GetProcessParams(c *gin.Context) {
|
ctx, ok := contextx.NewContext(c, nil)
|
if !ok {
|
return
|
}
|
idx := c.Param("id")
|
if idx == "" {
|
ctx.Fail(ecode.ParamsErr)
|
return
|
}
|
id := convertx.Atoi(idx)
|
procedure, code := service.NewTaskService().GetProcedureById(id)
|
if code != ecode.OK {
|
ctx.Fail(code)
|
return
|
}
|
|
order, err := service.NewTaskService().GetOrderByWorkOrderId(procedure.WorkOrderID)
|
if err != nil {
|
ctx.Fail(ecode.UnknownErr)
|
return
|
}
|
|
paramsMap := make(map[string]interface{})
|
var paramsNumber string
|
data, err := model.NewProcessModelSearch().
|
SetWorkOrder(procedure.WorkOrderID).
|
SetDevice(procedure.ProceduresInfo.DeviceName).
|
SetOrderId(procedure.OrderID).
|
SetProcedure(procedure.ProceduresInfo.ProcedureName).
|
SetProduct(order.ProductName).
|
SetOrder("id desc").First()
|
if err == nil {
|
err = json.Unmarshal([]byte(data.Params), &data.ParamsMap)
|
paramsMap = data.ParamsMap
|
paramsNumber = data.Number
|
if err != nil {
|
logx.Errorf("process model json.Unmarshal:%v", err)
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
} else if err == gorm.ErrRecordNotFound { //如何数据库没有从云端获取
|
caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicProcessParamsRequest, conf.Conf.NsqConf.NodeId), fmt.Sprintf(constvar.NsqTopicProcessParamsResponse, conf.Conf.NsqConf.NodeId))
|
var result common.ResponseProcessParams
|
err = caller.Call(common.RequestProcessParams{
|
WorkOrder: procedure.WorkOrderID,
|
OrderId: procedure.OrderID,
|
Product: order.ProductName,
|
Procedure: procedure.ProceduresInfo.ProcedureName,
|
Device: procedure.ProceduresInfo.DeviceName}, &result, time.Second*3)
|
if err != nil {
|
logx.Errorf("TaskStart GetProcessModel error:%v", err.Error())
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
if result.ParamsMap == nil {
|
logx.Errorf("TaskStart GetProcessModel response miss process params:%v", result)
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
paramsMap = result.ParamsMap
|
paramsNumber = result.Number
|
} else {
|
logx.Errorf("TaskStart GetProcessModel err:%v", err)
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
|
processParamsArr := make([]response.ProcessParams, 0, len(paramsMap))
|
for k, v := range paramsMap {
|
processParamsArr = append(processParamsArr, response.ProcessParams{
|
Key: k,
|
Value: v,
|
})
|
}
|
resp := response.ProcessParamsResponse{
|
Number: paramsNumber,
|
Params: processParamsArr,
|
}
|
ctx.OkWithDetailed(resp)
|
}
|
|
// TaskFinish
|
// @Tags Task
|
// @Summary 任务结束
|
// @Produce application/json
|
// @Param id path int true "工序id"
|
// @Success 200 {object} contextx.Response{service.GetProcessModel} "成功"
|
// @Router /v1/task/finish/{id} [put]
|
func (slf *TaskApi) TaskFinish(c *gin.Context) {
|
ctx, ok := contextx.NewContext(c, nil)
|
if !ok {
|
return
|
}
|
idx := c.Param("id")
|
if idx == "" {
|
ctx.Fail(ecode.ParamsErr)
|
return
|
}
|
id := convertx.Atoi(idx)
|
_, code := service.NewTaskService().GetProcedureById(id)
|
if code != ecode.OK {
|
ctx.Fail(code)
|
return
|
}
|
err := service.NewTaskService().UpdateProcedureStatus(nil, id, model.ProcedureStatusFinished)
|
if err != nil {
|
logx.Errorf("UpdateProcedureStatus err: %v", err.Error())
|
ctx.Fail(ecode.UnknownErr)
|
return
|
}
|
ctx.Ok()
|
}
|
|
// TaskStart
|
// @Tags Task
|
// @Summary 下发工艺参数(开始任务)
|
// @Produce application/json
|
// @Param id path int true "工序id"
|
// @Success 200 {object} contextx.Response{service.GetProcessModel} "成功"
|
// @Router /v1/task/sendProcessParams/{id} [post]
|
func (slf *TaskApi) TaskStart(c *gin.Context) {
|
ctx, ok := contextx.NewContext(c, nil)
|
if !ok {
|
return
|
}
|
idx := c.Param("id")
|
if idx == "" {
|
ctx.Fail(ecode.ParamsErr)
|
return
|
}
|
id := convertx.Atoi(idx)
|
procedure, code := service.NewTaskService().GetProcedureById(id)
|
if code != ecode.OK {
|
ctx.Fail(code)
|
return
|
}
|
order, err := service.NewTaskService().GetOrderByWorkOrderId(procedure.WorkOrderID)
|
if err != nil {
|
ctx.Fail(ecode.UnknownErr)
|
return
|
}
|
|
if procedure.Status == model.ProcedureStatusProcessing {
|
ctx.FailWithMsg(ecode.ParamsErr, "该工序已开始生产")
|
return
|
}
|
|
caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicProcessParamsRequest, conf.Conf.NsqConf.NodeId), fmt.Sprintf(constvar.NsqTopicProcessParamsResponse, conf.Conf.NsqConf.NodeId))
|
var result common.ResponseProcessParams
|
|
err = caller.Call(common.RequestProcessParams{
|
WorkOrder: procedure.WorkOrderID,
|
OrderId: procedure.OrderID,
|
Product: order.ProductName,
|
Procedure: procedure.ProceduresInfo.ProcedureName,
|
Device: procedure.ProceduresInfo.DeviceName}, &result, time.Second*3)
|
if err != nil {
|
logx.Errorf("SendProcessParams GetProcessModel error:%v", err.Error())
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
if result.ParamsMap == nil {
|
logx.Errorf("SendProcessParams GetProcessModel response miss process params:%v", result)
|
ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数")
|
return
|
}
|
|
err = model.WithTransaction(func(db *gorm.DB) error {
|
err = service.NewTaskService().UpdateProcedureStatus(db, id, model.ProcedureStatusProcessing)
|
if err != nil {
|
return err
|
}
|
err = service.NewTaskService().UpdateOrderStatus(db, order.ID, model.OrderStatusProcessing)
|
if err != nil {
|
return err
|
}
|
return nil
|
})
|
if err != nil {
|
logx.Errorf("SendProcessParams update order and procedure status error:%v", err.Error())
|
ctx.FailWithMsg(ecode.NeedConfirmedErr, "更改工单状态失败")
|
return
|
}
|
plcConfig, code := service.NewDevicePlcService().GetDevicePlc()
|
if code != ecode.OK || plcConfig.Id == 0 {
|
ctx.FailWithMsg(ecode.NeedConfirmedErr, "请先配置PLC")
|
return
|
}
|
plcConfig.MaxTryTimes = 2
|
err = SendParams(result.ParamsMap, plcConfig)
|
if err != nil {
|
logx.Errorf("SendProcessParams: %v", err.Error())
|
ctx.FailWithMsg(ecode.NeedConfirmedErr, "糟糕,工艺下发失败。")
|
return
|
}
|
if code != ecode.OK {
|
logx.Errorf("get plcConfig err: %v", err.Error())
|
return
|
}
|
plcConfig.CurrentTryTimes = 0
|
err = service.PlcWrite(plcConfig, constvar.PlcStartAddressTypeTotalNumber, order.Amount.IntPart())
|
if err != nil {
|
ctx.FailWithMsg(ecode.NeedConfirmedErr, "糟糕,工艺下发失败。")
|
return
|
}
|
ctx.Ok()
|
}
|
|
func SendParams(paramsMap map[string]interface{}, plcConfig *model.DevicePlc) error {
|
if len(paramsMap) == 0 {
|
return errors.New("empty params")
|
}
|
if plcConfig.CurrentTryTimes > plcConfig.MaxTryTimes {
|
return plcConfig.CurrentErr
|
}
|
conn, err := plc.GetModbusConnection(fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port))
|
if err != nil {
|
return errors.New(fmt.Sprintf("连接plc失败: %v", err.Error()))
|
}
|
if plcConfig.CurrentTryTimes == 0 {
|
logx.Info("----------------开始下发工艺参数-----------------")
|
}
|
var failedNumbers int
|
for k, v := range paramsMap {
|
if address, ok := plc_address.Get(k); ok {
|
result, err := plc.WriteHoldingRegister(conn, address, v)
|
if err != nil {
|
plcConfig.CurrentErr = err
|
failedNumbers++
|
logx.Errorf("plc write err:%v, address: %v, key: %v value: %v", err.Error(), address, k, v)
|
} else {
|
delete(paramsMap, k)
|
logx.Infof("plc write ok: key: %v, value: %v, result: %v", k, v, result)
|
}
|
} else {
|
logx.Errorf("miss param address, k:%v, v:%v", k, v)
|
}
|
}
|
if failedNumbers >= 1 { //写入plc失败, 重试
|
plcConfig.CurrentTryTimes++
|
return SendParams(paramsMap, plcConfig)
|
}
|
logx.Info("----------------下发工艺参数完毕-----------------")
|
return nil
|
}
|