/
Subscriber.go
461 lines (422 loc) · 19 KB
/
Subscriber.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
* 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 cbus
import (
"context"
"fmt"
"runtime/debug"
"strings"
"sync"
"time"
apiModel "github.com/apache/plc4x/plc4go/pkg/api/model"
apiValues "github.com/apache/plc4x/plc4go/pkg/api/values"
readWriteModel "github.com/apache/plc4x/plc4go/protocols/cbus/readwrite/model"
spiModel "github.com/apache/plc4x/plc4go/spi/model"
"github.com/apache/plc4x/plc4go/spi/options"
spiValues "github.com/apache/plc4x/plc4go/spi/values"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
//go:generate go run ../../tools/plc4xgenerator/gen.go -type=Subscriber
type Subscriber struct {
consumers map[*spiModel.DefaultPlcConsumerRegistration]apiModel.PlcSubscriptionEventConsumer `hasLocker:"consumersMutex"`
addSubscriber func(subscriber *Subscriber)
consumersMutex sync.RWMutex
log zerolog.Logger `ignore:"true"`
_options []options.WithOption `ignore:"true"` // Used to pass them downstream
}
func NewSubscriber(addSubscriber func(subscriber *Subscriber), _options ...options.WithOption) *Subscriber {
customLogger := options.ExtractCustomLoggerOrDefaultToGlobal(_options...)
return &Subscriber{
addSubscriber: addSubscriber,
consumers: make(map[*spiModel.DefaultPlcConsumerRegistration]apiModel.PlcSubscriptionEventConsumer),
log: customLogger,
_options: _options,
}
}
func (s *Subscriber) Subscribe(_ context.Context, subscriptionRequest apiModel.PlcSubscriptionRequest) <-chan apiModel.PlcSubscriptionRequestResult {
result := make(chan apiModel.PlcSubscriptionRequestResult, 1)
go func() {
defer func() {
if err := recover(); err != nil {
result <- spiModel.NewDefaultPlcSubscriptionRequestResult(subscriptionRequest, nil, errors.Errorf("panic-ed %v. Stack: %s", err, debug.Stack()))
}
}()
internalPlcSubscriptionRequest := subscriptionRequest.(*spiModel.DefaultPlcSubscriptionRequest)
// Add this subscriber to the connection.
s.addSubscriber(s)
// Just populate all requests with an OK
responseCodes := map[string]apiModel.PlcResponseCode{}
subscriptionValues := make(map[string]apiModel.PlcSubscriptionHandle)
for _, tagName := range internalPlcSubscriptionRequest.GetTagNames() {
responseCodes[tagName] = apiModel.PlcResponseCode_OK
handle := NewSubscriptionHandle(
s,
tagName,
internalPlcSubscriptionRequest.GetTag(tagName),
internalPlcSubscriptionRequest.GetType(tagName),
internalPlcSubscriptionRequest.GetInterval(tagName),
)
preRegisteredConsumers := internalPlcSubscriptionRequest.GetPreRegisteredConsumers(tagName)
for _, consumer := range preRegisteredConsumers {
_ = handle.Register(consumer)
}
subscriptionValues[tagName] = handle
}
result <- spiModel.NewDefaultPlcSubscriptionRequestResult(
subscriptionRequest,
spiModel.NewDefaultPlcSubscriptionResponse(
subscriptionRequest,
responseCodes,
subscriptionValues,
append(s._options, options.WithCustomLogger(s.log))...,
),
nil,
)
}()
return result
}
func (s *Subscriber) Unsubscribe(ctx context.Context, unsubscriptionRequest apiModel.PlcUnsubscriptionRequest) <-chan apiModel.PlcUnsubscriptionRequestResult {
// TODO: handle context
result := make(chan apiModel.PlcUnsubscriptionRequestResult, 1)
result <- spiModel.NewDefaultPlcUnsubscriptionRequestResult(unsubscriptionRequest, nil, errors.New("Not Implemented"))
// TODO: As soon as we establish a connection, we start getting data...
// subscriptions are more a internal handling of which values to pass where.
_ = ctx
_ = unsubscriptionRequest
return result
}
func (s *Subscriber) handleMonitoredMMI(calReply readWriteModel.CALReply) bool {
s.log.Debug().Stringer("calReply", calReply).Msg("handling")
var unitAddressString string
switch calReply := calReply.(type) {
case readWriteModel.CALReplyLongExactly:
if calReply.GetIsUnitAddress() {
unitAddressString = fmt.Sprintf("u%d", calReply.GetUnitAddress().GetAddress())
} else {
unitAddressString = fmt.Sprintf("b%d", calReply.GetBridgeAddress().GetAddress())
replyNetwork := calReply.GetReplyNetwork()
for _, bridgeAddress := range replyNetwork.GetNetworkRoute().GetAdditionalBridgeAddresses() {
unitAddressString += fmt.Sprintf("-b%d", bridgeAddress.GetAddress())
}
unitAddressString += fmt.Sprintf("-u%d", replyNetwork.GetUnitAddress().GetAddress())
}
default:
unitAddressString = "u0" // On short form it should be always unit 0 TODO: double check that
}
s.log.Debug().Str("unitAddressString", unitAddressString).Msg("Unit address string")
calData := calReply.GetCalData()
handled := false
s.consumersMutex.RLock()
defer s.consumersMutex.RUnlock()
for registration, consumer := range s.consumers {
s.log.Debug().
Stringer("registration", registration).
Interface("consumer", consumer).
Msg("Checking with registration and consumer")
for _, subscriptionHandle := range registration.GetSubscriptionHandles() {
s.log.Debug().Stringer("subscriptionHandle", subscriptionHandle).Msg("offering to")
handleHandled := s.offerMMI(unitAddressString, calData, subscriptionHandle.(*SubscriptionHandle), consumer)
s.log.Debug().Bool("handleHandled", handleHandled).Msg("handle handled")
handled = handled || handleHandled
}
}
s.log.Debug().Bool("handled", handled).Msg("final handled")
return handled
}
func (s *Subscriber) offerMMI(unitAddressString string, calData readWriteModel.CALData, subscriptionHandle *SubscriptionHandle, consumer apiModel.PlcSubscriptionEventConsumer) bool {
tag, ok := subscriptionHandle.tag.(*mmiMonitorTag)
if !ok {
s.log.Debug().
Interface("tag", subscriptionHandle.tag).
Msg("Unusable tag for mmi subscription")
return false
}
tags := map[string]apiModel.PlcTag{}
types := map[string]apiModel.PlcSubscriptionType{}
intervals := map[string]time.Duration{}
responseCodes := map[string]apiModel.PlcResponseCode{}
address := map[string]string{}
sources := map[string]string{}
plcValues := map[string]apiValues.PlcValue{}
tagName := subscriptionHandle.tagName
if unitAddress := tag.GetUnitAddress(); unitAddress != nil {
unitSuffix := fmt.Sprintf("u%d", unitAddress.GetAddress())
if !strings.HasSuffix(unitAddressString, unitSuffix) {
s.log.Debug().
Str("unitAddressString", unitAddressString).
Str("unitSuffix", unitSuffix).
Msg("Current address string unitAddressString has not the suffix unitSuffix")
return false
}
}
sources[tagName] = unitAddressString
subscriptionType := subscriptionHandle.subscriptionType
// TODO: handle subscriptionType
_ = subscriptionType
tags[tagName] = tag
types[tagName] = subscriptionHandle.subscriptionType
intervals[tagName] = subscriptionHandle.interval
var applicationString string
isLevel := true
blockStart := byte(0x0)
// var application readWriteModel.ApplicationIdContainer
switch calData := calData.(type) {
case readWriteModel.CALDataStatusExactly:
application := calData.GetApplication()
applicationString = application.ApplicationId().String()
blockStart = calData.GetBlockStart()
statusBytes := calData.GetStatusBytes()
responseCodes[tagName] = apiModel.PlcResponseCode_OK
plcListValues := make([]apiValues.PlcValue, len(statusBytes)*4)
for i, statusByte := range statusBytes {
plcListValues[i*4+0] = spiValues.NewPlcSTRING(statusByte.GetGav0().String())
plcListValues[i*4+1] = spiValues.NewPlcSTRING(statusByte.GetGav1().String())
plcListValues[i*4+2] = spiValues.NewPlcSTRING(statusByte.GetGav2().String())
plcListValues[i*4+3] = spiValues.NewPlcSTRING(statusByte.GetGav3().String())
}
plcValues[tagName] = spiValues.NewPlcStruct(map[string]apiValues.PlcValue{
"application": spiValues.NewPlcSTRING(application.PLC4XEnumName()),
"blockStart": spiValues.NewPlcBYTE(blockStart),
"values": spiValues.NewPlcList(plcListValues),
})
case readWriteModel.CALDataStatusExtendedExactly:
application := calData.GetApplication()
applicationString = application.ApplicationId().String()
isLevel = calData.GetCoding() == readWriteModel.StatusCoding_LEVEL_BY_ELSEWHERE || calData.GetCoding() == readWriteModel.StatusCoding_LEVEL_BY_THIS_SERIAL_INTERFACE
blockStart = calData.GetBlockStart()
coding := calData.GetCoding()
switch coding {
case readWriteModel.StatusCoding_BINARY_BY_THIS_SERIAL_INTERFACE:
fallthrough
case readWriteModel.StatusCoding_BINARY_BY_ELSEWHERE:
statusBytes := calData.GetStatusBytes()
responseCodes[tagName] = apiModel.PlcResponseCode_OK
plcListValues := make([]apiValues.PlcValue, len(statusBytes)*4)
for i, statusByte := range statusBytes {
plcListValues[i*4+0] = spiValues.NewPlcSTRING(statusByte.GetGav0().String())
plcListValues[i*4+1] = spiValues.NewPlcSTRING(statusByte.GetGav1().String())
plcListValues[i*4+2] = spiValues.NewPlcSTRING(statusByte.GetGav2().String())
plcListValues[i*4+3] = spiValues.NewPlcSTRING(statusByte.GetGav3().String())
}
plcValues[tagName] = spiValues.NewPlcStruct(map[string]apiValues.PlcValue{
"application": spiValues.NewPlcSTRING(application.PLC4XEnumName()),
"blockStart": spiValues.NewPlcBYTE(blockStart),
"values": spiValues.NewPlcList(plcListValues),
})
case readWriteModel.StatusCoding_LEVEL_BY_THIS_SERIAL_INTERFACE:
fallthrough
case readWriteModel.StatusCoding_LEVEL_BY_ELSEWHERE:
levelInformation := calData.GetLevelInformation()
responseCodes[tagName] = apiModel.PlcResponseCode_OK
plcListValues := make([]apiValues.PlcValue, len(levelInformation))
for i, levelInformation := range levelInformation {
switch levelInformation := levelInformation.(type) {
case readWriteModel.LevelInformationAbsentExactly:
plcListValues[i] = spiValues.NewPlcSTRING("is absent")
case readWriteModel.LevelInformationCorruptedExactly:
plcListValues[i] = spiValues.NewPlcSTRING("corrupted")
case readWriteModel.LevelInformationNormalExactly:
plcListValues[i] = spiValues.NewPlcUSINT(levelInformation.GetActualLevel())
}
}
plcValues[tagName] = spiValues.NewPlcList(plcListValues)
}
default:
s.log.Error().Type("calData", calData).Msg("Unmapped type")
return false
}
if application := tag.GetApplication(); application != nil {
if actualApplicationIdString := application.ApplicationId().String(); applicationString != actualApplicationIdString {
s.log.Debug().
Str("unitAddressString", unitAddressString).
Str("actualApplicationIdString", actualApplicationIdString).
Msg("Current application id unitAddressString doesn't match actual id actualApplicationIdString")
return false
}
}
statusType := "binary"
if isLevel {
statusType = fmt.Sprintf("level=%#02X", blockStart)
}
address[tagName] = fmt.Sprintf("status/%s/%s", statusType, applicationString)
// Assemble a PlcSubscription event
event := NewSubscriptionEvent(tags, types, intervals, responseCodes, address, sources, plcValues)
consumer(&event)
return true
}
func (s *Subscriber) handleMonitoredSAL(sal readWriteModel.MonitoredSAL) bool {
handled := false
s.consumersMutex.RLock()
defer s.consumersMutex.RUnlock()
for registration, consumer := range s.consumers {
for _, subscriptionHandle := range registration.GetSubscriptionHandles() {
handled = handled || s.offerSAL(sal, subscriptionHandle.(*SubscriptionHandle), consumer)
}
}
return handled
}
func (s *Subscriber) offerSAL(sal readWriteModel.MonitoredSAL, subscriptionHandle *SubscriptionHandle, consumer apiModel.PlcSubscriptionEventConsumer) bool {
tag, ok := subscriptionHandle.tag.(*salMonitorTag)
if !ok {
s.log.Debug().Interface("tag", subscriptionHandle.tag).Msg("Unusable tag for mmi subscription")
return false
}
tags := map[string]apiModel.PlcTag{}
types := map[string]apiModel.PlcSubscriptionType{}
intervals := map[string]time.Duration{}
responseCodes := map[string]apiModel.PlcResponseCode{}
address := map[string]string{}
sources := map[string]string{}
plcValues := map[string]apiValues.PlcValue{}
tagName := subscriptionHandle.tagName
subscriptionType := subscriptionHandle.subscriptionType
// TODO: handle subscriptionType
_ = subscriptionType
tags[tagName] = tag
types[tagName] = subscriptionType
intervals[tagName] = subscriptionHandle.interval
var salData readWriteModel.SALData
var unitAddressString, applicationString string
switch sal := sal.(type) {
case readWriteModel.MonitoredSALShortFormBasicModeExactly:
unitAddressString = "u0" // On short form it should be always unit 0 TODO: double check that
applicationString = sal.GetApplication().ApplicationId().String()
salData = sal.GetSalData()
case readWriteModel.MonitoredSALLongFormSmartModeExactly:
if sal.GetIsUnitAddress() {
unitAddressString = fmt.Sprintf("u%d", sal.GetUnitAddress().GetAddress())
} else {
unitAddressString = fmt.Sprintf("b%d", sal.GetBridgeAddress().GetAddress())
replyNetwork := sal.GetReplyNetwork()
for _, bridgeAddress := range replyNetwork.GetNetworkRoute().GetAdditionalBridgeAddresses() {
unitAddressString += fmt.Sprintf("-b%d", bridgeAddress.GetAddress())
}
unitAddressString += fmt.Sprintf("-u%d", replyNetwork.GetUnitAddress().GetAddress())
}
applicationString = sal.GetApplication().ApplicationId().String()
salData = sal.GetSalData()
}
if unitAddress := tag.GetUnitAddress(); unitAddress != nil {
unitSuffix := fmt.Sprintf("u%d", unitAddress.GetAddress())
if !strings.HasSuffix(unitAddressString, unitSuffix) {
s.log.Debug().
Str("unitAddressString", unitAddressString).
Str("unitSuffix", unitSuffix).
Msg("Current address string unitAddressString has not the suffix unitSuffix")
return false
}
}
sources[tagName] = unitAddressString
if application := tag.GetApplication(); application != nil {
if actualApplicationIdString := application.ApplicationId().String(); applicationString != actualApplicationIdString {
s.log.Debug().
Str("unitAddressString", unitAddressString).
Str("actualApplicationIdString", actualApplicationIdString).
Msg("Current application id unitAddressString doesn't match actual id actualApplicationIdString")
return false
}
}
var commandTypeGetter interface {
PLC4XEnumName() string
}
switch salData := salData.(type) {
case readWriteModel.SALDataAccessControlExactly:
commandTypeGetter = salData.GetAccessControlData().GetCommandType()
case readWriteModel.SALDataAirConditioningExactly:
commandTypeGetter = salData.GetAirConditioningData().GetCommandType()
case readWriteModel.SALDataAudioAndVideoExactly:
commandTypeGetter = salData.GetAudioVideoData().GetCommandType()
case readWriteModel.SALDataClockAndTimekeepingExactly:
commandTypeGetter = salData.GetClockAndTimekeepingData().GetCommandType()
case readWriteModel.SALDataEnableControlExactly:
commandTypeGetter = salData.GetEnableControlData().GetCommandType()
case readWriteModel.SALDataErrorReportingExactly:
commandTypeGetter = salData.GetErrorReportingData().GetCommandType()
case readWriteModel.SALDataFreeUsageExactly:
s.log.Info().Msg("Unknown command type")
case readWriteModel.SALDataHeatingExactly:
commandTypeGetter = salData.GetHeatingData().GetCommandType()
case readWriteModel.SALDataHvacActuatorExactly:
commandTypeGetter = salData.GetHvacActuatorData().GetCommandType()
case readWriteModel.SALDataIrrigationControlExactly:
commandTypeGetter = salData.GetIrrigationControlData().GetCommandType()
case readWriteModel.SALDataLightingExactly:
commandTypeGetter = salData.GetLightingData().GetCommandType()
case readWriteModel.SALDataMeasurementExactly:
commandTypeGetter = salData.GetMeasurementData().GetCommandType()
case readWriteModel.SALDataMediaTransportExactly:
commandTypeGetter = salData.GetMediaTransportControlData().GetCommandType()
case readWriteModel.SALDataMeteringExactly:
commandTypeGetter = salData.GetMeteringData().GetCommandType()
case readWriteModel.SALDataPoolsSpasPondsFountainsControlExactly:
commandTypeGetter = salData.GetPoolsSpaPondsFountainsData().GetCommandType()
case readWriteModel.SALDataReservedExactly:
s.log.Info().Msg("Unknown command type")
case readWriteModel.SALDataRoomControlSystemExactly:
s.log.Info().Msg("Unknown command type not implemented yet") // TODO: implement once there
case readWriteModel.SALDataSecurityExactly:
commandTypeGetter = salData.GetSecurityData().GetCommandType()
case readWriteModel.SALDataTelephonyStatusAndControlExactly:
commandTypeGetter = salData.GetTelephonyData().GetCommandType()
case readWriteModel.SALDataTemperatureBroadcastExactly:
commandTypeGetter = salData.GetTemperatureBroadcastData().GetCommandType()
case readWriteModel.SALDataTestingExactly:
s.log.Info().Msg("Unknown command type not implemented yet") // TODO: implement once there
case readWriteModel.SALDataTriggerControlExactly:
commandTypeGetter = salData.GetTriggerControlData().GetCommandType()
case readWriteModel.SALDataVentilationExactly:
commandTypeGetter = salData.GetVentilationData().GetCommandType()
default:
s.log.Error().Type("salData", salData).Msg("Unmapped type")
}
commandType := "Unknown"
if commandTypeGetter != nil {
commandType = commandTypeGetter.PLC4XEnumName()
}
// TODO: we need to map commands e.g. if we get a MeteringDataElectricityConsumption we can map that to MeteringDataMeasureElectricity
address[tagName] = fmt.Sprintf("sal/%s/%s", applicationString, commandType)
rbvb := spiValues.NewWriteBufferPlcValueBased()
err := salData.SerializeWithWriteBuffer(context.Background(), rbvb)
if err != nil {
s.log.Error().Err(err).Msg("Error serializing to plc value... just returning it as string")
plcValues[tagName] = spiValues.NewPlcSTRING(fmt.Sprintf("%s", salData))
} else {
plcValues[tagName] = rbvb.GetPlcValue()
}
responseCodes[tagName] = apiModel.PlcResponseCode_OK
// Assemble a PlcSubscription event
event := NewSubscriptionEvent(tags, types, intervals, responseCodes, address, sources, plcValues)
consumer(&event)
return true
}
func (s *Subscriber) Register(consumer apiModel.PlcSubscriptionEventConsumer, handles []apiModel.PlcSubscriptionHandle) apiModel.PlcConsumerRegistration {
s.consumersMutex.Lock()
defer s.consumersMutex.Unlock()
consumerRegistration := spiModel.NewDefaultPlcConsumerRegistration(s, consumer, handles...)
s.consumers[consumerRegistration.(*spiModel.DefaultPlcConsumerRegistration)] = consumer
return consumerRegistration
}
func (s *Subscriber) Unregister(registration apiModel.PlcConsumerRegistration) {
s.log.Trace().Msg("unregister")
s.consumersMutex.Lock()
defer s.consumersMutex.Unlock()
delete(s.consumers, registration.(*spiModel.DefaultPlcConsumerRegistration))
s.log.Trace().Msg("registration removed")
}