more backups
[rb-clock.git] / python / unit-test.py
1 import RPi.GPIO as GPIO
2 from RPLCD.gpio import CharLCD
3 import socket
4 import fcntl
5 import struct
6 import time
7 from signal import signal, SIGINT
8 from sys import exit
9 import gaugette.rotary_encoder
10 import gaugette.gpio
11 import gaugette.switch
12 import os
13
14 A_PIN  = 5
15 B_PIN  = 4
16 SW_PIN = 2
17
18 menusize=3
19 menupos=0
20 timeout=time.localtime()
21
22 lcd = CharLCD(cols=40, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23], numbering_mode=GPIO.BOARD)
23 lcd.clear()
24
25 gpio = gaugette.gpio.GPIO()
26 encoder = gaugette.rotary_encoder.RotaryEncoder(gpio, A_PIN, B_PIN)
27 encoder.start()
28 switch = gaugette.switch.Switch(gpio, SW_PIN)
29 last_state = None
30 sw = gaugette.switch.Switch(gpio, SW_PIN)
31 last_state = sw.get_state()
32
33 def handler(signal_received, frame):
34   lcd.close()
35   print('SIGINT or CTRL-C detected. Exiting gracefully')
36   exit(0)
37
38 def get_ip_address(ifname):
39   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
40   return socket.inet_ntoa(fcntl.ioctl(
41     s.fileno(),
42     0x8915, 
43     struct.pack('256s', ifname[:15])
44   )[20:24])
45
46 def display_ip(lcd):
47   lcd.clear()
48   lcd.write_string("IP Address:")
49   lcd.cursor_pos = (1, 0)
50   lcd.write_string(get_ip_address('eth0'))
51
52 def display_time(lcd):
53   lcd.clear()
54   lcd.write_string("Time: %s" %time.strftime("%H:%M:%S"))
55   lcd.cursor_pos = (1, 0)
56   lcd.write_string("Date: %s" %time.strftime("%m/%d/%Y"))
57
58 def display_reboot(lcd):
59   lcd.clear()
60   lcd.write_string("Reboot?")
61
62 def display_blank(lcd):
63   lcd.clear()
64   lcd.write_string("Dynamic screen status")
65
66 if __name__ == '__main__':
67   signal(SIGINT, handler)
68   while True:
69     delta = encoder.get_cycles()
70     state = sw.get_state()
71     if state != last_state:
72       print "switch %d" % state
73       last_state = state
74       if menupos==1:
75         lcd.clear()
76         lcd.write_string("Rebooting!!!")
77         time.sleep(3)
78         os.system("sudo reboot")
79
80     if delta!=0:
81       if delta>0:
82         menupos+=1
83       if delta<0:
84         menupos-=1
85       if menupos<0:
86         menupos=menusize
87       if menupos>menusize:
88         menupos=0
89
90       if menupos==0:
91         display_blank(lcd)
92       if menupos==1:
93         display_reboot(lcd)
94       if menupos==2:
95         display_time(lcd)
96       if menupos==3:
97         display_ip(lcd)
98       #print "rotate %d" % delta
99     else:
100       time.sleep(0.1)
101       if menupos==2:
102         if timeout!=time.localtime():
103           display_time(lcd)
104           timeout=time.localtime()
105
106 lcd.close()