Last active
September 7, 2024 21:22
-
-
Save vitouXY/a17f0e10cb419f037632468b4c7772fb to your computer and use it in GitHub Desktop.
1.3" OLED Display HAT for Raspberry Pi by Waveshare (SH1106)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding:utf-8 -*- | |
""" ? -> ALarm Py2 -> Raspbian Py3 | |
Original code: https://github.com/acegallagher/rpi_rp1/blob/master/new_display.py | |
https://github.com/tink3rtanner/opc/blob/master/listui.py | |
""" | |
from __future__ import print_function # the future is now, and it is good | |
from __future__ import unicode_literals | |
import time, os, datetime, argparse, sys | |
if sys.version_info < (3, 0): | |
sys.exit("{}:\n Currently, this program runs only under python3.".format(sys.version_info)) | |
if os.geteuid() != 0: | |
sys.exit('{}: Operation not permitted'.format(os.geteuid())) | |
if os.name != 'posix': | |
sys.exit('{}: Platform not supported'.format(os.name)) | |
import RPi.GPIO as GPIO | |
#import shutil as sh | |
import usb.core # pyusb | |
## python2 -m pip install luma.oled | |
# luma.core requires Python '>=3.5, <4' but the running Python is 2.7.16 | |
## Python 3.7.3 - Error: | |
# TypeError: 'odict_items' object is not subscriptable | |
## Python 2.x - Original: | |
# self.entries.items()[ | |
## Python 3.7.3 - Fix: | |
# list(self.entries.items())[ | |
from luma.core.interface.serial import spi | |
from luma.core.render import canvas | |
from luma.oled.device import sh1106 | |
from subprocess import * | |
from collections import OrderedDict | |
#from collections import defaultdict | |
from PIL import Image | |
from PIL import ImageDraw | |
from PIL import ImageFont | |
import sys | |
from datetime import datetime | |
import signal | |
import platform | |
import os.path | |
__version__='2004.18' | |
try: | |
import psutil | |
except ImportError: | |
sys.exit("The psutil library was not found. Run 'sudo -H pip install psutil' to install it.") | |
def keyboardInterruptHandler(signal, frame ): | |
GPIO.output(RST_PIN,GPIO.LOW) | |
device.clear() | |
GPIO.cleanup() | |
sys.exit( " KeyboardInterrupt (ID: {}) has been caught. Cleaning up..." . format(signal )) | |
signal.signal(signal.SIGINT, keyboardInterruptHandler) | |
print(os.getpid(), platform.system()) | |
# there are two terms you're using | |
# 1: menu -- menu entries that get displayed as a list on the screen | |
# 2: actions -- menu entries that call functions to complete tasks (i.e backing up the tape) | |
# TODO: | |
# ###### | |
# refactor Menu class out of main program and cleanup | |
# ... actually use the verboseprint function | |
# ... implement low battery info from adafruit lipo charger | |
# pick code style that's actually internally consistent | |
# GLOBALS | |
lowBat = 4 | |
VENDOR = 0x2367 | |
PRODUCT = 0x0002 | |
VENDOR = 0x12d1 | |
PRODUCT = 0x14db | |
statux = 1 | |
contaxt = 255 | |
#GPIO define | |
RST_PIN = 25 #Reset | |
CS_PIN = 8 | |
DC_PIN = 24 | |
# BUTTONS | |
key={} | |
key['key1'] = 21 # used as 'go back' key | |
key['key2'] = 20 # used as 'select entry' key | |
key['key3'] = 16 # not used yet | |
key['left'] = 5 # also used as go back (soon) | |
key['up'] = 6 # click through menu | |
key['down'] = 19 # click through menu | |
key['right'] = 26 # not used | |
key['press'] = 13 # could also be used to select entry | |
""" ./fonts/ | |
creep.bdf | |
fontawesome-webfont.ttf | |
FreePixel.ttf 8 10 | |
""" | |
#font = ImageFont.load_default() | |
tiny_font = ImageFont.truetype(os.path.abspath(os.path.join(os.path.dirname(__file__), | |
"fonts", | |
"FreePixel.ttf" | |
)), 9) | |
#draw.textsize(text, font=tiny_font)[0] | |
#draw.text((x, y), text=text, font=tiny_font, fill="white") | |
class Menu: | |
def __init__(self, _name, _exitable=True): | |
## Python 3.7.3 Error: # = {} # = defaultdict() # = OrderedDict() | |
# TypeError: 'odict_items' object is not subscriptable | |
#self.entries = OrderedDict() # display menu items in order they're added | |
self.entries = OrderedDict() # display menu items in order they're added! | |
self.name = _name # | |
self.currSelected = 0 # current selected entry to highlight | |
self.currTop = 0 # current entry displayed at top of menu screen | |
self.exitable = _exitable # are you allowed to leave this particular menu | |
# these can probably be combined into add entry, and then do a try:except when you actually call the thing | |
def addAction(self, actionName, action): | |
# add a check here to make sure 'action' is an Action | |
self.entries[actionName] = action | |
def addSubMenu(self, menuName, menu): | |
# add a check here to make sure 'entry' is of type Menu | |
self.entries[menuName] = menu | |
def size(self): # returns the number of options in this Menu | |
return len(self.entries) | |
# prints the Menu in its entirety -- not used......... | |
def log(self): | |
print(self.name) | |
for i in range(1, self.size()+1): | |
print("{} - {}".format( i, self.entries[i][0] )) | |
print() | |
def drawHeader(self, device, draw): # draw title and notifiers | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
draw.rectangle((0,0,128,12), outline='white', fill='white') # draw header/title | |
draw.text((2,0), self.name, 'black') | |
#draw.text((85,1), RunCmd("date +%R"), 'black') | |
draw.text((98,1), sshConnections(22), 'black') | |
#draw.text((98,1), '000', 'black') # -6 c/l | |
if IsConnected()==1: # draw OP1 status marker in top corner | |
draw.rectangle((116,2,124,10), outline='black', fill='black') | |
else: | |
draw.rectangle((116,2,124,10), outline='black', fill='white') | |
# it would be nice to eventually have a battery indicator, finish this at some point | |
# if GPIO.event_detected(lowBat): | |
# draw.rectangle((96,3,108,9), outline='black', fill='black') | |
# else: | |
# draw.rectangle((96,3,108,9), outline='black', fill='white') | |
def display(self, device): # put this Menu onto the screen | |
# move these consts somewhere else that makes more sense | |
xOffset = 12 | |
yOffset = 2 | |
if self.size() != 0: | |
with canvas(device) as draw: # draw the menu with the current five entries and the highlighted entry | |
self.drawHeader(device, draw) | |
pos = self.currSelected - self.currTop | |
draw.rectangle((xOffset, (pos+1)*10+yOffset, xOffset+120, ((pos+1)*10)+10+yOffset), outline='white', fill='white') | |
# this draw the text for each entry in the menu | |
textColor = ['white']*self.size() | |
textColor[self.currSelected] = 'black' | |
## Python 3.7.3 Error: # list(self.entries.items())[ # self.entries.items()[ | |
# TypeError: 'odict_items' object is not subscriptable | |
#for ind, entry in enumerate(self.entries.items()[self.currTop:self.currTop+5]): | |
for ind, entry in enumerate(list(self.entries.items())[self.currTop:self.currTop+5]): | |
entryName = entry[0] | |
draw.text((xOffset+3,(ind+1)*10+yOffset), entryName, textColor[ind+self.currTop]) | |
draw.rectangle((4, (ind+1)*10+7, 7, ((ind+1)*10)+9), outline='white', fill='white') | |
# if textColor[self.currSelected] == 'black': # draw an arrow... finish this! | |
# draw.rectangle((2, (ind+1)*10+8, 5, ((ind+1)*10)+10), outline='white', fill='white') | |
# else: | |
# draw.rectangle((2, (ind+1)*10+8, 5, ((ind+1)*10)+10), outline='white', fill='white') | |
else: # menu was empty, display warning... shouldn't happen often | |
currLoop = 0 | |
indOff = 0 | |
while True: | |
time.sleep(0.01) # don't need to poll for keys that often, high CPU without | |
warnText = ['this', 'menu', 'is', 'empty', '...sorry...', 'press', 'key 1!'] | |
if currLoop==-1: | |
with canvas(device) as draw: | |
self.drawHeader(device,draw) | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
dispInd = 0 | |
for textInd in range(indOff,indOff+5): | |
if textInd > len(warnText)-1: textInd = textInd - len(warnText) | |
#print("... looping... %s -- %s" % (warnText[textInd],textInd)) | |
draw.text((xOffset+2,(dispInd+1)*10+yOffset), warnText[textInd], "white") | |
draw.rectangle((2, (dispInd+1)*10+8, 5, ((dispInd+1)*10)+10), outline='white', fill='white') | |
dispInd +=1 | |
indOff += 1 | |
currLoop += 1 | |
if indOff == len(warnText): indOff = 0 | |
if currLoop == 75: currLoop = 0 | |
#if GPIO.event_detected(key['key1']): return | |
if GPIO.event_detected(key['left']): return | |
# check for user input and act accordingly (update menu, run action, etc) | |
# ... couldn't this be done using callbacks? might be weird with recursion | |
# ... you'd need some sort of current menu global state variable | |
# ... I think doing it with callbacks makes more sense | |
status = IsConnected() | |
while True: | |
time.sleep(0.01) # don't need to poll for keys that often, high CPU without | |
if status != IsConnected(): # state change! | |
break | |
if GPIO.event_detected(key['down']): | |
if self.currSelected < self.size()-1: # if not at the end of the menu entries | |
self.currSelected += 1 | |
if self.currTop <= self.currSelected-5: # selected past current buffer, display next 5 entries | |
self.currTop = self.currSelected-4 | |
else: | |
self.currSelected = 0 | |
self.currTop = 0 | |
break # exit while loop which redraws the menu | |
elif GPIO.event_detected(key['up']): | |
if self.currSelected > 0: # if not at the top of the menu entries | |
self.currSelected -= 1 | |
if self.currTop > self.currSelected: # selected past current buffer, display next 5 entries | |
self.currTop = self.currSelected | |
else: | |
self.currSelected = self.size()-1 | |
self.currTop = self.size()-5 | |
if self.currTop < 0: self.currTop=0 | |
break # exit loop and redraw menu | |
# MAKE THIS "OR ARROW PRESS" TOO | |
#elif GPIO.event_detected(key['key2']): # key2 is a selection, follow the action/submenu selected | |
elif GPIO.event_detected(key['right']): # key2 is a selection, follow the action/submenu selected | |
## Python 3.7.3 Error: # list(self.entries.items())[ # self.entries.items()[ | |
# TypeError: 'odict_items' object is not subscriptable | |
#currItem = self.entries.items()[self.currSelected] | |
currItem = list(self.entries.items())[self.currSelected] | |
if currItem[1].__class__.__name__=='Menu': # display submenu | |
currItem[1].display(device) | |
else: # call function that entry describes | |
currItem[1].run(device) | |
break | |
#elif GPIO.event_detected(key['key1']): | |
elif GPIO.event_detected(key['left']): | |
if self.exitable==True: | |
return | |
else: | |
with canvas(device) as draw: | |
# '2, 5 16 27 38 49 ' 11x6 c/l | |
#draw.rectangle((9,6,117,58), outline='white', fill='black') | |
draw.text((2,5), 'B[' + str(contaxt) + '] pid[' + str(os.getpid()) +']', 'white') | |
draw.text((2,19), '@' + sshConnections(66) + ' ', 'white') | |
draw.text((0,35), clock(), 'white') | |
draw.text((2,49), sys_usage(), 'white') | |
#draw.text((0,16)," I'M SORRY ",'white') | |
#draw.text((0,38)," I CAN'T DO THAT ",'white') | |
time.sleep(2.0) | |
break | |
# needs to be an exit condition somewhere... | |
self.display(device) # recursion | |
# probably don't actually need this, just pass a function instead of a menu class when you add an entry... :\ | |
class Action: | |
def __init__(self, _name, _function, _triggersExit=False): | |
self.name = _name | |
self.action = _function | |
self.triggersExit = _triggersExit | |
def name(self): | |
return self.name | |
def run(self, device): | |
self.action(device) | |
# ############################## | |
# SYSTEM UTILITIES | |
def RunCmd(cmd): # > /dev/null 2>&1 < /dev/null | |
p = Popen(cmd, shell=True, stdout=PIPE) | |
output = p.communicate()[0] | |
return output | |
def IsConnected(): | |
return usb.core.find(idVendor=VENDOR, idProduct=PRODUCT) is not None | |
def sshConnections(port=22): | |
port = str(port) | |
try: | |
conn = RunCmd("netstat -atn | grep 'ESTABLISHED' | awk '{print $4}' | grep ':"+ port + "' | wc -l") | |
return str(conn, 'utf-8') | |
except: return '' | |
def bytes2human_v2(n): | |
""" | |
>>> bytes2human(10000) | |
'9K' | |
>>> bytes2human(100001221) | |
'95M' | |
""" | |
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') | |
prefix = {} | |
for i, s in enumerate(symbols): | |
prefix[s] = 1 << (i + 1) * 10 | |
for s in reversed(symbols): | |
if n >= prefix[s]: | |
value = int(float(n) / prefix[s]) | |
return '%s%s' % (value, s) | |
return "%sB" % n | |
def bytes2human(n, fmt="{0:0.2f}"): | |
symbols = [ | |
('YB', 2 ** 80), | |
('ZB', 2 ** 70), | |
('EB', 2 ** 60), | |
('PB', 2 ** 50), | |
('TB', 2 ** 40), | |
('GB', 2 ** 30), | |
('MB', 2 ** 20), | |
('KB', 2 ** 10), | |
('B', 2 ** 0) | |
] | |
for suffix, v in symbols: | |
if n >= v: | |
value = float(n) / v | |
return fmt.format(value) + suffix | |
return "{0}B".format(n) | |
def sys_usage(): | |
# uptime | |
uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time()) | |
# 4:20:17.237432 | |
return "%s" \ | |
% (str(uptime).split('.')[0]) | |
def cpu_avg(): | |
#"top -bn1 | awk 'NR==3{printf \"CPU:%.1f%% idle\", $8}'" | |
#"free -mh | awk 'NR==2{printf \"Mem:%s/%s %.1f%%\", $3,$2,$3*100/$2 }'" | |
# load average | |
average = psutil.getloadavg() | |
#average = [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()] | |
#av1, av2, av3 = os.getloadavg() | |
return "Avg %.2f %.2f %.2f" % (average) #av1, av2, av3) | |
#return "Avg %s%%" % (average)) | |
def s_temp(sensor): | |
#"cat /sys/class/thermal/thermal_zone0/temp | awk '{printf \"Temp:%.1fC\", $1/1000}'" | |
stat = psutil.sensors_temperatures(fahrenheit=False)[sensor] | |
# {'cpu-thermal': [shwtemp(label='', current=41.16, high=None, critical=None)]} | |
for entry in stat: | |
return "Temp %s'C" \ | |
% (entry.current) | |
def mem_usage(): | |
usage = psutil.virtual_memory() | |
# svmem(total=453713920, available=344596480, percent=24.0, used=53592064, free=260489216, active=115425280, inactive=41242624, buffers=28708864, cached=110923776, shared=3297280, slab=24227840) | |
return "MemUsed %s (%s)" \ | |
% (bytes2human(usage.used), str(usage.percent)+'%') | |
def disk_usage(dir): | |
#"df -h /mnt/usb | awk '$NF==\"/mnt/usb\"{printf \"Disk:%s/%s %s\", $3,$2,$5}'" | |
usage = psutil.disk_usage(dir) | |
# sdiskusage(total=15385776128, used=2261024768, free=12466286592, percent=15.4) | |
return "DskUsed %s (%s)" \ | |
% (bytes2human(usage.used), str(usage.percent)+'%') | |
def network(iface, data): | |
try: | |
stat = psutil.net_io_counters(pernic=True)[iface] | |
# snetio(bytes_sent=1932595088, bytes_recv=64763177, packets_sent=1405372, packets_recv=946643, errin=0, errout=0, dropin=0, dropout=0) | |
#ifaceX = iface[:2] + iface[-2:] #2 'wl' ... -2 'n0' / -1 '0' | |
if data.lower() == 'up': | |
return "Up: %s" % \ | |
(bytes2human(stat.packets_sent)) | |
else: | |
return "Down: %s" % \ | |
(bytes2human(stat.packets_recv)) | |
except: | |
return "Up/Down %s" % (iface) | |
def address(iface): | |
try: | |
stat = psutil.net_if_addrs()[iface][0] # [0] IPv4 [1] MAC | |
# [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.43.118', netmask='255.255.255.0', broadcast='192.168.43.255', ptp=None), snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='b8:27:eb:c6:ed:59', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)] | |
# snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.43.118', netmask='255.255.255.0', broadcast='192.168.43.255', ptp=None) | |
return "%s" % \ | |
(str(stat.address)) | |
except: | |
return "000.000.000.000" | |
"""def alladdress(numb): | |
try: | |
addresses = psutil.net_if_addrs() | |
stats = psutil.net_if_stats() | |
available_networks = [] | |
for intface, addr_list in addresses.items(): | |
if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list): | |
continue | |
elif intface in stats and getattr(stats[intface], "isup"): | |
available_networks.append(intface) | |
#print(available_networks) | |
return address(available_networks[numb]) | |
except: | |
return "000.000.000.000" | |
" " "for value in available_networks: | |
if value == 'lo': | |
continue | |
else: | |
address(value)""" | |
def clock(): | |
# TZ=America/Santiago date -s "$(TZ=America/Santiago date --date='TZ="UTC" '"$(wget -S "http://www.google.com/" 2>&1 | grep -E '^[[:space:]]*[dD]ate:' | sed 's/^[[:space:]]*[dD]ate:[[:space:]]*//' | head -1l | awk '{print $1, $3, $2, $5 , $6, $4 }' | sed 's/,//')")" | |
# TZ=America/Santiago date -s "$(TZ=America/Santiago date --date='TZ="UTC" '"$(curl -H'Cache-Control:no-cache' -sI google.com | grep '^Date:' | cut -d' ' -f3-6)")" | |
#"date +\"%Y-%m-%d %H:%M:%S\"" | |
now = datetime.now() | |
today_date = now.strftime("%d-%b-%Y") | |
today_time = now.strftime("%H:%M:%S") | |
return "%s %s" % \ | |
(today_date, today_time) | |
def wifinfo(iface): | |
try: | |
#"iwgetid --raw | awk '{printf \"WiFi:%s\", $0}'" | |
#"iwgetid --freq | awk '{gsub(/Frequency:/,\"\"); printf \" %.1f %s\", $2,$3}'" | |
cmd = "iw dev "+ iface +" link | grep 'SSID:' | sed 's/\tSSID: //g'" | |
#return '@' + str(subprocess.check_output(cmd, shell = True),'utf-8') | |
return RunCmd(cmd).split('\n')[0] | |
except: | |
return "" | |
"""def stations(iface): # hotspot ap mode | |
try: # pkg iw | |
cmd = "iw dev " + iface + " station dump 2>&1 | grep -c 'Station' | awk '{printf \"%s\", $1}'" #%03d | |
return str(subprocess.check_output(cmd, shell = True),'utf-8') | |
except: | |
return "" """ | |
"""def iphostname(line): | |
try: | |
#cmd = "hostname --ip-addresses | cut -d' ' -f" + line | |
cmd = "hostname -I | cut -d' ' -f" + line | |
#cmd = "echo $(curl -s 'http://wttr.in/Santiago, Chile?m&format=Stgo%20%t' || echo '(*_*)/) !')" | |
#cmd = "echo $(curl -s 'http://icanhazip.com/' || echo '000.000.000.000')" # $(curl -s 'https://ipinfo.io/country' || echo '--')" | |
return str(subprocess.check_output(cmd, shell = True),'utf-8') | |
except: | |
return "" """ | |
def get_pid(process_name, num=0): | |
try: | |
lst_pid = [] | |
for proc in psutil.process_iter(): | |
if proc.name() == process_name: | |
lst_pid.append(proc.pid) | |
if num < len(lst_pid) and num >= 0 and lst_pid[num]: | |
return str(lst_pid[num]) | |
else: return '000' | |
except: | |
return '000' | |
def get_listenconn(pid, num=-1): | |
try: | |
#cmd = "netstat -putanel | grep 8081 | grep -o 'psiphon' | head -n1 | awk '{printf \"%s\", $1}'" | |
if pid and pid >= 1: | |
lst_conn = [] | |
pid_conn = psutil.Process(int(pid)).connections() | |
for conn in pid_conn: | |
if conn.status == 'LISTEN': | |
lst_conn.append(conn.laddr.port) #.ip .port | |
if num < len(lst_conn) and num >= 0 and lst_conn[num]: | |
return str(lst_conn[num]) | |
elif len(lst_conn) >= 0 : | |
return lst_conn | |
else: return 'None' | |
else: return 'None' | |
except: | |
return 'None' | |
"""def udevice(): | |
7try: # pkg ? | |
#cmd = "find /dev/ -name \"ttyUSB*\" | grep 'ttyUSB[01]' > /dev/null 2>&1 && printf 'H' || printf ''" # Device | |
cmd = "lsusb | grep '12d1:14db' > /dev/null 2>&1 && printf 'H' || printf ''" # Device | |
return str(subprocess.check_output(cmd, shell = True),'utf-8') | |
except: | |
return "" """ | |
def curll(urls=[], ports=[]): | |
try: | |
value = '' | |
conn = [] | |
data = [] | |
conn = ['--proxy http://127.0.0.1:', '--socks5-hostname 127.0.0.1:', '#'] | |
for u in urls: | |
for c in conn: | |
for p in ports: | |
#'/usr/bin/wget -qO - '+ u | |
value = RunCmd('/usr/bin/curl --silent --max-time 10 '+ u +' '+ c + str(p)) | |
#value = RunCmd('/usr/bin/curl --silent '+ u +' '+ c + str(p)) | |
value = str(value, 'utf-8').split('\n')[0] | |
if value != '': | |
data.append(str(value)) | |
if len(data) > 1: | |
data = list(dict.fromkeys(data)) | |
#for count in range(0,5): | |
# if len(data) < count + 1: data.insert(count,'--') | |
return data | |
except: return '--' | |
def psiphon_status(): | |
try: | |
cmd = RunCmd('/bin/bash /var/lib/psiphon/bin/psiphon_status') | |
return str(cmd, 'utf-8') | |
except: return '...' | |
# ############################## | |
# functions used for menu entries | |
# Array [] # Dictionary {} | |
def funMenuLIN01_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
disk_usage('/'), | |
mem_usage(), | |
s_temp('cpu-thermal'), | |
cpu_avg(), | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
time.sleep(0.01) | |
except: return | |
def funMenuLIN01_02(device): | |
DrawText(device,['Wait...']) | |
txtA='Start' | |
txtB='Starting' | |
cmd='on' | |
size=128 | |
sswap="free -h | grep 'Swap:' | awk '{printf \"%s\", $2}'" | |
try: | |
while True: | |
if size > 1024 or size < 128: size = 1024 | |
if cmd == 'off': | |
size = '' | |
ssize = '' | |
else: ssize = 'Set['+ str(size) +'Mi] ' | |
DrawText(device,[ | |
txtA +' Swap?', | |
ssize + 'Now('+ RunCmd(sswap) +')', | |
'<INTRO> to continue.' | |
]) | |
if GPIO.event_detected(key['press']): | |
DrawText(device,['... '+ txtB +'!']) | |
RunCmd('/usr/local/bin/swap'+ cmd +'-bin ' + str(size)) | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['right']): | |
if cmd == 'on': | |
txtA='Stop' | |
txtB='Stoping' | |
cmd='off' | |
elif cmd == 'off': | |
txtA='Start' | |
txtB='Starting' | |
cmd='on' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): | |
if size < 1024: size = size + 4 | |
else: size = 128 | |
elif GPIO.event_detected(key['down']): | |
if size <= 1024 or size > 132: size = size - 4 | |
else: size = 1024 | |
except: return | |
def funMenuLIN02_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
stats = psutil.net_if_stats() | |
available_networks = [] | |
for intface, addr_list in stats.items(): | |
if intface in stats and getattr(stats[intface], "isup"): | |
available_networks.append(intface) | |
count = 0 | |
while True: | |
iface = available_networks[count] | |
DrawText(device,[ | |
iface.upper(), | |
network(iface, 'up'), | |
network(iface, 'down'), | |
address(iface), | |
wifinfo(iface) | |
]) | |
if GPIO.event_detected(key['right']): | |
if count == len(available_networks) - 1: | |
count = 0 | |
else: | |
count = count + 1 | |
elif GPIO.event_detected(key['left']): | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
time.sleep(0.01) | |
except: return | |
def funMenuLIN02_02(device): | |
DrawText(device,['Wait...']) | |
try: | |
iface = 'wlan0' | |
result = [] | |
result = os.popen("iwlist {0} scan 2>/dev/null | grep '^..*ESSID:\"..*\"$' | sed 's/^.*ESSID:\"\\(..*\\)\".*$/\\1/'".format(iface)).read().splitlines() | |
count = 0 | |
countlen = len(result) | |
while True: | |
if countlen >= 5: | |
DrawText(device,[result[count+0],result[count+1],result[count+2],result[count+3],result[count+4]]) | |
elif countlen == 4: | |
DrawText(device,[result[count+0],result[count+1],result[count+2],result[count+3]]) | |
elif countlen == 3: | |
DrawText(device,[result[count+0],result[count+1],result[count+2]]) | |
elif countlen == 2: | |
DrawText(device,[result[count+0],result[count+1]]) | |
elif countlen == 1: | |
DrawText(device,[result[count+0]]) | |
else: | |
DrawText(device,['<None>']) | |
if GPIO.event_detected(key['right']): | |
count = count + 5 | |
if count > len(result): return | |
countlen = countlen - 5 | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN02_03(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,['Connect to Android BT?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): | |
DrawText(device,['... Connecting!']) | |
RunCmd('/usr/bin/python3 /opt/usr-scpts-py/bt_tether.py') # Set config in bt_tether.py | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN02_04(device): | |
DrawText(device,['Wait...']) | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
try: | |
while True: | |
DrawText(device,[txtA +' WPA service?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): | |
DrawText(device,['... '+ txtB +'!']) | |
RunCmd('systemctl '+ cmd +' wpa_supplicant.service') | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['right']): | |
if cmd == 'start': | |
txtA='Stop' | |
txtB='Stoping' | |
cmd='stop' | |
elif cmd == 'stop': | |
txtA='Enable' | |
txtB='Enabling' | |
cmd='enable' | |
elif cmd == 'enable': | |
txtA='Disable' | |
txtB='Disabling' | |
cmd='disable' | |
elif cmd == 'disable': | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN02_05(device): | |
DrawText(device,['Wait...']) | |
iface='wlan0' | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
try: | |
while True: | |
DrawText(device,[txtA +' '+ iface.upper() +' service?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): | |
DrawText(device,['... '+ txtB +'!']) | |
RunCmd('systemctl '+ cmd +' wpa_supplicant@'+ iface +'.service') | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['right']): | |
if cmd == 'start': | |
txtA='Stop' | |
txtB='Stoping' | |
cmd='stop' | |
elif cmd == 'stop': | |
txtA='Enable' | |
txtB='Enabling' | |
cmd='enable' | |
elif cmd == 'enable': | |
txtA='Disable' | |
txtB='Disabling' | |
cmd='disable' | |
elif cmd == 'disable': | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN03_01(device): | |
DrawText(device,['Wait...']) | |
info='...' | |
prog = str('psiphon-tunnel-core') | |
try: | |
while True: | |
DrawText(device,[ | |
prog, | |
'PID: ' + get_pid(prog), | |
str(get_listenconn(int(get_pid(prog)))), | |
psiphon_status() + ' ' + info | |
]) | |
#WaitForKey('left') | |
if GPIO.event_detected(key['right']): | |
ports = [] | |
urls = [] | |
ports = get_listenconn(int(get_pid(prog))) | |
urls = ['http://ipinfo.io/country'] | |
info = str(curll(urls, ports)) | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
time.sleep(0.01) | |
except: return | |
def funMenuLIN03_02(device): | |
DrawText(device,['Wait...']) | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
try: | |
while True: | |
DrawText(device,[txtA +' Psiphon service?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): | |
DrawText(device,['... '+ txtB +'!']) | |
RunCmd('systemctl '+ cmd +' psiphon.service') | |
#WaitForKey('left') | |
return | |
elif GPIO.event_detected(key['right']): | |
if cmd == 'start': | |
txtA='Stop' | |
txtB='Stoping' | |
cmd='stop' | |
elif cmd == 'stop': | |
txtA='Enable' | |
txtB='Enabling' | |
cmd='enable' | |
elif cmd == 'enable': | |
txtA='Disable' | |
txtB='Disabling' | |
cmd='disable' | |
elif cmd == 'disable': | |
txtA='Start' | |
txtB='Starting' | |
cmd='start' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN04_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN04_02(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN05_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN05_02(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN06_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN06_02(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN07_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN08_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
def funMenuLIN09_01(device): | |
DrawText(device,['Wait...']) | |
try: | |
while True: | |
DrawText(device,[ | |
'01 Text', | |
'02 Text', | |
'03 Text', | |
'04 Text', | |
'05 Text' | |
]) | |
if GPIO.event_detected(key['right']): pass | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
except: return | |
# ScreenOff # | |
# GPIO.output(RST_PIN,GPIO.LOW) | |
# ScreenOn # | |
# serial = spi(device=0, port=0, bus_speed_hz = 8000000, transfer_size = 4096, gpio_DC = DC_PIN, gpio_RST = RST_PIN) | |
# device = sh1106(serial, rotate=2) #sh1106 | |
# image = Image.new('1', (128, 64)) | |
# draw = ImageDraw.Draw(image) | |
# draw.rectangle((0,0,128,64), outline=0, fill=0) | |
def ScreenOff(device): | |
global statux | |
global contaxt | |
DrawText(device,['Wait...']) | |
while True: | |
DrawText(device,[ | |
' <UP>', | |
'<ON> Contrast[' + str(contaxt) + '] <OFF>', | |
' <DOWN>' | |
]) | |
if contaxt > 255 or contaxt < 5: contaxt = 255 | |
device.contrast(contaxt) | |
if GPIO.event_detected(key['right']): | |
if statux == 1 : | |
device.hide() | |
statux = 0 | |
elif GPIO.event_detected(key['left']): | |
device.show() | |
statux = 1 | |
return | |
elif GPIO.event_detected(key['press']): pass | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): | |
if contaxt < 255: contaxt = contaxt + 5 | |
else: contaxt = 10 | |
elif GPIO.event_detected(key['down']): | |
if contaxt <= 255 or contaxt > 10: contaxt = contaxt - 5 | |
else: contaxt = 255 | |
def WifiInfo(device): | |
# clean this up | |
getip = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1 | awk '{print $1}'" | |
getssid = "iw dev wlan0 info | grep -i ssid | awk '{print $2}'" | |
getmac = "iw dev wlan0 info | grep -i addr | awk '{print $2}'" | |
getchan = "iw dev wlan0 info | grep -i chann | awk '{print $1 \" \" $2 \" \" $3 $4 }'" | |
netstat = RunCmd(getip) | |
ssidstat = RunCmd(getssid) | |
macstat = RunCmd(getmac) | |
chanstat = RunCmd(getchan) | |
ip = netstat.split('\n')[0] | |
ssid = ssidstat.split('\n')[0] | |
mac = macstat.split('\n')[0] | |
chan = chanstat | |
#print('wlan0 ip\n %s' % ip) | |
#print('wlan0 essid\n %s' % ssid) | |
DrawText(device, ['WIFI CONFIG!', 'SSID: %s' % ssid, 'IP: %s' % ip, 'MAC: %s' % mac, '%s' % chan]) | |
WaitForKey('left') | |
def Halt(device): | |
DrawText(device,['Wait...']) | |
cod = 'Halt' | |
cmd = 'halt --halt' | |
while True: | |
DrawText(device,[cod + ' the system?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): # | |
with canvas(device) as draw: | |
DrawText(device,['... Bye!!']) | |
RunCmd(cmd) | |
return | |
elif GPIO.event_detected(key['right']): | |
if cod == 'Halt': | |
cod = 'Force Halt' | |
cmd = 'halt --halt --force' | |
else: | |
cod = 'Halt' | |
cmd = 'halt --halt' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
def Reboot(device): | |
DrawText(device,['Wait...']) | |
cod = 'Reboot' | |
cmd = 'halt --reboot' | |
while True: | |
DrawText(device,[cod + ' the system?', '<INTRO> to continue.']) | |
if GPIO.event_detected(key['press']): # | |
with canvas(device) as draw: | |
DrawText(device,['... See you!!']) | |
RunCmd(cmd) | |
return | |
elif GPIO.event_detected(key['right']): | |
if cod == 'Reboot': | |
cod = 'Force Reboot' | |
cmd = 'halt --reboot --force' | |
else: | |
cod = 'Reboot' | |
cmd = 'halt --reboot' | |
elif GPIO.event_detected(key['left']): return | |
elif GPIO.event_detected(key['key1']): pass | |
elif GPIO.event_detected(key['key2']): pass | |
elif GPIO.event_detected(key['key3']): pass | |
elif GPIO.event_detected(key['up']): pass | |
elif GPIO.event_detected(key['down']): pass | |
# ############################## | |
# waits for a keypress | |
def WaitForKey(waitkey): | |
while True: | |
if GPIO.event_detected(key[waitkey]): | |
#print(waitkey) | |
return | |
time.sleep(.01) | |
# proposition user, will only print up to five strings in textList | |
def DrawText(device, textList): | |
txtOff = list() | |
for ind in range(len(textList)): | |
if len(textList[ind]) >= 25: #20 | |
textList[ind] = textList[ind][0:22] + "(!)" #:17 | |
# 64 is the number of pixels for half the screen, 6 is the pixel width of each letter | |
txtOff.append(int(64-(len(textList[ind])/2.)*6)) | |
maxOff = min(txtOff) ## could be used to left align | |
#print("====================") | |
#print(maxOff) | |
if maxOff < 0: maxOff=0 | |
with canvas(device) as draw: | |
if len(textList) <= 4: | |
#draw.rectangle((4,4,124,60), outline='white', fill='black') | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
if len(textList) == 1: | |
#draw.text((maxOff,27) , textList[0], 'white') | |
draw.text((maxOff + 1,27) , textList[0], font=tiny_font, fill='white') | |
if len(textList) == 2: | |
#draw.text((maxOff,16) , textList[0] , 'white') | |
draw.text((maxOff + 1,16) , textList[0], font=tiny_font, fill='white') | |
#draw.text((maxOff,38) , textList[1] , 'white') | |
draw.text((maxOff + 1,38) , textList[1], font=tiny_font, fill='white') | |
if len(textList) == 3: | |
#draw.text((maxOff,8) , textList[0] , 'white') | |
draw.text((maxOff + 1,8) , textList[0], font=tiny_font, fill='white') | |
#draw.text((maxOff,27) , textList[1] , 'white') | |
draw.text((maxOff + 1,27) , textList[1], font=tiny_font, fill='white') | |
#draw.text((maxOff,46) , textList[2] , 'white') | |
draw.text((maxOff + 1,46) , textList[2], font=tiny_font, fill='white') | |
if len(textList) == 4: | |
#draw.text((maxOff,8) , textList[0] , 'white') | |
draw.text((maxOff + 1,8) , textList[0], font=tiny_font, fill='white') | |
#draw.text((maxOff,21) , textList[1] , 'white') | |
draw.text((maxOff + 1,21) , textList[1], font=tiny_font, fill='white') | |
#draw.text((maxOff,34) , textList[2] , 'white') | |
draw.text((maxOff + 1,34) , textList[2], font=tiny_font, fill='white') | |
#draw.text((maxOff,47) , textList[3] , 'white') | |
draw.text((maxOff + 1,47) , textList[3], font=tiny_font, fill='white') | |
if len(textList) == 5: | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
#draw.text((maxOff,5) , textList[0] , 'white') | |
draw.text((maxOff + 1,5) , textList[0], font=tiny_font, fill='white') | |
#draw.text((maxOff,16) , textList[1] , 'white') | |
draw.text((maxOff + 1,16) , textList[1], font=tiny_font, fill='white') | |
#draw.text((maxOff,27) , textList[2] , 'white') | |
draw.text((maxOff + 1,27) , textList[2], font=tiny_font, fill='white') | |
#draw.text((maxOff,38) , textList[3] , 'white') | |
draw.text((maxOff + 1,38) , textList[3], font=tiny_font, fill='white') | |
#draw.text((maxOff,49) , textList[4] , 'white') | |
draw.text((maxOff + 1,49) , textList[4], font=tiny_font, fill='white') | |
# proposition user, will only print up to five strings in textList | |
def DrawTextO(device, textList): | |
txtOff = list() | |
for ind in range(len(textList)): | |
if len(textList[ind]) >= 20: | |
textList[ind] = textList[ind][0:17] + "(!)" | |
# 64 is the number of pixels for half the screen, 6 is the pixel width of each letter | |
txtOff.append(int(64-(len(textList[ind])/2.)*6)) | |
maxOff = min(txtOff) ## could be used to left align | |
#print("====================") | |
#print(maxOff) | |
if maxOff < 0: maxOff=0 | |
with canvas(device) as draw: | |
if len(textList) <= 4: | |
draw.rectangle((4,4,124,60), outline='white', fill='black') | |
if len(textList) == 1: | |
draw.text((maxOff,27) , textList[0], 'white') | |
if len(textList) == 2: | |
draw.text((maxOff,16) , textList[0] , 'white') | |
draw.text((maxOff,38) , textList[1] , 'white') | |
if len(textList) == 3: | |
draw.text((maxOff,8) , textList[0] , 'white') | |
draw.text((maxOff,27) , textList[1] , 'white') | |
draw.text((maxOff,46) , textList[2] , 'white') | |
if len(textList) == 4: | |
draw.text((maxOff,8) , textList[0] , 'white') | |
draw.text((maxOff,21) , textList[1] , 'white') | |
draw.text((maxOff,34) , textList[2] , 'white') | |
draw.text((maxOff,47) , textList[3] , 'white') | |
if len(textList) == 5: | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
draw.text((maxOff,5) , textList[0] , 'white') | |
draw.text((maxOff,16) , textList[1] , 'white') | |
draw.text((maxOff,27) , textList[2] , 'white') | |
draw.text((maxOff,38) , textList[3] , 'white') | |
draw.text((maxOff,49) , textList[4] , 'white') | |
def DrawProgress(device, title, progress): | |
with canvas(device) as draw: | |
progpix=progress*64 | |
draw.text((16,8),title,'white') | |
draw.rectangle((32,32,96,42), outline='white', fill='black') | |
draw.rectangle((32,32,32+progpix,42), outline='white', fill='white') | |
def InitGPIO(): | |
verboseprint('Initializing GPIO') | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(key['key1'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['key2'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['key3'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['left'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['up'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['press'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['down'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(key['right'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
#LIPO LOW BATTERY | |
GPIO.setup(lowBat, GPIO.IN,pull_up_down=GPIO.PUD_UP) # figure this out...? | |
GPIO.add_event_detect(key['key1'], GPIO.FALLING) | |
GPIO.add_event_detect(key['key2'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['key3'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['left'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['up'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['press'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['down'], GPIO.FALLING, bouncetime=300) | |
GPIO.add_event_detect(key['right'], GPIO.FALLING, bouncetime=300) | |
def DrawSplash(device): | |
with canvas(device) as draw: | |
#draw.rectangle((18,12,108,52), outline='white', fill='black') | |
draw.rectangle((0,0,127,63), outline='white', fill='black') | |
# '2, 5 16 27 38 49 ' | |
# /etc/os-release | |
draw.text((2,13),' Raspberry Pi Zero W','white') | |
draw.text((2,24),' OLED SSH1106/SPI','white') | |
draw.text((2,35),' Python'+str(sys.version_info[0])+'/'+str(platform.system()),'white') | |
draw.text((2,49),' rev.' + __version__,'white') | |
time.sleep(2.0) | |
# ################################################### | |
# parse args and run the code! | |
def main(): | |
global device | |
global serial | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-v', '--verbose', action='count', | |
help='print verbose log messages') | |
args = parser.parse_args() | |
# print generic console messages only on --verbose flag | |
v_print = print if args.verbose else lambda *a, **k: None | |
global verboseprint | |
verboseprint = v_print | |
# get everything going | |
#serial = spi(device=0, port=0) | |
serial = spi(device=0, port=0, bus_speed_hz = 8000000, transfer_size = 4096, gpio_DC = DC_PIN, gpio_RST = RST_PIN) | |
device = sh1106(serial, rotate=2) | |
# ########################## | |
# there will be the main menu | |
mainMenu = Menu("MAIN", _exitable=False) ## don't let someone leave the main menu | |
# ########################## | |
# Actions | |
actMenuLIN01_01 = Action("01 - LINE01-2", funMenuLIN01_01) # entry that calls | |
actMenuLIN01_02 = Action("02 - LINE01-2", funMenuLIN01_02) # entry that calls | |
actMenuLIN02_01 = Action("01 - LINE02-2", funMenuLIN02_01) # entry that calls | |
actMenuLIN02_02 = Action("02 - LINE02-2", funMenuLIN02_02) # entry that calls | |
actMenuLIN02_03 = Action("03 - LINE02-2", funMenuLIN02_03) # entry that calls | |
actMenuLIN02_04 = Action("04 - LINE02-2", funMenuLIN02_04) # entry that calls | |
actMenuLIN02_05 = Action("05 - LINE02-2", funMenuLIN02_05) # entry that calls | |
actMenuLIN03_01 = Action("01 - LINE03-2", funMenuLIN03_01) # entry that calls | |
actMenuLIN03_02 = Action("02 - LINE03-2", funMenuLIN03_02) # entry that calls | |
actMenuLIN04_01 = Action("01 - LINE04-2", funMenuLIN04_01) # entry that calls | |
actMenuLIN04_02 = Action("02 - LINE04-2", funMenuLIN04_02) # entry that calls | |
actMenuLIN05_01 = Action("01 - LINE05-2", funMenuLIN05_01) # entry that calls | |
actMenuLIN05_02 = Action("02 - LINE05-2", funMenuLIN05_02) # entry that calls | |
actMenuLIN06_01 = Action("01 - LINE06-2", funMenuLIN06_01) # entry that calls | |
actMenuLIN06_02 = Action("02 - LINE06-2", funMenuLIN06_02) # entry that calls | |
actMenuLIN07_01 = Action("01 - LINE07-2", funMenuLIN07_01) # entry that calls | |
actMenuLIN08_01 = Action("01 - LINE08-2", Reboot) # entry that calls | |
actMenuLIN09_01 = Action("01 - LINE09-2", Halt) # entry that calls | |
actMenuLIN00_01 = Action("01 - LINE00-2", ScreenOff) # entry that calls | |
# ########################## | |
# Submenus titles | |
# and these will be entries in the menu | |
subMenuLIN01 = Menu("MAIN>Sys") # a menu | |
subMenuLIN02 = Menu("MAIN>Net") # a menu | |
subMenuLIN03 = Menu("MAIN>Psiphon3") # a menu | |
subMenuLIN04 = Menu("MAIN>LINE04") # a menu | |
subMenuLIN05 = Menu("MAIN>LINE05") # a menu | |
subMenuLIN06 = Menu("MAIN>LINE06") # a menu | |
subMenuLIN07 = Menu("MAIN>LINE07") # a menu | |
subMenuLIN08 = Menu("MAIN>LINE08") # a menu | |
subMenuLIN09 = Menu("MAIN>LINE09") # a menu | |
subMenuLIN00 = Menu("MAIN>LINE00") # a menu | |
# ########################## | |
# Submenus -> Actions | |
subMenuLIN01.addAction('System Info', actMenuLIN01_01) | |
#subMenuLIN01.addAction('Swap file', actMenuLIN01_02) | |
subMenuLIN02.addAction('Interface Info', actMenuLIN02_01) | |
subMenuLIN02.addAction('WLAN0 List', actMenuLIN02_02) | |
subMenuLIN02.addAction('<!> BT Tether <!>', actMenuLIN02_03) | |
subMenuLIN02.addAction('WPA Service', actMenuLIN02_04) | |
subMenuLIN02.addAction('WPA@WLAN0 Service', actMenuLIN02_05) | |
subMenuLIN03.addAction('Psiphon Info', actMenuLIN03_01) | |
subMenuLIN03.addAction('Psiphon Service', actMenuLIN03_02) | |
subMenuLIN04.addAction('01 - LINE04-1', actMenuLIN04_01) | |
subMenuLIN04.addAction('02 - LINE04-1', actMenuLIN04_02) | |
subMenuLIN05.addAction('01 - LINE05-1', actMenuLIN05_01) | |
subMenuLIN05.addAction('02 - LINE05-1', actMenuLIN05_02) | |
subMenuLIN06.addAction('01 - LINE06-1', actMenuLIN06_01) | |
subMenuLIN06.addAction('02 - LINE06-1', actMenuLIN06_02) | |
subMenuLIN07.addAction('01 - LINE07-1', actMenuLIN07_01) | |
subMenuLIN08.addAction('01 - LINE08-1', actMenuLIN08_01) | |
subMenuLIN09.addAction('01 - LINE09-1', actMenuLIN09_01) | |
# ########################## | |
# Mainmenus -> Submenus / Actions | |
# add the entries to the menu, the order you add them is the order they're listed | |
mainMenu.addSubMenu('Sys', subMenuLIN01) | |
mainMenu.addSubMenu('Net', subMenuLIN02) | |
mainMenu.addSubMenu('Psiphon3', subMenuLIN03) | |
#mainMenu.addSubMenu('04 - LINE04', subMenuLIN04) | |
#mainMenu.addSubMenu('05 - LINE05', subMenuLIN05) | |
#mainMenu.addSubMenu('06 - LINE06', subMenuLIN06) | |
#mainMenu.addSubMenu('07 - LINE07', subMenuLIN07) | |
mainMenu.addAction('Reboot', actMenuLIN08_01) | |
mainMenu.addAction('Halt', actMenuLIN09_01) | |
mainMenu.addAction('Display', actMenuLIN00_01) | |
DrawSplash(device) | |
InitGPIO() | |
mainMenu.display(device) # this loops forever | |
if __name__ == '__main__': | |
main() | |
# device.contrast(255) | |
# device.hide() | |
# device.show() | |
# device.clear() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment