Files
  • main.py
main.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
import urllib2
import os
from collections import deque
import threading
import logging
import time
import random

log = logging.getLogger(__name__)

def check_internet():
	hostname = "http://216.58.192.142" #example
	response = os.system("ping -c 1 -w2 " + hostname + " > /dev/null 2>&1")
	
	if response == 0:
	  print hostname, 'is up!'
	else:
	  print hostname, 'is down!'

def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except Exception as err: 
        return False

class offlineQueue:
	def __init__(self, size, drop_oldest, drop_newest):
		try: 
			assert size!=0 and drop_newest!=drop_oldest
		except AssertionError as e:
			raise e

		self.size = size
		self.drop_oldest = drop_oldest
		self.drop_newest = drop_newest
		if (self.size>0 and drop_oldest==1):
			self.d = deque(maxlen=self.size)
		else:
			self.d = deque()
		
	def append(self, data):
		if (self.size<0):	#for infinite length deque
			self.d.append(data)
		elif (self.size>0 and self.drop_oldest==1): #for deque with drop_oldest=1
			if len(self.d) is self.size:
				log.info("Message dropped: {}".format(self.d[0]))
			self.d.append(data)
		else:									#for deque with drop_newest=1
			if len(self.d) is self.size:
				log.info("Message dropped: {}".format(self.d.pop()))
				self.d.append(data)
			else:
				self.d.append(data)

	def _drain(self):
		while self.d:
			print "Data drain: ",self.d.pop()
			if self.d:
				print "Data drain: ",self.d.popleft()

	def start_drain(self):
		#should we check for internet connection again??
		queueDrain = threading.Thread(target=self._drain)
		queueDrain.daemon = True
		queueDrain.start()
		queueDrain.join()

	def show(self):
		print self.d

def random_data():
	return random.randint(1,100)

flag = 0
count = 0

while True:
	data = random_data()
	if internet_on():
		if flag != 0:
			print "Internet disconnected {} times till now.".format(count)
			flag = 0
			b.start_drain()
		print data
	else:
		if flag is 0:
			flag = 1 
			b = offlineQueue(4,1,0)
			count+=1
		print "Internet OFF!!"
		data = random_data()
		print "DATA appended: {}".format(data)
		b.append(data)
		time.sleep(0.5)