Skip to content

Instantly share code, notes, and snippets.

@vitouXY
Last active December 28, 2020 07:59
Show Gist options
  • Save vitouXY/ba048dffd07163f386c9c40c96c23ca9 to your computer and use it in GitHub Desktop.
Save vitouXY/ba048dffd07163f386c9c40c96c23ca9 to your computer and use it in GitHub Desktop.
1.3" OLED Display HAT for Raspberry Pi by Waveshare (SH1106)
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -*- coding:utf-8 -*-
""" RPi0W 20FEB2020_0400_nonTesting
Linux alarmpi 4.19.102-1-ARCH #1 SMP PREEMPT Sun Feb 9 19:27:01 UTC 2020 armv6l GNU/Linux
Original by pangduckwai (github.com/pangduckwai/)
raw.githubusercontent.com/pangduckwai/PiDisplay/master/monitor.py
LUMA.OLED : github.com/rm-hull/
#$ sudo pacman install ifstat
#$ sudo pip install psutil
"""
from __future__ import unicode_literals
from datetime import datetime
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.core import lib
from luma.oled.device import sh1106
import RPi.GPIO as GPIO
import sys
import time
import subprocess
import os
import string
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
if os.geteuid() != 0:
sys.exit('{}: Operation not permitted'.format(os.geteuid()))
if os.name != 'posix':
sys.exit('{} Platform not supported'.format(os.name))
try:
import psutil
except ImportError:
print("The psutil library was not found. Run 'sudo -H pip install psutil' to install it.")
sys.exit()
import signal
def keyboardInterruptHandler(signal, frame ):
print( " KeyboardInterrupt (ID: {}) has been caught. Cleaning up..." . format(signal ))
GPIO.cleanup()
exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
#GPIO define
RST_PIN = 25 #Reset
CS_PIN = 8
DC_PIN = 24
JS_U_PIN = 6 #Joystick Up
JS_D_PIN = 19 #Joystick Down
JS_L_PIN = 5 #Joystick Left
JS_R_PIN = 26 #Joystick Right
JS_P_PIN = 13 #Joystick Pressed
BTN1_PIN = 21
BTN2_PIN = 20
BTN3_PIN = 16
# Some constants
SCREEN_LINES = 4
SCREEN_SAVER = 20.0
CHAR_WIDTH = 19
font = ImageFont.load_default() # char in line: 19
#print(font.getname())
#print(font.getsize('0000000000000000000'))
width = 128
height = 64
x0 = 0
x1 = 84
y0 = -2
y1 = 12
x2 = x1+7
x3 = x1+14
x4 = x1+9
x5 = x2+9
x6 = x3+9
""" Arrow Select
2
/ |
/ |_________
/ 3 4|
1 |
\ 6_______5|
\ |
\ |
7
"""
arrowX = 127 - x3 + 5 # -(-5) ArrowX4&5
arrowX_1 = +3+arrowX
arrowX_2 = +arrowX
arrowY_2 = +3
arrowX_3 = arrowX
arrowX_4 = -5+arrowX
arrowX_5 = arrowX_4
arrowX_6 = arrowX
arrowX_7 = arrowX
arrowY_7 = -3
choices = [ # "z"] # 25
["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-"],
["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","_"],
["0","1","2","3","4","5","6","7","8","9","!","@","#","$","%","^","&","*","(",")",",",".","?",":",";","'"," "]
]
# init GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(JS_U_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(JS_D_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(JS_L_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(JS_R_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(JS_P_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(BTN1_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(BTN2_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(BTN3_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
# Initialize the display...
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
draw = ImageDraw.Draw(Image.new('1', (width, height)))
draw.rectangle((0,0,width,height), outline=0, fill=0)
state = 0 #System state: 0 - scrren is off; equal to channel number (e.g. BTN2_PIN, JS_P_PIN) otherwise
horz = 1 #Selection choice: 0 - Right; 1 - Left
horz_max = 5 # 0(1) 1(2) 2(3) 3(4) 4(5)
vert = 3 # 3 #Selection choice: 1 - Top; 2 - Middle; 3 - Bottom
stamp = time.time() #Current timestamp
start = time.time() #Start screen saver count down
iface = ""
_2idxWin = 0
_2idxLen = 0
_2aplist = []
_2apIndx = -1
_2pwdLst = []
_2pwdLst = ['p', '4', '5', '5', '_', 'r', 'P', 'i', 'z', '_', 'W', '0', 'r', 'd']
_2pwdLen = 0
_2pwdLen = 14
_2chaSel = 1 #possible values: 0, 1, 2
_2ssid = ''
test = 0 # For testing!@1!!!!!!!!!!!!!!!!!!!!
def bytes2human(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 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()
#av1, av2, av3 = os.getloadavg()
return "%.2f %.2f %.2f" \
% (average) #av1, av2, av3)
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 "%s" \
% (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 "%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 "%s (%s)" \
% (bytes2human(usage.used), str(usage.percent)+'%')
def network(iface):
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'
return "U:%s %s D:%s" % \
(bytes2human(stat.packets_sent), ifaceX, bytes2human(stat.packets_recv))
except:
return "U:-- %s D:--" % (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():
#"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')
except:
return ""
def stations(iface):
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 netstat_psi():
try:
cmd = "netstat -putanel | grep 8081 | grep -o 'psiphon' | head -n1 | awk '{printf \"%s\", $1}'"
psi = str(subprocess.check_output(cmd, shell = True),'utf-8')
cmd = 'pgrep psiphon3-armv6'
pssi = str(subprocess.check_output(cmd, shell = True),'utf-8')
if psi == 'psiphon':
return "HTTP://8081 PID"+ pssi
else:
return ""+ pssi
except:
return ""
def udevice():
try: # 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 click_b1(channel):
global _2chaSel
if state == BTN1_PIN:
main_fun(channel)
else:
if _2apIndx < 0:
main_fun(BTN1_PIN)
else:
if _2chaSel > 0:
_2chaSel = _2chaSel - 1
_2pwdLst[horz] = choices[_2chaSel][vert]
main_fun(BTN2_PIN)
def click_b3(channel):
global start
global vert
global _2apIndx
global _2chaSel
if state == BTN3_PIN:
_2apIndx = -1
if vert == 1:
if horz == 1:
main_fun(911)
#$#os.system
subprocess.call(['halt','--reboot'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif horz == 2:
main_fun(912)
#$#os.system
subprocess.call(['halt','--halt','--force'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif horz == 3:
main_fun(913)
#$#os.system
subprocess.call(['halt','--reboot','--force'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif horz == 4:
main_fun(914)
#$#os.system
subprocess.call(['echo','14'], shell=False)
#start = stamp - SCREEN_SAVER + 5
else:
main_fun(910)
#$#os.system
subprocess.call(['halt','--halt'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif vert == 2:
if horz == 1:
main_fun(921)
#$#os.system
cmd='export https_proxy="http://127.0.0.1:8081" ; export http_proxy="http://127.0.0.1:8081" ; psiphon3 > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
elif horz == 2:
main_fun(922)
#$#os.system
cmd='psiphon3-kill > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
elif horz == 3:
main_fun(923)
#$#os.system
cmd='export https_proxy="" ; export http_proxy="" ; psiphon3-stop > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
elif horz == 4:
main_fun(924)
#$#os.system
subprocess.call(['echo','24'], shell=False)
#start = stamp - SCREEN_SAVER + 5
else:
main_fun(920)
#$#os.system
cmd='/usr/local/bin/modem_subi > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
elif vert == 3:
if horz == 1:
main_fun(931)
#$#os.system
#subprocess.call(['echo','31'], shell=False)
cmd='/usr/local/bin/psiphon3-hpon > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
elif horz == 2:
main_fun(932)
#$#os.system
subprocess.call(['echo','32'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif horz == 3:
main_fun(933)
#$#os.system
subprocess.call(['echo','33'], shell=False)
#start = stamp - SCREEN_SAVER + 5
elif horz == 4:
main_fun(934)
#$#os.system
subprocess.call(['echo','34'], shell=False)
#start = stamp - SCREEN_SAVER + 5
else:
main_fun(930)
#$#os.system
#subprocess.call(['echo','30'], shell=False)
cmd='/usr/local/bin/psiphon3-hpoff > /dev/null 2>&1 < /dev/null'
subprocess.check_output(cmd, shell = True)
start = stamp - SCREEN_SAVER + 5
else:
main_fun(BTN1_PIN)
else:
if _2apIndx < 0:
vert = 4 # 3 # Default
main_fun(BTN3_PIN)
else:
if _2chaSel < 2:
_2chaSel = _2chaSel + 1
_2pwdLst[horz] = choices[_2chaSel][vert]
main_fun(BTN2_PIN)
def click_b2(channel):
global _2aplist
global _2idxWin
global _2idxLen
global start
global vert
global test
global horz
start = time.time()
if _2apIndx >= 0:
main_fun(299)
#print(''.join(_2pwdLst)) #TODO change password for real...
print('VALUE:['+ str(_2ssid) +'] TEXT:['+ ''.join(_2pwdLst) +']')
cmd='systemctl stop wpa_supplicant@'+ iface +'.service'
subprocess.check_output(cmd, shell = True)
cmd='systemctl enable wpa_supplicant@'+ iface +'.service'
subprocess.check_output(cmd, shell = True)
#if (os.path.exists('/tmp/') and os.path.isfile('/tmp/'+'wpa_supplicant.txt')):
kfile = open('/tmp/mon_wpa_s.key','w')
kfile.write(''.join(_2pwdLst))
kfile.close()
ckfile = open('/etc/wpa_supplicant/wpa_supplicant-wlan0.conf','w')
#ckfile = open('/tmp/mon_wpa_s.cfg','w')
ckfile.write('country=US\n')
ckfile.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=0\n')
ckfile.write('eapol_version=1\n')
ckfile.write('update_config=1\n')
ckfile.write('ap_scan=1\n')
ckfile.write('fast_reauth=1\n')
ckfile.write('network={\n')
ckfile.write(' ssid=\"'+ str(_2ssid) +'\"\n')
ckfile.write(' scan_ssid=1\n')
ckfile.write(' psk=\"'+ ''.join(_2pwdLst) +'\"\n')
ckfile.write(' priority=1\n')
ckfile.write('}\n')
ckfile.close()
cmd='systemctl start wpa_supplicant@'+ iface +'.service'
subprocess.check_output(cmd, shell = True)
# systemctl disable [email protected]
# systemctl stop [email protected]
"""cmd='pkill dhcpcd ; pkill wpa_supplicant'
cmd='dhcpcd -x '+ iface +' &'
#'wpa_supplicant -B -i '+ iface +' -c <(wpa_passphrase '+ str(_2ssid) +' < /tmp/mon_wpa_s.key)'
cmd='wpa_supplicant -B -D nl80211,wext -i '+ iface +' -c /tmp/mon_wpa_s.cfg &'
cmd='dhcpcd -q -w -t 0 '+ iface +' &'"""
start = stamp - SCREEN_SAVER + 5
horz = 0
else:
# Array [] # Dictionary {}
result = os.popen("iwlist {0} scan 2>/dev/null | grep '^..*ESSID:\"..*\"$' | sed 's/^.*ESSID:\"\\(..*\\)\".*$/\\1/'".format(iface)).read()
'''
result = """rline01
rline02
rline03
rline04
rline05
rline06"""
'''
_2aplist = result.splitlines()
_2idxLen = len(_2aplist)
if (_2idxWin + SCREEN_LINES) > _2idxLen:
_2idxWin = _2idxLen - SCREEN_LINES
if _2idxWin < 0:
_2idxWin = 0
if vert > _2idxLen:
vert = _2idxLen
main_fun(channel)
def select_h(channel):
global _2apIndx
global start
global _2pwdLen
global horz
global vert
if state == BTN2_PIN:
if _2apIndx < 0: #select ssid mode
if channel == JS_L_PIN or channel == JS_R_PIN:
start = time.time()
_2apIndx = _2idxWin + vert - 1
_2pwdLen = len(_2pwdLst)
if (_2pwdLen > 0):
horz = _2pwdLen - 1
else:
horz = 0
"""
elif channel == JS_L_PIN:
start = time.time()
_2apIndx = -1 #Exit input mode
horz = 0
vert = 1
"""
else: #input mode
if channel == JS_L_PIN:
start = time.time()
if horz > 0:
horz = horz - 1
else:
_2apIndx = -1 #Exit input mode
horz = 0
vert = 1
elif channel == JS_R_PIN:
start = time.time()
if horz < _2pwdLen:
horz = horz + 1
else:
# Horizontal move <-[][][]->
if channel == JS_L_PIN:
start = time.time()
#horz = 1
if horz == 0:
horz = 1
elif horz == 1:
horz = 2
elif horz == 2:
horz = 3
elif horz == 3:
horz = 4
elif horz == 4:
horz = 0
draw_scn(state)
elif channel == JS_R_PIN:
start = time.time()
#horz = 0
if horz == 0:
horz = 4
elif horz == 4:
horz = 3
elif horz == 3:
horz = 2
elif horz == 2:
horz = 1
elif horz == 1:
horz = 0
draw_scn(state)
else:
pass
def select_v(channel):
global _2idxWin
global start
global vert
if state == BTN2_PIN:
if _2apIndx < 0: #select ssid mode
if channel == JS_U_PIN:
start = time.time()
if vert > 1:
vert = vert - 1
elif _2idxWin > 0:
_2idxWin = _2idxWin - 1
elif channel == JS_D_PIN:
start = time.time()
if vert < 4 and vert < _2idxLen:
vert = vert + 1
elif (_2idxWin + SCREEN_LINES) < _2idxLen:
_2idxWin = _2idxWin + 1
else:
pass
else: #input mode
if channel == JS_U_PIN:
start = time.time()
if vert > 0:
vert = vert - 1
else:
vert = 26 # 25
elif channel == JS_D_PIN:
start = time.time()
if vert < 26: # 25
vert = vert + 1
else:
vert = 0
_2pwdLst[horz] = choices[_2chaSel][vert]
else:
if vert > 4: # 3
vert = 4 # 3
if channel == JS_U_PIN:
start = time.time()
if vert > 1:
vert = vert - 1
else:
vert = 4
elif channel == JS_D_PIN:
start = time.time()
if vert < 4: # 3
vert = vert + 1
else:
vert = 1
else:
pass
def draw_scn(channel):
global _2idxLen
global _2pwdLen
global _2apIndx
global _2ssid
with canvas(device) as draw:
LINE0 = clock()
LINE1 = ""
LINE2 = ""
LINE3 = ""
LINE4 = ""
if channel == BTN1_PIN:
if horz == 1:
LINE1 = "1 LINEA --- 01"
LINE1 = network('wlan0')
LINE2 = "1 LINEA --- 02"
LINE2 = address('wlan0') + ' ' + stations('wlan0')
LINE3 = "1 LINEA --- 03"
LINE3 = wifinfo('wlan0')
#'for_RPi0W:p455_rPiz_W0rd'#
LINE4 = "1 LINEA --- 04"
LINE4 = netstat_psi()
elif horz == 2:
LINE1 = "2 LINEA --- 01"
LINE1 = disk_usage('/')
LINE2 = "2 LINEA --- 02"
LINE2 = mem_usage() + ' ' + s_temp('cpu-thermal')
LINE3 = "2 LINEA --- 03"
LINE3 = cpu_avg()
LINE4 = "2 LINEA --- 04"
LINE4 = sys_usage() # + ' ' + s_temp('cpu-thermal')
elif horz == 3:
LINE1 = "3 LINEA --- 01"
#LINE1 = iphostname('1')
LINE1 = alladdress(2)
LINE2 = "3 LINEA --- 02"
#LINE2 = iphostname('2')
LINE2 = alladdress(3)
LINE3 = "3 LINEA --- 03"
#LINE3 = iphostname('3')
LINE3 = alladdress(4)
LINE4 = "3 LINEA --- 04"
#LINE4 = iphostname('4')
LINE4 = alladdress(1)
elif horz == 4:
LINE1 = "4 LINEA --- 01"
LINE2 = "4 LINEA --- 02"
LINE3 = "4 LINEA --- 03"
LINE4 = "4 LINEA --- 04"
else:
LINE1 = "0 LINEA --- 01"
LINE1 = network('wlan1')
LINE2 = "0 LINEA --- 02"
LINE2 = address('wlan1') + ' ' + stations('wlan1')
LINE3 = "0 LINEA --- 03"
LINE3 = network('eth0')
LINE4 = "0 LINEA --- 04"
LINE4 = address('eth0') # network('tun0')
thumb_s_mh = 127 / horz_max
thumb_h_mh = thumb_s_mh * horz_max
horz_mh = horz + 1
thumb_0_mh = thumb_h_mh - horz_mh * thumb_s_mh
thumb_1_mh = thumb_h_mh - horz * thumb_s_mh
if thumb_1_mh > 127:
thumb_1_mh = 127
draw.rectangle((0,61,127,63), outline=255, fill=0) # Horz Scroll
draw.rectangle((thumb_0_mh,61,thumb_1_mh,63), outline=255, fill=1) # Horz Scroll
"""
vert_mv = vert - 1
thumb_s_mv = 28.0 / 4
thumb_h_mv = thumb_s_mv * 4
thumb_0_mv = vert_mv * thumb_s_mv + 12
thumb_1_mv = thumb_0_mv + thumb_h_mv
if thumb_1_mv > 60:
thumb_1_mv = 60
draw.rectangle((125,12,127,60), outline=255, fill=0) # Vert Scroll
draw.rectangle((125, thumb_0_mv, 127, thumb_1_mv), outline=255, fill=1) # Vert Scroll
"""
"""
if vert == 1:
LINE1 = "> " + LINE1
elif vert == 2:
LINE2 = "> " + LINE2
elif vert == 3:
LINE3 = "> " + LINE3
elif vert == 4:
LINE4 = "> " + LINE4
"""
elif channel == BTN3_PIN:
y2 = y1*vert
LINE1 = "| System..."
LINE2 = "| Proxy..."
LINE3 = "| Others3..."
LINE4 = "| Cancel"
# LINE3 = "> XXXXXXXXXXXXXXXXX" # ~17ch
if vert == 1:
if horz == 1:
LINE1 = "> Reboot"
elif horz == 2:
LINE1 = "> Halt Force"
elif horz == 3:
LINE1 = "> Reboot Force"
elif horz == 4:
LINE1 = "> Others14"
else:
LINE1 = "> Halt"
elif vert == 2:
if horz == 1:
LINE2 = "> Start Psi3"
elif horz == 2:
LINE2 = "> Kill Psi3"
elif horz == 3:
LINE2 = "> Stop Psi3"
elif horz == 4:
LINE2 = "> Others24"
else:
LINE2 = "> SubInterface"
elif vert == 3:
if horz == 1:
LINE3 = "> Others31off"
elif horz == 2:
LINE3 = "> Others32"
elif horz == 3:
LINE3 = "> Others33"
elif horz == 4:
LINE3 = "> Others34"
else:
LINE3 = "> Others30on"
else:
LINE4 = "> Cancel"
""" # Arrow Select
if vert == 1:
if horz == 1:
draw.polygon([(x4,y2+6),(x5,y2-1),(x5,y2+4),(x6,y2+4),(x6,y2+8),(x5,y2+8),(x5,y2+13)], outline=255, fill=0)
draw.polygon([(x1,y2+6),(x2,y2-1),(x2,y2+4),(x3,y2+4),(x3,y2+8),(x2,y2+8),(x2,y2+13)], outline=255, fill=1)
else:
draw.polygon([(x1,y2+6),(x2,y2-1),(x2,y2+4),(x3,y2+4),(x3,y2+8),(x2,y2+8),(x2,y2+13)], outline=255, fill=0)
draw.polygon([(x4,y2+6),(x5,y2-1),(x5,y2+4),(x6,y2+4),(x6,y2+8),(x5,y2+8),(x5,y2+13)], outline=255, fill=1)
else:
draw.polygon([(x1,y2+6),(x2,y2-1),(x2,y2+4),(x3,y2+4),(x3,y2+8),(x2,y2+8),(x2,y2+13)], outline=255, fill=1)
"""
draw.polygon([(x1+arrowX_1,y2+6),(x2+arrowX_2,y2-1+arrowY_2),(x2+arrowX_3,y2+4),(x3+arrowX_4,y2+4),(x3+arrowX_5,y2+8),(x2+arrowX_6,y2+8),(x2+arrowX_7,y2+13+arrowY_7)], outline=255, fill=1)
thumb_s_b3h = 127 / horz_max
thumb_h_b3h = thumb_s_b3h * horz_max
horz_h_b3h = horz + 1
thumb_0_b3h = thumb_h_b3h - horz_h_b3h * thumb_s_b3h
thumb_1_b3h = thumb_h_b3h - horz * thumb_s_b3h
if thumb_1_b3h > 127:
thumb_1_b3h = 127
draw.rectangle((0,61,127,63), outline=255, fill=0) # Horz Scroll
draw.rectangle((thumb_0_b3h,61,thumb_1_b3h,63), outline=255, fill=1) # Horz Scroll
"""
vert_b3v = vert - 1
thumb_s_b3v = 28.0 / 4
thumb_h_b3v = thumb_s_b3v * 4
thumb_0_b3v = vert_b3v * thumb_s_b3v + 12
thumb_1_b3v = thumb_0_b3v + thumb_h_b3v
if thumb_1_b3v > 60:
thumb_1_b3v = 60
draw.rectangle((125,12,127,60), outline=255, fill=0) # Vert Scroll
draw.rectangle((125, thumb_0_b3v, 127, thumb_1_b3v), outline=255, fill=1) # Vert Scroll
"""
elif channel == BTN2_PIN:
if _2apIndx < 0: # select ssid mode
y2 = y1*vert
if (_2idxWin >= 0) and (_2idxWin < _2idxLen):
LINE1 = _2aplist[_2idxWin]
if (_2idxWin + 1 < _2idxLen):
LINE2 = _2aplist[_2idxWin + 1]
if (_2idxWin + 2 < _2idxLen):
LINE3 = _2aplist[_2idxWin + 2]
if (_2idxWin + 3 < _2idxLen):
LINE4 = _2aplist[_2idxWin + 3]
#draw.polygon([(x1,y2+6),(x2,y2-1),(x2,y2+4),(x3,y2+4),(x3,y2+8),(x2,y2+8),(x2,y2+13)], outline=255, fill=1) # Arrow Select
draw.polygon([(x1+arrowX_1,y2+6),(x2+arrowX_2,y2-1+arrowY_2),(x2+arrowX_3,y2+4),(x3+arrowX_4,y2+4),(x3+arrowX_5,y2+8),(x2+arrowX_6,y2+8),(x2+arrowX_7,y2+13+arrowY_7)], outline=255, fill=1)
draw.rectangle((125,12,127,60), outline=255, fill=0) # Vert Scroll
if _2idxLen <= 4: #
vert_v = vert - 1
if _2idxLen == 0: thumb_s = 28.0
else: thumb_s = 28.0 / _2idxLen #Step
thumb_h = thumb_s * 4 # 4 #Because the screen can display 4 rows at a time
thumb_0 = _2idxWin + vert_v * thumb_s + 12
else:
thumb_s = 48.0 / _2idxLen #Step
thumb_h = thumb_s * 4 # 4 #Because the screen can display 4 rows at a time
thumb_0 = _2idxWin * thumb_s + 12
thumb_1 = thumb_0 + thumb_h
if thumb_1 > 60:
thumb_1 = 60
draw.rectangle((125, thumb_0, 127, thumb_1), outline=255, fill=1) # Vert Scroll
else: #input mode
if horz >= _2pwdLen:
_2pwdLst.append(choices[_2chaSel][vert])
_2pwdLen = len(_2pwdLst)
cursorx = 6 * horz
cursory = y1 * 2
draw.text((122, y1) , choices[0][vert], font=font, fill=255)
draw.text((122, y1*2), choices[1][vert], font=font, fill=255)
draw.text((122, y1*3), choices[2][vert], font=font, fill=255)
draw.rectangle((cursorx,cursory+10,cursorx+4,cursory+11), outline=255, fill=1)
_2ssid = _2aplist[_2apIndx]
LINE1 = "SSID: " + _2ssid
#LINE3 = str(horz)
if _2pwdLen > 0:
LINE2 = ''.join(_2pwdLst)
elif channel == 910:
LINE2 = " Halting..."
elif channel == 911:
LINE2 = " Rebooting..."
elif channel == 912:
LINE2 = " Force Halting..."
elif channel == 913:
LINE2 = " Force Rebooting..."
elif channel == 914:
LINE2 = " Others14..."
elif channel == 920:
LINE2 = " SubInterface..."
elif channel == 921:
LINE2 = " Start Psi3..."
elif channel == 922:
LINE2 = " Kill Psi3..."
elif channel == 923:
LINE2 = " Stop Psi3..."
elif channel == 924:
LINE2 = " Others24..."
elif channel == 930:
LINE2 = " Others30..."
elif channel == 931:
LINE2 = " Others31..."
elif channel == 932:
LINE2 = " Others32..."
elif channel == 933:
LINE2 = " Others33..."
elif channel == 934:
LINE2 = " Others34..."
elif channel == 299:
LINE1 = "Setting passphrase"
LINE2 = "of '" + _2aplist[_2apIndx] + "'"
else:
pass
draw.text((x0, y0), LINE0, font=font, fill=255)
if len(LINE1) > CHAR_WIDTH:
draw.text((x0, y1), LINE1[:CHAR_WIDTH], font=font, fill=255)
else:
draw.text((x0, y1), LINE1, font=font, fill=255)
if len(LINE2) > CHAR_WIDTH:
draw.text((x0, y1*2), LINE2[:CHAR_WIDTH], font=font, fill=255)
else:
draw.text((x0, y1*2), LINE2, font=font, fill=255)
if len(LINE3) > CHAR_WIDTH:
draw.text((x0, y1*3), LINE3[:CHAR_WIDTH], font=font, fill=255)
else:
draw.text((x0, y1*3), LINE3, font=font, fill=255)
if len(LINE4) > CHAR_WIDTH:
draw.text((x0, y1*4), LINE4[:CHAR_WIDTH], font=font, fill=255)
else:
draw.text((x0, y1*4), LINE4, font=font, fill=255)
def main_fun(channel):
global serial
global device
global draw
global state
global start
global _2apIndx
if state <= 0: # Display is off
if channel > 0: # A button is pressed, turn on display
# Initialize the display...
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', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
state = channel
start = time.time()
_2apIndx = -1
draw_scn(channel)
else:
pass
else: # Display is on
if ((channel > 0) and (channel == state) and ((channel != BTN2_PIN) or (_2apIndx < 0))) or ((stamp - start) > SCREEN_SAVER): # A button is pressed or timed out, turn off display
GPIO.output(RST_PIN,GPIO.LOW)
state = 0
_2apIndx = -1
elif (channel > 0) and (channel != state) and ((state != BTN2_PIN) or (_2apIndx < 0) or (channel == 299)):
state = channel
start = time.time()
draw_scn(channel)
else: # state > 0 && channel == 0 && not-yet-timeout, refresh screen
draw_scn(state)
GPIO.add_event_detect(BTN1_PIN, GPIO.RISING, callback=click_b1, bouncetime=200)
GPIO.add_event_detect(BTN2_PIN, GPIO.RISING, callback=click_b2, bouncetime=200)
GPIO.add_event_detect(BTN3_PIN, GPIO.RISING, callback=click_b3, bouncetime=200)
GPIO.add_event_detect(JS_L_PIN, GPIO.RISING, callback=select_h, bouncetime=200)
GPIO.add_event_detect(JS_R_PIN, GPIO.RISING, callback=select_h, bouncetime=200)
GPIO.add_event_detect(JS_U_PIN, GPIO.RISING, callback=select_v, bouncetime=200)
GPIO.add_event_detect(JS_D_PIN, GPIO.RISING, callback=select_v, bouncetime=200)
#iface = subprocess.check_output("iwgetid | awk '{print $1}'", shell = True).rstrip("\r\n")
"""
Traceback (most recent call last):
File "mon_tmp.py", line 422, in <module>
iface = str(subprocess.check_output("iwgetid | awk '{print $1}'", shell = True).rstrip("\r\n"))
TypeError: a bytes-like object is required, not 'str'
"""
iface = 'wlan0'
# Main Loop
try:
main_fun(BTN1_PIN)
while True:
stamp = time.time()
main_fun(0)
time.sleep(1)
except:
print("Stopped", sys.exc_info()[0])
raise
GPIO.cleanup()
# 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