-
Notifications
You must be signed in to change notification settings - Fork 1
/
InternetWorks.py
92 lines (67 loc) · 2.11 KB
/
InternetWorks.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Gui (pekingmaster@gmail.com)
import sys
from time import sleep
from PyQt4.QtGui import *
from PyQt4.QtCore import QThread, SIGNAL
import requests
import icons
# Replace target as you want.
CHECK_TARGET = 'http://www.google.com'
class SysTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SysTrayIcon, self).__init__(parent)
self.okIcon = QIcon(':/ok.png')
self.failIcon = QIcon(':/broken.png')
self.initUI()
self.checkThread = CheckThread()
self.checkThread.start()
self.connect(self.checkThread, SIGNAL('inet'), self.statusToggle)
def initUI(self):
if self.isSystemTrayAvailable():
self.setIcon(self.okIcon)
self.quitAction = QAction('Quit', self)
self.trayMenu = QMenu()
self.trayMenu.addAction(self.quitAction)
self.connect(self.quitAction, SIGNAL('triggered()'), self.quitAll)
self.setContextMenu(self.trayMenu)
self.setVisible(True)
def statusToggle(self, status):
if status == 'OK':
self.setIcon(self.okIcon)
elif status == 'FAILED':
self.setIcon(self.failIcon)
def quitAll(self):
self.checkThread.quit()
self.hide()
del self
sys.exit(0)
class CheckThread(QThread):
def check_connection(self):
self.r = None
try:
self.r = requests.get(CHECK_TARGET, timeout=2.5)
if self.r.status_code == 200:
return 1
else:
return 0
except:
return 0
def run(self):
while 1:
sleep(2)
# Trigger the checking.
ret = self.check_connection()
if ret:
self.emit(SIGNAL('inet'), 'OK')
else:
self.emit(SIGNAL('inet'), 'FAILED')
# Clear the cache.
if self.r:
del self.r
if __name__ == '__main__':
app = QApplication([])
tray = SysTrayIcon(app)
tray.show()
sys.exit(app.exec_())