Finally I managed to switch the mode from Raspberry PI using ReaderThread
. Here is the code:
import sys
import traceback
import argparse
import json
import serial
from serial.threaded import LineReader, ReaderThread
from time import sleep
MODES = [
'Audio FFT',
'Code Detector',
'Face Detector',
'Lane Line Tracker',
'Motion Tracker',
'Shape Matching',
'Camera Stream',
'Online Classifier',
'Color Tracker',
'Face Recognition',
'Target Tracker',
'Shape Detector',
'Object Recognition',
]
ap = argparse.ArgumentParser()
ap.add_argument('-m', '--mode', help = 'Switch to mode: {}'.format(MODES))
ap.add_argument('-a', '--args', default = '', help = 'Some modes require extra args. For "Object Recognition" either "yolo_20class" or "nanodet_80class"')
args = vars(ap.parse_args())
if 'mode' not in args or args['mode'] not in MODES:
ap.print_help()
exit(1)
OBJECT_RECOGNITION_ARGS = [
'yolo_20class',
'nanodet_80class'
]
if args['mode'] == 'Object Recognition' and args['args'] not in OBJECT_RECOGNITION_ARGS:
ap.print_help()
exit(1)
class PrintLines(LineReader):
def connection_made(self, transport):
super(PrintLines, self).connection_made(transport)
sys.stdout.write('port opened\n')
def handle_line(self, data):
sys.stdout.write('line received: {}\n'.format(repr(data)))
def connection_lost(self, exc):
if exc:
traceback.print_exc(exc)
sys.stdout.write('port closed\n')
with serial.Serial() as s:
s.port = '/dev/ttyAMA0'
s.baudrate = 115200
s.timeout = .5
s.open()
with ReaderThread(s, PrintLines) as protocol:
js = {
'function': args['mode'],
'args': args['args']
}
protocol.write_line(json.dumps(js))
sleep(2)
And the output:
pi@rpi0:~/serial$ ./serial_mode.py --mode 'Object Recognition' --args 'yolo_20class'
port opened
line received: '{"msg":"function switched to object_recognition."}'
line received: '{"msg":"Running Object Recognition, Copyright 2021 M5Stack Technology Co., Ltd. All rights reserved.","running":"Object Recognition"}'
port closed