zhangqian
2023-09-22 71cc6deae4b873c3382895054fe2bd6816290755
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package v1
 
import (
    "apsClient/conf"
    "apsClient/constvar"
    "apsClient/model"
    "apsClient/model/common"
    "apsClient/model/request"
    "apsClient/model/response"
    "apsClient/nsq"
    "apsClient/pkg/contextx"
    "apsClient/pkg/convertx"
    "apsClient/pkg/ecode"
    "apsClient/pkg/logx"
    "apsClient/pkg/safe"
    "apsClient/service"
    "apsClient/service/plc_address"
    "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().GetNextTask()
    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
// @Param     object  query    request.TaskList true  "查询参数"
// @Success   200   {object}  contextx.Response{data=response.TaskData}  "成功"
// @Router    /v1/task/get [get]
func (slf *TaskApi) TaskGet(c *gin.Context) {
    var params request.TaskList
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    if params.Page <= 0 {
        params.Page = 1
    }
    if params.PageSize <= 0 {
        params.PageSize = 1
    }
 
    taskResponse, code := service.NewTaskService().GetTask(params.Page, params.PageSize, service.TaskModeCurrent) //取进行中的或未开始的
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    if len(taskResponse.Tasks) == 0 {
        taskResponse, code = service.NewTaskService().GetTask(params.Page, params.PageSize, service.TaskModeLastFinished) //取上一个完成的
        if code != ecode.OK {
            ctx.Fail(code)
            return
        }
    }
 
    for _, task := range taskResponse.Tasks {
        if task.Procedure.Status == model.ProcedureStatusWaitProcess {
            task.CanStarted = true
        }
    }
 
    taskResponse.Prompt = conf.Conf.Prompt
 
    ctx.OkWithDetailed(taskResponse)
}
 
// TaskGetUnStarted
// @Tags      Task
// @Summary   获取未开始的任务
// @Produce   application/json
// @Param     object  query    request.TaskList true  "查询参数"
// @Success   200   {object}  contextx.Response{data=response.TaskData}  "成功"
// @Router    /v1/task/get/unStarted [get]
func (slf *TaskApi) TaskGetUnStarted(c *gin.Context) {
    var params request.TaskList
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    if params.Page <= 0 {
        params.Page = 1
    }
    if params.PageSize <= 0 {
        params.PageSize = 1
    }
 
    taskResponse, code := service.NewTaskService().GetTask(params.Page, params.PageSize, service.TaskModeUnStarted) //时间到了未开始的
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    ctx.OkWithDetailed(taskResponse)
}
 
// 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
    }
 
    processModel, err := service.NewTaskService().GetProcessParams(procedure, order)
    if err != nil || processModel == nil || processModel.ParamsMap == nil {
        ctx.FailWithMsg(ecode.ParamsErr, "请先配置工艺参数")
        return
    }
 
    processParamsArr := make([]response.ProcessParams, 0, len(processModel.ParamsMap))
    for k, v := range processModel.ParamsMap {
        processParamsArr = append(processParamsArr, response.ProcessParams{
            Key:   k,
            Value: v,
        })
    }
 
    safe.Go(func() {
        caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicGetPlcAddress, conf.Conf.NsqConf.NodeId), fmt.Sprintf(constvar.NsqTopicSendPlcAddress, conf.Conf.NsqConf.NodeId))
        var addressResult common.ResponsePlcAddress
        err := caller.Call(common.RequestPlcAddress{DeviceId: conf.Conf.System.DeviceId}, &addressResult, time.Second*3)
        if err != nil {
            logx.Infof("get plc address err: %v", err.Error())
        }
    })
 
    resp := response.ProcessParamsResponse{
        Number: processModel.Number,
        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)
    procedure, code := service.NewTaskService().GetProcedureById(id)
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    err := service.NewTaskService().UpdateProcedureStatus(nil, id, model.ProcedureStatusFinished, procedure.Position)
    if err != nil {
        logx.Errorf("UpdateProcedureStatus err: %v", err.Error())
        ctx.Fail(ecode.UnknownErr)
        return
    }
 
    msg := &common.MsgTaskStatusUpdate{
        WorkOrderId:  procedure.WorkOrderID,
        ProcedureID:  procedure.ProceduresInfo.ProcedureID,
        DeviceId:     procedure.ProceduresInfo.DeviceID,
        IsProcessing: false,
        IsFinish:     true,
    }
 
    caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicTaskProcedureStatusUpdate, conf.Conf.NsqConf.NodeId), "")
    err = caller.Send(msg)
    if err != nil {
        logx.Errorf("send task status update msg error:%v", err.Error())
    }
 
    ctx.Ok()
}
 
