From 73b1a9a97d07943b1a5e4c110b7bddbff16ce5d8 Mon Sep 17 00:00:00 2001 From: LIN SE Date: Thu, 11 Jan 2024 13:08:36 +0100 Subject: [PATCH] wip temporary push --- display.py | 31 ++++++---- install.py | 105 ++++++++++++++++++++++++-------- servercfg/linse-box1_5b265c.cfg | 3 + 3 files changed, 101 insertions(+), 38 deletions(-) diff --git a/display.py b/display.py index 4dd7a60..e4cf402 100644 --- a/display.py +++ b/display.py @@ -5,6 +5,10 @@ import serial import socket import threading +# display tty device +tty = '/dev/ttyS1' +STARTUP_TEXT = '/root/aputools/startup_display.txt' + ESC = 0x1b ESCESC = bytes((ESC, ESC)) @@ -57,8 +61,22 @@ class Display: def __init__(self, dev, timeout=0.5, daemon=False): self.event = threading.Event() self.term = serial.Serial(dev, baudrate=115200, timeout=timeout) - if not daemon: - self.storage = bytearray() + self.storage = bytearray() + if daemon: + text = None + try: + with open(STARTUP_TEXT) as f: + text = f.read() + print('new startup text:') + print(text) + except FileNotFoundError: + pass + if text: + self.reset() + self.show(*todo_text.split('\n')[0:3]) + self.set_startup() + else: + self.storage = None self.gethost(False) self.reset() if daemon: @@ -98,14 +116,6 @@ class Display: self.storage = None self.send(SET_STARTUP, data) - def standard_startup(self): - self.storage = bytearray() - self.reset() - with open('/sys/class/net/enp1s0/address') as f: - netaddr = f.read().strip().lower() - self.show('startup ...', netaddr) - self.set_startup() - def version(self): self.term.write(bytes([ESC,ESC,1,0xf3])) reply = self.term.read(4) @@ -253,7 +263,6 @@ class Display: self.send(0xf0, 0xcb, 0xef, 0x20, 0x18) -tty = '/dev/ttyS1' daemon = False for arg in sys.argv[1:]: diff --git a/install.py b/install.py index 7e06ab6..e74e0f9 100755 --- a/install.py +++ b/install.py @@ -13,6 +13,7 @@ import os import filecmp import shutil import serial +import types from subprocess import Popen, PIPE from glob import glob from ipaddress import IPv4Interface @@ -24,6 +25,7 @@ os.chdir('/root/aputools/to_system') DEL = '__to_delete__' CFGPATH = '/root/aputools/servercfg/%s_%6.6x.cfg' +STARTUP_TEXT = '/root/aputools/startup_display.txt' COMMENT = "; please refer to README.md for help" @@ -48,6 +50,9 @@ enp4s0=192.168.3.3 [DISPLAY] {COMMENT} +line0=startup... +line1=HOST +line2=ADDR """ DHCP_HEADER = """ @@ -97,6 +102,11 @@ pip_requirements = { } +net_addr = {} # dict of +main_info = {} # info about WAN interface +dhcp_server_cfg = [] # configuration for dhcp + + def frappy(cfg=None, port=None, requirements='', **kwds): if not cfg: return None @@ -120,7 +130,37 @@ def router(**opts): return ROUTER_TEMPLATE +def display_update(cfg): + dirty = False + lines = [] + for key in ['line0', 'line1', 'line2']: + value = cfg.get(key, '') + if value.startswith('HOST'): + line = main_info.get('hostname', '') + value = 'HOST: ' + line + elif value.startswith('ADDR'): + line = main_info.get('addr', '') + value = 'ADDR: ' + line + else: + line = value + lines.append(line) + if cfg.get(key) != value: + if doit: + cfg[key] = value + dirty = True + if dirty: + text = '\n'.join(lines) + if doit: + with open(STARTUP_TEXT, 'w') as f: + f.write(text) + else: + print('new startup text:') + print('\n'.join(lines)) + + def display(**opts): + if not opts: + return None return DISPLAY_TEMPLATE @@ -215,7 +255,7 @@ def write_when_new(filename, content, ignore_reduction=False): return content -def create_if(name, cfg, mac, dhcp_server_cfg): +def create_if(name, cfg): result = dict( TYPE='Ethernet', NAME=name, @@ -229,6 +269,10 @@ def create_if(name, cfg, mac, dhcp_server_cfg): if cfg == 'off': result['ONBOOT'] = 'no' elif cfg.startswith('wan') or cfg == 'dhcp': + if main_info.get('mainif', name) != name: + raise ValueError('can not have more than one WAN/DHCP port') + main_info['mainif'] = name + main_info['addr'] = net_addr[name] result['BOOTPROTO'] = 'dhcp' # default: all <= 192.0.0.0 # others have to be added explicitly @@ -337,68 +381,72 @@ class Do: os.remove(join(self.syspath, file)) -netaddr_dict = {} for netif in os.scandir('/sys/class/net'): if netif.name != 'lo': # do not consider loopback interface with open(os.path.join(netif.path, 'address')) as f: - netaddr_dict[netif.name] = netaddr = f.read().strip().lower() + addr = f.read().strip().lower() + net_addr[netif.name] = addr + +sorted_if = sorted(net_addr) + +apuid = int(''.join(net_addr[sorted_if[0]].split(':')[-3:]), 16) & 0xffffff + def handle_config(): cfgfile = None cfgfiles = [] - shortids = {} - for netif, addr in netaddr_dict.items(): - shortid = int(''.join(addr.split(':')[-3:]), 16) & 0xffffff - cfgfiles += glob(CFGPATH % ('*', shortid)) - shortids[netif] = shortid + for file in glob(CFGPATH % ('*', apuid)): + cfgfiles.append(file) with open('/etc/hostname') as f: hostname = f.read().strip() + newhostname = hostname if not cfgfiles: disp = serial.Serial('/dev/ttyS1', baudrate=115200, timeout=1) disp.write(b'\x1b\x1b\x01\xf3') display_available = disp.read(8)[0:4] == b'\x1b\x1b\x05\xf3' - ids = sorted(shortids) if display_available: # leftmost interface labelled 'eth0' - apuid = shortids[ids[0]] + wan_if = sorted_if[0] typ = 'controlbox' template = CONTROLBOX_TEMPLATE else: # rightmost interface - apuid = shortid[idx[-1]] + wan_id = sorted_if[-1] typ = 'bare apu' template = CONFIG_TEMPLATE print('no cfg file found for this', typ, f'with id {apuid:%6.6x} (hostname={hostname})') - newname = input('enter host name: ') - if not newname: + newhostname = input('enter host name: ') + if not newhostname: print('no hostname given') return False - cfgfile = CFGPATH % (newname, apuid) + cfgfile = CFGPATH % (newhostname, apuid) with open(cfgfile, 'w') as f: f.write(template) elif len(cfgfiles) > 1: print('ERROR: ambiguous cfg files: %s' % ', '.join(cfgfiles)) else: cfgfile = cfgfiles[0] - apuid = int(cfgfile.split('_')[-1].split('.')[0], 16) + wan_if = None if cfgfile != CFGPATH % (hostname, apuid): + if cfgfile: + newhostname = basename(cfgfile).rpartition('_')[0] if doit: - os.system('sh ../sethostname.sh') + os.system('sh sethostname.sh') else: if cfgfile: - print('replace host name %r by %r' % (hostname, basename(cfgfile).rpartition('_')[0])) + print('replace host name %r by %r' % (hostname, newhostname)) show.dirty = True + main_info['hostname'] = newhostname if cfgfile is None: return False to_start = {} ifname = '' parser = ConfigParser() - dhcp_server_cfg = [] try: parser.read(cfgfile) network = dict(parser['NETWORK']) - for ifname, addr in netaddr_dict.items(): - content = create_if(ifname, network.pop(ifname, 'off'), addr, dhcp_server_cfg) + for ifname in net_addr: + content = create_if(ifname, network.pop(ifname, 'off')) content = '\n'.join('%s=%s' % kv for kv in content.items()) todo = write_when_new('/etc/sysconfig/network-scripts/ifcfg-%s' % ifname, content) if todo and more_info == 'NONE': @@ -434,7 +482,10 @@ def handle_config(): dirty = True content.append('[%s]' % section) content.append(COMMENT) - for key, value in parser[section].items(): + section_dict = dict(parser[section].items()) + if section == 'DISPLAY': + display_update(section_dict) + for key, value in section_dict.items(): content.append('%s=%s' % (key, value)) content.append('') if dirty: @@ -446,12 +497,12 @@ def handle_config(): return False reload_systemd = False - for service, template_func in SERVICES.items(): + for service, service_func in SERVICES.items(): section = service.upper() if parser.has_section(section): - template = template_func(**dict(parser[section])) + servicecfg = service_func(**dict(parser[section])) else: - template = None + servicecfg = None result = unix_cmd('systemctl show -p WantedBy -p ActiveState %s' % service, True) active = False enabled = False @@ -460,7 +511,7 @@ def handle_config(): enabled = True elif line.strip() == 'ActiveState=active': active = True - if template is None: + if servicecfg is None: if active: unix_cmd('systemctl stop %s' % service) show.dirty = True @@ -472,10 +523,10 @@ def handle_config(): to_start[service] = 'enable' elif not active: to_start[service] = 'restart' - if write_when_new('/etc/systemd/system/%s.service' % service, template): + if write_when_new('/etc/systemd/system/%s.service' % service, servicecfg): show.dirty = True reload_systemd = True - if template and to_start.get('service') is None: + if servicecfg and to_start.get('service') is None: to_start[service] = 'restart' pip() diff --git a/servercfg/linse-box1_5b265c.cfg b/servercfg/linse-box1_5b265c.cfg index 6e62f83..3a8dcbf 100644 --- a/servercfg/linse-box1_5b265c.cfg +++ b/servercfg/linse-box1_5b265c.cfg @@ -7,3 +7,6 @@ enp4s0=192.168.3.3 [DISPLAY] ; please refer to README.md for help +line0=startup... +line1=HOST: linse-box1 +line2=ADDR: 00:0d:b9:5b:26:5c