• Reorganized the scripts into different categories

• Refactored the graphical boot screens to have separate boot and shutdown images
• Changed the reboot and shutdown code to force the display of the splash images.
• Added 'Team Onefinity.ngc' to the installer files
This commit is contained in:
David Carley
2022-07-23 20:04:17 -07:00
parent 15a98972b3
commit 41e2334484
36 changed files with 743 additions and 324 deletions

View File

@@ -0,0 +1,206 @@
#!/usr/bin/env python3
import sys
import time
import serial
import binascii
dev = '/dev/ttyAMA0'
baud = 921600
boot_id = 'bbctrl '
verbose = False
def crc16(data):
crc = 0xffff
for x in data:
crc = crc ^ int(x)
for bit in range(8):
if crc & 1: crc = (crc >> 1) ^ 0xa001
else: crc = crc >> 1
return crc
def avr_crc32(data, length):
mem = [0xff] * length
for addr, chunk in data:
for x in chunk:
mem[addr] = x
addr += 1
return binascii.crc32(bytes(mem))
def read_intel_hex(f):
base = 0
pos = 0
start = 0
chunk = None
for line in f:
line = line.strip()
if not line or line[0] != ':': continue
count = int(line[1:3], 16)
addr = int(line[3:7], 16)
type = int(line[7:9], 16)
data = line[9:-2]
checksum = int(line[-2:], 16)
if type == 0:
addr += base
data = binascii.unhexlify(bytes(data, 'utf8'))
if chunk is None or pos != addr:
if chunk is not None: yield (start, chunk)
start = addr
chunk = data
else: chunk += data
pos = addr + len(data)
if type == 2: base = int(data, 16) * 16
if chunk is not None: yield (start, chunk)
def send(data):
if verbose: print('Sending:', data)
sp.write(bytes(data, 'utf8'))
def send_int(x, size):
if verbose: print('Sending: %d', x)
sp.write((x).to_bytes(size, byteorder = 'big'))
def recv(count):
data = sp.read(count).decode('utf8')
if count and verbose: print('Received:', data)
return data
def recv_int(size):
x = int.from_bytes(sp.read(size), byteorder = 'big')
if verbose: print('Received:', x)
return x
# Read firmware hex file
data = list(read_intel_hex(open(sys.argv[1], 'r')))
# Open serial port
sp = serial.Serial(dev, baud, timeout = 10)
# Reset AVR
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(27, gpio.OUT)
gpio.output(27, 0)
gpio.output(27, 1)
gpio.setup(27, gpio.IN, pull_up_down = gpio.PUD_UP)
time.sleep(0.1)
# Sync
for i in range(10): send('\x1b')
# Flush serial
try:
recv(sp.in_waiting)
except: pass
# Get bootloader ID
send('S')
if boot_id != recv(len(boot_id)):
raise Exception('Failed to communicate with bootloader')
# Get version
send('V')
major = int(recv(1))
minor = int(recv(1))
print('Bootloader version: %d.%d' % (major, minor))
# If bootloader is new enough compare checksums
if 0 < major or 1 < minor:
# Get flash length
send('n')
flash_len = recv_int(3)
# Get current flash CRC
send('X')
new_crc = avr_crc32(data, flash_len)
old_crc = recv_int(4)
if old_crc == new_crc:
print('Flash already up to date')
sys.exit(0)
print('CRC: old=0x%08x new=0x%08x' % (old_crc, new_crc))
# Erase
send('e')
if recv(1) != '\r': raise Exception('Flash erase failed')
# Get page size
send('b')
if recv(1) != 'Y': raise Exception('Cannot get page size')
page_size = recv_int(2)
print('Page size:', page_size)
# Program
print('Programming', end = '')
count = 0
retry = 0
for addr, chunk in data:
# Set address
send('H')
send_int(addr, 3)
if recv(1) != '\r': raise Exception('Failed to set address')
while len(chunk):
sys.stdout.flush()
page = chunk[0:512]
# Block command
send('B')
# Send block size
send_int(len(page), 2)
# Send memory type
send('F')
# Send block
sp.write(page)
if recv(1) != '\r': raise Exception('Failed to write block')
# Get and check block CRC
send('i')
crc = recv_int(2)
expect = crc16(page)
if crc != expect:
retry += 1
if retry == 5:
raise Exception('CRC mismatch %d != %d' % (crc, expect))
print('x', end = '')
continue
count += len(page)
chunk = chunk[512:]
retry = 0
print('.', end = '')
print('done')
print('Wrote %d bytes' % count)
# Exit bootloader
send('E')

