-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
258 lines (218 loc) · 7.01 KB
/
main.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
/*
Copyright (c) 2023 Michail Angelos Tsiantakis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/*
This program uses the SEN55 sensor from Sensirion to take various measurements and
print them to a file and or the community site sensor.community if configured.
A configuration file is available at the GitHub repository that you may use to configure
all the available
The folder sen5xlib contains the C bindings and the functions to communicate with the sensor
that Sensirion provides at their GitHub repository. This program is not endorsed by Sensirion!
*/
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/aggellos2001/sen5x-go/community"
"github.com/aggellos2001/sen5x-go/conf"
"github.com/aggellos2001/sen5xlib"
)
func handlePanic() {
if err := recover(); err != nil {
sen5xlib.FreeHal()
log.Fatalln(err)
}
}
func main() {
// this will handle any panics that may occur
defer handlePanic()
//handle ctrl-c from user in a different goroutine
sigintch := make(chan os.Signal, 1)
signal.Notify(sigintch, os.Interrupt)
go func() {
<-sigintch
err := sen5xlib.StopMeasurement()
if err != nil {
log.Fatalln("exiting the program with errors, check connection to sensor...", err)
}
log.Println("exiting gracefully...")
os.Exit(0)
}()
config, err := conf.LoadConfig()
if err != nil {
log.Fatalln("error while loading config:", err)
}
if !config.Console.Enabled {
// if console is disabled, discard all logs
log.SetOutput(io.Discard)
}
prettyPrintedConfig, _ := json.MarshalIndent(config, "", " ")
log.Println("read config successfully and found configuration: ", string(prettyPrintedConfig))
sen5xlib.InitializeHal()
defer sen5xlib.FreeHal()
log.Println("Initialized HAL")
err = sen5xlib.ResetDevice()
if err != nil {
log.Fatalln(err)
}
serial, err := sen5xlib.ReadSerialNumber()
if err != nil {
log.Fatalln(err)
}
log.Println("serial number:", serial)
prodName, err := sen5xlib.ReadProductName()
if err != nil {
log.Fatalln(err)
}
log.Println("product name:", prodName)
firmware, err := sen5xlib.ReadFirmwareVersion()
if err != nil {
log.Fatalln(err)
}
log.Println("firmware version:", firmware)
var csvMeasurementFile *os.File
if config.DataLogging.Enabled {
var fileName string
// check if the user entered a file name as an argument
if len(os.Args) > 1 {
if err != nil {
log.Fatalln(err)
}
fileName = os.Args[1]
// check if filename is defined in config
} else if config.DataLogging.FileName != "" {
fileName = config.DataLogging.FileName
} else {
//otherwise ask input from user
log.Println("please enter csv file to write the measurements :")
_, err := fmt.Scanln(&fileName)
if err != nil {
log.Fatalln(err)
}
}
// if the user did not enter the .csv extension, add it
if !strings.HasSuffix(fileName, ".csv") {
fileName += ".csv"
}
csvMeasurementFile, err = os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalln(err)
}
defer func(csvMeasurementFile *os.File) {
err := csvMeasurementFile.Close()
if err != nil {
log.Fatal("could not close measurement file. aborting program!")
}
}(csvMeasurementFile)
} else {
log.Println("data logging to a file is disabled")
}
for {
if config.Sensor.OperationMode.Main == "all" {
err := sen5xlib.StartMeasurement()
if err != nil {
log.Fatalln(err)
}
log.Println("Started measurement in all mode")
} else {
err := sen5xlib.StartMeasurementWithoutPM()
if err != nil {
log.Fatalln(err)
}
log.Println("started measurement without PM")
}
if config.Sensor.OperationMode.Main == "all" &&
config.Sensor.ForceCleanFan {
log.Println("Starting fan cleaning. PROGRAM WILL EXIT AFTER FAN CLEANING IS DONE! Change config afterwards!!!")
err := sen5xlib.StartFanCleaning()
if err != nil {
log.Fatalln(err)
}
os.Exit(0)
}
var sensorMeasurements []sen5xlib.SensorMeasurement
for i := 0; i < config.Measurement.TakeMeasurementsFor; i++ {
// read data from sensor. wait until data is ready or time that user specified
if config.Measurement.WaitBetweenMeasurements > 0 {
sen5xlib.SleepHal(uint32(config.Measurement.WaitBetweenMeasurements))
} else {
for {
dataReady, err := sen5xlib.ReadDataReady()
if err != nil {
log.Println(err)
}
if dataReady {
break
}
}
}
// if the user specified to ignore the first X measurements, do so
if i < config.Measurement.IgnoreFirstXMeasurements {
_, err := sen5xlib.ReadMeasuredValues()
if err != nil {
log.Println("error while reading values from sensor", err)
continue
}
continue
}
// read data from sensor
sensorMeasurement, err := sen5xlib.ReadMeasuredValues()
if err != nil {
log.Println(err)
} else {
// append measurement to slice if no errors occurred
sensorMeasurements = append(sensorMeasurements, sensorMeasurement)
log.Println("read measurement:", sensorMeasurement)
}
} //end of inner for loop
if config.Sensor.OperationMode.Secondary == "gas" {
err := sen5xlib.StartMeasurementWithoutPM()
if err != nil {
log.Println(err)
}
} else {
err := sen5xlib.StopMeasurement()
if err != nil {
log.Println(err)
}
}
// find the average of all measurements
avgMeasurement := AverageMeasurement(&sensorMeasurements)
// free the memory allocated for the slice of measurements
sensorMeasurements = nil
str := fmt.Sprintf("%d,%d,%d,%d,%d,%d,%d,%d,%d\n", time.Now().Unix(), avgMeasurement.PM1_0, avgMeasurement.PM2_5, avgMeasurement.PM4_0, avgMeasurement.PM10_0, avgMeasurement.Hum, avgMeasurement.Temp, avgMeasurement.VOC, avgMeasurement.NOx)
log.Println("average measurement:", str)
// write the average measurement to the csv file with a timestamp
// the timestamp is the number of seconds since 1/1/1970
if config.DataLogging.Enabled {
_, err := csvMeasurementFile.WriteString(str)
if err != nil {
log.Fatalln(err)
}
log.Println("wrote average measurement to csv file")
}
if config.SensorCommunity.Enabled {
community.SendDataToAPI(&avgMeasurement, &config)
log.Println("send average measurement to sensor.community API")
}
// sleep until next batch of measurements
log.Printf("sleeping until next batch of measurements %d seconds...\n", config.Measurement.SleepUntilNextBatchOfMeasurements)
sen5xlib.SleepHal(uint32(config.Measurement.SleepUntilNextBatchOfMeasurements))
}
}