forked from paparazzi/pprzlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.py
142 lines (118 loc) · 4.85 KB
/
serial.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
#
# This file is part of PPRZLINK.
#
# PPRZLINK is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PPRZLINK 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PPRZLINK. If not, see <https://www.gnu.org/licenses/>.
#
from __future__ import absolute_import, division, print_function
import threading
import serial
import logging
from .message import PprzMessage
from .pprz_transport import PprzTransport
logger = logging.getLogger("PprzLink")
class SerialMessagesInterface(threading.Thread):
def __init__(self, callback, verbose=False, device='/dev/ttyUSB0', baudrate=115200,
msg_class='telemetry'):
threading.Thread.__init__(self)
self.callback = callback
self.verbose = verbose
self.msg_class = msg_class
self.running = True
try:
self.ser = serial.Serial(device, baudrate, timeout=1.0)
except serial.SerialException:
logger.error("Error: unable to open serial port '%s'" % device)
exit(0)
self.trans = PprzTransport(msg_class)
def stop(self):
logger.info("End thread and close serial link")
self.running = False
self.ser.close()
def shutdown(self):
self.stop()
def __del__(self):
try:
self.ser.close()
except:
pass
def send(self, msg, sender_id):
""" Send a message over a serial link"""
if isinstance(msg, PprzMessage):
data = self.trans.pack_pprz_msg(sender_id, msg)
self.ser.write(data)
self.ser.flush()
def run(self):
"""Thread running function"""
try:
while self.running:
# Parse incoming data
c = self.ser.read(1)
if len(c) == 1:
if self.trans.parse_byte(c):
try:
(sender_id, msg) = self.trans.unpack()
except ValueError as e:
logger.warning("Ignoring unknown message, %s" % e)
else:
if self.verbose: # Can be replaced with the log level
logger.info("New incoming message '%s' from %i" % (msg.name, sender_id))
# Callback function on new message
self.callback(sender_id, msg)
except StopIteration:
pass
def test():
import time
import argparse
from . import messages_xml_map
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="path to messages.xml file")
parser.add_argument("-c", "--class", help="message class", dest='msg_class', default='telemetry')
parser.add_argument("-d", "--device", help="device name", dest='dev', default='/dev/ttyUSB0')
parser.add_argument("-b", "--baudrate", help="baudrate", dest='baud', default=115200, type=int)
args = parser.parse_args()
messages_xml_map.parse_messages(args.file)
serial_interface = SerialMessagesInterface(lambda s, m: print("new message from %i: %s" % (s, m)), device=args.dev,
baudrate=args.baud, msg_class=args.msg_class, verbose=True)
print("Starting serial interface on %s at %i baud" % (args.dev, args.baud))
try:
serial_interface.start()
# give the thread some time to properly start
time.sleep(0.1)
# send some datalink messages to aicraft for test
ac_id = 42
print("sending ping")
ping = PprzMessage('datalink', 'PING')
serial_interface.send(ping, 0)
get_setting = PprzMessage('datalink', 'GET_SETTING')
get_setting['index'] = 0
get_setting['ac_id'] = ac_id
serial_interface.send(get_setting, 0)
# change setting with index 0 (usually the telemetry mode)
set_setting = PprzMessage('datalink', 'SETTING')
set_setting['index'] = 0
set_setting['ac_id'] = ac_id
set_setting['value'] = 1
serial_interface.send(set_setting, 0)
# block = PprzMessage('datalink', 'BLOCK')
# block['block_id'] = 3
# block['ac_id'] = ac_id
# serial_interface.send(block, 0)
while serial_interface.isAlive():
serial_interface.join(1)
except (KeyboardInterrupt, SystemExit):
print('Shutting down...')
serial_interface.stop()
exit()
if __name__ == '__main__':
test()