error 更换

main
Rice 4 weeks ago
parent 59fc5b1156
commit af700018a8

@ -1,8 +1,8 @@
package internal package internal
import ( import (
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/towgo/towgo/errors/terror"
"regexp" "regexp"
"strings" "strings"
"time" "time"
@ -28,14 +28,14 @@ var durationMap = map[string]int64{
// parseSize 将带单位的大小字符串(如"100kb"、"2MB")转换为字节数 // parseSize 将带单位的大小字符串(如"100kb"、"2MB")转换为字节数
func parseSize(sizeStr string) (int64, error) { func parseSize(sizeStr string) (int64, error) {
if sizeStr == "" { if sizeStr == "" {
return 0, terror.New("空的大小配置") return 0, gerror.New("空的大小配置")
} }
// 正则匹配:提取数字和单位(支持整数/小数,如"1.5mb" // 正则匹配:提取数字和单位(支持整数/小数,如"1.5mb"
re := regexp.MustCompile(`^(\d+(\.\d+)?)([a-zA-Zb]+)$`) re := regexp.MustCompile(`^(\d+(\.\d+)?)([a-zA-Zb]+)$`)
matches := re.FindStringSubmatch(strings.TrimSpace(sizeStr)) matches := re.FindStringSubmatch(strings.TrimSpace(sizeStr))
if len(matches) != 4 { if len(matches) != 4 {
return 0, terror.New("无效的大小格式示例100kb、2mb、1g") return 0, gerror.New("无效的大小格式示例100kb、2mb、1g")
} }
// 提取数值和单位 // 提取数值和单位
@ -48,7 +48,7 @@ func parseSize(sizeStr string) (int64, error) {
// 查找单位对应的字节数 // 查找单位对应的字节数
unitBytes, ok := unitMap[unit] unitBytes, ok := unitMap[unit]
if !ok { if !ok {
return 0, terror.Newf("不支持的单位:{%+v}支持b、kb、mb、gb、tb", unit) return 0, gerror.Newf("不支持的单位:{%+v}支持b、kb、mb、gb、tb", unit)
} }
// 计算总字节数(数值 * 单位字节数) // 计算总字节数(数值 * 单位字节数)
@ -64,14 +64,14 @@ func parseDuration(intervalStr string) (time.Duration, error) {
re := regexp.MustCompile(`^(\d+)([smhd])$`) // 匹配数字+单位s/m/h/d re := regexp.MustCompile(`^(\d+)([smhd])$`) // 匹配数字+单位s/m/h/d
matches := re.FindStringSubmatch(strings.TrimSpace(intervalStr)) matches := re.FindStringSubmatch(strings.TrimSpace(intervalStr))
if len(matches) != 3 { if len(matches) != 3 {
return 0, terror.New("无效的时间格式示例30s、5m、1h") return 0, gerror.New("无效的时间格式示例30s、5m、1h")
} }
num := gconv.Int(matches[1]) num := gconv.Int(matches[1])
unit := matches[2] unit := matches[2]
sec, ok := durationMap[unit] sec, ok := durationMap[unit]
if !ok { if !ok {
return 0, terror.New("不支持的单位仅支持s/m/h/d") return 0, gerror.New("不支持的单位仅支持s/m/h/d")
} }
return time.Duration(num) * time.Duration(sec) * time.Second, nil return time.Duration(num) * time.Duration(sec) * time.Second, nil

@ -1,9 +1,9 @@
package initialize package initialize
import ( import (
"github.com/gogf/gf/v2/errors/gerror"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"github.com/towgo/towgo/errors/tcode" "github.com/towgo/towgo/errors/tcode"
"github.com/towgo/towgo/errors/terror"
"sync" "sync"
g "tgk-touch/internal/global" g "tgk-touch/internal/global"
m9zTtyApi "tgk-touch/internal/module/m9zTtyApi" m9zTtyApi "tgk-touch/internal/module/m9zTtyApi"
@ -25,7 +25,7 @@ func AddTaskByFunc(cronName string, taskName string, spec string, task func()) {
cronTaskName := cronName + "-" + taskName cronTaskName := cronName + "-" + taskName
_, ok := cronTaskNameMap[cronTaskName] _, ok := cronTaskNameMap[cronTaskName]
if ok { if ok {
panic(terror.New("定时任务名称重复 " + cronTaskName)) panic(gerror.New("定时任务名称重复 " + cronTaskName))
} }
var option []cron.Option var option []cron.Option
option = append(option, cron.WithSeconds(), cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger))) option = append(option, cron.WithSeconds(), cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger)))
@ -33,7 +33,7 @@ func AddTaskByFunc(cronName string, taskName string, spec string, task func()) {
defer func() { defer func() {
if exception := recover(); exception != nil { if exception := recover(); exception != nil {
if errv, ok := exception.(error); ok { if errv, ok := exception.(error); ok {
g.GVA_LOG.Sugar().Errorf("corn recovered panic err task [%s] sepc [%s] err:%+v \n", taskName, spec, terror.NewCodef(tcode.CodeInternalPanic, "%+v", errv)) g.GVA_LOG.Sugar().Errorf("corn recovered panic err task [%s] sepc [%s] err:%+v \n", taskName, spec, gerror.NewCodef(tcode.CodeInternalPanic, "%+v", errv))
} }
} }
}() }()

@ -1,7 +1,7 @@
package ADL200 package ADL200
import ( import (
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"tgk-touch/internal/global" "tgk-touch/internal/global"
"tgk-touch/internal/module/maincontrollerClient" "tgk-touch/internal/module/maincontrollerClient"
) )
@ -16,7 +16,7 @@ func pushCmd(commUid string, cmd []byte, detail string) ([]byte, error) {
return return
}) })
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "DeviceCallByDeviceID err ") return nil, gerror.Wrapf(err, "DeviceCallByDeviceID err ")
} }
return result, nil return result, nil
} }
@ -27,12 +27,12 @@ func readCmd(commUid string, address byte, startAddr, quantity uint16, detail st
g.Log().Debugf("ADL200 Modbus 下发 读取命令 = % X", cmd) g.Log().Debugf("ADL200 Modbus 下发 读取命令 = % X", cmd)
result, err := pushCmd(commUid, cmd, detail) result, err := pushCmd(commUid, cmd, detail)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "下发[% X]", cmd) return nil, gerror.Wrapf(err, "下发[% X]", cmd)
} }
g.Log().Debugf("ADL200 Modbus 响应 读取命令 = % X", result) g.Log().Debugf("ADL200 Modbus 响应 读取命令 = % X", result)
r, err := ReadHoldingRegisterParse(result, address, quantity) r, err := ReadHoldingRegisterParse(result, address, quantity)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "下发[% X],响应[% X]", cmd, result) return nil, gerror.Wrapf(err, "下发[% X],响应[% X]", cmd, result)
} }
return r, nil return r, nil
} }

