| | |
| | | "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/plc" |
| | | "apsClient/pkg/safe" |
| | | "apsClient/service" |
| | | "apsClient/service/plc_address" |
| | | "errors" |
| | | "fmt" |
| | | "github.com/gin-gonic/gin" |
| | | "github.com/jinzhu/gorm" |
| | | "github.com/spf13/cast" |
| | | "sort" |
| | | "sync" |
| | | "time" |
| | | ) |
| | | |
| | |
| | | return |
| | | } |
| | | var resp response.TaskCountdown |
| | | workOrder, err := service.NewTaskService().GetComingTask() |
| | | workOrder, err := service.NewTaskService().GetNextTask() |
| | | if err == nil { |
| | | seconds := workOrder.StartTime - time.Now().Unix() |
| | | resp.CountDownHour = seconds / 3600 |
| | |
| | | // @Tags Task |
| | | // @Summary 获取任务 |
| | | // @Produce application/json |
| | | // @Success 200 {object} contextx.Response{data=response.TaskData} "成功" |
| | | // @Param object query request.TaskList true "查询参数" |
| | | // @Success 200 {object} contextx.Response{data=response.TaskResponse} "成功" |
| | | // @Router /v1/task/get [get] |
| | | func (slf *TaskApi) TaskGet(c *gin.Context) { |
| | | ctx, ok := contextx.NewContext(c, nil) |
| | | var params request.TaskList |
| | | ctx, ok := contextx.NewContext(c, ¶ms) |
| | | if !ok { |
| | | return |
| | | } |
| | | |
| | | taskData, code := service.NewTaskService().GetTask() |
| | | channelAmount, err := service.NewDevicePlcService().GetDeviceChannelAmount() |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, err.Error()) |
| | | return |
| | | } |
| | | taskCount := service.NewTaskService().NewTaskCount(conf.Conf.CurrentDeviceID) |
| | | params.Page = 1 |
| | | if params.PageSize <= 0 { |
| | | if params.TaskMode == constvar.TaskModeUnStarted { |
| | | params.PageSize = int(taskCount) |
| | | } else { |
| | | params.PageSize = channelAmount |
| | | } |
| | | } |
| | | |
| | | taskMode := constvar.TaskModeCurrent |
| | | if params.TaskMode == constvar.TaskModeUnStarted { |
| | | taskMode = params.TaskMode |
| | | } |
| | | |
| | | taskResponse, code := service.NewTaskService().GetTask(conf.Conf.CurrentDeviceID, params.Page, params.PageSize, taskMode, nil) //取进行中的或未开始的 |
| | | if code != ecode.OK { |
| | | ctx.Fail(code) |
| | | return |
| | | } |
| | | ctx.OkWithDetailed(taskData) |
| | | |
| | | if len(taskResponse.Tasks) < channelAmount && taskMode == constvar.TaskModeCurrent { |
| | | var existsChannel = make(map[int32]bool, channelAmount) |
| | | for _, task := range taskResponse.Tasks { |
| | | existsChannel[task.Channel] = true |
| | | } |
| | | for i := 0; i < channelAmount; i++ { |
| | | if existsChannel[int32(i)] { |
| | | continue |
| | | } |
| | | taskResponseTemp, code := service.NewTaskService().GetTask(conf.Conf.CurrentDeviceID, params.Page, 1, constvar.TaskModeLastFinished, []int32{int32(i)}) //取上一个完成的 |
| | | if code != ecode.OK { |
| | | ctx.Fail(code) |
| | | return |
| | | } |
| | | taskResponse.Tasks = append(taskResponse.Tasks, taskResponseTemp.Tasks...) |
| | | } |
| | | } |
| | | |
| | | sort.Slice(taskResponse.Tasks, func(i, j int) bool { |
| | | return taskResponse.Tasks[i].Channel < taskResponse.Tasks[i].Channel |
| | | }) |
| | | |
| | | nowTs := time.Now().Unix() |
| | | flagMap := make(map[int32]struct{}, 0) |
| | | for _, task := range taskResponse.Tasks { |
| | | if task.Procedure.Status != model.ProcedureStatusWaitProcess { |
| | | continue |
| | | } |
| | | if _, ok := flagMap[task.Channel]; !ok && !service.TaskFlagGet(conf.Conf.CurrentDeviceID, task.Channel) && task.Procedure.StartTime <= nowTs { |
| | | task.CanStarted = true |
| | | flagMap[task.Channel] = struct{}{} |
| | | } |
| | | } |
| | | |
| | | taskResponse.Prompt = conf.Conf.Prompt |
| | | taskResponse.ChannelAmount = channelAmount |
| | | taskResponse.TaskCount = taskCount |
| | | |
| | | ctx.OkWithDetailed(taskResponse) |
| | | } |
| | | |
| | | // TaskStart |
| | | // GetProcessParams |
| | | // @Tags Task |
| | | // @Summary 任务开始 |
| | | // @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) TaskStart(c *gin.Context) { |
| | | func (slf *TaskApi) GetProcessParams(c *gin.Context) { |
| | | ctx, ok := contextx.NewContext(c, nil) |
| | | if !ok { |
| | | return |
| | |
| | | ctx.Fail(ecode.ParamsErr) |
| | | return |
| | | } |
| | | id := convertx.Atoi(idx) |
| | | id := cast.ToUint(idx) |
| | | procedure, code := service.NewTaskService().GetProcedureById(id) |
| | | if code != ecode.OK { |
| | | ctx.Fail(code) |
| | | return |
| | | } |
| | | if procedure.Status != model.ProcedureStatusUnFinished { |
| | | ctx.FailWithMsg(ecode.ParamsErr, "该工序已结束") |
| | | return |
| | | } |
| | | |
| | | order, err := service.NewTaskService().GetOrderByWorkOrderId(procedure.WorkOrderID) |
| | | if err != nil { |
| | | ctx.Fail(ecode.UnknownErr) |
| | | ctx.Fail(ecode.DBErr) |
| | | return |
| | | } |
| | | //params := service.GetProcessModelParams{ |
| | | // WorkOrder: procedure.WorkOrderID, |
| | | // OrderId: procedure.OrderID, |
| | | // Product: order.ProductName, |
| | | // Procedure: procedure.ProceduresInfo.ProcedureName, |
| | | // Device: procedure.ProceduresInfo.DeviceName, |
| | | //} |
| | | //resp, err := service.ProcessModel{}.GetProcessModel(params) |
| | | //if err != nil { |
| | | // logx.Errorf("TaskStart GetProcessModel error: %v", err.Error()) |
| | | // ctx.FailWithMsg(ecode.UnknownErr, "未获取到工艺参数") |
| | | // 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("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 |
| | | var processModel *model.ProcessModel |
| | | if procedure.ProcessModelNumber != "" { |
| | | processModel, err = service.GetProcessModelByNumber(procedure.ProcessModelNumber) |
| | | } else { |
| | | processModel, err = service.NewTaskService().GetProcessParams(procedure, order) |
| | | } |
| | | |
| | | processParamsArr := make([]response.ProcessParams, 0, len(result.ParamsMap)) |
| | | for k, v := range result.ParamsMap { |
| | | if err != nil || processModel == nil || processModel.ParamsMap == nil { |
| | | device, err := service.GetCurrentDevice() |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.UnknownErr, err.Error()) |
| | | return |
| | | } |
| | | if device.NeedSetProcessParams { |
| | | ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!") |
| | | return |
| | | } else { |
| | | ctx.OkWithDetailed(response.ProcessParamsResponse{}) |
| | | return |
| | | } |
| | | } |
| | | |
| | | processParamsArr := make([]response.ProcessParams, 0, len(processModel.ParamsMap)) |
| | | for k, v := range processModel.ParamsMap { |
| | | processParamsArr = append(processParamsArr, response.ProcessParams{ |
| | | Key: k, |
| | | Value: v, |
| | | }) |
| | | } |
| | | data := response.ProcessParamsResponse{ |
| | | Number: result.Number, |
| | | |
| | | resp := response.ProcessParamsResponse{ |
| | | Number: processModel.Number, |
| | | Params: processParamsArr, |
| | | } |
| | | logx.Infof("TaskStart Notice GetProcessModel: %+v", result) |
| | | ctx.OkWithDetailed(data) |
| | | ctx.OkWithDetailed(resp) |
| | | } |
| | | |
| | | // TaskFinish |
| | |
| | | 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(id, model.ProcedureStatusFinished) |
| | | if err != nil { |
| | | logx.Errorf("UpdateProcedureStatus err: %v", err.Error()) |
| | | ctx.Fail(ecode.UnknownErr) |
| | | return |
| | | } |
| | | ctx.Ok() |
| | | } |
| | | |
| | | // SendProcessParams |
| | | // @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) SendProcessParams(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) |
| | | id := cast.ToUint(idx) |
| | | procedure, code := service.NewTaskService().GetProcedureById(id) |
| | | if code != ecode.OK { |
| | | ctx.Fail(code) |
| | | return |
| | | } |
| | | order, err := service.NewTaskService().GetOrderByWorkOrderId(procedure.WorkOrderID) |
| | | if procedure.Status == model.ProcedureStatusFinished { |
| | | ctx.Ok() |
| | | return |
| | | } |
| | | if procedure.Status != model.ProcedureStatusProcessing { |
| | | ctx.Fail(ecode.ParamsErr) |
| | | return |
| | | } |
| | | |
| | | err := model.WithTransaction(func(db *gorm.DB) error { |
| | | err := service.NewTaskService().UpdateProcedureStatusAndChannel(db, id, model.ProcedureStatusFinished, procedure.Channel, procedure.ProcessModelNumber) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | record := model.TaskStatusSync{ |
| | | WorkOrderId: procedure.WorkOrderID, |
| | | ProcedureID: procedure.ProcedureID, |
| | | DeviceId: procedure.DeviceID, |
| | | ProductProcedureID: procedure.ProductProcedureID, |
| | | IsProcessing: false, |
| | | IsFinish: true, |
| | | FinishedQuantity: procedure.FinishedQuantity, |
| | | } |
| | | return service.NewTaskService().SaveTaskStatusSync(db, &record) |
| | | }) |
| | | |
| | | if err != nil { |
| | | logx.Errorf("TaskFinish UpdateProcedureStatus err: %v", err.Error()) |
| | | ctx.Fail(ecode.UnknownErr) |
| | | return |
| | | } |
| | | |
| | | service.TaskFlagUnset(conf.Conf.CurrentDeviceID, procedure.Channel) |
| | | service.TaskEndTimeSet(conf.Conf.CurrentDeviceID, procedure.Channel, time.Now().Unix()) //设置工序运行结束时间 |
| | | ctx.Ok() |
| | | } |
| | | |
| | | var mutex sync.Mutex |
| | | |
| | | // 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) { |
| | | mutex.Lock() |
| | | defer mutex.Unlock() |
| | | var params request.SendProcessParams |
| | | ctx, ok := contextx.NewContext(c, ¶ms) |
| | | if !ok { |
| | | return |
| | | } |
| | | taskService := service.NewTaskService() |
| | | procedure, code := taskService.GetProcedureById(params.ProcedureId) |
| | | if code != ecode.OK { |
| | | ctx.Fail(code) |
| | | return |
| | | } |
| | | if procedure.DeviceID != conf.Conf.CurrentDeviceID { |
| | | ctx.FailWithMsg(ecode.ParamsErr, "该任务不属于当前设备") |
| | | return |
| | | } |
| | | order, err := taskService.GetOrderByWorkOrderId(procedure.WorkOrderID) |
| | | if err != nil { |
| | | ctx.Fail(ecode.UnknownErr) |
| | | 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, "未获取到工艺参数") |
| | | if procedure.Status == model.ProcedureStatusProcessing { |
| | | ctx.Ok() |
| | | return |
| | | } |
| | | |
| | | //fmt.Println("----------------开始下发工艺参数-----------------") |
| | | //for k, v := range resp.ParamsMap { |
| | | // fmt.Println(fmt.Sprintf("%v : %v", k, v)) |
| | | // time.Sleep(time.Millisecond * 300) |
| | | //} |
| | | //fmt.Println("----------------下发工艺参数完毕-----------------") |
| | | |
| | | //err = SendParams(resp.ParamsMap) |
| | | //if err != nil { |
| | | // logx.Errorf("SendProcessParams: %v", err.Error()) |
| | | // ctx.Fail(ecode.UnknownErr) |
| | | // return |
| | | //} |
| | | |
| | | safe.Go(func() { |
| | | err = SendParams2(result.ParamsMap, 0) |
| | | var processModelNumber string |
| | | plcConfig, code := service.NewDevicePlcService().GetDevicePlc() |
| | | if code == ecode.OK && plcConfig.ID != 0 && len(plcConfig.Details) > 0 { |
| | | plcConfig.MaxTryTimes = 2 |
| | | device, err := service.GetCurrentDevice() |
| | | if err != nil { |
| | | logx.Errorf("SendProcessParams: %v", err.Error()) |
| | | ctx.FailWithMsg(ecode.DBErr, err.Error()) |
| | | return |
| | | } |
| | | if device.NeedSetProcessParams { |
| | | processModel, err := taskService.GetProcessParams(procedure, order) |
| | | if err != nil || processModel == nil || processModel.ParamsMap == nil { |
| | | ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!") |
| | | return |
| | | } |
| | | err = SendParams(processModel.ParamsMap, plcConfig) |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置!") |
| | | return |
| | | } |
| | | processModelNumber = processModel.Number |
| | | } |
| | | |
| | | plcConfig.CurrentTryTimes = 0 |
| | | err = service.PlcWrite(plcConfig, constvar.PlcStartAddressTypeTotalNumber, procedure.Channel, order.Amount.IntPart()) |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置!") |
| | | return |
| | | } |
| | | } |
| | | |
| | | err = model.WithTransaction(func(db *gorm.DB) error { |
| | | err = taskService.UpdateProcedureStatusAndChannel(db, params.ProcedureId, model.ProcedureStatusProcessing, procedure.Channel, processModelNumber) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | err = taskService.UpdateOrderStatus(db, order.ID, model.OrderStatusProcessing) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | record := model.TaskStatusSync{ |
| | | WorkOrderId: procedure.WorkOrderID, |
| | | ProcedureID: procedure.ProcedureID, |
| | | DeviceId: procedure.DeviceID, |
| | | ProductProcedureID: procedure.ProductProcedureID, |
| | | IsProcessing: true, |
| | | IsFinish: false, |
| | | } |
| | | return service.NewTaskService().SaveTaskStatusSync(db, &record) |
| | | }) |
| | | if err != nil { |
| | | logx.Errorf("SendProcessParams update order and procedure status error:%v", err.Error()) |
| | | ctx.FailWithMsg(ecode.DBErr, "更改工单状态失败") |
| | | return |
| | | } |
| | | |
| | | service.TaskFlagSet(conf.Conf.CurrentDeviceID, procedure.Channel, int(procedure.ID)) |
| | | service.TaskStartTimeSet(conf.Conf.CurrentDeviceID, procedure.Channel, time.Now().Unix()) //设置工序运行开始时间 |
| | | service.TaskEndTimeSet(conf.Conf.CurrentDeviceID, procedure.Channel, 0) //设置工序运行结束时间 |
| | | ctx.Ok() |
| | | } |
| | | |
| | | func SendParams(paramsMap map[string]interface{}) error { |
| | | if len(paramsMap) == 0 { |
| | | return errors.New("empty params") |
| | | // UpdateProcessParams |
| | | // @Tags Task |
| | | // @Summary 更新工艺参数(进行中的任务) |
| | | // @Produce application/json |
| | | // @Param object body request.SendProcessParams true "查询参数" |
| | | // @Success 200 {object} contextx.Response{} "成功" |
| | | // @Router /v1/task/updateProcessParams [post] |
| | | func (slf *TaskApi) UpdateProcessParams(c *gin.Context) { |
| | | mutex.Lock() |
| | | defer mutex.Unlock() |
| | | var params request.SendProcessParams |
| | | ctx, ok := contextx.NewContext(c, ¶ms) |
| | | if !ok { |
| | | return |
| | | } |
| | | plcAddressMap := make(map[string]*int, len(conf.Conf.PLCAddresses)) |
| | | for _, item := range conf.Conf.PLCAddresses { |
| | | plcAddressMap[item.FieldName] = &item.Address |
| | | 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.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!") |
| | | return |
| | | } |
| | | |
| | | plcConfig, code := service.NewDevicePlcService().GetDevicePlc() |
| | | if code != ecode.OK { |
| | | return errors.New("请先配置PLC") |
| | | if code != ecode.OK || plcConfig.ID == 0 { |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, "请先配置PLC") |
| | | return |
| | | } |
| | | conn, err := plc.NewModbusConnection(fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)) |
| | | plcConfig.MaxTryTimes = 2 |
| | | err = SendParams(processModel.ParamsMap, plcConfig) |
| | | if err != nil { |
| | | return errors.New(fmt.Sprintf("连接plc失败: %v", err.Error())) |
| | | logx.Errorf("update process params err: %v", err.Error()) |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置!") |
| | | return |
| | | } |
| | | defer conn.Close() |
| | | _ = taskService.UpdateProcessModelNumber(nil, params.ProcedureId, processModel.Number) |
| | | ctx.Ok() |
| | | } |
| | | |
| | | logx.Info("----------------开始下发工艺参数-----------------") |
| | | 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 |
| | | processModelAddress, err := service.GetProcessModelAddress(conf.Conf.CurrentDeviceID) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | for k, v := range paramsMap { |
| | | if plcAddressMap[k] != nil { |
| | | result, err := plc.WriteHoldingRegister(conn, *plcAddressMap[k], v) |
| | | if err != nil { |
| | | logx.Errorf("WriteHoldingRegister err:%v, address: %v, key: %v value: %v", err.Error(), *plcAddressMap[k], k, v) |
| | | } else { |
| | | logx.Infof("WriteHoldingRegister ok: key: %v, value: %v, result: %v", k, v, result) |
| | | } |
| | | address, ok := processModelAddress[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 |
| | | } |
| | | |
| | | func SendParams2(paramsMap map[string]interface{}, tryTimes int) error { |
| | | if len(paramsMap) == 0 { |
| | | return errors.New("empty params") |
| | | // TaskListByChannel |
| | | // @Tags Task |
| | | // @Summary 获取任务列表2 |
| | | // @Produce application/json |
| | | // @Param object query request.TaskListByChannel true "查询参数" |
| | | // @Success 200 {object} contextx.Response{data=map[int32]response.TaskResponse} "成功" |
| | | // @Router /v1/task/list [get] |
| | | func (slf *TaskApi) TaskListByChannel(c *gin.Context) { |
| | | var params request.TaskListByChannel |
| | | ctx, ok := contextx.NewContext(c, ¶ms) |
| | | if !ok { |
| | | return |
| | | } |
| | | if tryTimes > 2 { |
| | | return errors.New("beyond max try time") |
| | | } |
| | | plcConfig, code := service.NewDevicePlcService().GetDevicePlc() |
| | | if code != ecode.OK { |
| | | return errors.New("请先配置PLC") |
| | | } |
| | | conn, err := plc.NewModbusConnection(fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)) |
| | | if err != nil { |
| | | return errors.New(fmt.Sprintf("连接plc失败: %v", err.Error())) |
| | | } |
| | | defer conn.Close() |
| | | |
| | | logx.Info("----------------开始下发工艺参数-----------------") |
| | | var missNumbers int |
| | | for k, v := range paramsMap { |
| | | if address, ok := plc_address.Get(k); ok { |
| | | result, err := plc.WriteHoldingRegister(conn, address, v) |
| | | if err != nil { |
| | | logx.Errorf("WriteHoldingRegister err:%v, address: %v, key: %v value: %v", err.Error(), address, k, v) |
| | | } else { |
| | | delete(paramsMap, k) |
| | | logx.Infof("WriteHoldingRegister ok: key: %v, value: %v, result: %v", k, v, result) |
| | | } |
| | | } else { |
| | | missNumbers++ |
| | | } |
| | | channelAmount, err := service.NewDevicePlcService().GetDeviceChannelAmount() |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.NeedConfirmedErr, err.Error()) |
| | | return |
| | | } |
| | | if missNumbers >= 1 { |
| | | 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*2) |
| | | params.DeviceID = conf.Conf.CurrentDeviceID |
| | | |
| | | dataMap := make(map[int32]*response.TaskResponse, channelAmount) |
| | | if params.Channel != nil { |
| | | taskResponse, err := getTaskResponseByChannel(params, *params.Channel) |
| | | if err != nil { |
| | | logx.Infof("SendParams2 err: %v", err.Error()) |
| | | return err |
| | | ctx.FailWithMsg(ecode.DBErr, err.Error()) |
| | | return |
| | | } |
| | | tryTimes++ |
| | | return SendParams2(paramsMap, tryTimes) |
| | | dataMap[*params.Channel] = taskResponse |
| | | ctx.OkWithDetailed(dataMap) |
| | | return |
| | | } |
| | | logx.Info("----------------下发工艺参数完毕-----------------") |
| | | return nil |
| | | |
| | | //不传channel取所有channel的 |
| | | var wg sync.WaitGroup |
| | | var mu sync.Mutex |
| | | for i := 0; i < channelAmount; i++ { |
| | | wg.Add(1) |
| | | go func(channel int32) { |
| | | defer wg.Done() |
| | | taskResponse, err := getTaskResponseByChannel(params, channel) |
| | | if err != nil { |
| | | ctx.FailWithMsg(ecode.DBErr, err.Error()) |
| | | return |
| | | } |
| | | mu.Lock() |
| | | defer mu.Unlock() |
| | | dataMap[channel] = taskResponse |
| | | }(int32(i)) |
| | | } |
| | | wg.Wait() |
| | | ctx.OkWithDetailed(dataMap) |
| | | } |
| | | |
| | | func getTaskResponseByChannel(params request.TaskListByChannel, channel int32) (taskResponse *response.TaskResponse, err error) { |
| | | taskResponse, err = service.NewTaskService().GetTask2(params.DeviceID, params.Offset, params.Limit, []int32{channel}, params.Type) //取进行中的或未开始的 |
| | | if err != nil { |
| | | return |
| | | } |
| | | |
| | | nowTs := time.Now().Unix() |
| | | flagMap := make(map[int32]struct{}, 0) |
| | | for _, task := range taskResponse.Tasks { |
| | | if _, ok := flagMap[task.Channel]; !ok && !service.TaskFlagGet(conf.Conf.CurrentDeviceID, task.Channel) && task.Procedure.StartTime <= nowTs { |
| | | task.CanStarted = true |
| | | flagMap[task.Channel] = struct{}{} |
| | | } |
| | | } |
| | | taskResponse.Prompt = conf.Conf.Prompt |
| | | return |
| | | } |