// TaskStart
// @Tags      Task
// @Summary   下发工艺参数(开始任务)
// @Produce   application/json
// @Param     object  body    request.SendProcessParams true  "查询参数"
// @Success   200   {object}  contextx.Response{service.GetProcessModel}  "成功"
// @Router    /v1/task/sendProcessParams [post]
func (slf *TaskApi) TaskStart(c *gin.Context) {
    var params request.SendProcessParams
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    taskService := service.NewTaskService()
    procedure, code := taskService.GetProcedureById(params.ProcedureId)
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    order, err := taskService.GetOrderByWorkOrderId(procedure.WorkOrderID)
    if err != nil {
        ctx.Fail(ecode.UnknownErr)
        return
    }
 
    if procedure.Status == model.ProcedureStatusProcessing {
        ctx.FailWithMsg(ecode.ParamsErr, "该工序已开始生产")
        return
    }
 
    processModel, err := taskService.GetProcessParams(procedure, order)
    if err != nil || processModel == nil || processModel.ParamsMap == nil {
        ctx.Fail(ecode.UnknownErr)
        return
    }
 
    err = model.WithTransaction(func(db *gorm.DB) error {
        err = taskService.UpdateProcedureStatusAndPosition(db, params.ProcedureId, model.ProcedureStatusProcessing, params.Position)
        if err != nil {
            return err
        }
        procedure.Position = params.Position
        err = taskService.UpdateOrderStatus(db, order.ID, model.OrderStatusProcessing)
        if err != nil {
            return err
        }
        return service.NewProgressService().Add(db, procedure, order)
    })
    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(processModel.ParamsMap, plcConfig)
    if err != nil {
        logx.Errorf("SendProcessParams: %v", err.Error())
        err = model.WithTransaction(func(db *gorm.DB) error {
            err = taskService.UpdateProcedureStatusAndPosition(db, params.ProcedureId, model.ProcedureStatusWaitProcess, params.Position)
            if err != nil {
                return err
            }
            procedure.Position = params.Position
            err = taskService.UpdateOrderStatus(db, order.ID, model.OrderStatusWaitProcess)
            if err != nil {
                return err
            }
            return nil
        })
        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, params.Position, order.Amount.IntPart())
    if err != nil {
        ctx.FailWithMsg(ecode.NeedConfirmedErr, "糟糕,工艺下发失败。")
        return
    }
 
    msg := &common.MsgTaskStatusUpdate{
        WorkOrderId:  procedure.WorkOrderID,
        ProcedureID:  procedure.ProceduresInfo.ProcedureID,
        DeviceId:     procedure.ProceduresInfo.DeviceID,
        IsProcessing: true,
        IsFinish:     false,
    }
 
    caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicTaskProcedureStatusUpdate, conf.Conf.NsqConf.NodeId), "")
    err = caller.Send(msg)
    if err != nil {
        logx.Errorf("send task status update msg error:%v", err.Error())
    }
 
    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
    }
    if plcConfig.CurrentTryTimes == 0 {
        logx.Info("----------------开始下发工艺参数-----------------")
    }
    var failedNumbers int
    for k, v := range paramsMap {
        address, ok := plc_address.Get(k)
        if !ok {
            logx.Errorf("miss param address, k:%v, v:%v", k, v)
            continue
        }
        err := service.PlcWriteDirect(plcConfig, 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", k, v)
        }
    }
    if failedNumbers >= 1 { //写入plc失败, 重试
        plcConfig.CurrentTryTimes++
        return SendParams(paramsMap, plcConfig)
    }
    logx.Info("----------------下发工艺参数完毕-----------------")
    return nil
}