@ -1,7 +1,7 @@
package ADL400 package ADL400
import ( import (
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"tgk-touch/internal/global" "tgk-touch/internal/global"
"tgk-touch/internal/module/maincontrollerClient" "tgk-touch/internal/module/maincontrollerClient"
) )
@ -16,7 +16,7 @@ func pushCmd(commUid string, cmd []byte, detail string) ([]byte, error) {
return return
}) })
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "DeviceCallByDeviceID err ") return nil, gerror.Wrapf(err, "DeviceCallByDeviceID err ")
} }
return result, nil return result, nil
} }
@ -26,12 +26,12 @@ func readCmd(commUid string, address byte, startAddr, quantity uint16, detail st
g.Log().Debugf("Modbus 下发 读取命令 = % X", cmd) g.Log().Debugf("Modbus 下发 读取命令 = % X", cmd)
result, err := pushCmd(commUid, cmd, detail) result, err := pushCmd(commUid, cmd, detail)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "下发[% X]", cmd) return nil, gerror.Wrapf(err, "下发[% X]", cmd)
} }
g.Log().Debugf("Modbus 响应 读取命令 = % X", result) g.Log().Debugf("Modbus 响应 读取命令 = % X", result)
r, err := ReadHoldingRegisterParse(result, address, quantity) r, err := ReadHoldingRegisterParse(result, address, quantity)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "下发[% X],响应[% X]", cmd, result) return nil, gerror.Wrapf(err, "下发[% X],响应[% X]", cmd, result)
} }
return r, nil return r, nil
} }

@ -3,7 +3,7 @@ package m9z
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
) )
// 对应C的db_ble_extern_t结构体简化版使用bool型Enable // 对应C的db_ble_extern_t结构体简化版使用bool型Enable
@ -19,7 +19,7 @@ func BluetoothRead(deviceId string) (*BluetoothConfig, error) {
if err != nil { if err != nil {
errMsg := fmt.Sprintf("读取设备%s蓝牙配置失败: %v", deviceId, err) errMsg := fmt.Sprintf("读取设备%s蓝牙配置失败: %v", deviceId, err)
return nil, terror.New(errMsg) return nil, gerror.New(errMsg)
} }
data := cmd.Data data := cmd.Data
@ -29,7 +29,7 @@ func BluetoothRead(deviceId string) (*BluetoothConfig, error) {
if len(data) < minDataLen { if len(data) < minDataLen {
errMsg := fmt.Sprintf("蓝牙配置数据长度不足,至少需要%d字节实际收到%d字节", minDataLen, len(data)) errMsg := fmt.Sprintf("蓝牙配置数据长度不足,至少需要%d字节实际收到%d字节", minDataLen, len(data))
return nil, terror.New(errMsg) return nil, gerror.New(errMsg)
} }
// 3. 解析基础字段固定2字节 // 3. 解析基础字段固定2字节
@ -53,19 +53,19 @@ func BluetoothWrite(deviceId string, bleConfig *BluetoothConfig) error {
if bleConfig == nil { if bleConfig == nil {
errMsg := "蓝牙配置结构体为nil无法写入" errMsg := "蓝牙配置结构体为nil无法写入"
return terror.New(errMsg) return gerror.New(errMsg)
} }
nameBytes := []byte(bleConfig.BleName) nameBytes := []byte(bleConfig.BleName)
if len(nameBytes) > 20 { if len(nameBytes) > 20 {
errMsg := fmt.Sprintf("蓝牙名称超长最大支持20字节实际传入%d字节", len(nameBytes)) errMsg := fmt.Sprintf("蓝牙名称超长最大支持20字节实际传入%d字节", len(nameBytes))
return terror.New(errMsg) return gerror.New(errMsg)
} }
// 校验1是否包含中文/非ASCII字符 // 校验1是否包含中文/非ASCII字符
if hasChinese(bleConfig.BleName) { if hasChinese(bleConfig.BleName) {
errMsg := fmt.Sprintf("设备[%s]蓝牙名称包含中文/非ASCII字符仅支持英文/数字/符号等ASCII字符", deviceId) errMsg := fmt.Sprintf("设备[%s]蓝牙名称包含中文/非ASCII字符仅支持英文/数字/符号等ASCII字符", deviceId)
return terror.New(errMsg) return gerror.New(errMsg)
} }
// 2. 构造缓冲区2字节基础字段 + 动态长度蓝牙名称 // 2. 构造缓冲区2字节基础字段 + 动态长度蓝牙名称
@ -89,7 +89,7 @@ func BluetoothWrite(deviceId string, bleConfig *BluetoothConfig) error {
writeResp, err := WriteCmd(deviceId, bluetooth, buf, "设备蓝牙配置写入") writeResp, err := WriteCmd(deviceId, bluetooth, buf, "设备蓝牙配置写入")
if err != nil { if err != nil {
errMsg := fmt.Sprintf("设备[%s]蓝牙配置写入命令调用失败", deviceId) errMsg := fmt.Sprintf("设备[%s]蓝牙配置写入命令调用失败", deviceId)
return terror.Wrapf(err, errMsg) return gerror.Wrapf(err, errMsg)
} }
// 4. 检查写入响应状态修复err为nil的问题 // 4. 检查写入响应状态修复err为nil的问题
@ -97,7 +97,7 @@ func BluetoothWrite(deviceId string, bleConfig *BluetoothConfig) error {
errMsg := fmt.Sprintf("设备[%s]蓝牙配置写入失败,响应状态为失败", deviceId) errMsg := fmt.Sprintf("设备[%s]蓝牙配置写入失败,响应状态为失败", deviceId)
// 手动构造错误避免Wrapf传入nil // 手动构造错误避免Wrapf传入nil
return terror.New(errMsg) return gerror.New(errMsg)
} }
// 5. 写入成功日志修复切片越界问题用buf[2:]而非固定22 // 5. 写入成功日志修复切片越界问题用buf[2:]而非固定22

@ -3,7 +3,8 @@ package m9z
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"tgk-touch/internal/global" "tgk-touch/internal/global"
) )
@ -93,7 +94,7 @@ func DeviceConfigWrite(deviceId string, dc *DeviceConfig) error {
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("写入失败") return gerror.New("写入失败")
} }
return nil return nil
} }

