Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions dronecan/driver/mavcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import os
import sys
import time
import signal
import multiprocessing
from logging import getLogger
from .common import DriverError, CANFrame, AbstractDriver
Expand All @@ -29,12 +30,34 @@

logger = getLogger(__name__)
kill_process = False


def parent_process_alive(parent_pid):
'''check if the process that spawned us is still alive.

We can't compare os.getppid() to parent_pid: under the 'forkserver'
start method (the default on Linux from Python 3.14) the IO process is
forked from the fork-server, so getppid() returns the fork-server's pid,
not the bridge's. Check the recorded parent pid directly instead.'''
if sys.platform.startswith('win'):
return True # os.kill(pid, 0) is unreliable on Windows
try:
os.kill(parent_pid, 0)
except OSError:
return False
return True


class ControlMessage(object):
def __init__(self, command, data):
self.command = command
self.data = data

def io_process(url, bus, target_system, baudrate, tx_queue, rx_queue, exit_queue, parent_pid):
# leave Ctrl-C (SIGINT) handling to the parent process; this daemon
# child is torn down when the parent exits
signal.signal(signal.SIGINT, signal.SIG_IGN)

os.environ['MAVLINK20'] = '1'

target_component = 0
Expand Down Expand Up @@ -127,7 +150,7 @@ def handle_control_message(m):
if (not exit_queue.empty() and exit_queue.get() == "QUIT") or exit_proc:
conn.close()
return
if os.getppid() != parent_pid:
if not parent_process_alive(parent_pid):
# ensure we die when parent dies
conn.close()
return
Expand Down Expand Up @@ -222,7 +245,7 @@ def __init__(self, url, **kwargs):
self.set_signing_passphrase(pass_phrase)

def close(self):
if self.proc is not None:
if self.proc is not None and self.proc.is_alive():
self.exit_queue.put_nowait("QUIT")
self.proc.join()

Expand Down
43 changes: 40 additions & 3 deletions dronecan/driver/mcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import os
import sys
import time
import signal
import multiprocessing
import socket
import struct
Expand Down Expand Up @@ -65,7 +66,33 @@
except Exception:
pass

def io_process(url, tx_queue, rx_queue):
def parent_process_alive(parent_pid):
'''check if the process that spawned us is still alive.

We can't compare os.getppid() to parent_pid: under the 'forkserver'
start method (the default on Linux from Python 3.14) the IO process is
forked from the fork-server, so getppid() returns the fork-server's pid,
not the parent's. Check the recorded parent pid directly instead.'''
if RUNNING_ON_WINDOWS:
return True # os.kill(pid, 0) is unreliable on Windows
try:
os.kill(parent_pid, 0)
except OSError:
return False
return True


def io_process(url, tx_queue, rx_queue, exit_queue, parent_pid):
# leave Ctrl-C (SIGINT) handling to the parent process; this daemon
# child is torn down when the parent exits
signal.signal(signal.SIGINT, signal.SIG_IGN)

def should_exit():
'''return True when the parent has asked us to quit or has died'''
if not exit_queue.empty() and exit_queue.get() == "QUIT":
return True
return not parent_process_alive(parent_pid)

port = None
port_out = None
myport = None
Expand Down Expand Up @@ -104,6 +131,12 @@ def connect():


while True:
if should_exit():
if port is not None:
port.close()
if port_out is not None:
port_out.close()
return
if need_connect:
time.sleep(0.1)
need_connect = False
Expand Down Expand Up @@ -175,14 +208,18 @@ def __init__(self, url, **kwargs):

self.rx_queue = multiprocessing.Queue(maxsize=RX_QUEUE_SIZE)
self.tx_queue = multiprocessing.Queue(maxsize=TX_QUEUE_SIZE)
self.exit_queue = multiprocessing.Queue(maxsize=1)

self.proc = multiprocessing.Process(target=io_process, name='mcast_io_process',
args=(url, self.tx_queue, self.rx_queue))
args=(url, self.tx_queue, self.rx_queue,
self.exit_queue, os.getpid()))
self.proc.daemon = True
self.proc.start()

def close(self):
pass
if self.proc is not None and self.proc.is_alive():
self.exit_queue.put_nowait("QUIT")
self.proc.join()

