-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyTNC.py
462 lines (343 loc) · 13.4 KB
/
pyTNC.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#!/usr/local/python3
# This code was developed for MacOS but should work under Windows and Linux
# 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/>.
# Having said that, it would be great to know if this software gets used. If you want, buy me a coffee, or send me some hardware
# Darryl Smith, VK2TDS. [email protected] Copyright 2023
try:
import gnureadline as readline
except ImportError:
import readline
import logging
import asyncio
import aioax25
import sys
import time
import traceback
import library
from aioax25.kiss import make_device
from aioax25.signal import Signal
from aioax25.interface import AX25Interface
from aioax25.frame import AX25UnnumberedInformationFrame
from aioax25.station import AX25Station
from aioax25.version import AX25Version
from threading import Thread
from threading import Semaphore
from pathlib import Path
#local
import commands
import connect
import ROM
import packet
formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
LOG_FILENAME = '/tmp/pyTNC.log'
logging.basicConfig(
format='%(name)-13s: %(levelname)-8s %(message)s',
filename=LOG_FILENAME,
level=logging.DEBUG,
)
logger = logging.getLogger()
# create file handler which logs even debug messages
fh = logging.FileHandler(LOG_FILENAME)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
loggerfile = logging.getLogger('file')
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.DEBUG)
console.setFormatter(formater)
logging.getLogger('console').addHandler(console)
loggerconsole = logging.getLogger ('console')
loggerfile.info ('')
loggerfile.info ('Starting pyTNC - Copyright 2023 Darryl Smith VK2TDS')
#TODO remove this tracefunc ???
def tracefunc(frame, event, arg, indent=[0]):
# https://stackoverflow.com/questions/8315389/how-do-i-print-functions-as-they-are-called
if event == "call":
indent[0] += 2
print("-" * indent[0] + "> call function", frame.f_code.co_name)
elif event == "return":
print("<" + "-" * indent[0], "exit function", frame.f_code.co_name)
indent[0] -= 2
return tracefunc
# To activate sys.setprofile(tracefunc)
if False:
sys.setprofile(tracefunc)
class TNC:
def __init__(self):
self.modeConverse = 0
self.modeTransparent = 1
self.modeCommand = 2
self.tncMode = self.modeCommand
self.station = None
self.tncConnected = False
self.mheard = {}
self.kiss_interface = None
self.exitToCommandMode = '*** COMMAND MODE ***'
self.beaconCondition = 'AFTER'
self.beaconPeriod = 0 # Beacon every 0 * 10 seconds
self.beaconDue = 0
self.monitor = packet.Monitor()
self._completer = None
self.streams = {}
for s in commands.streamlist:
self.streams[s] = connect.Stream(s, loggerfile)
self.streams[s]._name = s
self._currentStream = commands.streamlist[0]
def receive(self):
# An indication that we have receieved a packet with payload from over the air
# This function can be called from a STREAM class, or can be called from a library when
# the user changes stream.
if self.activeStream._rxBuffer.qsize() > 0:
toPrint = False
if self.tncMode == self.modeCommand:
toPrint = False
elif self.tncMode == self.modeConverse:
toPrint = True
elif self.tncMode == self.modeTransparent:
toPrint = True
if toPrint:
while not self.activeStream._rxBuffer.empty():
tnc.output (self.activeStream._rxBuffer.get())
def justConnected(self, s, message):
# we are connected on a stream...
print ('--->', s, message)
@property
def completer (self):
return self._completer
@completer.setter
def completer (self, c):
self._completer = c
for s in self.streams:
self.streams[s].completer = self._completer
# These are letters
@property
def currentStream(self):
return self._currentStream
@currentStream.setter
def currentStream(self, s):
self._currentStream = s
# return the stream object.
@property
def activeStream (self):
return self.streams[self._currentStream]
def output (self, line):
print (line)
def sendID (self, port):
frame = aioax25.frame.AX25UnnumberedInformationFrame(
destination='ID',
source=self._completer.options['MYCALL'].Value,
repeaters=None,
pid=aioax25.frame.AX25Frame.PID_NO_L3,
payload=str.encode(self._completer.options['IDTEXT'].Value)
)
self.kiss_interface.kissInts[port].transmit (frame)
self.kiss_interface.kissIntsLastTX[port] = library.datetimenow(self._completer)
def setBeacon (self, cond, period):
self.beaconPeriod = int(period)
if cond == 'AFTER':
self.beaconCondition = 'AFTER'
if self.beaconPeriod > 0:
self.beaconDue = time.time() + 2 # if BEACON EVERY, send after 2 seconds
else:
self.beaconDue = 0
else: # EVERY
self.beaconCondition = 'EVERY'
if self.beaconPeriod > 0:
self.beaconDue = time.time() + self.beaconPeriod
else:
self.beaconDue = 0
def PPSbeacon(self):
# One pulse per second. Duh. Needs to be triggered of course.
try:
t = time.time()
if self.beaconDue != 0:
if self.beaconDue <= t:
#axint = self.kiss_interface.kissDevices['1'].KissPorts(0).AX25Interface
u = completer.options['UNPROTO'].Value.split()
dest = u[0]
r = None
if len(u) > 1:
u.pop (0)
if len(u) != 0:
r = u
frame = aioax25.frame.AX25UnnumberedInformationFrame(
destination=dest,
source=self._completer.options['MYCALL'].Value,
repeaters=r,
pid=aioax25.frame.AX25Frame.PID_NO_L3,
payload=str.encode(self._completer.options['BTEXT'].Value)
)
self.kiss_interface.kissInts[self.kiss_interface.activeStream.Port].transmit (frame)
self.kiss_interface.kissIntsLastTX[self.kiss_interface.activeStream.Port] = library.datetimenow(self._completer)
#axint.transmit (frame) #callback=None)
if self.beaconCondition == 'AFTER':
self.beaconDue = 0
else:
self.beaconDue = t + (self.beaconPeriod * 10)
except Exception:
traceback.print_exc()
def PPS(self):
self.PPSbeacon()
@property
def mode(self):
return self.tncMode
@mode.setter
def mode (self, m):
if m == self.modeCommand:
self.tncMode = m
readline.parse_and_bind('tab: complete')
elif m == self.modeTransparent:
self.tncMode = m
readline.parse_and_bind('tab: self-insert')
elif m == self.modeConverse:
self.tncMode = m
readline.parse_and_bind('tab: self-insert')
@property
def connected (self):
return self.tncConnected
@connected.setter
def connected (self, v):
self.tncConnected = v
def _on_receive(interface, frame, match=None):
# NOTE: Make sure the kissdevice lines up with the one you wnat to listen too
tnc.mheard[str(frame.header.source)] = library.datetimenow(completer)
tnc.monitor._on_receive_monitor(interface, frame)
async def periodic():
while True:
if tnc:
tnc.PPS() # call TNC 1PPS
await asyncio.sleep(1)
async def main_async():
while True:
chunk = await streaming_queue.get()
if tnc.mode == tnc.modeCommand:
ret = ip.input_process(chunk)
r = ret[0]
if r == commands.returns.Ok:
if ret[1]: tnc.output (ret[1])
elif r == commands.returns.Eh:
if ret[1]:
tnc.output ('?Eh %s' % ret[1])
else:
tnc.output ('?EH')
elif r == commands.returns.Bad:
if ret[1]:
tnc.output ('?Bad %s' % ret[1])
else:
tnc.output ('?Bad')
elif r == commands.returns.NotImplemented:
tnc.output ('?Not Implemented')
elif tnc.mode == tnc.modeConverse:
if tnc.exitToCommandMode in chunk:
tnc.mode = tnc.modeCommand
elif chunk[:3].upper() == 'BYE' :
tnc.output ('--->BYE')
tnc.activeStream.disconnect()
else:
tnc.activeStream.send (chunk)
True
elif tnc.mode == tnc.modeTrans:
True
semaphore.release()
def event_loop(loop):
#Remove comments in production
#try:
loop.run_until_complete(main_async())
#except asyncio.CancelledError:
# loop.close()
# print("loop closed")
def send_chunk(chunk):
streaming_queue.put_nowait(chunk)
def cancel_all():
for task in asyncio.all_tasks():
task.cancel()
def output (line):
print ('%s' %(line))
ip = None
tnc = None
streaming_queue = asyncio.Queue()
def init():
global completer
global ip
global tnc
global console
if not tnc is None:
# we must be doing a power on reset!!!
tnc.kiss_interface.closedown()
tnc.output ('Power On Reset')
del tnc
tnc = TNC()
tnc.kiss_interface = connect.kiss_interface (tnc, _on_receive, loggerfile)
tnc.output ('TAPR TNC2 Clone')
tnc.output ('Copyright 2023 Darryl Smith, VK2TDS')
tnc.output ('')
TNC2 = {}
for index in ROM.TNC2_ROM:
c = commands.Individual_Command()
c.set (ROM.TNC2_ROM[index])
c.Display = index
TNC2[index.upper()] = c
# Register our completer function
completer = commands.BufferAwareCompleter(TNC2, loggerfile)
tnc.completer = completer
tnc.monitor.completer = completer
tnc.monitor.setOutput(output)
tnc.monitor.setTnc(tnc)
readline.set_completer(completer.complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('"ç": "%s\n"' % (tnc.exitToCommandMode)) # Alt-C / Option-C on MacOS depending on the keyboard
ip = commands.process (completer, tnc, init)
# First, process defaults
for stage in range (1,4): # Process defaults in stages. 1 is default, then 2, 3, etc. Needed for KissDev and KissPort
for o in completer.options:
if completer.options[o].Stage == stage:
if completer.options[o].Default is not None:
line = o + ' ' + completer.options[o].Default
ip.input_process (line) # ignore the return values
# Only the upper case letters are an alternative
completer.options[o].Shorter = ''.join(filter(str.isupper, completer.options[o].Display))
# Load settings from custom settings file.
# Try... current directory, home directory, Install directory in that order...
path = None
config_file = 'pyTNC.conf'
if Path.cwd().joinpath(config_file).exists():
path = Path.cwd().joinpath(config_file)
elif Path.home().joinpath(config_file).exists():
path = Path.home().joinpath(config_file)
elif Path(__file__).with_name(config_file).exists():
path = Path(__file__).with_name(config_file)
if not path is None:
tnc.output ('Loading custom settings from %s' % (path))
#if os.path.isfile (filename):
with path.open('r') as f:
lines = f.readlines()
for custom in lines:
ret = ip.input_process (custom)
tnc.output (ret[1])
else:
tnc.output ('No custom settings found')
tnc.output ('')
init()
semaphore = Semaphore()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
event_thread = Thread(target=event_loop, args=(loop,))
event_thread.start()
task = loop.create_task(periodic()) # every second
if True:
chunk = ''
while chunk != 'stop':
# GNU readline overloads input()
semaphore.acquire()
if tnc.mode == tnc.modeCommand:
chunk = input('cmd: ')
elif tnc.mode == tnc.modeConverse:
chunk = input('> ')
elif tnc.mode == tnc.modeTrans:
chunk = input('> ')
loop.call_soon_threadsafe(send_chunk, chunk)