@ -5,7 +5,8 @@ import (
"encoding/base64" "encoding/base64"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"io" "io"
"net/http" "net/http"
"os" "os"
@ -60,13 +61,13 @@ func FirmwareRead(deviceId string, address uint32, length uint16) (*FirmwareRead
// 4. 发送命令并获取响应 // 4. 发送命令并获取响应
respData, err := pushCommand(deviceId, frame, "读取固件数据") respData, err := pushCommand(deviceId, frame, "读取固件数据")
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "设备[%s]读取固件数据失败(地址:0x%X, 长度:%d", deviceId, address, length) return nil, gerror.Wrapf(err, "设备[%s]读取固件数据失败(地址:0x%X, 长度:%d", deviceId, address, length)
} }
// 5. 解析响应帧 // 5. 解析响应帧
frameResp, err := ParseBlockFrame(respData) frameResp, err := ParseBlockFrame(respData)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "设备[%s]解析固件响应失败", deviceId) return nil, gerror.Wrapf(err, "设备[%s]解析固件响应失败", deviceId)
} }
block := &FirmwareReadBlock{} block := &FirmwareReadBlock{}
block.Address = binary.LittleEndian.Uint32(frameResp.Data[0:4]) block.Address = binary.LittleEndian.Uint32(frameResp.Data[0:4])
@ -182,14 +183,14 @@ func FirmwareUpgrade(deviceId string, firmware []byte, startAddr uint32) (unique
frimwareVer := hex.EncodeToString(blockHash[:]) frimwareVer := hex.EncodeToString(blockHash[:])
read, err := FirmwareRead(deviceId, startAddr, uint16(blockSize)) read, err := FirmwareRead(deviceId, startAddr, uint16(blockSize))
if err != nil { if err != nil {
return uniqueId, addr, terror.Wrapf(err, "验证设备上最新固件包失败") return uniqueId, addr, gerror.Wrapf(err, "验证设备上最新固件包失败")
} }
deviceHash := sha256.Sum256(read.Data) deviceHash := sha256.Sum256(read.Data)
deviceVer := hex.EncodeToString(deviceHash[:]) deviceVer := hex.EncodeToString(deviceHash[:])
if deviceVer != frimwareVer { if deviceVer != frimwareVer {
os.WriteFile("./blockData.txt", []byte(fmt.Sprintf("% X", blockData)), 0666) os.WriteFile("./blockData.txt", []byte(fmt.Sprintf("% X", blockData)), 0666)
os.WriteFile("./readData.txt", []byte(fmt.Sprintf("% X", read.Data)), 0666) os.WriteFile("./readData.txt", []byte(fmt.Sprintf("% X", read.Data)), 0666)
return uniqueId, addr, terror.Newf("设备最新不完整,建议擦除分区重试 %s != %s %d %d", frimwareVer, deviceVer, len(blockData), len(read.Data)) return uniqueId, addr, gerror.Newf("设备最新不完整,建议擦除分区重试 %s != %s %d %d", frimwareVer, deviceVer, len(blockData), len(read.Data))
}*/ }*/
} }
@ -264,7 +265,7 @@ func EraseSector(deviceId string) (*WriteResponse, error) {
// 发送写入命令 // 发送写入命令
resp, err := WriteCmd(deviceId, eraseSector, data, "擦除扇区", UpdateMarker) resp, err := WriteCmd(deviceId, eraseSector, data, "擦除扇区", UpdateMarker)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "设备[%s]擦除扇区失败", deviceId) return nil, gerror.Wrapf(err, "设备[%s]擦除扇区失败", deviceId)
} }
// 验证响应状态 // 验证响应状态
@ -317,7 +318,7 @@ func FirmwareDataWrite(deviceId string, extDataLen byte, addr uint32, writeLen u
// 4. 发送写入命令 // 4. 发送写入命令
resp, err := WriteCmd(deviceId, firmwareData, cmdData, "下发固件数据", UpdateMarker) resp, err := WriteCmd(deviceId, firmwareData, cmdData, "下发固件数据", UpdateMarker)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "\n设备[%s]下发固件数据失败", deviceId) return nil, gerror.Wrapf(err, "\n设备[%s]下发固件数据失败", deviceId)
} }
if !resp.Success { if !resp.Success {
@ -333,7 +334,7 @@ func LockFirmware(deviceId string) (*WriteResponse, error) {
// 无数据 payload参考示例指令数据长度0x00 // 无数据 payload参考示例指令数据长度0x00
resp, err := WriteCmd(deviceId, lockFirmware, []byte{00}, "固件加锁") resp, err := WriteCmd(deviceId, lockFirmware, []byte{00}, "固件加锁")
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "设备[%s]固件加锁失败", deviceId) return nil, gerror.Wrapf(err, "设备[%s]固件加锁失败", deviceId)
} }
if !resp.Success { if !resp.Success {
@ -348,26 +349,26 @@ func LockFirmware(deviceId string) (*WriteResponse, error) {
func GetFirmwareFromLocal(localPath string) ([]byte, error) { func GetFirmwareFromLocal(localPath string) ([]byte, error) {
// 校验路径合法性 // 校验路径合法性
if localPath == "" { if localPath == "" {
return nil, terror.New("本地固件路径不能为空") return nil, gerror.New("本地固件路径不能为空")
} }
absPath, err := filepath.Abs(localPath) absPath, err := filepath.Abs(localPath)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "读取固件绝对路径失败(%s", localPath) return nil, gerror.Wrapf(err, "读取固件绝对路径失败(%s", localPath)
} }
// 检查文件是否存在 // 检查文件是否存在
fileInfo, err := os.Stat(absPath) fileInfo, err := os.Stat(absPath)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "固件文件不存在或无法访问(%s", absPath) return nil, gerror.Wrapf(err, "固件文件不存在或无法访问(%s", absPath)
} }
if fileInfo.IsDir() { if fileInfo.IsDir() {
return nil, terror.Newf("路径指向目录,不是固件文件(%s", absPath) return nil, gerror.Newf("路径指向目录,不是固件文件(%s", absPath)
} }
// 读取文件内容 // 读取文件内容
firmwareData, err := os.ReadFile(absPath) firmwareData, err := os.ReadFile(absPath)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "读取固件文件失败(%s", absPath) return nil, gerror.Wrapf(err, "读取固件文件失败(%s", absPath)
} }
g.Log().Infof("成功从本地读取固件,路径:%s大小%d字节", absPath, len(firmwareData)) g.Log().Infof("成功从本地读取固件,路径:%s大小%d字节", absPath, len(firmwareData))
@ -379,7 +380,7 @@ func GetFirmwareFromLocal(localPath string) ([]byte, error) {
func GetFirmwareFromURL(url string) ([]byte, error) { func GetFirmwareFromURL(url string) ([]byte, error) {
// 校验URL合法性 // 校验URL合法性
if url == "" { if url == "" {
return nil, terror.New("固件下载URL不能为空") return nil, gerror.New("固件下载URL不能为空")
} }
if filepath.Ext(url) != ".bin" { if filepath.Ext(url) != ".bin" {
g.Log().Warnf("固件URL后缀非.bin可能不是有效固件文件%s", url) g.Log().Warnf("固件URL后缀非.bin可能不是有效固件文件%s", url)
@ -391,19 +392,19 @@ func GetFirmwareFromURL(url string) ([]byte, error) {
} }
resp, err := client.Get(url) resp, err := client.Get(url)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "固件下载请求失败(%s", url) return nil, gerror.Wrapf(err, "固件下载请求失败(%s", url)
} }
defer resp.Body.Close() // 确保响应体关闭 defer resp.Body.Close() // 确保响应体关闭
// 校验响应状态 // 校验响应状态
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, terror.Newf("固件下载失败HTTP状态码%d%s", resp.StatusCode, url) return nil, gerror.Newf("固件下载失败HTTP状态码%d%s", resp.StatusCode, url)
} }
// 读取响应内容 // 读取响应内容
firmwareData, err := io.ReadAll(resp.Body) firmwareData, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "读取固件响应内容失败(%s", url) return nil, gerror.Wrapf(err, "读取固件响应内容失败(%s", url)
} }
g.Log().Infof("成功从网络下载固件URL%s大小%d字节", url, len(firmwareData)) g.Log().Infof("成功从网络下载固件URL%s大小%d字节", url, len(firmwareData))

