-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotificationCenter.py
136 lines (117 loc) · 4.69 KB
/
NotificationCenter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import subprocess
import urllib2, json
from datetime import datetime
import psutil
import transmissionrpc
class NotificationCenter:
TEMP_SYS = '/sys/class/thermal/thermal_zone0/temp'
DATE_FMT = '%a %b %d %H:%M'
TORRENT_HOST = 'localhost'
TORRENT_PORT = 9091
TORRENT_USER = 'pi'
TORRENT_PASS = 'pi'
WEATHER_CITY = 'Kanata'
DISK_FS = ['/', '/media']
STATIC_MODE = False
def _splitCount(self, s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
def _fetchJson(self, url):
""" Load a JSON result from the given URL """
try:
req = urllib2.Request(url)
response = urllib2.urlopen(req)
except Exception:
return {}
return response.read()
def status_date(self):
""" Display the date, memory usage, and CPU temperature """
mem = psutil.virtual_memory()
try:
cpu_temp = float([line.strip() for line in open(self.TEMP_SYS)][0]) / 1000
except Exception:
cpu_temp = 0.0
if cpu_temp > 60 or mem.percent > 50:
self.STATIC_MODE = "status_date"
else:
self.STATIC_MODE = False
return [datetime.now().strftime(self.DATE_FMT),
'Mem: %4.1f%% %4.1f%c' % (mem.percent, cpu_temp, 223)]
def status_torrents(self):
""" Ping transmission-daemon over RPC and get an update """
try:
tc = transmissionrpc.Client(self.TORRENT_HOST,
port=self.TORRENT_PORT, user=self.TORRENT_USER,
password=self.TORRENT_PASS)
stats = tc.session_stats()
down = float(stats.downloadSpeed) / 1000
up = float(stats.uploadSpeed) / 1000
""" Show an infinity, or a turtle if alt speed enabled """
turtle = 244 if stats.alt_speed_enabled else 243
if down > 0:
self.STATIC_MODE = "status_torrents"
else:
self.STATIC_MODE = False
if stats.activeTorrentCount > 0:
return ['Status: %2d (%3d)' % (stats.activeTorrentCount, stats.torrentCount),
'%c %5dKB %4dKB' % (turtle, down, up)]
else:
return {};
except:
return ['{:^16}'.format("UNABLE TO LOAD"),
'{:^16}'.format("TORRENT DATA")]
def status_weather(self):
""" Grab the current, high, and low temperatures """
url = 'http://api.openweathermap.org/data/2.5/weather?cnt=1&q=' + self.WEATHER_CITY
try:
data = json.loads(self._fetchJson(url))
status = data['weather'][0]['main'].encode('utf-8')
desc = data['weather'][0]['description'].encode('utf-8')
""" Convert the temperatures from Kelvin to Celcius """
tmp_curr = data['main']['temp'] - 273.15
return ['%-11s %3d%c' % (status[:11], tmp_curr, 223),
'%-16s' % (desc[:16])]
except Exception:
return ['{:^16}'.format('UNABLE TO LOAD'),
'{:^16}'.format('WEATHER')]
def status_disk(self):
""" Displays disk usage """
try:
resp = []
for disk in self.DISK_FS:
df = subprocess.Popen(['df', disk],
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
output.split('\n')[1].split()
resp.append('%-12s %3s' % (disk[:12], percent))
return resp
except Exception:
return ['{:^16}'.format('UNABLE TO LOAD'),
'{:^16}'.format('DISK USAGE')]
def startup(self):
return ['{:^16}'.format('MAIN SCREEN'),
'{:^16}'.format('TURN ON')]
def fun1(self):
return ['{:^16}'.format('WEAPONS'),
'{:^16}'.format('ACTIVATED')]
def random_quotes(self):
""" Random quotes """
try:
p = subprocess.Popen(['/usr/games/fortune', '-s', '-n', '32'],
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.communicate()[0].replace('\n', '')
return self._splitCount('%-32s' % output, 16)
except Exception:
return []
if __name__ == '__main__':
nc = NotificationCenter()
print '\n'.join(nc.random_quotes())
print '----------------'
print '\n'.join(nc.status_date())
print '----------------'
print '\n'.join(nc.status_torrents())
print '----------------'
print '\n'.join(nc.status_weather())
print '----------------'
print '\n'.join(nc.status_disk())
print '----------------'