def __del__(self):
self.close()
Expand Down
10 changes: 9 additions & 1 deletion dronecan/driver/slcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,15 @@ def is_parent_process_alive():
if RUNNING_ON_WINDOWS:
return True # TODO: Find a working solution for Windows (os.kill(ppid, 0) doesn't work)
else:
return os.getppid() == parent_pid
# Can't compare os.getppid() to parent_pid: under the 'forkserver'
# start method (default on Linux from Python 3.14) the IO process is
# forked from the fork-server, so getppid() is the fork-server's pid.
# Check the recorded parent pid is still alive instead.
try:
os.kill(parent_pid, 0)
except OSError:
return False
return True

try:
_raise_self_process_priority()
Expand Down
85 changes: 46 additions & 39 deletions examples/canfd_msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,49 @@

# get command line arguments
from argparse import ArgumentParser
parser = ArgumentParser(description='ESC throttle control example')
parser.add_argument("--bitrate", default=1000000, type=int, help="CAN bit rate")
parser.add_argument("--node-id", default=100, type=int, help="CAN node ID")
parser.add_argument("--dna-server", action='store_true', default=False, help="run DNA server")
parser.add_argument("port", default=None, type=str, help="serial port")
args = parser.parse_args()

# Initializing a DroneCAN node instance.
node = dronecan.make_node(args.port, node_id=args.node_id, bitrate=args.bitrate)

# Initializing a node monitor, so we can see what nodes are online
node_monitor = dronecan.app.node_monitor.NodeMonitor(node)

if args.dna_server:
# optionally start a DNA server
dynamic_node_id_allocator = dronecan.app.dynamic_node_id.CentralizedServer(node, node_monitor)

def publish_message():
m = dronecan.uavcan.protocol.debug.LogMessage()
m.source = "X"
m.text = "Y"
node.broadcast(m, canfd=True)

m.source = "CANFDTest"
m.text = "ThisIsALongerTest"
node.broadcast(m, canfd=True)

m.source = "CANFDTestLong"
m.text = "ThisIsAVeryLongTest.MaryHadALittleLampWhosFleeceWasWhiteAsSnowAndEverywhereThatMaryWentThe"
node.broadcast(m, canfd=True)

# setup to a LogMessage at 1Hz
node.periodic(1, publish_message)

# Running the node until the application is terminated or until first error.
try:
node.spin()
except KeyboardInterrupt:
pass


def main():
parser = ArgumentParser(description='ESC throttle control example')
parser.add_argument("--bitrate", default=1000000, type=int, help="CAN bit rate")
parser.add_argument("--node-id", default=100, type=int, help="CAN node ID")
parser.add_argument("--dna-server", action='store_true', default=False, help="run DNA server")
parser.add_argument("port", default=None, type=str, help="serial port")
args = parser.parse_args()

# Initializing a DroneCAN node instance.
node = dronecan.make_node(args.port, node_id=args.node_id, bitrate=args.bitrate)

# Initializing a node monitor, so we can see what nodes are online
node_monitor = dronecan.app.node_monitor.NodeMonitor(node)

if args.dna_server:
# optionally start a DNA server
dynamic_node_id_allocator = dronecan.app.dynamic_node_id.CentralizedServer(node, node_monitor)

def publish_message():
m = dronecan.uavcan.protocol.debug.LogMessage()
m.source = "X"
m.text = "Y"
node.broadcast(m, canfd=True)

m.source = "CANFDTest"
m.text = "ThisIsALongerTest"
node.broadcast(m, canfd=True)

m.source = "CANFDTestLong"
m.text = "ThisIsAVeryLongTest.MaryHadALittleLampWhosFleeceWasWhiteAsSnowAndEverywhereThatMaryWentThe"
node.broadcast(m, canfd=True)

# setup to a LogMessage at 1Hz
node.periodic(1, publish_message)

# Running the node until the application is terminated or until first error.
try:
node.spin()
except KeyboardInterrupt:
pass


if __name__ == '__main__':
main()
65 changes: 35 additions & 30 deletions examples/canlog2gps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,46 @@
# progress bar
from tqdm import tqdm

if len(sys.argv) != 4:
print("Usage: python3 canlog2gps.py <messageName> <logfile> <outputfile>")
sys.exit(1)