@ -3,7 +3,8 @@ package m9z
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"math" "math"
"time" "time"
) )
@ -61,7 +62,7 @@ func LgnLatWrite(deviceId string, data *LgnLatData) error {
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
} }
return nil return nil
} }

@ -4,7 +4,8 @@ package m9z
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"strings" "strings"
"tgk-touch/internal/global" "tgk-touch/internal/global"
) )
@ -138,7 +139,7 @@ func ManualWrite(deviceId string, manualData *ManualData) error {
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
} }
return nil return nil
} }

@ -1,7 +1,7 @@
package m9z package m9z
import ( import (
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"log" "log"
) )
@ -21,7 +21,7 @@ func ModeWrite(deviceId string, m byte) error {
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
} }
return nil return nil
} }

@ -7,7 +7,7 @@ func Restart(deviceId string) error {
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
}*/ }*/
return nil return nil
} }

@ -1,8 +1,6 @@
package m9z package m9z
import ( import "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/errors/terror"
)
func Save(deviceId string) error { func Save(deviceId string) error {
writeResp, err := WriteCmd(deviceId, save, nil, "保存设置") writeResp, err := WriteCmd(deviceId, save, nil, "保存设置")
@ -11,7 +9,7 @@ func Save(deviceId string) error {
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
} }
return nil return nil
} }

@ -2,7 +2,8 @@ package m9z
import ( import (
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"log" "log"
) )
@ -62,7 +63,7 @@ func SunRiseSetWrite(deviceId string, srs *SunRiseSet) error {
// 5. 验证设备响应 // 5. 验证设备响应
if !resp.Success { if !resp.Success {
return terror.New("设备返回写入失败") return gerror.New("设备返回写入失败")
} }
return nil return nil

@ -3,7 +3,8 @@ package m9z
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"tgk-touch/internal/global" "tgk-touch/internal/global"
) )
@ -132,7 +133,7 @@ func taskWrite(deviceId string, cmd M9zCtrl, task *TaskProgram, detail string) e
return err return err
} }
if !writeResp.Success { if !writeResp.Success {
return terror.New("设置失败") return gerror.New("设置失败")
} }
// 发送写入命令 // 发送写入命令
return nil return nil

