forked from bemasher/rtlamr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
239 lines (201 loc) · 5.1 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
// RTLAMR - An rtl-sdr receiver for smart meters operating in the 900MHz ISM band.
// Copyright (C) 2015 Douglas Hall
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"bytes"
"encoding/xml"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/bemasher/rtlamr/parse"
"github.com/bemasher/rtltcp"
_ "github.com/bemasher/rtlamr/idm"
_ "github.com/bemasher/rtlamr/r900"
_ "github.com/bemasher/rtlamr/r900bcd"
_ "github.com/bemasher/rtlamr/scm"
_ "github.com/bemasher/rtlamr/scmplus"
)
var rcvr Receiver
type Receiver struct {
rtltcp.SDR
p parse.Parser
fc parse.FilterChain
}
func (rcvr *Receiver) NewReceiver() {
var err error
if rcvr.p, err = parse.NewParser(strings.ToLower(*msgType), *symbolLength, *decimation); err != nil {
log.Fatal(err)
}
// Connect to rtl_tcp server.
if err := rcvr.Connect(nil); err != nil {
log.Fatal(err)
}
rcvr.HandleFlags()
cfg := rcvr.p.Cfg()
gainFlagSet := false
flag.Visit(func(f *flag.Flag) {
switch f.Name {
case "centerfreq":
cfg.CenterFreq = uint32(rcvr.Flags.CenterFreq)
case "samplerate":
cfg.SampleRate = int(rcvr.Flags.SampleRate)
case "gainbyindex", "tunergainmode", "tunergain", "agcmode":
gainFlagSet = true
case "unique":
rcvr.fc.Add(NewUniqueFilter())
case "filterid":
rcvr.fc.Add(meterID)
case "filtertype":
rcvr.fc.Add(meterType)
}
})
rcvr.SetCenterFreq(cfg.CenterFreq)
rcvr.SetSampleRate(uint32(cfg.SampleRate))
if !gainFlagSet {
rcvr.SetGainMode(true)
}
if !*quiet {
rcvr.p.Log()
}
// Tell the user how many gain settings were reported by rtl_tcp.
if !*quiet {
log.Println("GainCount:", rcvr.SDR.Info.GainCount)
}
return
}
func (rcvr *Receiver) Run() {
// Setup signal channel for interruption.
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Kill, os.Interrupt)
// Setup time limit channel
tLimit := make(<-chan time.Time, 1)
if *timeLimit != 0 {
tLimit = time.After(*timeLimit)
}
in, out := io.Pipe()
go func() {
tcpBlock := make([]byte, 16384)
for {
n, err := rcvr.Read(tcpBlock)
if err != nil {
return
}
out.Write(tcpBlock[:n])
}
}()
block := make([]byte, rcvr.p.Cfg().BlockSize2)
sampleBuf := new(bytes.Buffer)
start := time.Now()
for {
// Exit on interrupt or time limit, otherwise receive.
select {
case <-sigint:
return
case <-tLimit:
fmt.Println("Time Limit Reached:", time.Since(start))
return
default:
// Read new sample block.
_, err := io.ReadFull(in, block)
if err != nil {
log.Fatal("Error reading samples: ", err)
}
// If dumping samples, discard the oldest block from the buffer if
// it's full and write the new block to it.
if *sampleFilename != os.DevNull {
if sampleBuf.Len() > rcvr.p.Cfg().BufferLength<<1 {
io.CopyN(ioutil.Discard, sampleBuf, int64(len(block)))
}
sampleBuf.Write(block)
}
pktFound := false
indices := rcvr.p.Dec().Decode(block)
for _, pkt := range rcvr.p.Parse(indices) {
if !rcvr.fc.Match(pkt) {
continue
}
var msg parse.LogMessage
msg.Time = time.Now()
msg.Offset, _ = sampleFile.Seek(0, os.SEEK_CUR)
msg.Length = sampleBuf.Len()
msg.Message = pkt
err = encoder.Encode(msg)
if err != nil {
log.Fatal("Error encoding message: ", err)
}
// The XML encoder doesn't write new lines after each
// element, add them.
if _, ok := encoder.(*xml.Encoder); ok {
fmt.Fprintln(logFile)
}
pktFound = true
if *single {
if len(meterID.UintMap) == 0 {
break
} else {
delete(meterID.UintMap, uint(pkt.MeterID()))
}
}
}
if pktFound {
if *sampleFilename != os.DevNull {
_, err = sampleFile.Write(sampleBuf.Bytes())
if err != nil {
log.Fatal("Error writing raw samples to file:", err)
}
}
if *single && len(meterID.UintMap) == 0 {
return
}
}
}
}
}
func init() {
log.SetFlags(log.Lshortfile | log.Lmicroseconds)
}
var (
buildDate string // date -u '+%Y-%m-%d'
commitHash string // git rev-parse HEAD
)
func main() {
rcvr.RegisterFlags()
RegisterFlags()
flag.Parse()
if *version {
if buildDate == "" || commitHash == "" {
fmt.Println("Built from source.")
fmt.Println("Build Date: Unknown")
fmt.Println("Commit: Unknown")
} else {
fmt.Println("Build Date:", buildDate)
fmt.Println("Commit: ", commitHash)
}
os.Exit(0)
}
HandleFlags()
rcvr.NewReceiver()
defer logFile.Close()
defer sampleFile.Close()
defer rcvr.Close()
rcvr.Run()
}