jl-iot/service/modbus_dc_mapping.go

288 lines
9.0 KiB
Go
Raw Normal View History

2023-12-08 18:08:15 +08:00
package service
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"joylink.club/iot/modbus"
"joylink.club/iot/service/model"
sproto "joylink.club/iot/service/proto"
)
2023-12-13 11:03:21 +08:00
// Modbus驱采服务
type modbusQcService struct {
2023-12-08 18:08:15 +08:00
config *sproto.ModbusConfig
cli modbus.MasterClient
2023-12-13 11:03:21 +08:00
qc model.QC
2023-12-08 18:08:15 +08:00
cancel context.CancelFunc
2023-12-15 18:08:06 +08:00
done chan struct{} // 服务协程退出信号
2023-12-08 18:08:15 +08:00
}
2023-12-13 11:03:21 +08:00
func NewModbusQcService(config *sproto.ModbusConfig, dc model.QC) (IotService, error) {
2023-12-08 18:08:15 +08:00
if err := checkConfig(config); err != nil {
return nil, err
}
_, ok := modbus.GetClient(config.Url)
if ok {
return nil, fmt.Errorf("modbus客户端已存在,url=%s", config.Url)
}
cli, err := modbus.NewClient(&modbus.ClientConfig{
Url: config.Url,
Timeout: config.Timeout,
})
2023-12-08 18:08:15 +08:00
if err != nil {
return nil, errors.Join(err, fmt.Errorf("modbus客户端创建失败,url=%s", config.Url))
}
cli.SetUnitId(uint8(config.UnitId))
cli.SetEndianness(convertEndianness(config.Endianness))
cli.Start()
2023-12-13 11:03:21 +08:00
s := &modbusQcService{
2023-12-08 18:08:15 +08:00
config: config,
cli: cli,
2023-12-13 11:03:21 +08:00
qc: dc,
2023-12-15 18:08:06 +08:00
done: make(chan struct{}),
2023-12-08 18:08:15 +08:00
}
s.initOnUpdateTask()
ctx, cancel := context.WithCancel(context.Background())
go s.run(ctx)
s.cancel = cancel
return s, nil
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) initOnUpdateTask() {
2023-12-08 18:08:15 +08:00
mapping := m.config.Mapping
for _, mdm := range mapping {
if mdm.WriteStrategy == sproto.Modbus_OnUpdate && isWriteFunction(mdm.Function) {
et := model.DCE_Drive_Update
if mdm.Type == sproto.DataType_CollectTable {
et = model.DCE_Collect_Update
}
2023-12-13 11:03:21 +08:00
m.qc.On(et, func(d model.QC) {
2023-12-08 18:08:15 +08:00
if !m.cli.IsConnected() {
slog.Warn("Modbus驱动采集服务数据更新写入失败,modbus客户端未连接", "url", m.config.Url, "Function", mdm.Function)
2023-12-08 18:08:15 +08:00
return
}
switch mdm.Function {
case sproto.Modbus_WriteCoil, sproto.Modbus_WriteCoils, sproto.Modbus_RWCoils:
err := m.cli.WriteCoils(uint16(mdm.Addr), m.GetDcBits(mdm))
if err != nil {
slog.Error("Modbus驱动采集服务写入线圈失败", "url", m.config.Url, "error", err, "Function", mdm.Function)
2023-12-08 18:08:15 +08:00
} else {
slog.Info("Modbus驱动采集服务写入线圈成功", "url", m.config.Url, "Function", mdm.Function)
2023-12-08 18:08:15 +08:00
}
case sproto.Modbus_WriteRegister, sproto.Modbus_WriteRegisters, sproto.Modbus_RWRegisters:
err := m.cli.WriteRegisterBytes(uint16(mdm.Addr), m.GetDcBytes(mdm))
if err != nil {
slog.Error("Modbus驱动采集服务写入寄存器失败", "url", m.config.Url, "error", err, "Function", mdm.Function)
2023-12-08 18:08:15 +08:00
} else {
slog.Info("Modbus驱动采集服务写入寄存器成功", "url", m.config.Url, "Function", mdm.Function)
2023-12-08 18:08:15 +08:00
}
}
})
}
}
}
func isWriteFunction(modbus_Function sproto.Modbus_Function) bool {
return modbus_Function == sproto.Modbus_WriteCoil ||
modbus_Function == sproto.Modbus_WriteCoils ||
modbus_Function == sproto.Modbus_WriteRegister ||
modbus_Function == sproto.Modbus_WriteRegisters ||
modbus_Function == sproto.Modbus_RWCoils ||
modbus_Function == sproto.Modbus_RWRegisters
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) run(ctx context.Context) {
2023-12-15 18:08:06 +08:00
defer close(m.done)
mainLoop:
2023-12-08 18:08:15 +08:00
for {
select {
case <-ctx.Done():
2023-12-15 18:08:06 +08:00
slog.Debug("Modbus驱采映射循环取消,关闭modbus客户端", "url", m.config.Url)
modbus.DeleteClient(m.config.Url)
break mainLoop
2023-12-08 18:08:15 +08:00
default:
}
m.mappingTaskExecute()
time.Sleep(time.Millisecond * time.Duration(m.config.Interval))
}
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) mappingTaskExecute() {
2023-12-08 18:08:15 +08:00
if m.cli.IsConnected() {
for _, mdm := range m.config.Mapping {
switch mdm.Function {
case sproto.Modbus_ReadCoil, sproto.Modbus_RWCoils:
data, err := m.cli.ReadCoil(uint16(mdm.Addr), uint16(mdm.Quantity))
if err != nil {
slog.Error("Modbus驱动采集服务读取线圈失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
err = m.updateDcByBits(mdm, data)
if err != nil {
slog.Error("Modbus驱动采集服务更新驱采数据失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
case sproto.Modbus_ReadDiscreteInput:
data, err := m.cli.ReadDiscreteInput(uint16(mdm.Addr), uint16(mdm.Quantity))
if err != nil {
slog.Error("Modbus驱动采集服务读取离散输入失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
err = m.updateDcByBits(mdm, data)
if err != nil {
slog.Error("Modbus驱动采集服务更新驱采数据失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
case sproto.Modbus_ReadHoldingRegister, sproto.Modbus_RWRegisters:
data, err := m.cli.ReadHoldingRegisterBytes(uint16(mdm.Addr), uint16(mdm.Quantity*2))
if err != nil {
slog.Error("Modbus驱动采集服务读取保持寄存器失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
err = m.updateDcByBytes(mdm, data)
if err != nil {
slog.Error("Modbus驱动采集服务更新驱采数据失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
case sproto.Modbus_ReadInputRegister:
data, err := m.cli.ReadInputRegisterBytes(uint16(mdm.Addr), uint16(mdm.Quantity*2))
if err != nil {
slog.Error("Modbus驱动采集服务读取输入寄存器失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
err = m.updateDcByBytes(mdm, data)
if err != nil {
slog.Error("Modbus驱动采集服务更新驱采数据失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
case sproto.Modbus_WriteCoil:
if mdm.WriteStrategy == sproto.Modbus_OnScheduled { // 定时写
bits := m.GetDcBits(mdm)
err := m.cli.WriteCoil(uint16(mdm.Addr), bits[0])
if err != nil {
slog.Error("Modbus驱动采集服务写单线圈失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
}
case sproto.Modbus_WriteCoils:
if mdm.WriteStrategy == sproto.Modbus_OnScheduled { // 定时写
bits := m.GetDcBits(mdm)
err := m.cli.WriteCoils(uint16(mdm.Addr), bits)
if err != nil {
slog.Error("Modbus驱动采集服务写多线圈失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
}
case sproto.Modbus_WriteRegister:
if mdm.WriteStrategy == sproto.Modbus_OnScheduled { // 定时写
data := m.GetDcBytes(mdm)
err := m.cli.WriteRegisterBytes(uint16(mdm.Addr), data)
if err != nil {
slog.Error("Modbus驱动采集服务写单寄存器失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
}
case sproto.Modbus_WriteRegisters:
if mdm.WriteStrategy == sproto.Modbus_OnScheduled { // 定时写
data := m.GetDcBytes(mdm)
err := m.cli.WriteRegisterBytes(uint16(mdm.Addr), data)
if err != nil {
slog.Error("Modbus驱动采集服务写多寄存器失败", "url", m.config.Url, "error", err)
2023-12-08 18:08:15 +08:00
continue
}
}
}
}
} else {
slog.Error("Modbus驱动采集服务映射任务执行失败,Modbus未连接", "url", m.config.Url)
2023-12-08 18:08:15 +08:00
}
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) GetDcBits(mdm *sproto.ModbusDcMapping) []bool {
2023-12-08 18:08:15 +08:00
switch mdm.Type {
case sproto.DataType_CollectTable: // 采集数据
2023-12-13 11:03:21 +08:00
return m.qc.GetCollectBits(mdm.Start, mdm.Quantity)
2023-12-08 18:08:15 +08:00
case sproto.DataType_DriveTable: // 驱动数据
2023-12-13 11:03:21 +08:00
return m.qc.GetDriveBits(mdm.Start, mdm.Quantity)
2023-12-08 18:08:15 +08:00
default:
panic("未知数据类型")
}
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) GetDcBytes(mdm *sproto.ModbusDcMapping) []byte {
2023-12-08 18:08:15 +08:00
switch mdm.Type {
case sproto.DataType_CollectTable: // 采集数据
2023-12-13 11:03:21 +08:00
return m.qc.GetCollectBytes(mdm.Start, mdm.Quantity*2)
2023-12-08 18:08:15 +08:00
case sproto.DataType_DriveTable: // 驱动数据
2023-12-13 11:03:21 +08:00
return m.qc.GetDriveBytes(mdm.Start, mdm.Quantity*2)
2023-12-08 18:08:15 +08:00
default:
panic("未知数据类型")
}
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) updateDcByBits(mdm *sproto.ModbusDcMapping, bits []bool) error {
2023-12-08 18:08:15 +08:00
switch mdm.Type {
case sproto.DataType_CollectTable: // 采集数据
2023-12-13 11:03:21 +08:00
return m.qc.UpdateCollectByBits(mdm.Start, bits)
2023-12-08 18:08:15 +08:00
case sproto.DataType_DriveTable: // 驱动数据
2023-12-13 11:03:21 +08:00
return m.qc.UpdateDriveByBits(mdm.Start, bits)
2023-12-08 18:08:15 +08:00
}
return nil
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) updateDcByBytes(mdm *sproto.ModbusDcMapping, bytes []byte) error {
2023-12-08 18:08:15 +08:00
switch mdm.Type {
case sproto.DataType_CollectTable: // 采集数据
2023-12-13 11:03:21 +08:00
return m.qc.UpdateCollectByBytes(mdm.Start, bytes)
2023-12-08 18:08:15 +08:00
case sproto.DataType_DriveTable: // 驱动数据
2023-12-13 11:03:21 +08:00
return m.qc.UpdateDriveByBytes(mdm.Start, bytes)
2023-12-08 18:08:15 +08:00
}
return nil
}
func checkConfig(config *sproto.ModbusConfig) error {
if config.Url == "" {
return fmt.Errorf("Modbus配置未设置url")
}
if !strings.HasPrefix(config.Url, "tcp") {
return fmt.Errorf("Modbus配置url必须以tcp开头")
}
if config.UnitId == 0 {
return fmt.Errorf("Modbus配置未设置unitId")
}
if config.Interval == 0 {
return fmt.Errorf("Modbus配置未设置interval")
}
if len(config.Mapping) == 0 {
return fmt.Errorf("Modbus配置无映射配置")
}
return nil
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) Start() error {
2023-12-08 18:08:15 +08:00
return nil
}
2023-12-13 11:03:21 +08:00
func (m *modbusQcService) Stop() error {
2023-12-08 18:08:15 +08:00
m.cancel()
2023-12-15 18:08:06 +08:00
<-m.done
slog.Info("Modbus驱采映射服务线程退出", "url", m.config.Url)
2023-12-08 18:08:15 +08:00
return nil
}
func convertEndianness(endianness sproto.Modbus_Endianness) modbus.Endianness {
switch endianness {
case sproto.Modbus_BigEndian:
return modbus.BigEndian
case sproto.Modbus_LittleEndian:
return modbus.LittleEndian
}
return modbus.BigEndian
}