作者 yangfu

Merge branch 'dev' of http://gitlab.fjmaimaimai.com/allied-creation/allied-creat…

…ion-manufacture into dev

# Conflicts:
#	pkg/application/factory/repository.go
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CreateDeviceCollectionCommand struct {
// 数据采集ID
DeviceCollectionId int64 `cname:"数据采集ID" json:"deviceCollectionId,string" valid:"Required"`
// 车间名
WorkShopName string `cname:"车间名" json:"workShopName" valid:"Required"`
// 启动状态 1-启动 0-停止
StartupStatus int64 `cname:"启动状态 1-启动 0-停止" json:"startupStatus,string" valid:"Required"`
// 设备名
DeviceSn string `cname:"设备名" json:"deviceSn" valid:"Required"`
// 通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障
ComStatus int64 `cname:"通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障" json:"comStatus,string" valid:"Required"`
// 设备数据值
Values string `cname:"设备数据值" json:"values" valid:"Required"`
}
func (createDeviceCollectionCommand *CreateDeviceCollectionCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createDeviceCollectionCommand *CreateDeviceCollectionCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createDeviceCollectionCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createDeviceCollectionCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveDeviceCollectionCommand struct {
// 数据采集ID
DeviceCollectionId int64 `cname:"数据采集ID" json:"deviceCollectionId,string" valid:"Required"`
}
func (removeDeviceCollectionCommand *RemoveDeviceCollectionCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeDeviceCollectionCommand *RemoveDeviceCollectionCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeDeviceCollectionCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeDeviceCollectionCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateDeviceCollectionCommand struct {
// 数据采集ID
DeviceCollectionId int64 `cname:"数据采集ID" json:"deviceCollectionId,string" valid:"Required"`
// 车间名
WorkShopName string `cname:"车间名" json:"workShopName" valid:"Required"`
// 启动状态 1-启动 0-停止
StartupStatus int64 `cname:"启动状态 1-启动 0-停止" json:"startupStatus,string" valid:"Required"`
// 设备名
DeviceSn string `cname:"设备名" json:"deviceSn" valid:"Required"`
// 通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障
ComStatus int64 `cname:"通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障" json:"comStatus,string" valid:"Required"`
// 设备数据值
Values string `cname:"设备数据值" json:"values" valid:"Required"`
}
func (updateDeviceCollectionCommand *UpdateDeviceCollectionCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateDeviceCollectionCommand *UpdateDeviceCollectionCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateDeviceCollectionCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateDeviceCollectionCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetDeviceCollectionQuery struct {
// 数据采集ID
DeviceCollectionId int64 `cname:"数据采集ID" json:"deviceCollectionId,string" valid:"Required"`
}
func (getDeviceCollectionQuery *GetDeviceCollectionQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getDeviceCollectionQuery *GetDeviceCollectionQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getDeviceCollectionQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getDeviceCollectionQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListDeviceCollectionQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
// 查询限制
Limit int `cname:"查询限制" json:"limit" valid:"Required"`
}
func (listDeviceCollectionQuery *ListDeviceCollectionQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listDeviceCollectionQuery *ListDeviceCollectionQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listDeviceCollectionQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listDeviceCollectionQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/deviceCollection/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/deviceCollection/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type DeviceCollectionService struct {
}
// 创建
func (deviceCollectionService *DeviceCollectionService) CreateDeviceCollection(createDeviceCollectionCommand *command.CreateDeviceCollectionCommand) (interface{}, error) {
if err := createDeviceCollectionCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newDeviceCollection := &domain.DeviceCollection{
DeviceCollectionId: createDeviceCollectionCommand.DeviceCollectionId,
WorkShopName: createDeviceCollectionCommand.WorkShopName,
StartupStatus: createDeviceCollectionCommand.StartupStatus,
DeviceSn: createDeviceCollectionCommand.DeviceSn,
ComStatus: createDeviceCollectionCommand.ComStatus,
Values: createDeviceCollectionCommand.Values,
}
var deviceCollectionRepository domain.DeviceCollectionRepository
if value, err := factory.CreateDeviceCollectionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
deviceCollectionRepository = value
}
if deviceCollection, err := deviceCollectionRepository.Save(newDeviceCollection); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return deviceCollection, nil
}
}
// 返回
func (deviceCollectionService *DeviceCollectionService) GetDeviceCollection(getDeviceCollectionQuery *query.GetDeviceCollectionQuery) (interface{}, error) {
if err := getDeviceCollectionQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var deviceCollectionRepository domain.DeviceCollectionRepository
if value, err := factory.CreateDeviceCollectionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
deviceCollectionRepository = value
}
deviceCollection, err := deviceCollectionRepository.FindOne(map[string]interface{}{"deviceCollectionId": getDeviceCollectionQuery.DeviceCollectionId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if deviceCollection == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getDeviceCollectionQuery.DeviceCollectionId)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return deviceCollection, nil
}
}
// 返回列表
func (deviceCollectionService *DeviceCollectionService) ListDeviceCollection(listDeviceCollectionQuery *query.ListDeviceCollectionQuery) (interface{}, error) {
if err := listDeviceCollectionQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var deviceCollectionRepository domain.DeviceCollectionRepository
if value, err := factory.CreateDeviceCollectionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
deviceCollectionRepository = value
}
if count, deviceCollections, err := deviceCollectionRepository.Find(tool_funs.SimpleStructToMap(listDeviceCollectionQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"deviceCollections": deviceCollections,
}, nil
}
}
// 移除
func (deviceCollectionService *DeviceCollectionService) RemoveDeviceCollection(removeDeviceCollectionCommand *command.RemoveDeviceCollectionCommand) (interface{}, error) {
if err := removeDeviceCollectionCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var deviceCollectionRepository domain.DeviceCollectionRepository
if value, err := factory.CreateDeviceCollectionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
deviceCollectionRepository = value
}
deviceCollection, err := deviceCollectionRepository.FindOne(map[string]interface{}{"deviceCollectionId": removeDeviceCollectionCommand.DeviceCollectionId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if deviceCollection == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeDeviceCollectionCommand.DeviceCollectionId)))
}
if deviceCollection, err := deviceCollectionRepository.Remove(deviceCollection); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return deviceCollection, nil
}
}
// 更新
func (deviceCollectionService *DeviceCollectionService) UpdateDeviceCollection(updateDeviceCollectionCommand *command.UpdateDeviceCollectionCommand) (interface{}, error) {
if err := updateDeviceCollectionCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var deviceCollectionRepository domain.DeviceCollectionRepository
if value, err := factory.CreateDeviceCollectionRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
deviceCollectionRepository = value
}
deviceCollection, err := deviceCollectionRepository.FindOne(map[string]interface{}{"deviceCollectionId": updateDeviceCollectionCommand.DeviceCollectionId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if deviceCollection == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateDeviceCollectionCommand.DeviceCollectionId)))
}
if err := deviceCollection.Update(tool_funs.SimpleStructToMap(updateDeviceCollectionCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if deviceCollection, err := deviceCollectionRepository.Save(deviceCollection); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return deviceCollection, nil
}
}
func NewDeviceCollectionService(options map[string]interface{}) *DeviceCollectionService {
newDeviceCollectionService := &DeviceCollectionService{}
return newDeviceCollectionService
}
... ...
... ... @@ -118,6 +118,14 @@ func CreateProductPlanDispatchRecordRepository(options map[string]interface{}) (
return repository.NewProductPlanDispatchRecordRepository(transactionContext)
}
func CreateDeviceCollectionRepository(options map[string]interface{}) (domain.DeviceCollectionRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewDeviceCollectionRepository(transactionContext)
}
func CreateDeviceRunningRecordRepository(options map[string]interface{}) (domain.DeviceRunningRecordRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
... ...
package domain
import "time"
// 设备采集数据
type DeviceCollection struct {
// 数据采集ID
DeviceCollectionId int64 `json:"deviceCollectionId,string"`
// 车间名
WorkShopName string `json:"workShopName"`
// 采集时间
CollectionTime time.Time `json:"collectionTime"`
// 设备名
DeviceSn string `json:"deviceSn"`
// 设备类型
DeviceType string `json:"deviceType"`
// 启动状态 1-启动 0-停止
StartupStatus int64 `json:"startupStatus"`
// 通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障
ComStatus int64 `json:"comStatus"`
// 设备数据值
Values interface{} `json:"values"`
}
var (
// 包馅机
DeviceTypeBaoXianJi = "BXJ"
// 打浆机
DeviceTypeDaJiangJi = "DJJ"
// 面包屑机
DeviceTypeMianBaoXieJi = "MBXJ"
// 油炸机
DeviceTypeYouZhaJi = "YZJ"
// 串串机
DeviceTypeChuanChuanJi = "CCJ"
// 速冻线
DeviceTypeSuDongXian = "SDX"
// 封口机
DeviceTypeFengKouJi = "FKJ"
// 封箱机
DeviceTypeFengXiangJi = "FXJ"
)
type DeviceCollectionRepository interface {
Save(deviceCollection *DeviceCollection) (*DeviceCollection, error)
Remove(deviceCollection *DeviceCollection) (*DeviceCollection, error)
FindOne(queryOptions map[string]interface{}) (*DeviceCollection, error)
Find(queryOptions map[string]interface{}) (int64, []*DeviceCollection, error)
}
func (deviceCollection *DeviceCollection) Identify() interface{} {
if deviceCollection.DeviceCollectionId == 0 {
return nil
}
return deviceCollection.DeviceCollectionId
}
func (deviceCollection *DeviceCollection) Update(data map[string]interface{}) error {
if workShopName, ok := data["workShopName"]; ok {
deviceCollection.WorkShopName = workShopName.(string)
}
if deviceSn, ok := data["deviceSn"]; ok {
deviceCollection.DeviceSn = deviceSn.(string)
}
if deviceType, ok := data["deviceType"]; ok {
deviceCollection.DeviceSn = deviceType.(string)
}
if startupStatus, ok := data["startupStatus"]; ok {
deviceCollection.StartupStatus = startupStatus.(int64)
}
if comStatus, ok := data["comStatus"]; ok {
deviceCollection.ComStatus = comStatus.(int64)
}
if values, ok := data["values"]; ok {
deviceCollection.Values = values
}
return nil
}
... ...
package domain
// 包馅机
type DeviceBaoXianJi struct {
InterSpeed int64 `json:"InterSpeed"` // 内包材速度:内包材运行速率
ExterSpeed int64 `json:"ExterSpeed"` // 外包材速度:内包材运行速率
KnifeSpeed int64 `json:"KnifeSpeed"` // 切刀速度:切刀运行速率
TransSpeed int64 `json:"TransSpeed"` // 输送速度:输送带运行速率
Count int64 `json:"Count"` // 生产计数:生产统计数量
}
// 油炸机
type DeviceYouZhaJi struct {
FrontTemp float64 `json:"FontTemp"` // 炸机前段温度:炸机前段当前温度
BackTemp float64 `json:"BackTemp"` // 炸机后段温度:炸机后段当前温度
TankTemp float64 `json:"TankTemp"` // 储油罐温度 :储油罐当前温度
TubeTemp float64 `json:"TubeTemp"` // 管路温度:管路当前温度
}
// 串串机
type DeviceChuanChuanJi struct {
Count int64 `json:"Count"` // 生产计数:生产统计数量
Year string `json:"Year"` // 年
Month string `json:"Month"` // 月
Day string `json:"Day"` // 日
ProductType string `json:"ProductType"` // 产品类型:当前产品种类
}
// 速冻线
type DeviceSuDongXian struct {
CurrTemp float64 `json:"CurrTemp"` // 当前温度:当前温度
}
// 封口机
type DeviceFengKouJi struct {
Count int64 `json:"Count"` // 生产计数:生产统计数量
Year string `json:"Year"` // 年
Month string `json:"Month"` // 月
Day string `json:"Day"` // 日
ProductType string `json:"ProductType"` // 产品类型:当前产品种类
}
// 封箱机
type DeviceFengXiangJi struct {
Count int64 `json:"Count"` // 生产计数:生产统计数量
Year string `json:"Year"` // 年
Month string `json:"Month"` // 月
Day string `json:"Day"` // 日
ProductType string `json:"ProductType"` // 产品类型:当前产品种类
}
... ...
package domain
import "time"
type DeviceWorkShop struct {
WorkShop string `json:"WorkShop"` // 车间名
DeviceSn string `json:"DeviceSn"` // 设备名称
CurrTime time.Time `json:"CurrTime"` // 当前时间
StartupState int64 `json:"StartupState"` // 启动状态:1:启动,0:停止
ComStatus int64 `json:"ComStatus"` // 通讯状态:1:通讯正常,0:设备未上电或与采集端通讯故障
InterSpeed int64 `json:"InterSpeed"` // 内包材速度:内包材运行速率
ExterSpeed int64 `json:"ExterSpeed"` // 外包材速度:内包材运行速率
KnifeSpeed int64 `json:"KnifeSpeed"` // 切刀速度:切刀运行速率
TransSpeed int64 `json:"TransSpeed"` // 输送速度:输送带运行速率
FrontTemp float64 `json:"FontTemp"` // 炸机前段温度:炸机前段当前温度
BackTemp float64 `json:"BackTemp"` // 炸机后段温度:炸机后段当前温度
TankTemp float64 `json:"TankTemp"` // 储油罐温度 :储油罐当前温度
TubeTemp float64 `json:"TubeTemp"` // 管路温度:管路当前温度
Temp1 float64 `json:"Temp1"` // 温度1:温度1当前温度
Temp2 float64 `json:"Temp2"` // 温度2:温度2当前温度
Temp3 float64 `json:"Temp3"` // 温度3:温度3当前温度
Year string `json:"Year"` // 年
Month string `json:"Month"` // 月
Day string `json:"Day"` // 日
ProductType string `json:"ProductType"` // 产品类型:当前产品种类
CurrTemp float64 `json:"CurrTemp"` // 当前温度:当前温度
}
package models
import "time"
type DeviceCollection struct {
tableName string `comment:"设备采集数据" pg:"manufacture.device_collections,alias:device_collection"`
// 数据采集ID
DeviceCollectionId int64 `comment:"数据采集ID" pg:"pk:device_collection_id"`
// 车间名
WorkShopName string `comment:"车间名"`
// 设备名
DeviceSn string `comment:"设备名"`
// 设备类型
DeviceType string `comment:"设备类型"`
// 启动状态 1-启动 0-停止
StartupStatus int64 `comment:"启动状态 1-启动 0-停止" pg:",use_zero"`
// 通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障
ComStatus int64 `comment:"通讯状态 1-通讯正常 0-设备未上电或与采集端通讯故障" pg:",use_zero"`
// 设备数据值
Values interface{} `comment:"设备数据值"`
// 创建时间
CreatedAt time.Time `comment:"创建时间" pg:",default:now()"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间" pg:",default:now()"`
// 删除时间
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
func TransformToDeviceCollectionDomainModelFromPgModels(deviceCollectionModel *models.DeviceCollection) (*domain.DeviceCollection, error) {
return &domain.DeviceCollection{
DeviceCollectionId: deviceCollectionModel.DeviceCollectionId,
WorkShopName: deviceCollectionModel.WorkShopName,
DeviceSn: deviceCollectionModel.DeviceSn,
StartupStatus: deviceCollectionModel.StartupStatus,
ComStatus: deviceCollectionModel.ComStatus,
Values: deviceCollectionModel.Values,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)
type DeviceCollectionRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *DeviceCollectionRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *DeviceCollectionRepository) Save(deviceCollection *domain.DeviceCollection) (*domain.DeviceCollection, error) {
sqlBuildFields := []string{
"device_collection_id",
"work_shop_name",
"device_sn",
"startup_status",
"com_status",
"values",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "deviceCollection_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if deviceCollection.Identify() == nil {
deviceCollectionId, err := repository.nextIdentify()
if err != nil {
return deviceCollection, err
} else {
deviceCollection.DeviceCollectionId = deviceCollectionId
}
if _, err := tx.QueryOne(
pg.Scan(
&deviceCollection.DeviceCollectionId,
&deviceCollection.WorkShopName,
&deviceCollection.DeviceSn,
&deviceCollection.StartupStatus,
&deviceCollection.ComStatus,
&deviceCollection.Values,
),
fmt.Sprintf("INSERT INTO device_collections (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
deviceCollection.DeviceCollectionId,
deviceCollection.WorkShopName,
deviceCollection.DeviceSn,
deviceCollection.StartupStatus,
deviceCollection.ComStatus,
deviceCollection.Values,
); err != nil {
return deviceCollection, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&deviceCollection.DeviceCollectionId,
&deviceCollection.WorkShopName,
&deviceCollection.DeviceSn,
&deviceCollection.StartupStatus,
&deviceCollection.ComStatus,
&deviceCollection.Values,
),
fmt.Sprintf("UPDATE device_collections SET %s WHERE device_collection_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
deviceCollection.DeviceCollectionId,
deviceCollection.WorkShopName,
deviceCollection.DeviceSn,
deviceCollection.StartupStatus,
deviceCollection.ComStatus,
deviceCollection.Values,
deviceCollection.Identify(),
); err != nil {
return deviceCollection, err
}
}
return deviceCollection, nil
}
func (repository *DeviceCollectionRepository) Remove(deviceCollection *domain.DeviceCollection) (*domain.DeviceCollection, error) {
tx := repository.transactionContext.PgTx
deviceCollectionModel := new(models.DeviceCollection)
deviceCollectionModel.DeviceCollectionId = deviceCollection.Identify().(int64)
if _, err := tx.Model(deviceCollectionModel).WherePK().Delete(); err != nil {
return deviceCollection, err
}
return deviceCollection, nil
}
func (repository *DeviceCollectionRepository) FindOne(queryOptions map[string]interface{}) (*domain.DeviceCollection, error) {
tx := repository.transactionContext.PgTx
deviceCollectionModel := new(models.DeviceCollection)
query := sqlbuilder.BuildQuery(tx.Model(deviceCollectionModel), queryOptions)
query.SetWhereByQueryOption("device_collection.device_collection_id = ?", "deviceCollectionId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if deviceCollectionModel.DeviceCollectionId == 0 {
return nil, nil
} else {
return transform.TransformToDeviceCollectionDomainModelFromPgModels(deviceCollectionModel)
}
}
func (repository *DeviceCollectionRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.DeviceCollection, error) {
tx := repository.transactionContext.PgTx
var deviceCollectionModels []*models.DeviceCollection
deviceCollections := make([]*domain.DeviceCollection, 0)
query := sqlbuilder.BuildQuery(tx.Model(&deviceCollectionModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("device_collection_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, deviceCollections, err
} else {
for _, deviceCollectionModel := range deviceCollectionModels {
if deviceCollection, err := transform.TransformToDeviceCollectionDomainModelFromPgModels(deviceCollectionModel); err != nil {
return 0, deviceCollections, err
} else {
deviceCollections = append(deviceCollections, deviceCollection)
}
}
return int64(count), deviceCollections, nil
}
}
func NewDeviceCollectionRepository(transactionContext *pgTransaction.TransactionContext) (*DeviceCollectionRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &DeviceCollectionRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -352,3 +352,30 @@ func LoadQueryObject(queryOption map[string]interface{}, obj interface{}) error
}
return err
}
// 字符串截取
func SubStr(str string, start, length int) string {
rs := []rune(str)
rl := len(rs)
end := 0
if start < 0 {
start = rl - 1 + start
}
end = start + length
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
if start > rl {
start = rl
}
if end < 0 {
end = 0
}
if end > rl {
end = rl
}
return string(rs[start:end])
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/deviceCollection/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/deviceCollection/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/deviceCollection/service"
)
type DeviceCollectionController struct {
beego.BaseController
}
func (controller *DeviceCollectionController) CreateDeviceCollection() {
deviceCollectionService := service.NewDeviceCollectionService(nil)
createDeviceCollectionCommand := &command.CreateDeviceCollectionCommand{}
controller.Unmarshal(createDeviceCollectionCommand)
data, err := deviceCollectionService.CreateDeviceCollection(createDeviceCollectionCommand)
controller.Response(data, err)
}
func (controller *DeviceCollectionController) UpdateDeviceCollection() {
deviceCollectionService := service.NewDeviceCollectionService(nil)
updateDeviceCollectionCommand := &command.UpdateDeviceCollectionCommand{}
controller.Unmarshal(updateDeviceCollectionCommand)
//Id, _ := controller.GetString(":Id")
//updateDeviceCollectionCommand.Id = Id
data, err := deviceCollectionService.UpdateDeviceCollection(updateDeviceCollectionCommand)
controller.Response(data, err)
}
func (controller *DeviceCollectionController) GetDeviceCollection() {
deviceCollectionService := service.NewDeviceCollectionService(nil)
getDeviceCollectionQuery := &query.GetDeviceCollectionQuery{}
//Id, _ := controller.GetString(":Id")
//getDeviceCollectionQuery.Id = Id
data, err := deviceCollectionService.GetDeviceCollection(getDeviceCollectionQuery)
controller.Response(data, err)
}
func (controller *DeviceCollectionController) RemoveDeviceCollection() {
deviceCollectionService := service.NewDeviceCollectionService(nil)
removeDeviceCollectionCommand := &command.RemoveDeviceCollectionCommand{}
controller.Unmarshal(removeDeviceCollectionCommand)
//Id, _ := controller.GetString(":Id")
//removeDeviceCollectionCommand.Id = Id
data, err := deviceCollectionService.RemoveDeviceCollection(removeDeviceCollectionCommand)
controller.Response(data, err)
}
func (controller *DeviceCollectionController) ListDeviceCollection() {
deviceCollectionService := service.NewDeviceCollectionService(nil)
listDeviceCollectionQuery := &query.ListDeviceCollectionQuery{}
offset, _ := controller.GetInt("offset")
listDeviceCollectionQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listDeviceCollectionQuery.Limit = limit
data, err := deviceCollectionService.ListDeviceCollection(listDeviceCollectionQuery)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/controllers"
)
func init() {
web.Router("/device-collections/", &controllers.DeviceCollectionController{}, "Post:CreateDeviceCollection")
web.Router("/device-collections/:Id", &controllers.DeviceCollectionController{}, "Put:UpdateDeviceCollection")
web.Router("/device-collections/:Id", &controllers.DeviceCollectionController{}, "Get:GetDeviceCollection")
web.Router("/device-collections/:Id", &controllers.DeviceCollectionController{}, "Delete:RemoveDeviceCollection")
web.Router("/device-collections/", &controllers.DeviceCollectionController{}, "Get:ListDeviceCollection")
}
... ...
... ... @@ -3,10 +3,12 @@ package mqtt
import (
"encoding/json"
pahomqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/tidwall/gjson"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/mqtt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
... ... @@ -24,35 +26,96 @@ func Start() {
if key == "WorkShop" {
continue
}
deviceWorkShop := &domain.DeviceWorkShop{}
mBytes, err := json.Marshal(item)
if err != nil {
continue
}
err = json.Unmarshal(mBytes, deviceWorkShop)
if err != nil {
continue
}
// 获取当前时间
deviceWorkShop.CurrTime = time.Now()
// 车间名称
deviceWorkShop.WorkShop = workShop.(string)
// 设备名称
deviceWorkShop.DeviceSn = key
workShopBytes, err := json.Marshal(deviceWorkShop)
if err != nil {
continue
deviceCollection := &domain.DeviceCollection{
WorkShopName: workShop.(string),
DeviceSn: key,
CollectionTime: time.Now(),
StartupStatus: gjson.Get(string(message.Payload()), key+".StartupState").Int(),
ComStatus: gjson.Get(string(message.Payload()), key+".ComStatus").Int(),
}
err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err()
if err != nil {
log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
if utils.SubStr(key, 0, 4) == domain.DeviceTypeMianBaoXieJi {
deviceCollection.DeviceType = domain.DeviceTypeMianBaoXieJi
} else {
deviceType := utils.SubStr(key, 0, 3)
deviceCollection.DeviceType = deviceType
switch deviceType {
//包馅机
case domain.DeviceTypeBaoXianJi:
deviceBaoXianJi := &domain.DeviceBaoXianJi{}
err = json.Unmarshal(mBytes, deviceBaoXianJi)
if err != nil {
continue
}
deviceCollection.Values = deviceBaoXianJi
break
//油炸机
case domain.DeviceTypeYouZhaJi:
deviceYouZhaJi := &domain.DeviceYouZhaJi{}
err = json.Unmarshal(mBytes, deviceYouZhaJi)
if err != nil {
continue
}
deviceCollection.Values = deviceYouZhaJi
break
//串串机
case domain.DeviceTypeChuanChuanJi:
deviceChuanChuanJi := &domain.DeviceChuanChuanJi{}
err = json.Unmarshal(mBytes, deviceChuanChuanJi)
if err != nil {
continue
}
deviceCollection.Values = deviceChuanChuanJi
break
//速冻线
case domain.DeviceTypeSuDongXian:
deviceSuDongXian := &domain.DeviceSuDongXian{}
err = json.Unmarshal(mBytes, deviceSuDongXian)
if err != nil {
continue
}
deviceCollection.Values = deviceSuDongXian
break
//封口机
case domain.DeviceTypeFengKouJi:
deviceFengKouJi := &domain.DeviceFengKouJi{}
err = json.Unmarshal(mBytes, deviceFengKouJi)
if err != nil {
continue
}
deviceCollection.Values = deviceFengKouJi
break
//封箱机
case domain.DeviceTypeFengXiangJi:
deviceFengXiangJi := &domain.DeviceFengXiangJi{}
err = json.Unmarshal(mBytes, deviceFengXiangJi)
if err != nil {
continue
}
deviceCollection.Values = deviceFengXiangJi
break
//打浆机
case domain.DeviceTypeDaJiangJi:
default:
}
workShopBytes, err := json.Marshal(deviceCollection)
if err != nil {
continue
}
err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err()
if err != nil {
log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
}
}
}
log.Logger.Info("MQTT", map[string]interface{}{
"Topic": message.Topic(),
"MessageId": message.MessageID(),
"Message": payload,
})
}
log.Logger.Info("MQTT", map[string]interface{}{
"Topic": message.Topic(),
"MessageId": message.MessageID(),
"Message": payload,
})
})
}
... ...
package device_collection
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("创建", func() {
Describe("提交数据创建", func() {
Context("提交正确的新设备采集数据数据", func() {
It("返回设备采集数据数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"deviceCollectionId": "int64",
"workShopName": "string",
"startupStatus": "int64",
"deviceSn": "string",
"comStatus": "int64",
"values": "string",
}
httpExpect.POST("/device-collections/").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("deviceCollectionId").ValueNotEqual("deviceCollectionId", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM device_collections WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package device_collection
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego"
)
func TestDeviceCollection(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port DeviceCollection Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package device_collection
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回", func() {
var deviceCollectionId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&deviceCollectionId),
"INSERT INTO device_collections (device_collection_id, work_shop_name, device_sn, startup_status, com_status, values) VALUES (?, ?, ?, ?, ?, ?) RETURNING device_collection_id",
"testDeviceCollectionId", "testWorkShopName", "testDeviceSn", "testStartupStatus", "testComStatus", "testValues")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据deviceCollectionId参数返回设备采集数据", func() {
Context("传入有效的deviceCollectionId", func() {
It("返回设备采集数据数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/device-collections/{Id}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM device_collections WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package device_collection
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回列表", func() {
var deviceCollectionId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&deviceCollectionId),
"INSERT INTO device_collections (device_collection_id, work_shop_name, device_sn, startup_status, com_status, values) VALUES (?, ?, ?, ?, ?, ?) RETURNING device_collection_id",
"testDeviceCollectionId", "testWorkShopName", "testDeviceSn", "testStartupStatus", "testComStatus", "testValues")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数返回设备采集数据列表", func() {
Context("传入有效的参数", func() {
It("返回设备采集数据数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/device-collections/").
WithQuery("offset", "int").
WithQuery("limit", "int").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("count").ValueEqual("count", 1).
ContainsKey("deviceCollections").Value("deviceCollections").Array()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM device_collections WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package device_collection
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("移除", func() {
var deviceCollectionId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&deviceCollectionId),
"INSERT INTO device_collections (device_collection_id, work_shop_name, device_sn, startup_status, com_status, values) VALUES (?, ?, ?, ?, ?, ?) RETURNING device_collection_id",
"testDeviceCollectionId", "testWorkShopName", "testDeviceSn", "testStartupStatus", "testComStatus", "testValues")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数移除", func() {
Context("传入有效的deviceCollectionId", func() {
It("返回被移除设备采集数据的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/device-collections/{Id}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM device_collections WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package device_collection
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("更新", func() {
var deviceCollectionId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&deviceCollectionId),
"INSERT INTO device_collections (device_collection_id, work_shop_name, device_sn, startup_status, com_status, values) VALUES (?, ?, ?, ?, ?, ?) RETURNING device_collection_id",
"testDeviceCollectionId", "testWorkShopName", "testDeviceSn", "testStartupStatus", "testComStatus", "testValues")
Expect(err).NotTo(HaveOccurred())
})
Describe("提交数据更新", func() {
Context("提交正确的设备采集数据数据", func() {
It("返回更新后的设备采集数据数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"deviceCollectionId": "int64",
"workShopName": "string",
"startupStatus": "int64",
"deviceSn": "string",
"comStatus": "int64",
"values": "string",
}
httpExpect.PUT("/device-collections/{Id}").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("deviceCollectionId").ValueEqual("deviceCollectionId", deviceCollectionId)
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM device_collections WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...