# Create a CAN bus instance
global node
print('Starting server as Node ID', 10)
def main():
if len(sys.argv) != 4:
print("Usage: python3 canlog2gps.py <messageName> <logfile> <outputfile>")
sys.exit(1)

filename = sys.argv[2]
out_file = open(sys.argv[3],'wb')
node = dronecan.make_node("filein:"+filename, node_id=10, bitrate=1000000,speedup=-1)
# Create a CAN bus instance
print('Starting server as Node ID', 10)

def handle_Data(msg):
# dump the message data to a file
out_file.write(msg.message.data.to_bytes())
filename = sys.argv[2]
out_file = open(sys.argv[3],'wb')
node = dronecan.make_node("filein:"+filename, node_id=10, bitrate=1000000,speedup=-1)

# message type by key name
message_type = getattr(dronecan.ardupilot.gnss, sys.argv[1])
node.add_handler(message_type, handle_Data)
def handle_Data(msg):
# dump the message data to a file
out_file.write(msg.message.data.to_bytes())

# progress bar
pbar = tqdm(total=100)

while True:
try:
node.spin(0.001)
# print(node.can_driver.stream_progress())
# show the progress of the stream
pbar.update(node.can_driver.stream_progress() - pbar.n)
if node.can_driver.end_of_stream():
print('End of stream')
# message type by key name
message_type = getattr(dronecan.ardupilot.gnss, sys.argv[1])
node.add_handler(message_type, handle_Data)

# progress bar
pbar = tqdm(total=100)

while True:
try:
node.spin(0.001)
# print(node.can_driver.stream_progress())
# show the progress of the stream
pbar.update(node.can_driver.stream_progress() - pbar.n)
if node.can_driver.end_of_stream():
print('End of stream')
out_file.flush()
out_file.close()
sys.exit(0)
except KeyboardInterrupt:
out_file.flush()
out_file.close()
sys.exit(0)
except KeyboardInterrupt:
out_file.flush()
out_file.close()
sys.exit(0)


if __name__ == '__main__':
main()
57 changes: 32 additions & 25 deletions examples/dump_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,35 @@

# get command line arguments
from argparse import ArgumentParser
parser = ArgumentParser(description='dump all DroneCAN messages')
parser.add_argument("--bitrate", default=1000000, type=int, help="CAN bit rate")
parser.add_argument("--node-id", default=100, type=int, help="CAN node ID")
parser.add_argument("--dna-server", action='store_true', default=False, help="run DNA server")
parser.add_argument("port", default=None, type=str, help="serial port")
args = parser.parse_args()

# Initializing a DroneCAN node instance.
node = dronecan.make_node(args.port, node_id=args.node_id, bitrate=args.bitrate)

# Initializing a node monitor, so we can see what nodes are online
node_monitor = dronecan.app.node_monitor.NodeMonitor(node)

if args.dna_server:
# optionally start a DNA server
dynamic_node_id_allocator = dronecan.app.dynamic_node_id.CentralizedServer(node, node_monitor)

# callback for printing all messages in human-readable YAML format.
node.add_handler(None, lambda msg: print(dronecan.to_yaml(msg)))

# Running the node until the application is terminated or until first error.
try:
node.spin()
except KeyboardInterrupt:
pass


def main():
parser = ArgumentParser(description='dump all DroneCAN messages')
parser.add_argument("--bitrate", default=1000000, type=int, help="CAN bit rate")
parser.add_argument("--node-id", default=100, type=int, help="CAN node ID")
parser.add_argument("--dna-server", action='store_true', default=False, help="run DNA server")
parser.add_argument("port", default=None, type=str, help="serial port")
args = parser.parse_args()

# Initializing a DroneCAN node instance.
node = dronecan.make_node(args.port, node_id=args.node_id, bitrate=args.bitrate)

# Initializing a node monitor, so we can see what nodes are online
node_monitor = dronecan.app.node_monitor.NodeMonitor(node)

if args.dna_server:
# optionally start a DNA server
dynamic_node_id_allocator = dronecan.app.dynamic_node_id.CentralizedServer(node, node_monitor)

# callback for printing all messages in human-readable YAML format.
node.add_handler(None, lambda msg: print(dronecan.to_yaml(msg)))

# Running the node until the application is terminated or until first error.
try:
node.spin()
except KeyboardInterrupt:
pass


if __name__ == '__main__':
main()
Loading
Loading