-
Notifications
You must be signed in to change notification settings - Fork 387
/
MessageCodec.go
290 lines (266 loc) · 8.92 KB
/
MessageCodec.go
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package bacnetip
import (
"context"
"fmt"
"github.com/apache/plc4x/plc4go/spi/options"
"github.com/rs/zerolog"
"net"
"net/url"
"time"
"github.com/apache/plc4x/plc4go/protocols/bacnetip/readwrite/model"
"github.com/apache/plc4x/plc4go/spi"
"github.com/apache/plc4x/plc4go/spi/default"
"github.com/apache/plc4x/plc4go/spi/transports"
"github.com/apache/plc4x/plc4go/spi/transports/udp"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
// ApplicationLayerMessageCodec is a wrapper for MessageCodec which takes care of segmentation, retries etc.
//
//go:generate go run ../../tools/plc4xgenerator/gen.go -type=ApplicationLayerMessageCodec
type ApplicationLayerMessageCodec struct {
bipSimpleApplication *BIPSimpleApplication
messageCode *MessageCodec
deviceInfoCache DeviceInfoCache
localAddress *net.UDPAddr `stringer:"true"`
remoteAddress *net.UDPAddr `stringer:"true"`
}
func NewApplicationLayerMessageCodec(udpTransport *udp.Transport, transportUrl url.URL, options map[string][]string, localAddress *net.UDPAddr, remoteAddress *net.UDPAddr) (*ApplicationLayerMessageCodec, error) {
// TODO: currently this is done by the BIP down below
// Have the transport create a new transport-instance.
//transportInstance, err := udpTransport.CreateTransportInstanceForLocalAddress(transportUrl, options, localAddress)
//if err != nil {
// return nil, errors.Wrap(err, "error creating transport instance")
//}
a := &ApplicationLayerMessageCodec{
localAddress: localAddress,
remoteAddress: remoteAddress,
}
address, err := NewAddress(localAddress)
if err != nil {
return nil, errors.Wrap(err, "error creating address")
}
// TODO: workaround for strange address parsing
at := AddressTuple[string, uint16]{fmt.Sprintf("%d.%d.%d.%d", address.AddrAddress[0], address.AddrAddress[1], address.AddrAddress[2], address.AddrAddress[3]), *address.AddrPort}
address.AddrTuple = &at
application, err := NewBIPSimpleApplication(&LocalDeviceObject{
NumberOfAPDURetries: func() *uint { retries := uint(10); return &retries }(),
}, *address, &a.deviceInfoCache, nil)
if err != nil {
return nil, err
}
a.bipSimpleApplication = application
// TODO: this is currently done by the BIP
//a.messageCode = NewMessageCodec(transportInstance)
return a, nil
}
func (m *ApplicationLayerMessageCodec) GetCodec() spi.MessageCodec {
return m
}
func (m *ApplicationLayerMessageCodec) Connect() error {
// TODO: this is currently done by the BIP
// return m.messageCode.Connect()
return nil
}
func (m *ApplicationLayerMessageCodec) ConnectWithContext(ctx context.Context) error {
// TODO: this is currently done by the BIP
// return m.messageCode.ConnectWithContext(ctx)
return nil
}
func (m *ApplicationLayerMessageCodec) Disconnect() error {
if err := m.bipSimpleApplication.Close(); err != nil {
log.Error().Err(err).Msg("error closing application")
}
return m.messageCode.Disconnect()
}
func (m *ApplicationLayerMessageCodec) IsRunning() bool {
return m.messageCode.IsRunning()
}
func (m *ApplicationLayerMessageCodec) Send(message spi.Message) error {
address, err := NewAddress(m.remoteAddress)
if err != nil {
return err
}
iocb, err := NewIOCB(NewPDU(message, WithPDUDestination(address)), address)
if err != nil {
return errors.Wrap(err, "error creating IOCB")
}
go func() {
go func() {
if err := m.bipSimpleApplication.RequestIO(iocb); err != nil {
log.Debug().Err(err).Msg("errored")
}
}()
iocb.Wait()
if iocb.ioError != nil {
// TODO: handle error
fmt.Printf("Err: %v\n", iocb.ioError)
} else if iocb.ioResponse != nil {
// TODO: response?
fmt.Printf("Response: %v\n", iocb.ioResponse)
} else {
// TODO: what now?
}
}()
return nil
}
func (m *ApplicationLayerMessageCodec) Expect(ctx context.Context, acceptsMessage spi.AcceptsMessage, handleMessage spi.HandleMessage, handleError spi.HandleError, ttl time.Duration) error {
// TODO: implement me
panic("not yet implemented")
}
func (m *ApplicationLayerMessageCodec) SendRequest(ctx context.Context, message spi.Message, acceptsMessage spi.AcceptsMessage, handleMessage spi.HandleMessage, handleError spi.HandleError, ttl time.Duration) error {
address, err := NewAddress(m.remoteAddress)
if err != nil {
return err
}
iocb, err := NewIOCB(NewPDU(message, WithPDUDestination(address)), address)
if err != nil {
return errors.Wrap(err, "error creating IOCB")
}
go func() {
go func() {
if err := m.bipSimpleApplication.RequestIO(iocb); err != nil {
}
}()
iocb.Wait()
if err := iocb.ioError; err != nil {
if err := handleError(err); err != nil {
log.Debug().Err(err).Msg("error handling error")
return
}
} else if response := iocb.ioResponse; response != nil {
// TODO: we wrap it into a BVLC for now. Once we change the Readers etc. to accept apdus we can remove that
tempBVLC := model.NewBVLCOriginalUnicastNPDU(
model.NewNPDU(
0,
model.NewNPDUControl(
false,
false,
false,
false,
model.NPDUNetworkPriority_NORMAL_MESSAGE,
),
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
response.GetMessage().(model.APDU),
0,
),
0,
)
if acceptsMessage(tempBVLC) {
if err := handleMessage(
tempBVLC,
); err != nil {
log.Debug().Err(err).Msg("error handling message")
return
}
}
} else {
// TODO: what now?
}
}()
return nil
}
func (m *ApplicationLayerMessageCodec) GetDefaultIncomingMessageChannel() chan spi.Message {
// TODO: this is currently done by the BIP
//return m.messageCode.GetDefaultIncomingMessageChannel()
return make(chan spi.Message)
}
//go:generate go run ../../tools/plc4xgenerator/gen.go -type=MessageCodec
type MessageCodec struct {
_default.DefaultCodec
passLogToModel bool
log zerolog.Logger `ignore:"true"`
}
func NewMessageCodec(transportInstance transports.TransportInstance) *MessageCodec {
codec := &MessageCodec{}
codec.DefaultCodec = _default.NewDefaultCodec(codec, transportInstance, _default.WithCustomMessageHandler(codec.handleCustomMessage))
return codec
}
func (m *MessageCodec) GetCodec() spi.MessageCodec {
return m
}
func (m *MessageCodec) Send(message spi.Message) error {
log.Trace().Msg("Sending message")
// Cast the message to the correct type of struct
bvlcPacket := message.(model.BVLC)
// Serialize the request
theBytes, err := bvlcPacket.Serialize()
if err != nil {
return errors.Wrap(err, "error serializing request")
}
// Send it to the PLC
err = m.GetTransportInstance().Write(theBytes)
if err != nil {
return errors.Wrap(err, "error sending request")
}
return nil
}
func (m *MessageCodec) Receive() (spi.Message, error) {
// We need at least 6 bytes in order to know how big the packet is in total
if num, err := m.GetTransportInstance().GetNumBytesAvailableInBuffer(); (err == nil) && (num >= 4) {
log.Debug().Uint32("num", num).Msg("we got num readable bytes")
data, err := m.GetTransportInstance().PeekReadableBytes(4)
if err != nil {
log.Warn().Err(err).Msg("error peeking")
// TODO: Possibly clean up ...
return nil, nil
}
packetSize := uint32((uint16(data[2]) << 8) + uint16(data[3]))
if num < packetSize {
log.Debug().
Uint32("num", num).
Uint32("packetSize", packetSize).
Msg("Not enough bytes. Got: num Need: packetSize")
return nil, nil
}
data, err = m.GetTransportInstance().Read(packetSize)
if err != nil {
log.Debug().Err(err).Msg("Error reading")
// TODO: Possibly clean up ...
return nil, nil
}
ctxForModel := options.GetLoggerContextForModel(context.TODO(), m.log, options.WithPassLoggerToModel(m.passLogToModel))
bvlcPacket, err := model.BVLCParse(ctxForModel, data)
if err != nil {
log.Warn().Err(err).Msg("error parsing")
// TODO: Possibly clean up ...
return nil, nil
}
return bvlcPacket, nil
} else if err != nil {
log.Warn().Err(err).Msg("Got error reading")
return nil, nil
}
// TODO: maybe we return here a not enough error error
return nil, nil
}
func (m *MessageCodec) handleCustomMessage(_ _default.DefaultCodecRequirements, message spi.Message) bool {
// For now, we just put them in the incoming channel
m.GetDefaultIncomingMessageChannel() <- message
return true
}