fix
zhangqian
2023-12-09 c0fa4c8f502607f739ce3c91099b7fb7573258ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package service
 
import (
    "apsClient/conf"
    "apsClient/constvar"
    "apsClient/model"
    "apsClient/model/common"
    "apsClient/pkg/logx"
    "apsClient/pkg/plc"
    "apsClient/pkg/plc/apacheplc4x"
    "apsClient/pkg/plc/modbusx"
    "apsClient/pkg/plccom"
    "encoding/binary"
    "errors"
    "fmt"
    "github.com/spf13/cast"
    "sync"
)
 
// 串口不支持并行读写,所以需要加个锁,防止timeout和资源不可用报错
var lock sync.Mutex
 
func PlcWrite(plcConfig *model.DevicePlc, fieldType constvar.PlcStartAddressType, channel int32, value interface{}) (err error) {
    var (
        startAddress int
    )
 
    if plcConfig.CurrentTryTimes > plcConfig.MaxTryTimes {
        return plcConfig.CurrentErr
    }
    plcConfig.CurrentTryTimes++
 
    for _, pc := range plcConfig.Details {
        if pc.FieldName == fieldType && pc.Channel == channel {
            startAddress = pc.StartAddress
        }
    }
    return PlcWriteDirect(plcConfig, startAddress, value)
}
 
func PlcWriteDirect(plcConfig *model.DevicePlc, address int, value interface{}) (err error) {
    lock.Lock()
    defer lock.Unlock()
    var (
        ipAddr string
    )
    defer func() {
        dealErr(err)
    }()
    if plcConfig.Method == constvar.PlcMethodModbusTCP {
        ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
        err = WriteByModbusTCP(ipAddr, address, value)
 
        if err != nil {
            logx.Errorf("plc write failed, address: %v, value: %v, err: %v", address, value, err.Error())
            return err
        }
        logx.Infof("plc write ok, address: %v, value: %v", address, value)
    } else if plcConfig.Method == constvar.PlcMethodModbusRTU {
        ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
        err = WriteByModbusRTU(plcConfig, address, value)
 
        if err != nil {
            logx.Errorf("plc write failed, address: %v, value: %v, err: %v", address, value, err.Error())
            return err
        }
        logx.Infof("plc write ok, address: %v, value: %v", address, value)
    } else if plcConfig.Method == constvar.PlcMethodSerial {
        ipAddr = conf.Conf.Services.Serial
        if ipAddr == "" {
            return errors.New("conf.Conf.Services.Serial config not set yet")
        }
        label := fmt.Sprintf("D%d", address)
        return plccom.WritePLC(plccom.DeviceTypeMitsubishi, ipAddr, label, cast.ToInt(value))
    }
    return
}
 
func PlcReadDirect(plcConfig *model.DevicePlc, address int, dataLength int, valueType constvar.PlcStartAddressValueType) (val interface{}, err error) {
    lock.Lock()
    defer lock.Unlock()
    var (
        ipAddr string
    )
    defer func() {
        dealErr(err)
    }()
    if plcConfig.Method == constvar.PlcMethodModbusTCP || plcConfig.Method == constvar.PlcMethodModbusRTU {
        var value []byte
        if plcConfig.Method == constvar.PlcMethodModbusTCP {
            ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
            value, err = ReadByModbusTCP(ipAddr, address, dataLength)
            if err != nil {
                return nil, err
            }
        } else {
            value, err = ReadByModbusRTU(plcConfig, address, dataLength)
            if err != nil {
                return nil, err
            }
        }
 
        switch valueType {
        case constvar.PlcStartAddressValueTypeString:
            return string(value), nil
        case constvar.PlcStartAddressValueTypeInt32:
            if len(value) == 2 {
                val = binary.BigEndian.Uint16(value)
            } else if len(value) == 4 {
                val = binary.BigEndian.Uint32(value)
            } else {
                logx.Errorf("plc read get an unknown int value: %v, address:%v", value, address)
                return nil, errors.New(fmt.Sprintf("unknown int value:%v", value))
            }
        default:
            if len(value) == 2 {
                val = binary.BigEndian.Uint16(value)
            } else if len(value) == 4 {
                low16Val := uint32(binary.BigEndian.Uint16(value[:2]))
                high16 := uint32(binary.BigEndian.Uint16(value[2:])) << 16
                val = low16Val + high16
            } else {
                logx.Errorf("plc read get an unknown int value: %v, address:%v", value, address)
                return nil, errors.New(fmt.Sprintf("unknown int value:%v", value))
            }
        }
        logx.Infof("plc read ok, address: %v, result: %v, dataLength: %v, value: %v", address, val, dataLength, value)
        return val, nil
    } else if plcConfig.Method == constvar.PlcMethodSerial {
        ipAddr = conf.Conf.Services.Serial
        if ipAddr == "" {
            return nil, errors.New("conf.Conf.Services.Serial config not set yet")
        }
        label := fmt.Sprintf("D%d", address)
        return plccom.ReadPLC(plccom.DeviceTypeMitsubishi, ipAddr, label, dataLength)
    }
    return
}
 
