This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
/
collect.go
296 lines (235 loc) · 6.44 KB
/
collect.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
package main
import (
"log"
"strconv"
"strings"
"time"
emitter "github.com/icaropires/go/v2"
)
var (
port Port
serialPortNameCh = make(chan string, 1)
serialAttrs = make([]SerialAttribute, numSerialAttrs)
)
// Index of information get on reading from serial
const (
frequencyIdx = iota
temperature1Idx
temperature2Idx
brakingForce1Idx
brakingForce2Idx
vibrationIdx
speedIdx
pressureIdx
currentSnubIdx
)
var data [][]string
// Subchannels for each information sent to MQTT, same index rules
// as the original data string from serial
var mqttSubchannelSerialAttrs = []string{
"/frequency",
"/temperature/sensor1",
"/temperature/sensor2",
"/brakingForce/sensor1",
"/brakingForce/sensor2",
"/vibration",
"/speed",
"/pressure",
}
const (
mqttSubchannelCurrentSnub = "/currentSnub"
mqttSubchannelSnubState = "/snubState"
mqttSubchannelIsAvailable = "/isAvailable"
)
var (
numberOfDataToFilter = 50
dutyCycleAndDistanceCh = make(chan float64)
)
// SerialAttribute represent one attributes of the many that are returned as values
// from the physical device on serial communication
type SerialAttribute struct {
mqttSubchannel string // Subchannel associated at mqtt broker
publishCh chan string // for publishing
handleCh chan float64 // for handling values
}
// CollectData will collect data from serial bus and distributes it to others goroutines
func CollectData() {
defer wgGeneral.Done()
var ReadingDelay = time.Second / frequencyReading
continueCollecting := true
for continueCollecting {
aplicationStatusCh <- "Esperando seleção de porta válida"
log.Println("Waiting for valid serial port selection...")
serialPortName := <-serialPortNameCh
err := port.Open(serialPortName)
if err != nil {
log.Println(err)
if port.IsOpen() {
port.Close()
}
continue
}
if !isCorrectDevice() {
aplicationStatusCh <- "Selecione a porta correta"
port.Close()
continue
}
aplicationStatusCh <- "Coletando dados"
log.Println("Initializing collectData routine...")
log.Printf("Simulator Port = %s", serialPortName)
log.Printf("Buffer size = %d", bufferSize)
log.Printf("Baud rate = %d", baudRate)
log.Printf("Reading delay = %v", ReadingDelay)
for {
select {
case stop := <-stopCollectingDataCh:
if stop {
continueCollecting = false
}
case sig := <-sigsCh:
log.Println("Signal received: ", sig)
continueCollecting = false
case serialPortName = <-serialPortNameCh:
serialPortNameCh <- serialPortName
CollectData()
default:
getData("\"")
time.Sleep(ReadingDelay)
}
}
}
}
// Will get the data from the bus and returns it as an
// array of bytes
func getData(command string) []byte {
n := port.Write([]byte(command))
buf := make([]byte, bufferSize)
n, err := port.Read(buf)
if err != nil {
log.Println("Error reading from serial ", err, ". Is this the right port?")
}
split := strings.Split(string(buf[:n]), ",")
if len(split) == numSerialAttrs { // Was a complete read
data = append(data, split)
if len(data) == numberOfDataToFilter {
split = dataFilter(data)
out := strings.Join(split, ", ")
log.Println(out)
frequency, _ := strconv.ParseFloat(split[frequencyIdx], 64)
select {
case dutyCycleAndDistanceCh <- frequency:
default:
}
for i, attr := range split {
attrValue, _ := strconv.ParseFloat(attr, 64)
select {
case serialAttrs[i].handleCh <- attrValue:
default:
}
select {
case serialAttrs[i].publishCh <- attr:
default:
}
}
data = data[:0]
}
}
return buf
}
func convertTemperature(value float64, convertionFactor float64, offset float64) float64 {
const (
maxDigitalSignalValue = 1023
milliVots = 5000
)
value = (value * milliVots) / maxDigitalSignalValue
return value*convertionFactor + offset
}
func convertSpeed(value float64, tireRadius float64) float64 {
const (
maxDigitalSignalValue = 1023
milliVots = 5000
)
value = (value * milliVots) / maxDigitalSignalValue
return value * tireRadius
}
func dataFilter(data [][]string) []string {
var (
out []string
counter int
intValue int
stringValue string
)
for i := 0; i < numSerialAttrs; i++ {
for j := 0; j < len(data); j++ {
intValue, _ = strconv.Atoi(data[j][i])
counter += intValue
}
stringValue = strconv.Itoa(counter / len(data))
out = append(out, stringValue)
counter = 0
}
return out
}
func tireRadius(transversalSelectionWidth int, heightWidthRelation int, rimDiameter int) float64 {
return float64((transversalSelectionWidth*heightWidthRelation)/100000) + (0.0254*float64(rimDiameter))/2
}
func travelledDistance(speed float64) float64 {
return (speed / 3600000.0) * (1000 / frequencyReading) * float64(numberOfDataToFilter)
}
// Publish to MQTT broker the whole current state of local application
func publishSerialAttrs() {
for i := 0; i < numSerialAttrs; i++ {
go func(idx int) {
for {
publishData(<-serialAttrs[idx].publishCh, serialAttrs[idx].mqttSubchannel)
}
}(i)
}
}
// Publish data to MQTT broker
func publishData(data string, subChannel string) {
if key := getMqttKey(); key != "" {
clientWriting.OnError(func(_ *emitter.Client, err emitter.Error) {
mqttHasWritingPermission = false
})
channel, data := getMqttChannelPrefix()+subChannel, data
clientWriting.Publish(key, channel, data)
} else {
log.Println("MQTT key not set!!! Not publishing any data...")
mqttKeyStatusCh <- "Chave do MQTT: Ausente"
return
}
}
func writeDutyCycle(duty float64) {
asciiBase := 75.0
perCentByAcii := 4.0
var command []byte
command = append(command, byte(int(duty/perCentByAcii+asciiBase)))
port.Write(command)
}
func testKeys() {
log.Println("Testing MQTT keys...")
key := getMqttKey()
var channel = getMqttChannelPrefix() + "/testingKeys"
clientReading.OnError(func(_ *emitter.Client, err emitter.Error) {
mqttHasReadingPermission = false
})
clientReading.Subscribe(key, channel, func(_ *emitter.Client, msg emitter.Message) {
mqttHasReadingPermission = true
})
publishData("testing", "/testingKeys")
if mqttHasWritingPermission {
if mqttHasReadingPermission {
mqttKeyStatusCh <- "Chave de acesso: Válida"
} else {
mqttKeyStatusCh <- "Chave de acesso: Válida apenas para escrita"
}
} else {
if mqttHasReadingPermission {
mqttKeyStatusCh <- "Chave de acesso: Válida apenas para leitura"
} else {
mqttKeyStatusCh <- "Chave de acesso: Inválida"
}
}
return
}