15
installer/scripts/browser Normal file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env python3
import os
import sys
import subprocess
def enter_cgroup():
with open('/sys/fs/cgroup/memory/chrome/tasks', 'w') as f:
f.write(str(os.getpid()))
# Start browser
args = ['/usr/lib/chromium-browser/chromium-browser'] + sys.argv[1:]
subprocess.Popen(args, preexec_fn = enter_cgroup).wait()

View File

@@ -0,0 +1,262 @@
#!/bin/bash -e
AP=false
DISABLE=false
SSID=
PASS=
CHANNEL=7
REBOOT=false
WLAN0_CFG=/etc/network/interfaces.d/wlan0
HOSTAPD_CFG=/etc/hostapd/hostapd.conf
DNSMASQ_CFG=/etc/dnsmasq.conf
DHCPCD_CFG=/etc/dhcpcd.conf
WPA_CFG=/etc/wpa_supplicant/wpa_supplicant.conf
function query_config() {
if [ -e $WLAN0_CFG ]; then
SSID=$(grep wpa-ssid $WLAN0_CFG |
sed 's/^[[:space:]]*wpa-ssid "\([^"]*\)"/\1/')
# echo "{\"ssid\": \"$SSID\", \"mode\": \"client\"}"
echo "{\"ssid\": \"$SSID\"}"
else
# if [ -e $HOSTAPD_CFG -a -e /etc/default/hostapd ]; then
# SSID=$(grep ^ssid= $HOSTAPD_CFG | sed 's/^ssid=\(.*\)$/\1/')
# CHANNEL=$(grep ^channel= $HOSTAPD_CFG |
# sed 's/^channel=\(.*\)$/\1/')
# echo -n "{\"ssid\": \"$SSID\", "
# echo "\"channel\": $CHANNEL, \"mode\": \"ap\"}"
# else
# echo "{\"mode\": \"disabled\"}"
# fi
echo "{}"
fi
}
function disable_wifi() {
rm -f $WLAN0_CFG $HOSTAPD_CFG /etc/default/hostapd
}
function configure_wlan0() {
echo "auto wlan0"
echo "allow-hotplug wlan0"
echo "iface wlan0 inet dhcp"
echo " wpa-scan-ssid 1"
echo " wpa-ap-scan 1"
echo " wpa-key-mgmt WPA-PSK"
echo " wpa-proto RSN WPA"
echo " wpa-pairwise CCMP TKIP"
echo " wpa-group CCMP TKIP"
echo " wpa-ssid \"$SSID\""
if [ ${#PASS} -ne 0 ]; then
echo " wpa-psk \"$PASS\""
fi
}
function configure_wpa() {
echo "country=US"
echo "ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev"
echo "update_config=1"
if [ ${#PASS} -eq 0 ]; then
echo "network={"
echo " ssid=\"$SSID\""
echo " key_mgmt=NONE"
echo "}"
fi
}
function configure_dhcpcd() {
echo "hostname"
echo "clientid"
echo "persistent"
echo "option rapid_commit"
echo "option domain_name_servers, domain_name, domain_search, host_name"
echo "option classless_static_routes"
echo "option ntp_servers"
echo "option interface_mtu"
echo "require dhcp_server_identifier"
echo "slaac private"
if $AP; then
echo
echo "interface wlan0"
echo " static ip_address=192.168.43.1/24"
fi
}
function configure_wifi() {
disable_wifi
echo "source-directory /etc/network/interfaces.d" > /etc/network/interfaces
configure_wlan0 > $WLAN0_CFG
configure_wpa > $WPA_CFG
configure_dhcpcd > $DHCPCD_CFG
}
function configure_dnsmasq() {
echo "interface=wlan0"
echo "domain-needed"
echo "bogus-priv"
echo "dhcp-range=192.168.43.2,192.168.43.20,255.255.255.0,12h"
}
function configure_hostapd() {
echo "interface=wlan0"
echo "driver=nl80211"
echo "ssid=$SSID"
echo "hw_mode=g"
echo "channel=$CHANNEL"
echo "wmm_enabled=0"
echo "macaddr_acl=0"
echo "auth_algs=1"
echo "ignore_broadcast_ssid=0"
echo "wpa=2"
echo "wpa_passphrase=$PASS"
echo "wpa_key_mgmt=WPA-PSK"
echo "wpa_pairwise=TKIP"
echo "rsn_pairwise=CCMP"
}
function is_installed() {
dpkg-query -W --showformat='${Status}' $1 |
grep "install ok installed" >/dev/null
if [ $? -eq 0 ]; then echo true; else echo false; fi
}
function configure_ap() {
disable_wifi
# Install packages
(
$(is_installed dnsmasq) &&
$(is_installed hostapd) &&
$(is_installed iptables-persistent)
) || (
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -yq dnsmasq hostapd iptables-persistent
)
configure_dhcpcd > $DHCPCD_CFG
configure_dnsmasq > $DNSMASQ_CFG
configure_hostapd > $HOSTAPD_CFG
echo "DAEMON_CONF=\"/etc/hostapd/hostapd.conf\"" > /etc/default/hostapd
# Enable IP forwarding
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
echo 1 > /proc/sys/net/ipv4/ip_forward
# Enable IP masquerading
iptables -t nat -F
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables-save > /etc/iptables/rules.v4
}
function usage() {
echo "Usage: config-wifi [OPTIONS]"
echo
echo "Configure wifi as either a client or access point."
echo
echo "OPTIONS:"
echo
echo " -a Configure access point."
echo " -d Disable wifi."
echo " -r Reboot when done."
echo " -s <SSID> Set SSID."
echo " -p <PASS> Set password."
echo " -c <CHANNEL> Set wifi channel."
echo " -j Report wifi config as JSON data."
echo
}
# Parse args
while [ $# -ne 0 ]; do
case "$1" in
-a) AP=true ;;
-d) DISABLE=true ;;
-r) REBOOT=true; ;;
-s) SSID="$2"; shift ;;
-p) PASS="$2"; shift ;;
-c) CHANNEL="$2"; shift ;;
-j) query_config; exit 0 ;;
-h)
usage
exit 0
;;
*)
usage
echo "Unknown argument '$1'"
exit 1
esac
shift
done
if $DISABLE; then
disable_wifi
else
# Check args
function clean_str() {
echo "$1" | tr -d '\n\r"'
}
SSID=$(clean_str "$SSID")
PASS=$(clean_str "$PASS")
LANG=C LC_ALL=C # For correct string byte length
if [ ${#SSID} -eq 0 -o 32 -lt ${#SSID} ]; then
echo "Invalid or missing SSID '$SSID'"
exit 1
fi
if [ ${#PASS} -ne 0 ]; then
if [ ${#PASS} -lt 8 -o 128 -lt ${#PASS} ]; then
echo "Invalid passsword"
exit 1
fi
fi
echo "$CHANNEL" | grep '^[0-9]\{1,2\}' > /dev/null
if [ $? -ne 0 ]; then
echo "Invalid channel '$CHANNEL'"
exit 1
fi
# Execute
if $AP; then
echo "Configuring Wifi access point"
configure_ap
else
echo "Configuring Wifi"
configure_wifi
fi
fi
if $REBOOT; then nohup reboot & fi

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env python3
import sqlite3
db = sqlite3.connect('/home/pi/.config/chromium/Default/Cookies')
cur = db.cursor()
cur.execute("DELETE FROM cookies WHERE creation_utc < 13240000000000000")
db.commit()

View File

@@ -0,0 +1,12 @@
#!/bin/bash
cp /boot/config.txt /tmp/
edit-config /tmp/config.txt "$@"
diff /boot/config.txt /tmp/config.txt >/dev/null
if [ $? -eq 1 ]; then
mount -o remount,rw /boot
mv /tmp/config.txt /boot/
mount -o remount,ro /boot
fi

83
installer/scripts/edit-config Executable file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env python3
import sys
import argparse
import re
def option_type(s, pat = re.compile(r'\w+=.*')):
if not pat.match(s): raise argparse.ArgumentTypeError
return s
parser = argparse.ArgumentParser(description = 'Edit config file.')
parser.add_argument('config', help = 'The configuration file to edit.')
parser.add_argument('options', nargs = '*', type = option_type,
metavar = '<name>=<value>', help = 'An option to set.')
args = parser.parse_args()
# Parse config lines and options
lines = []
options = {}
optRE = re.compile(r'(\w+)\s*=\s*([^#]+)(#.*)?')
class Line:
def __init__(self, text, name = None, value = None, comment = None):
self.text = text
self.name = name
self.value = value
self.comment = comment
def __str__(self):
if self.name is not None:
if self.value.strip():
text = '%s=%s' % (self.name, self.value)
if self.comment: text += ' # ' + self.comment
text += '\n'
return text
else: return ''
return self.text
with open(args.config, 'r') as f:
for line in f:
m = optRE.match(line.strip())
if m: name, value, comment = m.groups()
else: name, value, comment = None, None, None
l = Line(line, name, value, comment)
lines.append(l)
if name is not None: options[name] = l
# Save original config
config = ''.join(map(str, lines))
# Set options
first = True
for opt in args.options:
name, value = opt.split('=', 1)
if name in options: options[name].value = value
else:
if first and len(lines) and str(lines[:-1]).strip() != '':
first = False
lines.append(Line('\n'))
lines.append(Line(None, name, value, None))
# Assemble new config
new_config = ''.join(map(str, lines))
if new_config != config:
with open(args.config, 'w') as f:
f.write(new_config)

View File

@@ -0,0 +1,25 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: resize2fs_once
# Required-Start:
# Required-Stop:
# Default-Start: 3
# Default-Stop:
# Short-Description: Resize the root filesystem to fill partition
# Description:
### END INIT INFO
. /lib/lsb/init-functions
case "$1" in
start)
log_daemon_msg "Starting resize2fs_once"
ROOT_DEV=$(findmnt / -o source -n) &&
resize2fs $ROOT_DEV &&
update-rc.d resize2fs_once remove &&
rm /etc/init.d/resize2fs_once &&
log_end_msg $?
;;
*)
echo "Usage: $0 start" >&2
exit 3
;;
esac

View File

@@ -0,0 +1,79 @@
#!/bin/bash
# Used by the OneFinity firmware to determine if the root filesystem
# needs to be enlarged to maximize usage of the SD card.
#
# The majority of this code originates from /usr/lib/raspi-config/init_resize.sh
get_fs_resize_variables () {
ROOT_PART_DEV=$(findmnt / -o source -n)
ROOT_PART_NAME=$(echo "$ROOT_PART_DEV" | cut -d "/" -f 3)
ROOT_DEV_NAME=$(echo /sys/block/*/"${ROOT_PART_NAME}" | cut -d "/" -f 4)
ROOT_DEV="/dev/${ROOT_DEV_NAME}"
ROOT_PART_NUM=$(cat "/sys/block/${ROOT_DEV_NAME}/${ROOT_PART_NAME}/partition")
BOOT_PART_DEV=$(findmnt /boot -o source -n)
BOOT_PART_NAME=$(echo "$BOOT_PART_DEV" | cut -d "/" -f 3)
BOOT_DEV_NAME=$(echo /sys/block/*/"${BOOT_PART_NAME}" | cut -d "/" -f 4)
ROOT_DEV_SIZE=$(cat "/sys/block/${ROOT_DEV_NAME}/size")
TARGET_END=$((ROOT_DEV_SIZE - 1))
PARTITION_TABLE=$(parted -m "$ROOT_DEV" unit s print | tr -d 's')
LAST_PART_NUM=$(echo "$PARTITION_TABLE" | tail -n 1 | cut -d ":" -f 1)
ROOT_PART_LINE=$(echo "$PARTITION_TABLE" | grep -e "^${ROOT_PART_NUM}:")
ROOT_PART_END=$(echo "$ROOT_PART_LINE" | cut -d ":" -f 3)
}
should_resize_root_partition() {
get_fs_resize_variables
if [ "$BOOT_DEV_NAME" != "$ROOT_DEV_NAME" ]; then
FAIL_REASON="Boot and root partitions are on different devices"
return 1
fi
if [ "$ROOT_PART_NUM" -ne "$LAST_PART_NUM" ]; then
FAIL_REASON="Root partition should be last partition"
return 1
fi
if [ "$ROOT_PART_END" -gt "$TARGET_END" ]; then
FAIL_REASON="Root partition runs past the end of device"
echo $FAIL_REASON
return 1
fi
if [ ! -b "$ROOT_DEV" ] || [ ! -b "$ROOT_PART_DEV" ] || [ ! -b "$BOOT_PART_DEV" ] ; then
FAIL_REASON="Could not determine partitions"
return 1
fi
if [ "$ROOT_PART_END" -eq "$TARGET_END" ]; then
FAIL_REASON="Root partition is already expanded"
return 1
fi
}
if should_resize_root_partition; then
grep "init_resize" /boot/cmdline.txt >/dev/null
if [ $? -ne 0 ]; then
# On the next boot, init_resize.sh will:
# Resize the root partition to use the rest of the SD card
# Remove itself from /boot/cmdline.txt
# Reboot the machine
sudo mount /boot -o rw,remount
sed -i 's/\(.*\)/\1 init=\/usr\/lib\/raspi-config\/init_resize.sh/' /boot/cmdline.txt
fi
# On the first boot after init_resize, resize2fs_once will:
# Resize the root fs to fill its partition
# Remove itself from the registered systemd services
# Delete itself from the filesystem
# Therefore, never run again
cp scripts/resize2fs_once /etc/init.d/resize2fs_once
chmod +x /etc/init.d/resize2fs_once
systemctl enable resize2fs_once
exit 0
else
echo "Not resizing root partition: $FAIL_REASON"
exit 1
fi

View File

@@ -0,0 +1,26 @@
#!/bin/bash -e
HOSTNAME="$(echo "$1" | tr '[:upper:]' '[:lower:]')"
if [ "$HOSTNAME" == "" ]; then
echo "Usage: $0 <hostname>"
exit 1
fi
if [ "$HOSTNAME" == "localhost" ]; then
echo "Cannot set hostname to 'localhost'"
exit 1
fi
if [ "$HOSTNAME" =~ ^.*\.local$ ]; then
echo "Hostname cannot end with '.local'"
exit 1
fi
if [[ ! "$HOSTNAME" =~ ^[a-zA-Z][a-zA-Z0-9-]{0,62}$ ]]; then
echo "Invalid hostname '$HOSTNAME'"
exit 1
fi
sed -i "s/^127.0.1.1\([[:space:]]*\).*$/127.0.1.1\1$HOSTNAME/" /etc/hosts
echo "$HOSTNAME" > /etc/hostname

27
installer/scripts/update-bbctrl Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
(
flock -n 9
UPDATE=/var/lib/bbctrl/firmware/update.tar.bz2
if [ ! -e "$UPDATE" ]; then
echo "Missing $UPDATE"
exit 1
fi
systemctl stop bbctrl
rm -rf /tmp/update
mkdir /tmp/update
cd /tmp/update
LOG=/var/log/bbctrl.$(date +%Y%m%d-%H%M%S).install
tar xf "$UPDATE"
cd *
./scripts/install.sh "$*" 2>&1 > $LOG
cd -
rm -rf /tmp/update $UPDATE
) 9> /var/lock/bbctrl.update.lock

View File

@@ -0,0 +1,25 @@
#!/bin/bash -e
(
flock -n 9
VERSION=$(curl -s https://raw.githubusercontent.com/OneFinityCNC/onefinity-release/master/latest.txt)
PKG_NAME=onefinity-$VERSION
PKG=/var/lib/bbctrl/firmware/update.tar.bz2
PKG_URL=https://raw.githubusercontent.com/OneFinityCNC/onefinity-release/master/$PKG_NAME.tar.bz2
logger Installing onefinity firmware $VERSION
cd /var/lib/bbctrl
mkdir -p firmware
echo Downloading $PKG_URL
curl -s $PKG_URL > $PKG
/usr/local/bin/update-bbctrl
echo Success
logger bbctrl firmware $VERSION installed
) 9> /var/lock/bbctrl.upgrade.lock