aprslib-aprsd 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aprslib/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ # aprslib - Python library for working with APRS
2
+ # Copyright (C) 2013-2014 Rossen Georgiev
3
+ #
4
+ # This program is free software; you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation; either version 2 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License along
15
+ # with this program; if not, write to the Free Software Foundation, Inc.,
16
+ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
+
18
+ """
19
+ APRS library in Python
20
+
21
+ Currently the library provides facilities to:
22
+ - parse APRS packets
23
+ - Connect and listen to an aprs-is packet feed
24
+ """
25
+
26
+ # Py2 & Py3 compability
27
+ import sys
28
+ if sys.version_info[0] >= 3:
29
+ is_py3 = True
30
+ string_type = (str, )
31
+ string_type_parse = string_type + (bytes, )
32
+ int_type = int
33
+ else:
34
+ is_py3 = False
35
+ string_type = (str, unicode)
36
+ string_type_parse = string_type
37
+ int_type = (int, long)
38
+
39
+
40
+ from datetime import date as _date
41
+ __date__ = str(_date.today())
42
+ del _date
43
+
44
+ __version__ = "0.8.0"
45
+ version_info = (0, 7, 2)
46
+ __author__ = "Rossen Georgiev"
47
+ __all__ = ['IS', 'parse', 'passcode']
48
+
49
+ from aprslib.exceptions import *
50
+ from aprslib.parsing import parse
51
+ from aprslib.passcode import passcode
52
+ from aprslib.inet import IS
aprslib/base91.py ADDED
@@ -0,0 +1,74 @@
1
+ # aprslib - Python library for working with APRS
2
+ # Copyright (C) 2013-2014 Rossen Georgiev
3
+ #
4
+ # This program is free software; you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation; either version 2 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License along
15
+ # with this program; if not, write to the Free Software Foundation, Inc.,
16
+ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
+
18
+ """
19
+ Provides facilities for covertion from/to base91
20
+ """
21
+
22
+ __all__ = ['to_decimal', 'from_decimal']
23
+ from math import log, ceil
24
+ import sys
25
+ from re import findall
26
+ from aprslib import string_type, int_type
27
+
28
+ if sys.version_info < (3,):
29
+ _range = xrange
30
+ else:
31
+ _range = range
32
+
33
+
34
+ def to_decimal(text):
35
+ """
36
+ Takes a base91 char string and returns decimal
37
+ """
38
+
39
+ if not isinstance(text, string_type):
40
+ raise TypeError("expected str or unicode, %s given" % type(text))
41
+
42
+ if findall(r"[\x00-\x20\x7c-\xff]", text):
43
+ raise ValueError("invalid character in sequence")
44
+
45
+ text = text.lstrip('!')
46
+ decimal = 0
47
+ length = len(text) - 1
48
+ for i, char in enumerate(text):
49
+ decimal += (ord(char) - 33) * (91 ** (length - i))
50
+
51
+ return decimal if text != '' else 0
52
+
53
+
54
+ def from_decimal(number, width=1):
55
+ """
56
+ Takes a decimal and returns base91 char string.
57
+ With optional parameter for fix with output
58
+ """
59
+ text = []
60
+
61
+ if not isinstance(number, int_type):
62
+ raise TypeError("Expected number to be int, got %s", type(number))
63
+ elif not isinstance(width, int_type):
64
+ raise TypeError("Expected width to be int, got %s", type(number))
65
+ elif number < 0:
66
+ raise ValueError("Expected number to be positive integer")
67
+ elif number > 0:
68
+ max_n = ceil(log(number) / log(91))
69
+
70
+ for n in _range(int(max_n), -1, -1):
71
+ quotient, number = divmod(number, 91**n)
72
+ text.append(chr(33 + quotient))
73
+
74
+ return "".join(text).lstrip('!').rjust(max(1, width), '!')
aprslib/exceptions.py ADDED
@@ -0,0 +1,81 @@
1
+ # aprslib - Python library for working with APRS
2
+ # Copyright (C) 2013-2014 Rossen Georgiev
3
+ #
4
+ # This program is free software; you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation; either version 2 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License along
15
+ # with this program; if not, write to the Free Software Foundation, Inc.,
16
+ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
+
18
+ """
19
+ Contains exception definitions for the module
20
+ """
21
+
22
+ __all__ = [
23
+ "GenericError",
24
+ "UnknownFormat",
25
+ "ParseError",
26
+ "LoginError",
27
+ "ConnectionError",
28
+ "ConnectionDrop",
29
+ ]
30
+
31
+
32
+ class GenericError(Exception):
33
+ """
34
+ Base exception class for the library. Logs information via logging module
35
+ """
36
+ def __init__(self, message):
37
+ super(GenericError, self).__init__(message)
38
+ self.message = message
39
+
40
+
41
+ class UnknownFormat(GenericError):
42
+ """
43
+ Raised when aprs.parse() encounters an unsupported packet format
44
+
45
+ """
46
+ def __init__(self, message, packet=''):
47
+ super(UnknownFormat, self).__init__(message)
48
+
49
+ self.packet = packet
50
+
51
+
52
+ class ParseError(GenericError):
53
+ """
54
+ Raised when unexpected format of a supported packet format is encountered
55
+ """
56
+ def __init__(self, message, packet=''):
57
+ super(ParseError, self).__init__(message)
58
+
59
+ self.packet = packet
60
+
61
+
62
+ class LoginError(GenericError):
63
+ """
64
+ Raised when IS servers didn't respond correctly to our loging attempt
65
+ """
66
+ def __init__(self, message):
67
+ super(LoginError, self).__init__(message)
68
+
69
+
70
+ class ConnectionError(GenericError):
71
+ """
72
+ Riased when connection dies for some reason
73
+ """
74
+ pass
75
+
76
+
77
+ class ConnectionDrop(ConnectionError):
78
+ """
79
+ Raised when connetion drops or detected to be dead
80
+ """
81
+ pass
aprslib/inet.py ADDED
@@ -0,0 +1,349 @@
1
+ # aprslib - Python library for working with APRS
2
+ # Copyright (C) 2013-2014 Rossen Georgiev
3
+ #
4
+ # This program is free software; you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation; either version 2 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License along
15
+ # with this program; if not, write to the Free Software Foundation, Inc.,
16
+ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
+
18
+ """
19
+ IS class is used for connection to APRS-IS network
20
+ """
21
+ import socket
22
+ import select
23
+ import time
24
+ import logging
25
+
26
+ from aprslib import __version__, string_type, is_py3
27
+ from aprslib.parsing import parse
28
+ from aprslib.packets.base import APRSPacket
29
+ from aprslib.exceptions import (
30
+ GenericError,
31
+ ConnectionDrop,
32
+ ConnectionError,
33
+ LoginError,
34
+ ParseError,
35
+ UnknownFormat,
36
+ )
37
+
38
+ __all__ = ['IS']
39
+
40
+ logging.addLevelName(11, "ParseError")
41
+ logging.addLevelName(9, "UnknownFormat")
42
+
43
+
44
+ class IS(object):
45
+ """
46
+ The IS class is used to connect to aprs-is network and listen to the stream
47
+ of packets. You can either run them through aprs.parse() or get them in raw
48
+ form.
49
+
50
+ Note: sending of packets is not supported yet
51
+
52
+ """
53
+ def __init__(self, callsign, passwd="-1", host="rotate.aprs.net", port=10152, skip_login=False):
54
+ """
55
+ callsign - used when login in
56
+ passwd - for verification, or "-1" if only listening
57
+ Host & port - aprs-is server
58
+ """
59
+
60
+ self.logger = logging.getLogger("%s.%s" % (__name__, self.__class__.__name__))
61
+ self._parse = parse
62
+
63
+ self.set_server(host, port)
64
+ self.set_login(callsign, passwd, skip_login)
65
+
66
+ self.sock = None
67
+ self.filter = "" # default filter, everything
68
+
69
+ self._connected = False
70
+ self.buf = b''
71
+
72
+ def _sendall(self, text):
73
+ if is_py3:
74
+ text = text.encode('utf-8')
75
+ self.sock.sendall(text)
76
+
77
+ def set_filter(self, filter_text):
78
+ """
79
+ Set a specified aprs-is filter for this connection
80
+ """
81
+ self.filter = filter_text
82
+
83
+ self.logger.info("Setting filter to: %s", self.filter)
84
+
85
+ if self._connected:
86
+ self._sendall("#filter %s\r\n" % self.filter)
87
+
88
+ def set_login(self, callsign, passwd="-1", skip_login=False):
89
+ """
90
+ Set callsign and password
91
+ """
92
+ self.__dict__.update(locals())
93
+
94
+ def set_server(self, host, port):
95
+ """
96
+ Set server ip/host and port to use
97
+ """
98
+ self.server = (host, port)
99
+
100
+ def connect(self, blocking=False, retry=30):
101
+ """
102
+ Initiate connection to APRS server and attempt to login
103
+
104
+ blocking = False - Should we block until connected and logged-in
105
+ retry = 30 - Retry interval in seconds
106
+ """
107
+
108
+ if self._connected:
109
+ return
110
+
111
+ while True:
112
+ try:
113
+ self._connect()
114
+ if not self.skip_login:
115
+ self._send_login()
116
+ break
117
+ except (LoginError, ConnectionError):
118
+ if not blocking:
119
+ raise
120
+
121
+ self.logger.info("Retrying connection is %d seconds." % retry)
122
+ time.sleep(retry)
123
+
124
+ def close(self):
125
+ """
126
+ Closes the socket
127
+ Called internally when Exceptions are raised
128
+ """
129
+
130
+ self._connected = False
131
+ self.buf = b''
132
+
133
+ if self.sock is not None:
134
+ self.sock.close()
135
+
136
+ def sendall(self, line):
137
+ """
138
+ Send a line, or multiple lines sperapted by '\\r\\n'
139
+ """
140
+ if isinstance(line, APRSPacket):
141
+ line = str(line)
142
+ elif not isinstance(line, string_type):
143
+ raise TypeError("Expected line to be str or APRSPacket, got %s", type(line))
144
+ if not self._connected:
145
+ raise ConnectionError("not connected")
146
+
147
+ if line == "":
148
+ return
149
+
150
+ line = line.rstrip("\r\n") + "\r\n"
151
+
152
+ try:
153
+ self.sock.setblocking(1)
154
+ self.sock.settimeout(5)
155
+ self._sendall(line)
156
+ except socket.error as exp:
157
+ self.close()
158
+ raise ConnectionError(str(exp))
159
+
160
+ def consumer(self, callback, blocking=True, immortal=False, raw=False):
161
+ """
162
+ When a position sentence is received, it will be passed to the callback function
163
+
164
+ blocking: if true (default), runs forever, otherwise will return after one sentence
165
+ You can still exit the loop, by raising StopIteration in the callback function
166
+
167
+ immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions
168
+ if false (default), consumer will return
169
+
170
+ raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()
171
+ """
172
+
173
+ if not self._connected:
174
+ raise ConnectionError("not connected to a server")
175
+
176
+ line = b''
177
+
178
+ while True:
179
+ try:
180
+ for line in self._socket_readlines(blocking):
181
+ if line[0:1] != b'#':
182
+ if raw:
183
+ callback(line)
184
+ else:
185
+ callback(self._parse(line))
186
+ else:
187
+ self.logger.debug("Server: %s", line.decode('utf8'))
188
+ except ParseError as exp:
189
+ self.logger.log(11, "%s\n Packet: %s", exp.message, exp.packet)
190
+ except UnknownFormat as exp:
191
+ self.logger.log(9, "%s\n Packet: %s", exp.message, exp.packet)
192
+ except LoginError as exp:
193
+ self.logger.error("%s: %s", exp.__class__.__name__, exp.message)
194
+ except (KeyboardInterrupt, SystemExit):
195
+ raise
196
+ except (ConnectionDrop, ConnectionError):
197
+ self.close()
198
+
199
+ if not immortal:
200
+ raise
201
+ else:
202
+ self.connect(blocking=blocking)
203
+ continue
204
+ except GenericError:
205
+ pass
206
+ except StopIteration:
207
+ break
208
+ except:
209
+ self.logger.error("APRS Packet: %s", line)
210
+ raise
211
+
212
+ if not blocking:
213
+ break
214
+
215
+ def _open_socket(self):
216
+ """
217
+ Creates a socket
218
+ """
219
+ self.sock = socket.create_connection(self.server, 15)
220
+
221
+ def _connect(self):
222
+ """
223
+ Attemps connection to the server
224
+ """
225
+
226
+ self.logger.info("Attempting connection to %s:%s", self.server[0], self.server[1])
227
+
228
+ try:
229
+ self._open_socket()
230
+
231
+ peer = self.sock.getpeername()
232
+
233
+ self.logger.info("Connected to %s", str(peer))
234
+
235
+ # 5 second timeout to receive server banner
236
+ self.sock.setblocking(1)
237
+ self.sock.settimeout(5)
238
+
239
+ self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
240
+
241
+ banner = self.sock.recv(512)
242
+ if is_py3:
243
+ banner = banner.decode('latin-1')
244
+
245
+ if banner[0] == "#":
246
+ self.logger.debug("Banner: %s", banner.rstrip())
247
+ else:
248
+ raise ConnectionError("invalid banner from server")
249
+
250
+ except ConnectionError as e:
251
+ self.logger.error(str(e))
252
+ self.close()
253
+ raise
254
+ except (socket.error, socket.timeout) as e:
255
+ self.close()
256
+
257
+ self.logger.error("Socket error: %s" % str(e))
258
+ if str(e) == "timed out":
259
+ raise ConnectionError("no banner from server")
260
+ else:
261
+ raise ConnectionError(e)
262
+
263
+ self._connected = True
264
+
265
+ def _send_login(self):
266
+ """
267
+ Sends login string to server
268
+ """
269
+ login_str = "user {0} pass {1} vers aprslib {3}{2}\r\n"
270
+ login_str = login_str.format(
271
+ self.callsign,
272
+ self.passwd,
273
+ (" filter " + self.filter) if self.filter != "" else "",
274
+ __version__
275
+ )
276
+
277
+ self.logger.info("Sending login information")
278
+
279
+ try:
280
+ self._sendall(login_str)
281
+ self.sock.settimeout(5)
282
+ test = self.sock.recv(len(login_str) + 100)
283
+ if is_py3:
284
+ test = test.decode('latin-1')
285
+ test = test.rstrip()
286
+
287
+ self.logger.debug("Server: %s", test)
288
+
289
+ _, _, callsign, status, _ = test.split(' ', 4)
290
+
291
+ if callsign == "":
292
+ raise LoginError("Server responded with empty callsign???")
293
+ if callsign != self.callsign:
294
+ raise LoginError("Server: %s" % test)
295
+ if status != "verified," and self.passwd != "-1":
296
+ raise LoginError("Password is incorrect")
297
+
298
+ if self.passwd == "-1":
299
+ self.logger.info("Login successful (receive only)")
300
+ else:
301
+ self.logger.info("Login successful")
302
+
303
+ except LoginError as e:
304
+ self.logger.error(str(e))
305
+ self.close()
306
+ raise
307
+ except:
308
+ self.close()
309
+ self.logger.error("Failed to login")
310
+ raise LoginError("Failed to login")
311
+
312
+ def _socket_readlines(self, blocking=False):
313
+ """
314
+ Generator for complete lines, received from the server
315
+ """
316
+ try:
317
+ self.sock.setblocking(0)
318
+ except socket.error as e:
319
+ self.logger.error("socket error when setblocking(0): %s" % str(e))
320
+ raise ConnectionDrop("connection dropped")
321
+
322
+ while True:
323
+ short_buf = b''
324
+ newline = b'\r\n'
325
+
326
+ select.select([self.sock], [], [], None if blocking else 0)
327
+
328
+ try:
329
+ short_buf = self.sock.recv(4096)
330
+
331
+ # sock.recv returns empty if the connection drops
332
+ if not short_buf:
333
+ self.logger.error("socket.recv(): returned empty")
334
+ raise ConnectionDrop("connection dropped")
335
+ except socket.error as e:
336
+ # ignore error when blocking=false, and we attempt to read empty socket
337
+ if ("Resource temporarily unavailable" in str(e)
338
+ and not blocking
339
+ and len(self.buf) == 0):
340
+ break
341
+ else:
342
+ self.logger.error("socket error on recv(): %s" % str(e))
343
+
344
+ self.buf += short_buf
345
+
346
+ while newline in self.buf:
347
+ line, self.buf = self.buf.split(newline, 1)
348
+
349
+ yield line
@@ -0,0 +1,2 @@
1
+ from aprslib.packets.position import PositionReport
2
+ from aprslib.packets.telemetry import TelemetryReport
@@ -0,0 +1,56 @@
1
+ from aprslib import parse
2
+ from aprslib.parsing.common import parse_header
3
+
4
+ class APRSPacket(object):
5
+ format = 'raw'
6
+ fromcall = 'N0CALL'
7
+ tocall = 'N0CALL'
8
+ path = []
9
+
10
+ def __init__(self, data=None):
11
+ if data:
12
+ self.load(data)
13
+
14
+ def __repr__(self):
15
+ return "<%s(%s)>" % (
16
+ self.__class__.__name__,
17
+ repr(str(self)),
18
+ )
19
+
20
+ def __str__(self):
21
+ return "%s:%s" % (
22
+ self._serialize_header(),
23
+ self._serialize_body(),
24
+ )
25
+
26
+ def __eq__(self, other):
27
+ return str(self) == str(other)
28
+
29
+ def _serialize_header(self):
30
+ header = "%s>%s" % (self.fromcall, self.tocall)
31
+
32
+ if self.path:
33
+ header += "," + ",".join(self.path)
34
+
35
+ return header
36
+
37
+ def _serialize_body(self):
38
+ return getattr(self, 'body', '')
39
+
40
+
41
+ def load(self, obj):
42
+ if not isinstance(obj, dict):
43
+ if self.format == 'raw':
44
+ header, self.body = obj.split(":", 1)
45
+ obj = parse_header(header)
46
+ else:
47
+ obj = parse(obj)
48
+
49
+ for k, v in obj.items():
50
+ if k == 'format':
51
+ continue
52
+ if k == 'to' or k == 'from':
53
+ k += 'call'
54
+
55
+ if hasattr(self, k):
56
+ setattr(self, k, v)
@@ -0,0 +1,62 @@
1
+ from datetime import datetime
2
+ from aprslib.packets.base import APRSPacket
3
+ from aprslib.util import latitude_to_ddm, longitude_to_ddm, comment_altitude
4
+
5
+
6
+ class PositionReport(APRSPacket):
7
+ format = 'uncompressed'
8
+
9
+ _latitude = 0
10
+ @property
11
+ def latitude(self):
12
+ return self._latitude
13
+
14
+ @latitude.setter
15
+ def latitude(self, val):
16
+ if -90 <= val <= 90:
17
+ self._latitude = val
18
+ else:
19
+ raise ValueError("Latitude outside of -90 to 90 degree range")
20
+
21
+ _longitude = 0
22
+ @property
23
+ def longitude(self):
24
+ return self._longitude
25
+
26
+ @longitude.setter
27
+ def longitude(self, val):
28
+ if -180 <= val <= 180:
29
+ self._longitude = val
30
+ else:
31
+ raise ValueError("Longitude outside of -180 to 180 degree range")
32
+
33
+ symbol_table = '/'
34
+ symbol = 'l'
35
+ altitude = None
36
+ timestamp = None
37
+ comment = ''
38
+
39
+ def _serialize_body(self):
40
+
41
+ if self.timestamp is None:
42
+ timestamp = ''
43
+ elif isinstance(self.timestamp, str):
44
+ timestamp = self.timestamp
45
+ else:
46
+ timestamp = datetime.utcfromtimestamp(self.timestamp).strftime("%d%H%M") + 'z'
47
+
48
+ body = [
49
+ '/' if self.timestamp else '!', # packet type
50
+ timestamp,
51
+ latitude_to_ddm(self.latitude),
52
+ self.symbol_table,
53
+ longitude_to_ddm(self.longitude),
54
+ self.symbol,
55
+ comment_altitude(self.altitude) if self.altitude is not None else '',
56
+ self.comment,
57
+ ]
58
+
59
+ return "".join(body)
60
+
61
+
62
+
@@ -0,0 +1,25 @@
1
+ from aprslib.packets.base import APRSPacket
2
+
3
+ class TelemetryReport(APRSPacket):
4
+ format = 'raw'
5
+ telemetry = dict(seq=0,
6
+ vals=['0']*6)
7
+ telemetry['vals'][5] = ['1']*8 # Replace io data with list of 8 values
8
+ comment = ''
9
+
10
+ def _serialize_body(self):
11
+ # What do we do when len(digitalvalue) != 8?
12
+ tempio = ''.join(self.telemetry['vals'][5])
13
+
14
+ body = [
15
+ str(self.telemetry['seq']).zfill(3),
16
+ str(self.telemetry['vals'][0]).zfill(3),
17
+ str(self.telemetry['vals'][1]).zfill(3),
18
+ str(self.telemetry['vals'][2]).zfill(3),
19
+ str(self.telemetry['vals'][3]).zfill(3),
20
+ str(self.telemetry['vals'][4]).zfill(3),
21
+ str(tempio),
22
+ self.comment,
23
+ ]
24
+ # Add packet type to body joined by commas
25
+ return 'T#' + ",".join(body)