canboot: initial source commit

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Arksine committed 2021-02-06 20:04:47 -05:00
1 parent 55f89916cf
commit 2762299895
122 files changed
+657354

No files matched your search

+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python2
# Script to handle build time requests embedded in C code.
#
# Copyright (C) 2016-2018 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys, optparse, logging
FILEHEADER = """
/* DO NOT EDIT! This is an autogenerated file. See scripts/buildcommands.py. */
#include <stdint.h>
#include "compiler.h"
#include "board/misc.h"
#include "board/gpio.h"
"""
def error(msg):
sys.stderr.write(msg + "\n")
sys.exit(-1)
Handlers = []
######################################################################
# Enumeration and static string generation
######################################################################
STATIC_STRING_MIN = 2
# Generate a dynamic string to integer mapping
class HandleEnumerations:
def __init__(self):
self.static_strings = []
self.enumerations = {}
self.ctr_dispatch = {
'DECL_ENUMERATION': self.decl_enumeration,
'DECL_ENUMERATION_RANGE': self.decl_enumeration_range
}
def add_enumeration(self, enum, name, value):
enums = self.enumerations.setdefault(enum, {})
if name in enums and enums[name] != value:
error("Conflicting definition for enumeration '%s %s'" % (
enum, name))
enums[name] = value
def decl_enumeration(self, req):
enum, name, value = req.split()[1:]
self.add_enumeration(enum, name, int(value, 0))
def decl_enumeration_range(self, req):
enum, name, value, count = req.split()[1:]
self.add_enumeration(enum, name, (int(value, 0), int(count, 0)))
def get_available_pins(self):
avail_pins = {}
pin_enums = self.enumerations.get('pin')
if pin_enums is None:
error("No pin enumeration available")
for port_id, (offset, count) in pin_enums.items():
for i in range(count):
pin_name = "%s%d" % (port_id[:-1], i)
pin_num = i + offset
avail_pins[pin_name] = pin_num
return avail_pins
def generate_code(self, options):
return ""
HandlerEnumerations = HandleEnumerations()
Handlers.append(HandlerEnumerations)
######################################################################
# Constants
######################################################################
# Allow adding build time constants to the data dictionary
class HandleConstants:
def __init__(self):
self.constants = {}
self.ctr_dispatch = {
'DECL_CONSTANT': self.decl_constant,
'DECL_CONSTANT_STR': self.decl_constant_str,
}
self.reserved_pins = []
def set_value(self, name, value):
if name in self.constants and self.constants[name] != value:
error("Conflicting definition for constant '%s'" % name)
self.constants[name] = value
def decl_constant(self, req):
name, value = req.split()[1:]
self.set_value(name, int(value, 0))
def decl_constant_str(self, req):
name, value = req.split(None, 2)[1:]
value = value.strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
self.set_value(name, value)
def get_reserved_pins(self):
reserved_pins = []
for name, val in self.constants.items():
if name.upper().startswith("RESERVE_PINS"):
rpins = [v.strip() for v in val.split(',') if v.strip()]
reserved_pins.extend(rpins)
return reserved_pins
def generate_code(self, options):
return ""
HandlerConstants = HandleConstants()
Handlers.append(HandlerConstants)
######################################################################
# ARM IRQ vector table generation
######################################################################
# Create ARM IRQ vector table from interrupt handler declarations
class Handle_arm_irq:
def __init__(self):
self.irqs = {}
self.ctr_dispatch = { 'DECL_ARMCM_IRQ': self.decl_armcm_irq }
def decl_armcm_irq(self, req):
func, num = req.split()[1:]
num = int(num, 0)
if num in self.irqs and self.irqs[num] != func:
error("Conflicting IRQ definition %d (old %s new %s)"
% (num, self.irqs[num], func))
self.irqs[num] = func
def generate_code(self, options):
armcm_offset = 16
if 1 - armcm_offset not in self.irqs:
# The ResetHandler was not defined - don't build VectorTable
return ""
max_irq = max(self.irqs.keys())
table = [" DefaultHandler,\n"] * (max_irq + armcm_offset + 1)
defs = []
for num, func in self.irqs.items():
if num < 1 - armcm_offset:
error("Invalid IRQ %d (%s)" % (num, func))
defs.append("extern void %s(void);\n" % (func,))
table[num + armcm_offset] = " %s,\n" % (func,)
table[0] = " &_stack_end,\n"
fmt = """
extern void DefaultHandler(void);
extern uint32_t _stack_end;
%s
const void *VectorTable[] __visible __section(".vector_table") = {
%s};
"""
return fmt % (''.join(defs), ''.join(table))
Handlers.append(Handle_arm_irq())
######################################################################
# Status LED Functionality
######################################################################
class HandleStatusLED:
def __init__(self):
self.ctr_dispatch = {}
def generate_code(self, options):
pin = options.led_pin
if not pin:
led_def = led_init = led_toggle = led_on = led_off = ""
else:
led_def = "static struct gpio_out led;"
led_init = "led = gpio_out_setup(%d, %d);"
led_toggle = "gpio_out_toggle(led);"
led_write = "gpio_out_write(led, %d);"
write_on = 1
if pin[0] == "!":
write_on = 0
pin = pin[1:].upper()
avail_pins = HandlerEnumerations.get_available_pins()
reserved_pins = HandlerConstants.get_reserved_pins()
pin_num = avail_pins.get(pin)
if pin_num is None:
error("Pin %s is not available for this build" % pin)
if pin in reserved_pins:
error("Pin %s is reserved by an active MCU peripheral" % pin)
led_init = led_init % (pin_num, write_on)
led_on = led_write % (write_on)
led_off = led_write % (int(not write_on))
fmt = """
%s
void __always_inline
led_init(void)
{
%s
}
void __always_inline
led_toggle(void)
{
%s
}
void __always_inline
led_on(void)
{
%s
}
void __always_inline
led_off(void)
{
%s
}
"""
return fmt % (led_def, led_init, led_toggle, led_on, led_off)
Handlers.append(HandleStatusLED())
######################################################################
# Main code
######################################################################
def main():
usage = "%prog [options] <cmd section file> <output.c>"
opts = optparse.OptionParser(usage)
opts.add_option("-l", "--ledpin", dest="led_pin", default="",
help="LED Status Pin")
opts.add_option("-v", action="store_true", dest="verbose",
help="enable debug messages")
options, args = opts.parse_args()
if len(args) != 2:
opts.error("Incorrect arguments")
incmdfile, outcfile = args
if options.verbose:
logging.basicConfig(level=logging.DEBUG)
# Parse request file
ctr_dispatch = { k: v for h in Handlers for k, v in h.ctr_dispatch.items() }
f = open(incmdfile, 'rb')
data = f.read()
f.close()
for req in data.split('\n'):
req = req.lstrip()
if not req:
continue
cmd = req.split()[0]
if cmd not in ctr_dispatch:
error("Unknown build time command '%s'" % cmd)
ctr_dispatch[cmd](req)
# Write output
code = "".join([FILEHEADER] + [h.generate_code(options) for h in Handlers])
f = open(outcfile, 'wb')
f.write(code)
f.close()
if __name__ == '__main__':
main()
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# This script checks for a broken Ubuntu 18.04 arm-none-eabi-gcc compile
f1="$1"
f2="$2"
s1=`readelf -A "$f1" | grep "Tag_ARM_ISA_use"`
s2=`readelf -A "$f2" | grep "Tag_ARM_ISA_use"`
if [ "$s1" != "$s2" ]; then
echo ""
echo "ERROR: The compiler failed to correctly compile Klipper"
echo "It will be necessary to upgrade the compiler"
echo "See: https://bugs.launchpad.net/ubuntu/+source/newlib/+bug/1767223"
echo ""
rm -f "$f1"
exit 99
fi
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env python2
# Script to upload software via Can Bootloader
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
import os
import time
import argparse
import hashlib
import traceback
import serial
def output_line(msg):
sys.stdout.write(msg + "\n")
sys.stdout.flush()
def output(msg):
sys.stdout.write(msg)
sys.stdout.flush()
SERIAL_BAUD = 250000
CMD_HEADER = b"cbtl"
CMD_TRAILER = b"\x03"
BOOTLOADER_CMDS = {
'CONNECT': b"\x01",
'SEND_BLOCK': b"\x02",
'SEND_EOF': b"\x03",
'REQUEST_BLOCK': b"\x04",
'COMPLETE': b"\x05"
}
ACK_CMD = bytearray(CMD_HEADER + b"\x10")
ACK_BLOCK_RECD = bytearray(CMD_HEADER + b"\x11")
NACK = bytearray(CMD_HEADER + b"\x20")
class FlashCanError(Exception):
pass
class FlashCan:
def __init__(self, dev_name, fw_file):
if not os.path.exists(dev_name):
raise FlashCanError("Cannot find device '%s'" % (dev_name))
if not os.path.isfile(fw_file):
raise FlashCanError("Invalid firmware path '%s'" % (fw_file))
# TODO: We need to enter the bootloader first
self.ser = serial.Serial(dev_name, SERIAL_BAUD, timeout=.1)
self.fw_name = fw_file
self.fw_sha = hashlib.sha1()
self.file_size = 0
self.block_size = 64
self.block_count = 0
def connect_btl(self):
output_line("Attempting to connect to bootloader")
self.block_size = self.send_command('CONNECT')
if self.block_size not in [64, 128, 256, 512]:
raise FlashCanError("Invalid Block Size: %d" % (self.block_size,))
output_line("Connected, Block Size: %d bytes" % (self.block_size,))
def serial_read(self, count):
ret = b""
tries = 10
while tries:
data = self.ser.read(count)
count -= len(data)
ret += data
if not count:
break
tries -= 1
return ret
def send_command(self, cmdname, ack=ACK_CMD, arg=0, tries=5):
cmd = BOOTLOADER_CMDS[cmdname]
out_cmd = bytearray(CMD_HEADER + cmd)
out_cmd.append((arg >> 8) & 0xFF)
out_cmd.append(arg & 0xFF)
out_cmd.append(CMD_TRAILER)
while tries:
try:
self.ser.write(out_cmd)
data = bytearray(self.serial_read(8))
except Exception:
traceback.print_exc()
else:
if len(data) == 8 and data.startswith(ack) and \
data.endswith(CMD_TRAILER):
return (data[5] << 8) | data[6]
tries -= 1
time.sleep(.1)
raise FlashCanError("Error sending command [%s] to Can Device"
% (cmdname))
def send_file(self):
last_percent = 0
output_line("Flashing '%s'..." % (self.fw_name))
output("\n[")
with open(self.fw_name, 'rb') as f:
f.seek(0, os.SEEK_END)
self.file_size = f.tell()
f.seek(0)
while True:
buf = f.read(self.block_size)
if not buf:
break
self.send_command('SEND_BLOCK', arg=self.block_count)
if len(buf) < self.block_size:
buf += b"\xFF" * (self.block_size - len(buf))
self.fw_sha.update(buf)
self.ser.write(buf)
ack = self.serial_read(8)
expect = bytearray(ACK_BLOCK_RECD)
expect.append((self.block_count >> 8) & 0xFF)
expect.append(self.block_count & 0xFF)
expect.append(CMD_TRAILER)
if ack != expect:
output_line("\nExpected resp: %s, Recd: %s" % (expect, ack))
raise FlashCanError("Did not receive ACK for sent block %d"
% (self.block_count))
self.block_count += 1
uploaded = self.block_count * self.block_size
pct = int(uploaded / float(self.file_size) * 100 + .5)
if pct >= last_percent + 2:
last_percent += 2.
output("#")
page_count = self.send_command('SEND_EOF')
output_line("]\n\nWrite complete: %d pages" % (page_count))
def verify_file(self):
last_percent = 0
output_line("Verifying (block count = %d)..." % (self.block_count,))
output("\n[")
ver_sha = hashlib.sha1()
for i in range(self.block_count):
tries = 3
while tries:
resp = self.send_command("REQUEST_BLOCK", arg=i)
if resp == i:
# command should ack with the requested block as
# parameter
buf = self.serial_read(self.block_size)
if len(buf) == self.block_size:
break
tries -= 1
time.sleep(.1)
else:
output_line("Error")
raise FlashCanError("Block Request Error, block: %d" % (i,))
ver_sha.update(buf)
pct = int(i * self.block_size / float(self.file_size) * 100 + .5)
if pct >= last_percent + 2:
last_percent += 2
output("#")
ver_hex = ver_sha.hexdigest().upper()
fw_hex = self.fw_sha.hexdigest().upper()
if ver_hex != fw_hex:
raise FlashCanError("Checksum mismatch: Expected %s, Received %s"
% (fw_hex, ver_hex))
output_line("]\n\nVerification Complete: SHA = %s" % (ver_hex))
def finish(self):
self.send_command("COMPLETE")
def close(self):
self.ser.close()
def main():
parser = argparse.ArgumentParser(
description="Can Bootloader Flash Utility")
parser.add_argument('device', metavar="<device>",
help="Can device location")
parser.add_argument('fwpath', metavar="<klipper.bin>",
help="Path to firmware file")
args = parser.parse_args()
fcan = None
dev = args.device
fname = os.path.abspath(os.path.expanduser(args.fwpath))
try:
fcan = FlashCan(dev, fname)
time.sleep(1.)
fcan.connect_btl()
fcan.send_file()
fcan.verify_file()
fcan.finish()
except Exception as e:
output("Can Flash Error: ")
output_line(str(e))
sys.exit(-1)
finally:
if fcan is not None:
fcan.close()
output_line("CAN Flash Success")
if __name__ == '__main__':
main()