@ -2,7 +2,8 @@ package m9z // 插件
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"sort" "sort"
"tgk-touch/internal/global" "tgk-touch/internal/global"
"time" "time"
@ -282,7 +283,7 @@ func TaskProgramToControlTask(program *TaskProgram) (*ControlTask, error) {
minute := minutes % 60 minute := minutes % 60
parse, err := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %02d:%02d:00", time.Now().Format(time.DateOnly), hour, minute), time.Local) parse, err := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %02d:%02d:00", time.Now().Format(time.DateOnly), hour, minute), time.Local)
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "failed to parse time") return nil, gerror.Wrapf(err, "failed to parse time")
} }
task.ExecTime = parse task.ExecTime = parse
@ -512,7 +513,7 @@ func TaskProgramToMiddleControlTask(program *TaskProgram) (*MiddleControlTask, e
parse, err := time.ParseInLocation("2006-01-02 15:04", fmt.Sprintf("%s %02d:%02d", time.Now().Format(time.DateOnly), hour, minute), time.Local) parse, err := time.ParseInLocation("2006-01-02 15:04", fmt.Sprintf("%s %02d:%02d", time.Now().Format(time.DateOnly), hour, minute), time.Local)
if err != nil { if err != nil {
return nil, terror.Wrap(err, "parse time error") return nil, gerror.Wrap(err, "parse time error")
} }
currentTask.ExecTime = parse currentTask.ExecTime = parse

@ -2,7 +2,8 @@ package m9z
import ( import (
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"tgk-touch/internal/global" "tgk-touch/internal/global"
"tgk-touch/internal/module/maincontrollerClient" "tgk-touch/internal/module/maincontrollerClient"
) )
@ -128,21 +129,21 @@ func ParseFrame(data []byte) (interface{}, error) {
case isResponse && cmdType == CmdWrite: case isResponse && cmdType == CmdWrite:
return parseWriteResponse(payload) return parseWriteResponse(payload)
default: default:
return nil, terror.New("unsupported command type") return nil, gerror.New("unsupported command type")
} }
} }
// 解析读取响应 // 解析读取响应
func parseReadResponse(payload []byte) (*ReadResponse, error) { func parseReadResponse(payload []byte) (*ReadResponse, error) {
if len(payload) < 4 { if len(payload) < 4 {
return nil, terror.New("invalid read response format") return nil, gerror.New("invalid read response format")
} }
index := payload[2] index := payload[2]
dataLength := payload[3] dataLength := payload[3]
if len(payload) < 4+int(dataLength) { if len(payload) < 4+int(dataLength) {
return nil, terror.New("data length mismatch") return nil, gerror.New("data length mismatch")
} }
return &ReadResponse{ return &ReadResponse{
@ -153,14 +154,14 @@ func parseReadResponse(payload []byte) (*ReadResponse, error) {
} }
func parseReadBlockResponse(payload []byte) (*ReadResponse, error) { func parseReadBlockResponse(payload []byte) (*ReadResponse, error) {
if len(payload) < 4 { if len(payload) < 4 {
return nil, terror.New("invalid read response format") return nil, gerror.New("invalid read response format")
} }
index := payload[2] index := payload[2]
dataLength := payload[3:5] dataLength := payload[3:5]
le := BytesToUint16LE(dataLength) le := BytesToUint16LE(dataLength)
if len(payload) < 4+int(le) { if len(payload) < 4+int(le) {
return nil, terror.New("data length mismatch") return nil, gerror.New("data length mismatch")
} }
return &ReadResponse{ return &ReadResponse{
@ -173,14 +174,14 @@ func parseReadBlockResponse(payload []byte) (*ReadResponse, error) {
// 解析写入响应 // 解析写入响应
func parseWriteResponse(payload []byte) (*WriteResponse, error) { func parseWriteResponse(payload []byte) (*WriteResponse, error) {
if len(payload) < 5 { if len(payload) < 5 {
return nil, terror.New("invalid write response format") return nil, gerror.New("invalid write response format")
} }
index := payload[2] index := payload[2]
dataLength := payload[3] dataLength := payload[3]
if dataLength != 1 { if dataLength != 1 {
return nil, terror.New("invalid data length in write response") return nil, gerror.New("invalid data length in write response")
} }
success := payload[4] == 0x01 success := payload[4] == 0x01
@ -243,7 +244,7 @@ func pushCommand(deviceId string, cmd []byte, detail string) ([]byte, error) {
return return
}) })
if err != nil { if err != nil {
return nil, terror.Wrapf(err, "单灯控制命令 deviceID={%v} cmd={% X} 下发失败", deviceId, cmd) return nil, gerror.Wrapf(err, "单灯控制命令 deviceID={%v} cmd={% X} 下发失败", deviceId, cmd)
} }
return result, nil return result, nil

@ -2,7 +2,8 @@ package adl400TtyApi
import ( import (
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/towgo" "github.com/towgo/towgo/towgo"
"math" "math"
"tgk-touch/internal/global" "tgk-touch/internal/global"
@ -88,7 +89,7 @@ func getDailyFreezingTime(rpc towgo.JsonRpcConnection) {
time, err := mc.ReadDailyFreezingTime(p.CommUid, getMeterAddr(p.CommUid)) time, err := mc.ReadDailyFreezingTime(p.CommUid, getMeterAddr(p.CommUid))
if err != nil { if err != nil {
panic(terror.Wrap(err, "getDailyFreezingTime")) panic(gerror.Wrap(err, "getDailyFreezingTime"))
} }
rpc.WriteResult(time) rpc.WriteResult(time)
@ -102,7 +103,7 @@ func geDeviceTime(rpc towgo.JsonRpcConnection) {
time, err := mc.ReadTime(p.CommUid, getMeterAddr(p.CommUid)) time, err := mc.ReadTime(p.CommUid, getMeterAddr(p.CommUid))
if err != nil { if err != nil {
panic(terror.Wrap(err, "geTime")) panic(gerror.Wrap(err, "geTime"))
} }
rpc.WriteResult(time.Format("2006-01-02 15:04:05")) rpc.WriteResult(time.Format("2006-01-02 15:04:05"))
@ -116,7 +117,7 @@ func getReadMonthlyFreezingTime(rpc towgo.JsonRpcConnection) {
day, hour, err := mc.ReadMonthlyFreezingTime(p.CommUid, getMeterAddr(p.CommUid)) day, hour, err := mc.ReadMonthlyFreezingTime(p.CommUid, getMeterAddr(p.CommUid))
if err != nil { if err != nil {
panic(terror.Wrap(err, "getReadMonthlyFreezingTime")) panic(gerror.Wrap(err, "getReadMonthlyFreezingTime"))
} }
r := map[string]interface{}{} r := map[string]interface{}{}
r["day"] = day r["day"] = day

@ -3,8 +3,9 @@ package licenseterminal
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/towgo/towgo/errors/terror"
"io" "io"
"log" "log"
"net" "net"
@ -261,7 +262,7 @@ func activecodeRequestCheck(rpcConn towgo.JsonRpcConnection) error {
rpcConn.ReadParams(&requestParams) rpcConn.ReadParams(&requestParams)
if requestParams.LicenseKey == "" { if requestParams.LicenseKey == "" {
return terror.New("license_key can not be null") return gerror.New("license_key can not be null")
} }
if requestParams.ProductNumber == "" { if requestParams.ProductNumber == "" {
@ -270,18 +271,18 @@ func activecodeRequestCheck(rpcConn towgo.JsonRpcConnection) error {
licenseKeys := strings.Split(requestParams.LicenseKey, "-") licenseKeys := strings.Split(requestParams.LicenseKey, "-")
if len(licenseKeys) != 4 { if len(licenseKeys) != 4 {
return terror.New("license_key error") return gerror.New("license_key error")
} }
if strings.ToUpper(cehckSumString([]byte(requestParams.ProductNumber))) != licenseKeys[0] { if strings.ToUpper(cehckSumString([]byte(requestParams.ProductNumber))) != licenseKeys[0] {
return terror.New("license_key not support for product number") return gerror.New("license_key not support for product number")
} }
check := licenseKeys[0] + "-" + licenseKeys[1] + "-" + licenseKeys[2] check := licenseKeys[0] + "-" + licenseKeys[1] + "-" + licenseKeys[2]
check = strings.ToUpper(check) check = strings.ToUpper(check)
crcStr := strings.ToUpper(cehckSumString([]byte(check))) crcStr := strings.ToUpper(cehckSumString([]byte(check)))
if crcStr != licenseKeys[3] { if crcStr != licenseKeys[3] {
return terror.New("license_key error") return gerror.New("license_key error")
} }
return nil return nil
} }
@ -333,10 +334,10 @@ func notifyReNew(ProductSerialNumber string) {
func CheckLicense(l License) error { func CheckLicense(l License) error {
if l.AccessCode != accessCode { if l.AccessCode != accessCode {
return terror.New("许可证与授权码不匹配") return gerror.New("许可证与授权码不匹配")
} }
if l.Endtime < time.Now().UnixMilli() { if l.Endtime < time.Now().UnixMilli() {
return terror.New("许可证到期") return gerror.New("许可证到期")
} }
return nil return nil
} }
@ -541,7 +542,7 @@ func QueryLicense(name string) (License, error) {
} }
} }
var l License var l License
return l, terror.New("license not found") return l, gerror.New("license not found")
} }
func OpenLicense(path string) (License, error) { func OpenLicense(path string) (License, error) {

@ -3,7 +3,8 @@ package m9zApi
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/lib/system" "github.com/towgo/towgo/lib/system"
"os" "os"
"path/filepath" "path/filepath"
@ -65,7 +66,7 @@ func ScanM9z() {
} }
err = addData(mph) err = addData(mph)
if err != nil { if err != nil {
g.Log().Error(terror.Wrap(err, "create error")) g.Log().Error(gerror.Wrap(err, "create error"))
} }
} }
@ -78,7 +79,7 @@ func readData() ([]M9zFaultHistory, error) {
if _, err := os.Stat(filePath); os.IsNotExist(err) { if _, err := os.Stat(filePath); os.IsNotExist(err) {
_, err := createFileWithPath(filePath) _, err := createFileWithPath(filePath)
if err != nil { if err != nil {
return nil, terror.Wrap(err, "create file error") return nil, gerror.Wrap(err, "create file error")
} }
return []M9zFaultHistory{}, nil // 文件不存在,返回空切片 return []M9zFaultHistory{}, nil // 文件不存在,返回空切片
} }
@ -116,7 +117,7 @@ func addData(newItem M9zFaultHistory) error {
// 1. 读取现有数据 // 1. 读取现有数据
items, err := readData() items, err := readData()
if err != nil { if err != nil {
return terror.Wrap(err, "readData") return gerror.Wrap(err, "readData")
} }
// 2. 追加新数据 // 2. 追加新数据
@ -139,7 +140,7 @@ func addData(newItem M9zFaultHistory) error {
err = writeData(items) err = writeData(items)
if err != nil { if err != nil {
return terror.Wrap(err, "writeData") return gerror.Wrap(err, "writeData")
} }
return nil return nil
@ -149,7 +150,7 @@ func addData(newItem M9zFaultHistory) error {
func deleteById(id int) error { func deleteById(id int) error {
items, err := readData() items, err := readData()
if err != nil { if err != nil {
return terror.Wrap(err, "readData") return gerror.Wrap(err, "readData")
} }
if id < 1 || id > len(items) { if id < 1 || id > len(items) {

@ -2,7 +2,8 @@ package m9zApi
import ( import (
"encoding/json" "encoding/json"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/towgo" "github.com/towgo/towgo/towgo"
"tgk-touch/internal/global" "tgk-touch/internal/global"
) )
@ -89,7 +90,7 @@ func faultDelete(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadResult(&p) rpc.ReadResult(&p)
if p.Id == 0 { if p.Id == 0 {
panic(terror.New("id 为空")) panic(gerror.New("id 为空"))
} }

@ -2,6 +2,7 @@ package m9zApi
import ( import (
"fmt" "fmt"
"github.com/gogf/gf/v2/errors/gerror"
"math" "math"
"sort" "sort"
"sync" "sync"
@ -9,7 +10,6 @@ import (
"tgk-touch/internal/library/m9z" "tgk-touch/internal/library/m9z"
"time" "time"
"github.com/towgo/towgo/errors/terror"
"github.com/towgo/towgo/towgo" "github.com/towgo/towgo/towgo"
) )
@ -20,7 +20,7 @@ func getDeviceId(rpc towgo.JsonRpcConnection) (string, []uint) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
return p.CommUid, p.Idxs return p.CommUid, p.Idxs
} }
@ -213,7 +213,7 @@ func getStartTask(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.StartTaskRead(p.CommUid, p.Mode) read, err := m9z.StartTaskRead(p.CommUid, p.Mode)
@ -240,7 +240,7 @@ func getMiddleTaskRead(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.MiddleTaskRead(p.CommUid, p.Mode) read, err := m9z.MiddleTaskRead(p.CommUid, p.Mode)
@ -258,7 +258,7 @@ func getStopTaskRead(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.StopTaskRead(p.CommUid, p.Mode) read, err := m9z.StopTaskRead(p.CommUid, p.Mode)
@ -275,12 +275,12 @@ func getStartTask2(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.StartTaskRead(p.CommUid, p.Mode) read, err := m9z.StartTaskRead(p.CommUid, p.Mode)
if err != nil { if err != nil {
panic(terror.Wrap(err, "")) panic(gerror.Wrap(err, ""))
} }
task, err := m9z.TaskProgramToControlTask(read) task, err := m9z.TaskProgramToControlTask(read)
if err != nil { if err != nil {
@ -294,7 +294,7 @@ func getStartTask2(rpc towgo.JsonRpcConnection) {
} }
task.ExecTime = timeRead.Sunrise task.ExecTime = timeRead.Sunrise
} }
rpc.WriteResult(&m9z.TaskProgram{}) rpc.WriteResult(task)
} }
func getStopTask2(rpc towgo.JsonRpcConnection) { func getStopTask2(rpc towgo.JsonRpcConnection) {
@ -304,7 +304,7 @@ func getStopTask2(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.StopTaskRead(p.CommUid, p.Mode) read, err := m9z.StopTaskRead(p.CommUid, p.Mode)
@ -334,7 +334,7 @@ func getMiddleTask2(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
read, err := m9z.MiddleTaskRead(p.CommUid, p.Mode) read, err := m9z.MiddleTaskRead(p.CommUid, p.Mode)
@ -360,7 +360,7 @@ func getSubLoopParameters(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
r, err := m9z.SubLoopParametersRead(p.CommUid, p.Idx) r, err := m9z.SubLoopParametersRead(p.CommUid, p.Idx)
@ -376,7 +376,7 @@ func getAllSubLoopParameter(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
result := make(map[string]interface{}) result := make(map[string]interface{})

@ -2,12 +2,12 @@ package m9zApi
import ( import (
"fmt" "fmt"
"github.com/gogf/gf/v2/errors/gerror"
"strings" "strings"
g "tgk-touch/internal/global" g "tgk-touch/internal/global"
m9z "tgk-touch/internal/library/m9z" m9z "tgk-touch/internal/library/m9z"
"time" "time"
"github.com/towgo/towgo/errors/terror"
"github.com/towgo/towgo/towgo" "github.com/towgo/towgo/towgo"
) )
@ -233,7 +233,7 @@ func setStartTaskWrite(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
err := m9z.StartTaskWrite(p.CommUid, &p.TaskProgram) err := m9z.StartTaskWrite(p.CommUid, &p.TaskProgram)
if err != nil { if err != nil {
@ -254,7 +254,7 @@ func setMiddleTaskWrite(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
err := m9z.MiddleTaskWrite(p.CommUid, &p.TaskProgram) err := m9z.MiddleTaskWrite(p.CommUid, &p.TaskProgram)
if err != nil { if err != nil {
@ -275,7 +275,7 @@ func setStopTaskWrite(rpc towgo.JsonRpcConnection) {
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
err := m9z.StopTaskWrite(p.CommUid, &p.TaskProgram) err := m9z.StopTaskWrite(p.CommUid, &p.TaskProgram)
if err != nil { if err != nil {
@ -288,22 +288,27 @@ func setStopTaskWrite(rpc towgo.JsonRpcConnection) {
rpc.WriteResult("ok") rpc.WriteResult("ok")
} }
// 写入结束任务 (优化指令 CMD=0x15) // 写入开始任务 (优化指令 CMD=0x15)
func setStartTask2(rpc towgo.JsonRpcConnection) { func setStartTask2(rpc towgo.JsonRpcConnection) {
var p struct { var p struct {
CommUid string `json:"comm_uid"` ExecTime string `json:"execTime"`
Mode uint8 `json:"mode"` CommUid string `json:"comm_uid"`
Mode uint8 `json:"mode"`
m9z.ControlTask m9z.ControlTask
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
}
parse, err := time.Parse("2006-01-02 15:04:05", p.ExecTime)
if err != nil {
panic(err)
} }
p.ControlTask.ExecTime = parse
program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode) program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode)
if err != nil { if err != nil {
panic(err) panic(err)
} }
g.Log().Debugf("program: %+v", program)
err = m9z.StartTaskWrite(p.CommUid, program) err = m9z.StartTaskWrite(p.CommUid, program)
if err != nil { if err != nil {
panic(err) panic(err)
@ -316,14 +321,21 @@ func setStartTask2(rpc towgo.JsonRpcConnection) {
} }
func setStopTask2(rpc towgo.JsonRpcConnection) { func setStopTask2(rpc towgo.JsonRpcConnection) {
var p struct { var p struct {
CommUid string `json:"comm_uid"` ExecTime string `json:"execTime"`
Mode uint8 `json:"mode"` CommUid string `json:"comm_uid"`
Mode uint8 `json:"mode"`
m9z.ControlTask m9z.ControlTask
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
parse, err := time.Parse("2006-01-02 15:04:05", p.ExecTime)
if err != nil {
panic(err)
}
p.ControlTask.ExecTime = parse
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode) program, err := m9z.ControlTaskToTaskProgram(p.ControlTask, p.Mode)
if err != nil { if err != nil {
panic(err) panic(err)
@ -342,15 +354,28 @@ func setStopTask2(rpc towgo.JsonRpcConnection) {
func setMiddleTask2(rpc towgo.JsonRpcConnection) { func setMiddleTask2(rpc towgo.JsonRpcConnection) {
var p struct { var p struct {
CommUid string `json:"comm_uid"` CommUid string `json:"comm_uid"`
Mode uint8 `json:"mode"` Mode uint8 `json:"mode"`
m9z.MiddleControlTask ControlTaskList []struct {
m9z.ControlTask
ExecTime string `json:"execTime"` // "2006-01-02 15:04:05" 格式时间
} `json:"controlTaskList"`
} }
rpc.ReadParams(&p) rpc.ReadParams(&p)
if p.CommUid == "" { if p.CommUid == "" {
panic(terror.New("comm_uid is empty")) panic(gerror.New("comm_uid is empty"))
} }
program, err := m9z.MiddleControlTaskToTaskProgram(p.MiddleControlTask, p.Mode) middleTask := m9z.MiddleControlTask{}
middleTask.ControlTaskList = make([]m9z.ControlTask, len(p.ControlTaskList))
for i, controlTask := range p.ControlTaskList {
parse, err := time.Parse("2006-01-02 15:04:05", controlTask.ExecTime)
if err != nil {
panic(err)
}
controlTask.ControlTask.ExecTime = parse
middleTask.ControlTaskList[i] = controlTask.ControlTask
}
program, err := m9z.MiddleControlTaskToTaskProgram(middleTask, p.Mode)
if err != nil { if err != nil {
panic(err) panic(err)
} }

@ -4,10 +4,9 @@ import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/towgo" "github.com/towgo/towgo/towgo"
"go.uber.org/zap" "go.uber.org/zap"
"sync"
g "tgk-touch/internal/global" g "tgk-touch/internal/global"
) )
@ -86,13 +85,8 @@ type LogFormatter func(deviceID, method string, params, result interface{}) (dev
// 带日志记录的设备调用函数新增formatter参数用于自定义日志格式 // 带日志记录的设备调用函数新增formatter参数用于自定义日志格式
func DeviceCallByDeviceID(deviceID, method, token string, params, destResult any, formatter LogFormatter) error { func DeviceCallByDeviceID(deviceID, method, token string, params, destResult any, formatter LogFormatter) error {
var err error var err error
// 最多重试3次
for i := 0; i < 3; i++ { err = deviceCallByDeviceID(deviceID, method, token, params, destResult)
err = deviceCallByDeviceID(deviceID, method, token, params, destResult)
if err == nil {
break
}
}
// 构建日志基础信息 // 构建日志基础信息
logEntry := New(deviceID, params, destResult) logEntry := New(deviceID, params, destResult)
@ -170,12 +164,8 @@ func isPrintableASCII(b []byte) bool {
return true return true
} }
var pushDeviceLock sync.Mutex
func deviceCallByDeviceID(deviceID, method, token string, params, destResult any) error { func deviceCallByDeviceID(deviceID, method, token string, params, destResult any) error {
if serialPortMode { if serialPortMode {
pushDeviceLock.Lock()
defer pushDeviceLock.Unlock()
b, err := ToBytes(params) b, err := ToBytes(params)
if err != nil { if err != nil {
return err return err
@ -183,11 +173,12 @@ func deviceCallByDeviceID(deviceID, method, token string, params, destResult any
result, err := serialPort.BIO(b) result, err := serialPort.BIO(b)
if err != nil { if err != nil {
g.Log().Error("serialPort.BIO err:", err.Error()) g.Log().Error("serialPort.BIO err:", err.Error())
return terror.Wrap(err, "serialPort.BIO result err") return gerror.Wrap(err, "serialPort.BIO result err")
} }
b, err = json.Marshal(result) b, err = json.Marshal(result)
if err != nil { if err != nil {
g.Log().Error("serialPort.BIO json.Marshal(result) err:", err.Error()) g.Log().Error("serialPort.BIO json.Marshal(result) err:", err.Error())
return gerror.Wrap(err, "json.Marshal(result) err")
} }
return json.Unmarshal(b, destResult) return json.Unmarshal(b, destResult)
@ -209,7 +200,7 @@ func deviceCallByDeviceID(deviceID, method, token string, params, destResult any
Call(mainControllerRequest, func(jrc towgo.JsonRpcConnection) { Call(mainControllerRequest, func(jrc towgo.JsonRpcConnection) {
//g.Log().Debug(jrc.GetRpcResponse()) //g.Log().Debug(jrc.GetRpcResponse())
if jrc.GetRpcResponse().Error.Code != 200 { if jrc.GetRpcResponse().Error.Code != 200 {
err = terror.Newf("deviceId [%s],msg %s", deviceID, jrc.GetRpcResponse().Error.Message) err = gerror.Newf("deviceId [%s],msg %s", deviceID, jrc.GetRpcResponse().Error.Message)
return return
} }
jrc.ReadResult(destResult) jrc.ReadResult(destResult)

@ -6,7 +6,7 @@ import (
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/errors/gerror"
"github.com/towgo/towgo/errors/terror"
"io" "io"
"reflect" "reflect"
"sync" "sync"
@ -90,7 +90,7 @@ func UseSerialPort(portName string, baudRate int) error {
func (sp *SerialPort) Open() error { func (sp *SerialPort) Open() error {
if sp.isOpen { if sp.isOpen {
return terror.New("port is already open") return gerror.New("port is already open")
} }
port, err := serial.Open(sp.address, sp.config) port, err := serial.Open(sp.address, sp.config)
@ -112,13 +112,12 @@ func (sp *SerialPort) BIO(data []byte) ([]byte, error) {
sp.bioWriteLock.Lock() sp.bioWriteLock.Lock()
defer sp.bioWriteLock.Unlock() defer sp.bioWriteLock.Unlock()
sp.SetisBIO(true) sp.SetisBIO(true)
sp.port.Write(data) sp.port.Write(data)
timer := time.NewTimer(time.Second * 3) timer := time.NewTimer(time.Second * 3)
select { select {
case <-timer.C: case <-timer.C:
sp.SetisBIO(false) sp.SetisBIO(false)
return nil, terror.New("数据读取超时") return nil, gerror.New("数据读取超时")
case message := <-sp.bioChan: case message := <-sp.bioChan:
sp.SetisBIO(false) sp.SetisBIO(false)
return message, nil return message, nil
@ -129,7 +128,7 @@ func (sp *SerialPort) BIO(data []byte) ([]byte, error) {
func (sp *SerialPort) Close() error { func (sp *SerialPort) Close() error {
if !sp.isOpen { if !sp.isOpen {
return terror.New("port is already closed") return gerror.New("port is already closed")
} }
// 执行关闭操作 // 执行关闭操作

@ -1,7 +1,7 @@
package utility package utility
import ( import (
"github.com/towgo/towgo/errors/terror" "github.com/gogf/gf/v2/errors/gerror"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -24,7 +24,7 @@ func PathExists(path string) (bool, error) {
if fi.IsDir() { if fi.IsDir() {
return true, nil return true, nil
} }
return false, terror.New("存在同名文件") return false, gerror.New("存在同名文件")
} }
if os.IsNotExist(err) { if os.IsNotExist(err) {
return false, nil return false, nil
@ -119,7 +119,7 @@ func FileCopy(src string, dst string) (err error) {
return err return err
} }
if srcInfo.IsDir() { if srcInfo.IsDir() {
return terror.New("源路径是一个目录,不是文件") return gerror.New("源路径是一个目录,不是文件")
} }
// 确保目标目录存在 // 确保目标目录存在

Loading…
Cancel
Save