func ReadByModbusTCP(ipAddr string, address, length int) ([]byte, error) {
    if conf.Conf.PLC.Package == constvar.PlcPackageApache {
        return apacheplc4x.ReadHoldingRegister(ipAddr, address, length)
    } else if conf.Conf.PLC.Package == constvar.PlcPackageApacheLongConnection {
        conn, err := plc.GetModbusConnection(ipAddr)
        if err != nil {
            return nil, err
        }
        return plc.ReadHoldingRegister(conn, address, length)
    } else {
        return modbusx.Read(ipAddr, uint16(address), uint16(length))
    }
}
 
func WriteByModbusTCP(ipAddr string, address int, value any) (err error) {
    if conf.Conf.PLC.Package == constvar.PlcPackageApache {
        _, err = apacheplc4x.WriteHoldingRegister(ipAddr, address, value)
        return err
    } else if conf.Conf.PLC.Package == constvar.PlcPackageApacheLongConnection {
        conn, err := plc.GetModbusConnection(ipAddr)
        if err != nil {
            return err
        }
        _, err = plc.WriteHoldingRegister(conn, address, value)
        return err
    } else {
        return modbusx.Write(ipAddr, uint16(address), cast.ToInt(value))
    }
}
 
func ReadByModbusRTU(plcConfig *model.DevicePlc, address, length int) ([]byte, error) {
    rtuConfig := &common.RTUConfig{
        BaudRate:   plcConfig.BaudRate,
        SerialName: plcConfig.SerialName,
        DataBit:    plcConfig.DataBit,
        StopBit:    plcConfig.StopBit,
        Parity:     plcConfig.Parity,
    }
    if conf.Conf.PLC.Package == constvar.PlcPackageApache {
        return apacheplc4x.ReadHoldingRegisterByRTU(rtuConfig, address, length)
    } else {
        return modbusx.ReadByRTU(rtuConfig, uint16(address), uint16(length))
    }
}
 
func WriteByModbusRTU(plcConfig *model.DevicePlc, address int, value any) (err error) {
    rtuConfig := &common.RTUConfig{
        BaudRate:   plcConfig.BaudRate,
        SerialName: plcConfig.SerialName,
        DataBit:    plcConfig.DataBit,
        StopBit:    plcConfig.StopBit,
        Parity:     plcConfig.Parity,
    }
    if conf.Conf.PLC.Package == constvar.PlcPackageApache {
        _, err = apacheplc4x.WriteHoldingRegisterByRTU(rtuConfig, address, value)
        return err
    } else {
        return modbusx.WriteByRTU(rtuConfig, uint16(address), cast.ToInt(value))
    }
}
 
func PlcIsConnect() bool {
    return IsConnect()
}
 
func dealErr(err error) {
    if err != nil {
        FailureRemainingOpportunitiesDecr() //减少失败剩余机会
    } else {
        FailureRemainingOpportunitiesReset() //重置失败剩余机会
    }
}
 
var connectionStatus sync.Map
 
const (
    defaultFailureRemainingOpportunities = 20
)
 
func IsConnect() bool {
    val, ok := connectionStatus.Load(conf.Conf.CurrentDeviceID)
    if !ok {
        return false
    }
    failureRemainingOpportunities := val.(int)
    return failureRemainingOpportunities > 0
}
 
func FailureRemainingOpportunitiesDecr() {
    val, ok := connectionStatus.Load(conf.Conf.CurrentDeviceID)
    if !ok {
        return
    }
    failureRemainingOpportunities := val.(int)
    if failureRemainingOpportunities > 0 {
        failureRemainingOpportunities--
    }
    connectionStatus.Store(conf.Conf.CurrentDeviceID, failureRemainingOpportunities)
    return
}
 
func FailureRemainingOpportunitiesReset() {
    val, ok := connectionStatus.Load(conf.Conf.CurrentDeviceID)
    if !ok || val.(int) < defaultFailureRemainingOpportunities {
        connectionStatus.Store(conf.Conf.CurrentDeviceID, defaultFailureRemainingOpportunities)
        return
    }
    return
}