Commit 52f47943 authored by Nelso Jost's avatar Nelso Jost

FIX: improved pio manager Makefile

parent 0a4a89a7
BOARD := uno
PROJDIR := firmware/adafruit_bmp
PIOSETUP := python ../../utils/piosetup.py
PIODIR := .pio
.PHONY: monitor uno due nano mega clean
all:
$(MAKE) $(BOARD)
uno:
$(PIOSETUP) --board uno --project-dir $(PROJDIR) --pio-dir $(PIODIR)
$(MAKE) monitor
due:
$(PIOSETUP) --board diecimilaatmega328 --pio-dir $(PIODIR)
nano:
$(PIOSETUP) --board nanoatmega328 --pio-dir $(PIODIR)
mega:
$(PIOSETUP) --board megaatmega2560 --pio-dir $(PIODIR)
monitor:
picocom --baud $(shell $(GET_BAUD)) $(shell $(GET_PORT))
clean:
rm -rf .pio .travis.yml
define GET_BAUD
cat $(PROJDIR)/*.ino | grep '^#define BAUDRATE' | awk '{print $$3}'
endef
define GET_PORT
platformio device list | head -1
endef
/home/nelso/devel/meteorolog/utils/pioman/Makefile
\ No newline at end of file
BOARD := uno
PROJDIR := meteorolog
PIOSETUP := python ../utils/piosetup.py
PIODIR := .pio
.PHONY: monitor uno due nano mega clean
all:
$(MAKE) $(BOARD)
uno:
$(PIOSETUP) --board uno --project-dir $(PROJDIR) --pio-dir $(PIODIR)
$(MAKE) monitor
due:
$(PIOSETUP) --board diecimilaatmega328 --pio-dir $(PIODIR)
nano:
$(PIOSETUP) --board nanoatmega328 --pio-dir $(PIODIR)
mega:
$(PIOSETUP) --board megaatmega2560 --pio-dir $(PIODIR)
monitor:
python3 ../utils/qtsermon.py --baud $(shell $(GET_BAUD))
picocom:
picocom --baud $(shell $(GET_BAUD)) $(shell $(GET_PORT))
clean:
rm -rf .pio .travis.yml
define GET_BAUD
cat $(PROJDIR)/*.ino | grep '^#define BAUDRATE' | awk '{print $$3}'
endef
define GET_PORT
platformio device list | head -1
endef
/home/nelso/devel/meteorolog/utils/pioman/Makefile
\ No newline at end of file
| Uno | Due | Mega | Nano
------------------------|-----|-----|------|------
bmp085 (Vin-->3.3V) | 4.7 | 3.3 | 4.4 | 3.4
rtcDS1307 (Vin-->5V) | 5.0 | 5.0 | 5.0 | 4.7
SDA/SCL | 4.9 | 3.4 | 4.9 | 3.3
------------------------|-----|-----|------|------
bmp085 (Vin-->ext) | 3.3 | 3.3 | |
rtcDS1307 (Vin->5V) | 5.0 | 5.0 | |
SDA/SCL | 3.9 | 3.9 | |
import serial
import sys
import time
from datetime import datetime
def get_serial(baudrate=9600, read_timeout=1.5, board_reset_timeout=2,
find_port_timeout=0.5):
ports = []
for i in range(5):
ports.append('/dev/ttyACM{}'.format(i))
ports.append('/dev/ttyUSB{}'.format(i))
i = 0
while True:
serial_port = ports[i]
try:
ser = serial.Serial(port=serial_port,
baudrate=baudrate,
timeout=read_timeout,
xonxoff=True)
time.sleep(board_reset_timeout)
return ser
except Exception as e:
print("Exception: {}".format(e))
if i < len(ports) - 1:
i += 1
else:
i = 0
time.sleep(find_port_timeout)
def send(command_str, response_wait=0):
'''
Send the string 'command_str' to the serial port and return the response.
'''
ser.write(bytes(command_str, encoding='utf-8'))
# time.sleep(response_wait)
try:
raw = ser.readall()
return raw.decode('ascii').strip()
except:
print("Unable to decode raw response to ASCII:\n{}".format(raw))
def sync_rtc():
'''
Synchronizes the board clock with the system's.
'''
dt = datetime.now()
print('\nCurrent system time:', dt.isoformat().replace('T', ' '))
print("\nAttempting serial connection ...", end='')
ser = get_serial()
print('got it!')
print(ser)
ser.flush()
command = 'setrtc,{Y},{m},{d},{H},{M},{S}'.format(
Y=dt.year, m=dt.month, d=dt.day, H=dt.hour, M=dt.minute, S=dt.second)
print('\nSending serial command:\n "{}"\n'.format(command))
ser.write(bytes(command, encoding='utf-8'))
try:
raw = ser.readall()
return raw.decode('ascii').strip()
except:
print("Unable to decode raw response to ASCII:\n{}".format(raw))
def loop_serial():
print(
"""\
Examples:
> read,t,l # for reading temp. and lum.
> setrtc,2015,7,15,17,45,0 # for setting RTC datetime
Hit Ctrl+C to exit!""")
print('-'*40 + '\n')
try:
while True:
print(send(input('> ')))
except:
pass
print('baka')
print("\nAttempting serial connection ...\n")
ser = get_serial()
print(ser)
ser.flush()
print("\nSent 'help'... waiting for board response ...")
response = send('help')
print("\nBoard commands:\n" + '-'*40 + '\n' + response + '\n' + '-'*40)
print('-'*40 + '\n')
if '-c' in sys.argv and len(sys.argv) == 3:
print(send(input('> ')))
elif '--loop' in sys.argv:
loop_serial()
elif '--syncrtc' in sys.argv:
print(sync_rtc())
BUILDDIR=".build"
exec 3>&1;
BOARDNAME=$(dialog --no-cancel --no-ok --no-tags --menu \
"Select your Arduino board model:" 0 0 4 \
"uno" "Uno" \
"diecimilaatmega328" "Duemilanove ATmega328" \
"megaatmega2560" "Mega ATmega2560" \
"nanoatmega328" "Nano ATmega328" \
"leonardo" "Leonardo" \)
2>&1 1>&3);
EXITCODE=$?;
exec 3>&-;
mkdir -p $BUILDDIR && rm -rf $BUILDDIR/* && cd $BUILDDIR \
&& yes | platformio init --board $BOARDNAME \
&& cp -r ../firmware/meteorolog/* src/. && \
platformio run -t upload
BOARD := uno
PIODIR := .pio
MAKEFILEDIR := $(shell python -c "import os; print(os.path.dirname(\
'$(shell readlink Makefile)'))")
PIOMAN := python3 $(MAKEFILEDIR)/pioman.py
QTSERMON := python3 $(MAKEFILEDIR)/qtsermon.py
.PHONY: build monitor uno due nano mega qtsermon picocom clean baka
all: build monitor
monitor: qtsermon
build:
$(PIOMAN) build --board $(BOARD) --pio-dir $(PIODIR)
uno:
$(PIOMAN) build --board uno --pio-dir $(PIODIR)
due:
$(PIOMAN) build --board diecimilaatmega328 --pio-dir $(PIODIR)
nano:
$(PIOMAN) build --board nanoatmega328 --pio-dir $(PIODIR)
mega:
$(PIOMAN) build --board megaatmega2560 --pio-dir $(PIODIR)
qtsermon:
$(QTSERMON) --baud $(shell $(PIOMAN) getbaud)
picocom:
picocom --baud $(shell $(GET_BAUD)) $(shell $(GET_PORT))
getbaud:
@ $(PIOMAN) getbaud
clean:
rm -rf $(PIODIR) .travis.yml
define GET_PORT
platformio device list | head -1
endef
import argparse
import os
def getproj(args):
hasproj = lambda d: any(x for x in os.listdir(d) if x.endswith(".ino")\
or x.endswith(".pde"))
dirs = [d for d in os.listdir(".") if os.path.isdir(d) and hasproj(d)]
if dirs:
return dirs[0]
else:
print('[Error] Unable to find Arduino IDE project directory here!\nIt must have a ".ino" or ".pde" file in it.')
raise SystemExit(1)
def getbaud(args):
args.project_dir = args.project_dir or getproj(args)
ino_filename = [x for x in os.listdir(args.project_dir)
if x.endswith('ino') or x.endswith('pde')][0]
for line in open(os.path.join(args.project_dir, ino_filename)):
if line.strip().startswith('#define BAUDRATE'):
print(line.strip().split(' ')[-1])
def build(args):
args.project_dir = args.project_dir or getproj(args)
SCRIPT_BUILD =\
"""\
mkdir -p {pio_dir}
rm -rf {pio_dir}/src
platformio init --project-dir {pio_dir} --board {board}
rm -rf {pio_dir}/src/*
cp -rf {project_dir}/* {pio_dir}/src/
cd {pio_dir} && platformio run --environment {board} --target upload
""".format(**vars(args))
print(SCRIPT_BUILD)
os.system(SCRIPT_BUILD)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='''\
Utility for building Arduino IDE based projects with PlatformIO''')
parser.add_argument('command', choices=['build', 'getproj', 'getbaud'])
parser.add_argument('-p', '--project-dir', default=None)
parser.add_argument('-d', '--pio-dir', default='.pio')
parser.add_argument('-b', '--board', default='uno')
args = parser.parse_args()
globals()[args.command](args)
......@@ -60,8 +60,11 @@ class MainWindow(qt.QMainWindow):
print('Trying to find ttyUSB|ttyACM port automatically..')
ports = [x for x in os.listdir("/dev")
if x.startswith("ttyUSB") or x.startswith("ttyACM")]
if ports:
print('Got: {}'.format(' | '.join(ports)))
return '/dev/' + ports[0]
else:
raise Exception
except Exception as e:
print("Error: Unable to find a ttyUSB/ttyACM serial port")
raise SystemExit(1)
......
import argparse
import os
parser = argparse.ArgumentParser(
description='''\
Utility for building Arduino IDE based projects with PlatformIO''')
parser.add_argument('-p', '--project-dir', required=True)
parser.add_argument('-d', '--pio-dir', default='.pio')
parser.add_argument('-b', '--board', default='uno')
args = vars(parser.parse_args())
args['project_dir'] = os.path.abspath(args['project_dir'])
SETUP_SCRIPT =\
"""\
mkdir -p {pio_dir}
rm -rf {pio_dir}/src
platformio init --project-dir {pio_dir} --board {board}
cp -rf {project_dir}/* {pio_dir}/src/
cd {pio_dir} && platformio run -t upload
""".format(**args)
print(args)
print(SETUP_SCRIPT)
os.system(SETUP_SCRIPT)
import subprocess
import dialog
import os
TOP_BOARDS = ['uno', 'diecimilaatmega328', 'megaatmega2560', 'nanoatmega328',
'leonardo']
SOURCE_DIR = "firmware/meteorolog"
shexec = lambda command:\
subprocess.check_output(command, shell=True).decode('ascii')
def get_platformio_atmelavr_boards(top_boards=[]):
''' Executes platformio board list command and parse results to a
nice and clean Python list of tuples.
'''
boards_lines = shexec("platformio boards atmelavr").splitlines()[5:]
boards, top_names = [], {}
for b in boards_lines:
cols = [x.strip() for x in b.split(' ') if x.strip() != '']
if cols[0] in top_boards:
top_names[cols[0]] = cols[-1]
else:
boards.append((cols[0], cols[-1]))
return [(x, top_names[x]) for x in TOP_BOARDS] + boards
def exec_dialog_select_board():
''' Launch a dialog with a list of boards for the user to choose.
Return the platformio board name selected.
'''
boards = get_platformio_atmelavr_boards(top_boards=TOP_BOARDS)
d = dialog.Dialog(dialog="dialog")
code, tag = d.menu("Select your board:", choices=boards,
no_cancel=True, no_ok=True, no_tags=True)
return tag
def platformio_setup(source_dir, build_dir='.build'):
board_name = exec_dialog_select_board()
print('Using board:', board_name)
os.system("""
rm -rf {build_dir} &&
mkdir -p {build_dir} &&
cd {build_dir} &&
yes | platformio init --board {board_name} &&
cp -r ../{source_dir}/* src/. &&
platformio run -t upload
""".format(**locals()).strip())
platformio_setup(source_dir=SOURCE_DIR)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment