Advertisement
muetzenfrosch

bakebit_nanohat_oled

Feb 27th, 2020
443
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.76 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # BakeBit example for the basic functions of BakeBit 128x64 OLED (http://wiki.friendlyarm.com/wiki/index.php/BakeBit_-_OLED_128x64)
  4. #
  5. # The BakeBit connects the NanoPi NEO and BakeBit sensors.
  6. # You can learn more about BakeBit here:  http://wiki.friendlyarm.com/BakeBit
  7. #
  8. # Have a question about this example?  Ask on the forums here:  http://www.friendlyarm.com/Forum/
  9. #
  10. '''
  11. ## License
  12.  
  13. The MIT License (MIT)
  14.  
  15. BakeBit: an open source platform for connecting BakeBit Sensors to the NanoPi NEO.
  16. Copyright (C) 2016 FriendlyARM
  17.  
  18. Permission is hereby granted, free of charge, to any person obtaining a copy
  19. of this software and associated documentation files (the "Software"), to deal
  20. in the Software without restriction, including without limitation the rights
  21. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  22. copies of the Software, and to permit persons to whom the Software is
  23. furnished to do so, subject to the following conditions:
  24.  
  25. The above copyright notice and this permission notice shall be included in
  26. all copies or substantial portions of the Software.
  27.  
  28. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  30. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  32. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  33. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  34. THE SOFTWARE.
  35. '''
  36.  
  37. import bakebit_128_64_oled as oled
  38. from PIL import Image
  39. from PIL import ImageFont
  40. from PIL import ImageDraw
  41. import time
  42. import sys
  43. import subprocess
  44. import threading
  45. import signal
  46. import os
  47. import socket
  48. import fcntl
  49. import struct
  50.  
  51. global width
  52. width=128
  53. global height
  54. height=64
  55.  
  56. global pageCount
  57. pageCount=2
  58. global pageIndex
  59. pageIndex=0
  60. global showPageIndicator
  61. showPageIndicator=False
  62.  
  63. global pageSleep
  64. pageSleep=120
  65. global pageSleepCountdown
  66. pageSleepCountdown=pageSleep
  67.  
  68. oled.init()  #initialze SEEED OLED display
  69. oled.setNormalDisplay()      #Set display to normal mode (i.e non-inverse mode)
  70. oled.setHorizontalMode()
  71.  
  72. global drawing
  73. drawing = False
  74.  
  75. global image
  76. image = Image.new('1', (width, height))
  77. global draw
  78. draw = ImageDraw.Draw(image)
  79. global fontb24
  80. fontb24 = ImageFont.truetype('DejaVuSansMono-Bold.ttf', 24);
  81. global font14
  82. font14 = ImageFont.truetype('DejaVuSansMono.ttf', 14);
  83. global smartFont
  84. smartFont = ImageFont.truetype('DejaVuSansMono-Bold.ttf', 10);
  85. global fontb14
  86. fontb14 = ImageFont.truetype('DejaVuSansMono-Bold.ttf', 14);
  87. global font11
  88. font11 = ImageFont.truetype('DejaVuSansMono.ttf', 11);
  89.  
  90. global lock
  91. lock = threading.Lock()
  92.  
  93. def get_ip_address(ifname):
  94.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  95.     return socket.inet_ntoa(fcntl.ioctl(
  96.         s.fileno(),
  97.         0x8915,  # SIOCGIFADDR
  98.         struct.pack('256s', ifname[:15])
  99.     )[20:24])
  100.  
  101. def get_ip():
  102.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  103.     try:
  104.         # doesn't even have to be reachable
  105.         s.connect(('10.255.255.255', 1))
  106.         IP = s.getsockname()[0]
  107.     except:
  108.         IP = '127.0.0.1'
  109.     finally:
  110.         s.close()
  111.     return IP
  112.  
  113. def draw_page():
  114.     global drawing
  115.     global image
  116.     global draw
  117.     global oled
  118.     global font
  119.     global font14
  120.     global smartFont
  121.     global width
  122.     global height
  123.     global pageCount
  124.     global pageIndex
  125.     global showPageIndicator
  126.     global width
  127.     global height
  128.     global lock
  129.     global pageSleepCountdown
  130.  
  131.     lock.acquire()
  132.     is_drawing = drawing
  133.     page_index = pageIndex
  134.     lock.release()
  135.  
  136.     if is_drawing:
  137.         return
  138.  
  139.     #if the countdown is zero we should be sleeping (blank the display to reduce screenburn)
  140.     if pageSleepCountdown == 1:
  141.         oled.clearDisplay()
  142.         pageSleepCountdown = pageSleepCountdown - 1
  143.         return
  144.  
  145.     if pageSleepCountdown == 0:
  146.         return
  147.  
  148.     pageSleepCountdown = pageSleepCountdown - 1
  149.  
  150.     lock.acquire()
  151.     drawing = True
  152.     lock.release()
  153.  
  154.     # Draw a black filled box to clear the image.            
  155.     draw.rectangle((0,0,width,height), outline=0, fill=0)
  156.     # Draw current page indicator
  157.     if showPageIndicator:
  158.         dotWidth=4
  159.         dotPadding=2
  160.         dotX=width-dotWidth-1
  161.         dotTop=(height-pageCount*dotWidth-(pageCount-1)*dotPadding)/2
  162.         for i in range(pageCount):
  163.             if i==page_index:
  164.                 draw.rectangle((dotX, dotTop, dotX+dotWidth, dotTop+dotWidth), outline=255, fill=255)
  165.             else:
  166.                 draw.rectangle((dotX, dotTop, dotX+dotWidth, dotTop+dotWidth), outline=255, fill=0)
  167.             dotTop=dotTop+dotWidth+dotPadding
  168.  
  169.     if page_index==0:
  170.         text = time.strftime("%A")
  171.         draw.text((2,2),text,font=font14,fill=255)
  172.         text = time.strftime("%e %b %Y")
  173.         draw.text((2,18),text,font=font14,fill=255)
  174.         text = time.strftime("%X")
  175.         draw.text((2,40),text,font=fontb24,fill=255)
  176.     elif page_index==1:
  177.         # Draw some shapes.
  178.         # First define some constants to allow easy resizing of shapes.
  179.         padding = 2
  180.         top = padding
  181.         bottom = height-padding
  182.         # Move left to right keeping track of the current x position for drawing shapes.
  183.         x = 0
  184.         try:
  185.             IPAddress = get_ip_address('eth0')
  186.         except:
  187.             IPAddress = get_ip()
  188.         cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
  189.         CPU = subprocess.check_output(cmd, shell = True )
  190.         cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
  191.         MemUsage = subprocess.check_output(cmd, shell = True )
  192.         cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
  193.         Disk = subprocess.check_output(cmd, shell = True )
  194.         tempI = int(open('/sys/class/thermal/thermal_zone0/temp').read());
  195.         if tempI>1000:
  196.             tempI = tempI/1000
  197.         tempStr = "CPU TEMP: %sC" % str(tempI)
  198.         cmd = "curl -f -s http://127.0.0.1/admin/api.php | jq .dns_queries_today"
  199.         Queries = subprocess.check_output(cmd, shell = True )
  200.         cmd = "curl -f -s http://127.0.0.1/admin/api.php | jq .ads_blocked_today"
  201.         AdsToday = subprocess.check_output(cmd, shell = True )
  202.         cmd = "curl -f -s http://127.0.0.1/admin/api.php | jq .ads_percentage_today"
  203.         AdsPercentage = subprocess.check_output(cmd, shell = True )
  204.         cmd = "curl -f -s http://127.0.0.1/admin/api.php | jq .clients_ever_seen"
  205.         ClientsEver = subprocess.check_output(cmd, shell = True )
  206.         cmd = "curl -f -s http://127.0.0.1/admin/api.php | jq .unique_clients"
  207.         ClientsUnique = subprocess.check_output(cmd, shell = True )
  208.  
  209.         draw.text((x, top+2),       "IP: " + str(IPAddress),  font=smartFont, fill=255)
  210.         draw.text((x, top+2+12),    "Queries: " + str(Queries), font=smartFont, fill=255)
  211.         draw.text((x, top+2+24),    "Blocked: " + str(AdsToday),  font=smartFont, fill=255)
  212.         draw.text((x, top+2+36),    "Percent: " + str(AdsPercentage),  font=smartFont, fill=255)
  213.         draw.text((x, top+2+48),    "Clients: " + str(ClientsUnique),  font=smartFont, fill=255)
  214.     elif page_index==3: #Reboot -- no
  215.         draw.text((2, 2),  'Reboot?',  font=fontb14, fill=255)
  216.  
  217.         draw.rectangle((2,20,width-4,20+16), outline=0, fill=0)
  218.         draw.text((4, 22),  'Yes',  font=font11, fill=255)
  219.  
  220.         draw.rectangle((2,38,width-4,38+16), outline=0, fill=255)
  221.         draw.text((4, 40),  'No',  font=font11, fill=0)
  222.  
  223.     elif page_index==4: #Reboot -- yes
  224.         draw.text((2, 2),  'Reboot?',  font=fontb14, fill=255)
  225.  
  226.         draw.rectangle((2,20,width-4,20+16), outline=0, fill=255)
  227.         draw.text((4, 22),  'Yes',  font=font11, fill=0)
  228.  
  229.         draw.rectangle((2,38,width-4,38+16), outline=0, fill=0)
  230.         draw.text((4, 40),  'No',  font=font11, fill=255)
  231.  
  232.     elif page_index==5:
  233.         draw.text((2, 2),  'Rebooting',  font=fontb14, fill=255)
  234.         draw.text((2, 20),  'Please wait...',  font=font11, fill=255)
  235.  
  236.     oled.drawImage(image)
  237.  
  238.     lock.acquire()
  239.     drawing = False
  240.     lock.release()
  241.  
  242.  
  243. def is_showing_power_msgbox():
  244.     global pageIndex
  245.     lock.acquire()
  246.     page_index = pageIndex
  247.     lock.release()
  248.     if page_index==3 or page_index==4:
  249.         return True
  250.     return False
  251.  
  252.  
  253. def update_page_index(pi):
  254.     global pageIndex
  255.     lock.acquire()
  256.     pageIndex = pi
  257.     lock.release()
  258.  
  259. def receive_signal(signum, stack):
  260.     global pageIndex
  261.     global pageSleepCountdown
  262.     global pageSleep
  263.  
  264.     pageSleepCountdown = pageSleep #user pressed a button, reset the sleep counter
  265.  
  266.     lock.acquire()
  267.     page_index = pageIndex
  268.     lock.release()
  269.  
  270.     if page_index==5:
  271.         return
  272.  
  273.     if signum == signal.SIGUSR1:
  274.         print 'K1 pressed'
  275.         if is_showing_power_msgbox():
  276.             if page_index==3:
  277.                 update_page_index(4)
  278.             else:
  279.                 update_page_index(3)
  280.             draw_page()
  281.         else:
  282.             pageIndex=0
  283.             draw_page()
  284.  
  285.     if signum == signal.SIGUSR2:
  286.         print 'K2 pressed'
  287.         if is_showing_power_msgbox():
  288.             if page_index==4:
  289.                 update_page_index(5)
  290.                 draw_page()
  291.  
  292.             else:
  293.                 update_page_index(0)
  294.                 draw_page()
  295.         else:
  296.             update_page_index(1)
  297.             draw_page()
  298.  
  299.     if signum == signal.SIGALRM:
  300.         print 'K3 pressed'
  301.         if is_showing_power_msgbox():
  302.             update_page_index(0)
  303.             draw_page()
  304.         else:
  305.             update_page_index(3)
  306.             draw_page()
  307.  
  308.  
  309. image0 = Image.open('pihole.png').convert('1')
  310. oled.drawImage(image0)
  311. time.sleep(2)
  312.  
  313. signal.signal(signal.SIGUSR1, receive_signal)
  314. signal.signal(signal.SIGUSR2, receive_signal)
  315. signal.signal(signal.SIGALRM, receive_signal)
  316.  
  317. while True:
  318.     try:
  319.         draw_page()
  320.  
  321.         lock.acquire()
  322.         page_index = pageIndex
  323.         lock.release()
  324.  
  325.         if page_index==5:
  326.             time.sleep(2)
  327.             while True:
  328.                 lock.acquire()
  329.                 is_drawing = drawing
  330.                 lock.release()
  331.                 if not is_drawing:
  332.                     lock.acquire()
  333.                     drawing = True
  334.                     lock.release()
  335.                     oled.clearDisplay()
  336.                     break
  337.                 else:
  338.                     time.sleep(.1)
  339.                     continue
  340.             time.sleep(1)
  341.             os.system('systemctl reboot')
  342.             break
  343.         time.sleep(1)
  344.     except KeyboardInterrupt:
  345.         break
  346.     except IOError:
  347.         print ("Error")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement