-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaprstar.py
291 lines (235 loc) · 6.57 KB
/
aprstar.py
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
#!/usr/bin/python3
# pylint: disable=missing-docstring
import json
import logging
import os
import platform
import sys
import time
from configparser import ConfigParser
from io import StringIO
import aprslib
try: # Python 3
from urllib.request import urlopen
except ImportError: # Python 2
from urllib import urlopen
from aprslib.exceptions import ConnectionError
CONFIG_FILE = "/etc/aprstar.conf"
CONFIG_DEFAULT = u"""
[APRS]
call: N0CALL-1
latitude: 0
longitude: 0
sleep: 600
symbol: n
symbol_table: /
"""
THERMAL_FILE = "/sys/class/thermal/thermal_zone0/temp"
LOADAVG_FILE = "/proc/loadavg"
DEFAULT_PORT = 14580
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%H:%M:%S',
level=logging.INFO)
class Config(object):
def __init__(self):
parser = ConfigParser()
parser.read_file(StringIO(CONFIG_DEFAULT))
self._passcode = ""
self._call = "NOCALL-1"
self._longitude = 0.0
self._latitude = 0.0
self._sleep = 900
self._symbol = "n"
self._symbol_table = "/"
if not os.path.exists(CONFIG_FILE):
logging.info('Using default config')
else:
try:
logging.info('Reading config file')
with open(CONFIG_FILE, 'r') as fdc:
parser.readfp(fdc)
logging.info('Config file %s read', CONFIG_FILE)
except (IOError, SystemError):
raise SystemError('No [APRS] section configured')
self.call = parser.get('APRS', 'call')
self.sleep = parser.get('APRS', 'sleep')
self.symbol_table = parser.get('APRS', 'symbol_table')
self.symbol = parser.get('APRS', 'symbol')
lat, lon = [float(parser.get('APRS', c)) for c in ('latitude', 'longitude')]
if not lat or not lon:
self.latitude, self.longitude = get_coordinates()
else:
self.latitude, self.longitude = lat, lon
if parser.has_option('APRS', 'passcode'):
self.passcode = parser.get('APRS', 'passcode')
else:
logging.warning('Generating passcode')
self.passcode = aprslib.passcode(self.call)
def __repr__(self):
return ("<Config> call: {0.call}, passcode: {0.passcode} - "
"{0.latitude}/{0.longitude}").format(self)
@property
def call(self):
return self._call
@call.setter
def call(self, val):
self._call = str(val)
@property
def sleep(self):
return self._sleep
@sleep.setter
def sleep(self, val):
try:
self._sleep = int(val)
except ValueError:
logging.warning('Sleep value error using 600')
self._sleep = 600
@property
def latitude(self):
return self._latitude
@latitude.setter
def latitude(self, val):
self._latitude = val
@property
def longitude(self):
return self._longitude
@longitude.setter
def longitude(self, val):
self._longitude = val
@property
def passcode(self):
return self._passcode
@passcode.setter
def passcode(self, val):
self._passcode = str(val)
@property
def symbol(self):
return self._symbol
@symbol.setter
def symbol(self, val):
self._symbol = str(val)
@property
def symbol_table(self):
return self._symbol_table
@symbol_table.setter
def symbol_table(self, val):
self._symbol_table = str(val)
class Sequence(object):
"""Generate an APRS sequence number."""
def __init__(self):
self.sequence_file = '/tmp/aprstar.sequence'
try:
with open(self.sequence_file) as fds:
self._count = int(fds.readline())
except (IOError, ValueError):
self._count = 0
def flush(self):
try:
with open(self.sequence_file, 'w') as fds:
fds.write("{0:d}".format(self._count))
except IOError:
pass
def __iter__(self):
return self
def next(self):
return self.__next__()
def __next__(self):
self._count = (1 + self._count) % 999
self.flush()
return self._count
def get_coordinates():
logging.warning('Trying to figure out the coordinate using your IP address')
url = "http://ip-api.com/json/"
try:
response = urlopen(url)
_data = response.read()
data = json.loads(_data.decode())
except IOError as err:
logging.error(err)
return (0, 0)
else:
logging.warning('Position: %f, %f', data['lat'], data['lon'])
return data['lat'], data['lon']
def get_load():
try:
with open(LOADAVG_FILE) as lfd:
loadstr = lfd.readline()
except IOError:
return 0
try:
load15 = float(loadstr.split()[1])
except ValueError:
return 0
return int(load15 * 1000)
def get_freemem():
proc_file = '/proc/meminfo'
try:
with open(proc_file) as pfd:
for line in pfd:
if 'MemFree' in line:
freemem = int(line.split()[1])
except (IOError, ValueError):
return 0
return int(freemem / 1024)
def get_temp():
try:
with open(THERMAL_FILE) as tfd:
_tmp = tfd.readline()
temperature = int(_tmp.strip())
except (IOError, ValueError):
temperature = 20000
return temperature
def send_position(ais, config):
packet = aprslib.packets.PositionReport()
packet.fromcall = config.call
packet.tocall = 'APRS'
packet.symbol = config.symbol
packet.symbol_table = config.symbol_table
packet.timestamp = time.time()
packet.latitude = config.latitude
packet.longitude = config.longitude
packet.comment = "{} - https://github.com/0x9900/aprstar".format(platform.node())
logging.info(str(packet))
try:
ais.sendall(packet)
except ConnectionError as err:
logging.warning(err)
def send_header(ais, config):
send_position(ais, config)
try:
ais.sendall("{0}>APRS::{0:9s}:PARM.Temp,Load,FreeMem".format(config.call))
ais.sendall("{0}>APRS::{0:9s}:EQNS.0,0.001,0,0,0.001,0,0,1,0".format(config.call))
except ConnectionError as err:
logging.warning(err)
def ais_connect(config):
ais = aprslib.IS(config.call, passwd=config.passcode, port=DEFAULT_PORT)
for retry in range(5):
try:
ais.connect()
except ConnectionError as err:
logging.warning(err)
time.sleep(10)
else:
return ais
logging.error('Connection error exiting')
sys.exit(os.EX_NOHOST)
def main():
config = Config()
ais = ais_connect(config)
send_header(ais, config)
for sequence in Sequence():
if sequence % 10 == 1:
send_header(ais, config)
temp = get_temp()
load = get_load()
freemem = get_freemem()
data = "{}>APRS:T#{:03d},{:d},{:d},{:d},0,0,00000000".format(
config.call, sequence, temp, load, freemem)
ais.sendall(data)
logging.info(data)
time.sleep(config.sleep)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit()