aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--FbClient.py176
-rw-r--r--Message_parser.py37
-rw-r--r--event_constants.py14
-rw-r--r--fb_client.py91
-rw-r--r--internet_status.py63
-rw-r--r--message_data.py11
-rw-r--r--repeating_event_object.py40
-rw-r--r--run_system.py54
-rw-r--r--thread_handler.py63
-rw-r--r--time_event_queuer.py (renamed from timeEventQueuer.py)102
-rw-r--r--weather_forcast.py107
11 files changed, 468 insertions, 290 deletions
diff --git a/FbClient.py b/FbClient.py
deleted file mode 100644
index 194bfdc..0000000
--- a/FbClient.py
+++ /dev/null
@@ -1,176 +0,0 @@
-from fbchat import log, Client
-from fbchat.models import *
-from geeteventbus.subscriber import subscriber
-from geeteventbus.eventbus import eventbus
-from geeteventbus.event import event
-from timeEventQueuer import *
-from Message_parser import *
-
-import time
-import requests
-import threading
-import random
-import datetime
-
-#class types
-ID_TIMER = 0;
-ID_LISTENER = 1;
-EVENTID_CLIENT_SEND = "Topic Message Send"
-EVENTID_CLIENT_STOP = "Topic Stop Client"
-EVENTID_CLIENT_START = "Topic Start Client"
-EVENTID_INTERNET_CHECK = "check internet status"
-
-_BASE_URL = 'http://spaghettiprojecti.no/saitama/'
-_THREAD_ID = '1434497743266652'
-
-# Subclass fbchat.Client and override required methods
-class Fb_client(threading.Thread,Client,subscriber):
- def __init__(self,eventbus,parser):
- with open('passwd.txt', 'r') as f:
- passwd = [a.strip() for a in f.readlines()]
- threading.Thread.__init__(self)
- Client.__init__(self,passwd[0],passwd[1])
- subscriber.__init__(self)
-
- self.parser = parser
- self.eb = eventbus
- print("Registering Topics")
- self.eb.register_consumer(self,EVENTID_CLIENT_SEND)
- self.eb.register_consumer(self,EVENTID_CLIENT_STOP)
- self.eb.register_consumer(self,EVENTID_CLIENT_START)
- def run(self):
- self.listen()
-
- def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
- self.markAsDelivered(author_id, thread_id)
- self.markAsRead(author_id)
-
- #log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
-
- # If Saitama-san is the author -> sayonara
- if author_id == self.uid:
- return
-
- message_data = Message_data(message_object.text, thread_id, thread_type)
- self.parser.parse(message_data)
- print("Message parsed")
-
- #Listens on the bus, subscribed to client send, stop and start
- def process(self,new_event):
- print("Event Recieved: {}".format(new_event.get_topic()))
- if not isinstance(new_event,event):
- print("Invalid event type passed")
- return
- if(new_event.get_topic()==EVENTID_CLIENT_SEND):
- self.send_message(new_event)
- elif(new_event.get_topic()==EVENTID_CLIENT_STOP):
- self.stopClient()
- elif(new_event.get_topic()==EVENTID_CLIENT_START):
- self.startClient()
-
- def startClient(self):
- self.listen()
- print("Exiting Client")
-
- def stopClient(self):
- print("Stop listneing and logging out")
- self.stopListening()
- self.logout()
-
- def send_message(self,message_event):
- message_data = message_event.get_data()
- self.send(Message(text=message_data.get_text()),
- thread_id=message_data.get_id(),
- thread_type = message_data.get_type())
-
- @staticmethod
- def post_message_event(eb,message_data):
- print("Posting event")
- eb.post(event(EVENTID_CLIENT_SEND,message_data))
-
-class Message_data():
- def __init__(self,text,thread_id,thread_type):
- self.text = text
- self.thread_id = thread_id
- self.thread_type = thread_type
-
- def get_text(self): return self.text
- def set_text(self,text): self.text = text
- def get_id(self,): return self.thread_id
- def get_type(self,): return self.thread_type
-
-
-class Internet_status(threading.Thread, subscriber):
- def __init__(self, eb):
- super().__init__()
- self.previous = "Internet Status: Det er ikke registrert noen problemer i ditt område."
- self.eb = eb
- self.eb.register_consumer(self, EVENTID_INTERNET_CHECK)
- self.msg_data = Message_data('', thread_id=_THREAD_ID,
- thread_type=ThreadType.GROUP)
- self.repeating_event = Repeating_event_object(eb,
- event(EVENTID_INTERNET_CHECK, None), datetime.datetime.now(),
- datetime.timedelta(minutes = 4))
- self.repeating_event.queue()
- print("internet status init")
-
- def process(self,new_event):
- # print("Event Recieved: {}".format(new_event.get_topic()))
- if not isinstance(new_event, event):
- print("Invalid event type passed")
- return
- if(new_event.get_topic() == EVENTID_INTERNET_CHECK):
- self.get_status()
-
- def get_status(self):
- url = "https://kabel.canaldigital.no/hjelp/sok-etter-feil/?facebook=False&q=7033"
- a = requests.get(url)
-
- start_str = "class=\"searchresultItem\">"
- end_str = "</h2>"
- start = a.text.find(start_str)
- end = a.text.find(end_str, start)
-
- s = a.text[start+len(start_str):end]
- s = s.replace("<h2>", "")
- s = s.replace("&#229;", "å") # superhacky. klarer ikke fikse utf-8
- s = s.strip()
- s = "Internet Status: " + s
-
- # print("post internet status")
- if s != self.previous:
- self.previous = s
- self.msg_data.set_text(s)
- Fb_client.post_message_event(self.eb, self.msg_data)
-
-
-
-
-def main():
- eb = eventbus()
- parser = Message_parser(eb)
-
- cv = threading.Condition() #conditional Variable
- teq = Time_event_queuer(eb,cv)
- teq.start()
-
- internet_check = Internet_status(eb)
-
- client = Fb_client(eb,parser)
- client.start()
- #eb.post(event(EVENTID_CLIENT_START,""))
- """
- print("Joining")
- while(client.isAlive()):
- time.sleep(1)
- client.join()
- """
- client.join()
- print ("Exiting Main Thread")
- eb.post(event(EVENTID_QUEUE_STOP,""))
- teq.join()
- eb.shutdown()
-
-
-if __name__ == "__main__":
- main()
diff --git a/Message_parser.py b/Message_parser.py
index 4542353..e57ea30 100644
--- a/Message_parser.py
+++ b/Message_parser.py
@@ -1,9 +1,12 @@
-from FbClient import *
from geeteventbus.event import event
-from datetime import datetime, timedelta
+from message_data import MessageData
+
+
+from fb_client import *
+from event_constants import *
TIME_KEYES = ['d','h','m','s']
-class Message_parser():
+class MessageParser():
def __init__(self,event_bus):
self.eb = event_bus
@@ -14,7 +17,7 @@ class Message_parser():
if text.startswith('!echo'):
print("Echoing")
message_data.set_text(text[6::])
- Fb_client.post_message_event(self.eb,message_data)
+ FbClient.post_message_event(self.eb,message_data)
return
# send dad joke if message start with @dad
@@ -24,7 +27,7 @@ class Message_parser():
headers={'Accept': 'text/plain'})
joke.encoding = 'utf-8'
message_data.set_text(joke.text)
- Fb_client.post_message_event(self.eb,message_data)
+ FbClient.post_message_event(self.eb,message_data)
return
if '!logout' in text:
@@ -39,9 +42,13 @@ class Message_parser():
elif text.startswith('!repeat'):
self.parseRepeat(message_data)
+
+ elif text.startswith('!weather'):
+ self.parseWeather(message_data)
#Returns timedelta object from text on format ?w?d?h?m?s
def get_time_delta_from_text(self,text):
+ from datetime import datetime, timedelta
time_delta = timedelta(seconds=0)
number = "0"
for c in text:
@@ -70,7 +77,7 @@ class Message_parser():
time_delta = self.get_time_delta_from_text(text_time)
else:
message_data.set_text("Please Specify Time: !rm ?w?d?h?m?s")
- Fb_client.post_message_event(self.eb,message_data)
+ FbClient.post_message_event(self.eb,message_data)
return
text_message = "REMINDER"
@@ -79,30 +86,32 @@ class Message_parser():
message_data.set_text(text_message)
send_message_event = event(EVENTID_CLIENT_SEND,message_data)
- Time_event_queuer.post_time_event(self.eb,send_message_event,time_delta)
+ TimeEventQueuer.post_time_event(self.eb,send_message_event,time_delta)
if(time_delta>timedelta(seconds = 15)):
- time_at = datetime.now() + time_delta
+ time_at = datetime.datetime.now() + time_delta
reciept_text = "Reminder set at {} in {}".format(
(':').join(str(time_at).split(':')[:-1]),
str(time_delta).split('.')[0])
- reciept_data = Message_data(reciept_text,message_data.get_id(),
+ reciept_data = MessageData(reciept_text,message_data.get_id(),
message_data.get_type())
- Fb_client.post_message_event(self.eb,reciept_data)
+ FbClient.post_message_event(self.eb,reciept_data)
def parseHelp(self,message_data):
message_data.set_text("Help is on the way")
- Fb_client.post_message_event(self.eb,message_data)
+ FbClient.post_message_event(self.eb,message_data)
def parseRepeat(self,message_data):
+ from repeating_event_object import RepeatingEventObject
print("Parsing Repeat")
message_data.set_text("Reapting This lol")
send_message_event = event(EVENTID_CLIENT_SEND,message_data)
- start_time = datetime.now() + timedelta(seconds=5)
+ start_time = datetime.datetime.now() + timedelta(seconds=5)
repeat_delta = timedelta(seconds=5)
- repeat_event = Repeating_event_object(self.eb, send_message_event,
+ repeat_event = RepeatingEventObject(self.eb, send_message_event,
start_time, repeat_delta)
repeat_event.queue()
-
+ def parseWeather(self,message_data):
+ self.eb.post(event(EVENTID_WEATHER_CHECK,message_data))
diff --git a/event_constants.py b/event_constants.py
new file mode 100644
index 0000000..9a68fae
--- /dev/null
+++ b/event_constants.py
@@ -0,0 +1,14 @@
+
+EVENTID_CLIENT_SEND = "Topic Message Send"
+EVENTID_CLIENT_STOP = "Topic Stop Client"
+EVENTID_CLIENT_START = "Topic Start Client"
+
+EVENTID_INTERNET_CHECK = "Topic: Check internet status"
+
+EVENTID_TIME = "Topic: Time Event"
+EVENTID_REPEATING = "Topic: Repeating Event"
+EVENTID_QUEUE_START = "Topic: Start Event Queue"
+EVENTID_QUEUE_STOP = "Topic: Stop Event Queue"
+
+EVENTID_WEATHER_CHECK = "Topic: Check Weather"
+
diff --git a/fb_client.py b/fb_client.py
new file mode 100644
index 0000000..e1c5f13
--- /dev/null
+++ b/fb_client.py
@@ -0,0 +1,91 @@
+
+from fbchat import log, Client
+from fbchat.models import *
+from geeteventbus.subscriber import subscriber
+from geeteventbus.eventbus import eventbus
+from geeteventbus.event import event
+
+from event_constants import *
+from time_event_queuer import *
+from message_data import MessageData
+
+
+import time
+import requests
+import threading
+import random
+import datetime
+
+
+
+#class types
+ID_TIMER = 0;
+ID_LISTENER = 1;
+
+# Subclass fbchat.Client and override required methods
+class FbClient(threading.Thread,Client,subscriber):
+ def __init__(self,eventbus,parser):
+ with open('passwd.txt', 'r') as f:
+ passwd = [a.strip() for a in f.readlines()]
+ threading.Thread.__init__(self)
+ Client.__init__(self,passwd[0],passwd[1])
+ subscriber.__init__(self)
+
+ self.parser = parser
+ self.eb = eventbus
+ print("Registering Topics")
+ self.eb.register_consumer(self,EVENTID_CLIENT_SEND)
+ self.eb.register_consumer(self,EVENTID_CLIENT_STOP)
+ self.eb.register_consumer(self,EVENTID_CLIENT_START)
+ def run(self):
+ self.listen()
+
+ def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
+ self.markAsDelivered(author_id, thread_id)
+ self.markAsRead(author_id)
+
+ #log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
+
+ # If Saitama-san is the author -> sayonara
+ if author_id == self.uid:
+ return
+
+ message_data = MessageData(message_object.text, thread_id, thread_type)
+ self.parser.parse(message_data)
+ print("Message parsed")
+
+ #Listens on the bus, subscribed to client send, stop and start
+ def process(self,new_event):
+ print("Event Recieved: {}".format(new_event.get_topic()))
+ if not isinstance(new_event,event):
+ print("Invalid event type passed")
+ return
+ if(new_event.get_topic()==EVENTID_CLIENT_SEND):
+ self.send_message(new_event)
+ elif(new_event.get_topic()==EVENTID_CLIENT_STOP):
+ self.stopClient()
+ elif(new_event.get_topic()==EVENTID_CLIENT_START):
+ self.startClient()
+
+ def startClient(self):
+ self.listen()
+ print("Exiting Client")
+
+ def stopClient(self):
+ print("Stop listneing and logging out")
+ self.stopListening()
+ self.logout()
+
+ def send_message(self,message_event):
+ message_data = message_event.get_data()
+ self.send(Message(text=message_data.get_text()),
+ thread_id=message_data.get_id(),
+ thread_type = message_data.get_type())
+
+ @staticmethod
+ def post_message_event(eb,message_data):
+ print("Posting event")
+ eb.post(event(EVENTID_CLIENT_SEND,message_data))
+
+
+
diff --git a/internet_status.py b/internet_status.py
new file mode 100644
index 0000000..9edc113
--- /dev/null
+++ b/internet_status.py
@@ -0,0 +1,63 @@
+
+
+
+from geeteventbus.subscriber import subscriber
+from geeteventbus.eventbus import eventbus
+from geeteventbus.event import event
+
+from fbchat.models import *
+import threading
+import requests
+import datetime
+
+from event_constants import *
+from time_event_queuer import *
+from message_data import MessageData
+from repeating_event_object import RepeatingEventObject
+
+_BASE_URL = 'http://spaghettiprojecti.no/saitama/'
+_THREAD_ID = '1434497743266652'
+
+class InternetStatus(threading.Thread, subscriber):
+ def __init__(self, eb):
+ super().__init__()
+ self.previous = "Internet Status: Det er ikke registrert noen problemer i ditt område."
+ self.eb = eb
+ self.eb.register_consumer(self, EVENTID_INTERNET_CHECK)
+ self.msg_data = MessageData('', thread_id=_THREAD_ID,
+ thread_type=ThreadType.GROUP)
+ self.repeating_event = RepeatingEventObject(eb,
+ event(EVENTID_INTERNET_CHECK, None), datetime.now(),
+ timedelta(minutes = 4))
+ self.repeating_event.queue()
+ print("internet status init")
+
+ def process(self,new_event):
+ # print("Event Recieved: {}".format(new_event.get_topic()))
+ if not isinstance(new_event, event):
+ print("Invalid event type passed")
+ return
+ if(new_event.get_topic() == EVENTID_INTERNET_CHECK):
+ self.get_status()
+
+ def get_status(self):
+ url = "https://kabel.canaldigital.no/hjelp/sok-etter-feil/?facebook=False&q=7033"
+ a = requests.get(url)
+
+ start_str = "class=\"searchresultItem\">"
+ end_str = "</h2>"
+ start = a.text.find(start_str)
+ end = a.text.find(end_str, start)
+
+ s = a.text[start+len(start_str):end]
+ s = s.replace("<h2>", "")
+ s = s.replace("&#229;", "å") # superhacky. klarer ikke fikse utf-8
+ s = s.strip()
+ s = "Internet Status: " + s
+
+ # print("post internet status")
+ if s != self.previous:
+ self.previous = s
+ self.msg_data.set_text(s)
+ Fb_client.post_message_event(self.eb, self.msg_data)
+
diff --git a/message_data.py b/message_data.py
new file mode 100644
index 0000000..e9f20a8
--- /dev/null
+++ b/message_data.py
@@ -0,0 +1,11 @@
+
+class MessageData():
+ def __init__(self,text,thread_id,thread_type):
+ self.text = text
+ self.thread_id = thread_id
+ self.thread_type = thread_type
+
+ def get_text(self): return self.text
+ def set_text(self,text): self.text = text
+ def get_id(self,): return self.thread_id
+ def get_type(self,): return self.thread_type
diff --git a/repeating_event_object.py b/repeating_event_object.py
new file mode 100644
index 0000000..b961152
--- /dev/null
+++ b/repeating_event_object.py
@@ -0,0 +1,40 @@
+from datetime import timedelta
+from event_constants import *
+
+"""
+Repeating Event repeats itself on set intervals
+eb - to post the events on
+event2execute - event that is to be executed, could be send message or other.
+occurence_time - start time of first event
+repeat_time - delta between repeats: defaults to two seconds
+n - number of repeats: defaults to 5
+
+to execute object do object.queue()
+"""
+class RepeatingEventObject():
+ def __init__(self,eb,event2execute,occurence_time,repeat_time=timedelta(seconds=2),n=5):
+ self.eb = eb
+ self.event2execute = event2execute #Event to be posted
+ self.occurence_time = occurence_time
+ self.repeat_time = repeat_time
+ self.n = n #number of repeats
+
+ def get_event(self): return self.event2execute
+
+ def queue(self):
+ if(self.n==0):
+ print("RepeatingEvent Finished")
+ return
+
+ from datetime import datetime
+ from time_event_queuer import TimeEventQueuer
+ from geeteventbus.event import event
+
+ self.n-=1
+ # print("Posting REPEATING event")
+ while(datetime.now() > self.occurence_time):
+ self.occurence_time += self.repeat_time
+ delta_time = self.occurence_time - datetime.now()
+ time_event = event( EVENTID_REPEATING, self)
+ TimeEventQueuer.post_time_event(self.eb, time_event, delta_time)
+
diff --git a/run_system.py b/run_system.py
new file mode 100644
index 0000000..761e6f4
--- /dev/null
+++ b/run_system.py
@@ -0,0 +1,54 @@
+
+
+
+from fbchat import log, Client
+from fbchat.models import *
+from geeteventbus.subscriber import subscriber
+from geeteventbus.eventbus import eventbus
+from geeteventbus.event import event
+
+from time_event_queuer import *
+from message_parser import *
+from fb_client import *
+from event_constants import *
+from internet_status import InternetStatus
+from weather_forcast import WeatherForcast
+
+
+import time
+import requests
+import threading
+import random
+import datetime
+
+
+
+def main():
+ eb = eventbus()
+ parser = MessageParser(eb)
+
+ cv = threading.Condition() #conditional Variable
+ teq = TimeEventQueuer(eb,cv)
+ teq.start()
+
+ internet_check = InternetStatus(eb)
+ weather_forcast = WeatherForcast(eb)
+
+ client = FbClient(eb,parser)
+ client.start()
+ #eb.post(event(EVENTID_CLIENT_START,""))
+ """
+ print("Joining")
+ while(client.isAlive()):
+ time.sleep(1)
+ client.join()
+ """
+ client.join()
+ print ("Exiting Main Thread")
+ eb.post(event(EVENTID_QUEUE_STOP,""))
+ teq.join()
+ eb.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/thread_handler.py b/thread_handler.py
new file mode 100644
index 0000000..0039e5e
--- /dev/null
+++ b/thread_handler.py
@@ -0,0 +1,63 @@
+
+class Thread_handler():
+ def __init__(self,eb):
+ self.threads = []
+ self.eb = eb
+
+ def add_thread(self,threadObject):
+ self.threads.append(threadObject)
+
+ def start_threads(self):
+ for t in self.threads:
+ print("Registering consumer")
+ self.eb.register_consumer(t,EVENTID_TIME)
+ self.eb.register_consumer(t,EVENTID_QUEUE_START)
+ self.eb.register_consumer(t,EVENTID_QUEUE_STOP)
+ t.start()
+ self.eb.post(event(EVENTID_QUEUE_START,""))
+
+ def join_threads(self):
+ self.eb.post(event(EVENTID_QUEUE_STOP,""))
+ for t in self.threads:
+ print("Joining thread: {}".format(t.getName()))
+ t.join()
+
+def main():
+ # Create Thread Handler
+ eb = eventbus()
+ th = Thread_handler(eb)
+ cv = threading.Condition()
+
+ # Create new threads
+ teq = Time_event_queuer(eb,cv)
+ teq.start()
+ th.add_thread(teq)
+
+ # Start new Threads
+ #th.start_threads()
+
+ # Post Information
+ teq.post_time_event(eb,"post1",timedelta(seconds=3))
+ time.sleep(2)
+ teq.post_time_event(eb,"post2",timedelta(seconds=10))
+ time.sleep(2)
+ teq.post_time_event(eb,"post3",timedelta(seconds=6))
+ time.sleep(1)
+ teq.post_time_event(eb,"post4",timedelta(seconds=1))
+ time.sleep(1)
+ teq.post_time_event(eb,"post5",timedelta(seconds=2))
+ time.sleep(1)
+
+ # Stopping threads
+ #th.join_threads()
+ eb.post(event(EVENTID_QUEUE_STOP,""))
+ teq.join()
+
+
+
+ print ("Exiting Main Thread")
+ eb.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/timeEventQueuer.py b/time_event_queuer.py
index 9b86f35..40b3d6b 100644
--- a/timeEventQueuer.py
+++ b/time_event_queuer.py
@@ -2,6 +2,7 @@ from geeteventbus.subscriber import subscriber
from geeteventbus.eventbus import eventbus
from geeteventbus.event import event
+from event_constants import *
import time
import requests
import threading
@@ -9,10 +10,6 @@ import random
from datetime import datetime, timedelta
import heapq
-EVENTID_TIME = "Topic: Time Event"
-EVENTID_REPEATING = "Topic: Repeating Event"
-EVENTID_QUEUE_START = "Topic: Start Event Queue"
-EVENTID_QUEUE_STOP = "Topic: Stop Event Queue"
"""
Event Queuer for Time Events
@@ -24,7 +21,7 @@ Edit execute_event to fit execution process of event
The Queuer must be added as a subscriber to the event bus on the desired topics
"""
-class Time_event_queuer(threading.Thread,subscriber):
+class TimeEventQueuer(threading.Thread,subscriber):
def __init__(self,eb,cv):
super().__init__()
self.eb = eb #Event Bus
@@ -149,100 +146,5 @@ class Time_event_queuer(threading.Thread,subscriber):
eb.post(event(EVENTID_TIME,data))
-"""
-Repeating Event repeats itself on set intervals
-eb - to post the events on
-event2execute - event that is to be executed, could be send message or other.
-occurence_time - start time of first event
-repeat_time - delta between repeats: defaults to two seconds
-n - number of repeats: defaults to 5
-
-to execute object do object.queue()
-"""
-class Repeating_event_object():
- def __init__(self,eb,event2execute,occurence_time,repeat_time=timedelta(seconds=2),n=5):
- self.eb = eb
- self.event2execute = event2execute #Event to be posted
- self.occurence_time = occurence_time
- self.repeat_time = repeat_time
- self.n = n #number of repeats
-
- def get_event(self): return self.event2execute
-
- def queue(self):
- if(self.n==0):
- print("RepeatingEvent Finished")
- return
- self.n-=1
- # print("Posting REPEATING event")
- now = datetime.now()
- while(now > self.occurence_time):
- self.occurence_time += self.repeat_time
- delta_time = self.occurence_time - datetime.now()
- time_event = event( EVENTID_REPEATING, self)
- Time_event_queuer.post_time_event(self.eb, time_event, delta_time)
-
-
-class Thread_handler():
- def __init__(self,eb):
- self.threads = []
- self.eb = eb
-
- def add_thread(self,threadObject):
- self.threads.append(threadObject)
-
- def start_threads(self):
- for t in self.threads:
- print("Registering consumer")
- self.eb.register_consumer(t,EVENTID_TIME)
- self.eb.register_consumer(t,EVENTID_QUEUE_START)
- self.eb.register_consumer(t,EVENTID_QUEUE_STOP)
- t.start()
- self.eb.post(event(EVENTID_QUEUE_START,""))
-
- def join_threads(self):
- self.eb.post(event(EVENTID_QUEUE_STOP,""))
- for t in self.threads:
- print("Joining thread: {}".format(t.getName()))
- t.join()
-
-
-def main():
- # Create Thread Handler
- eb = eventbus()
- th = Thread_handler(eb)
- cv = threading.Condition()
-
- # Create new threads
- teq = Time_event_queuer(eb,cv)
- teq.start()
- th.add_thread(teq)
-
- # Start new Threads
- #th.start_threads()
-
- # Post Information
- teq.post_time_event(eb,"post1",timedelta(seconds=3))
- time.sleep(2)
- teq.post_time_event(eb,"post2",timedelta(seconds=10))
- time.sleep(2)
- teq.post_time_event(eb,"post3",timedelta(seconds=6))
- time.sleep(1)
- teq.post_time_event(eb,"post4",timedelta(seconds=1))
- time.sleep(1)
- teq.post_time_event(eb,"post5",timedelta(seconds=2))
- time.sleep(1)
-
- # Stopping threads
- #th.join_threads()
- eb.post(event(EVENTID_QUEUE_STOP,""))
- teq.join()
-
-
-
- print ("Exiting Main Thread")
- eb.shutdown()
-if __name__ == "__main__":
- main()
diff --git a/weather_forcast.py b/weather_forcast.py
new file mode 100644
index 0000000..73a7a46
--- /dev/null
+++ b/weather_forcast.py
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+from geeteventbus.subscriber import subscriber
+from geeteventbus.eventbus import eventbus
+from geeteventbus.event import event
+
+from fbchat.models import *
+import threading
+import requests
+import datetime
+import sys
+
+from event_constants import *
+from message_data import MessageData
+from repeating_event_object import RepeatingEventObject
+_THREAD_ID = '1434497743266652'
+class WeatherForcast(threading.Thread,subscriber):
+ def __init__(self, eb):
+ super().__init__()
+ self.eb = eb
+ self.eb.register_consumer(self, EVENTID_WEATHER_CHECK)
+ self.msg_data = MessageData('', thread_id=_THREAD_ID,
+ thread_type=ThreadType.GROUP)
+ print("Weather Module status Init")
+
+
+ def process(self,new_event):
+ # print("Event Recieved: {}".format(new_event.get_topic()))
+ if not isinstance(new_event, event):
+ print("Invalid event type passed")
+ return
+ if(new_event.get_topic() == EVENTID_WEATHER_CHECK):
+ msg_data = new_event.get_data()
+ msg_data.set_text(self.get_weather())
+ self.eb.post(event(EVENTID_CLIENT_SEND,msg_data))
+
+ def get_weather(self):
+ url = "https://www.yr.no/place/Norway/S%C3%B8r-Tr%C3%B8ndelag/Trondheim/Trondheim/"
+ content = requests.get(url)
+
+ table_class = "class=\"yr-table yr-table-overview2 yr-popup-area\""
+ table_start = content.text.find(table_class)
+ table_end = content.text.find(table_class,table_start+1)
+ table_content = content.text[table_start:table_end]
+
+ body_tag = "<tbody>"
+ body_start = table_content.find(body_tag)
+ body_end = table_content.find("</tbody>",body_start+1)
+ body_content = table_content[body_start:body_end]
+
+ row_end = 0
+ weather = ""
+ while(True):
+ row_tag = "<tr>"
+ row_start = body_content.find(row_tag,row_end)
+ row_end = body_content.find("</tr>",row_start+1)
+ if(row_start < 0 or row_end < 0): break
+ row_content = body_content[row_start:row_end]
+
+ td_end = 0
+ row_array = row_content.split("<td")
+ time = self.get_time(row_array[1])
+ temp = self.get_temp(row_array[3])
+ rain = self.get_rain(row_array[4])
+ wind = self.get_wind(row_array[5])
+ weather += time + " \t " + temp + " \t " + rain + "\t " + wind + "\n"
+ return weather
+
+ def get_time(self,t):
+ t_s = t.find(">")
+ t_e = t.find("<")
+ s = t[t_s+2:t_e].encode(sys.stdout.encoding, errors="replace").decode("utf8")
+ s = s.replace("?","-")
+ return s
+
+ def get_temp(self,t):
+ t_s = t.find(">")
+ t_e = t.find("<")
+ s = t[t_s+1:t_e]
+ return s
+
+ def get_rain(self,t):
+ t_s = t.find(">")
+ t_e = t.find("<")
+ s = t[t_s+1:t_e].encode(sys.stdout.encoding, errors="replace").decode("utf8")
+ s = s.replace("?","-")
+ return s
+
+ def get_wind(self,t):
+ i_s = t.find("<img")
+ t_s = t.find(">",i_s)
+ t_e = t.find("<",t_s)
+ s = t[t_s+1:t_e].encode(sys.stdout.encoding, errors="replace").decode("utf8")
+ return s
+
+
+
+ def encode_print(self,text):
+ print(text.encode(sys.stdout.encoding, errors='replace'))
+
+if __name__ == "__main__":
+ eb = eventbus()
+ wf = WeatherForcast(eb)
+ print(wf.get_weather())
+
+ eb.shutdown()
+
+