Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor shared code and make requested changes #2

Merged
merged 3 commits into from
Jun 25, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 0 additions & 65 deletions Python_Examples/PiLiteJson.py

This file was deleted.

63 changes: 63 additions & 0 deletions Python_Examples/PiLiteLib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from collections import deque
from time import sleep

import requests
import serial


class PiLiteBoard(object):
def __init__(self):
self.ser = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=3.0)
self.ser.write("$$$SPEED50\r")

def write(self, text):
text = text.encode('utf-8')
while text:
self.ser.write(text[:14])
text = text[14:]
sleep(3)


def poll_for_updates(source, sink, interval=60, repeat=True):
oldstatus = None
while True:
try:
status = source.message()
if repeat or status != oldstatus:
print(status)
oldstatus = status
sink.write(status)
except (KeyboardInterrupt, SystemExit):
raise
except Exception as e:
print("Error:" + str(e))
sink.write("...oops...error...")
sink.write(str(e))
sleep(interval)


class JSONPoll(object):
def __init__(self, url, message_format, params=None):
self.url = url
self.message_format = message_format
self.params = params or {}

def message(self):
data = requests.get(self.url, params=self.params).json()
return self.message_format.format(**self.mung_data(data))

def mung_data(self, data):
return data


class CyclingSources(object):
def __init__(self, *sources):
self.sources = deque(sources)

def message(self):
message = self.sources[0].message()
self.sources.rotate(-1)
return message

def __len__(self):
return len(self.sources)
35 changes: 35 additions & 0 deletions Python_Examples/PiLiteStock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python
import urllib

from PiLiteLib import PiLiteBoard, poll_for_updates, JSONPoll


class StockPoll(JSONPoll):
def __init__(self, stock, message_format=""):
""" Encoding a space in the url a + breaks YQL, so requests params
handling can't be used
"""
default_format = "{symbol} {Bid},{PercentChange}"
base_url = "http://query.yahooapis.com/v1/public/yql"
querystring = "from yahoo.finance.quotes where symbol='%s'"
fmt = "format=json"
env = "env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
url = "%s?q=select%%20*%%20%s&%s&%s"%(base_url, urllib.quote(querystring%stock), fmt, env)
super(StockPoll, self).__init__(url, message_format or default_format)

def mung_data(self, data):
""" Drill down to the result to make message_format more readable"""
return super(StockPoll, self).mung_data(data['query']['results']['quote'])



def main():
source = StockPoll("MSFT")
sink = PiLiteBoard()
print("ready")
sink.write("ready ")
poll_for_updates(source, sink)


if __name__ == "__main__":
main()
34 changes: 2 additions & 32 deletions Python_Examples/PiLiteTwitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,11 @@

import ConfigParser
import os
from time import sleep

import twitter
import serial


class PiLiteBoard(object):
def __init__(self):
self.ser = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=3.0)
self.ser.write("$$$SPEED50\r")

def write(self, text):
text = text.encode('utf-8')
while text:
self.ser.write(text[:14])
text = text[14:]
sleep(3)
from PiLiteLib import PiLiteBoard, poll_for_updates


class TwitterTimeline(object):
Expand All @@ -67,30 +55,12 @@ def message(self):
return "@%s::%s..."%(status.GetUser().GetScreenName(), status.GetText())


def poll_for_updates(source, sink, interval=60):
oldstatus = None
while True:
try:
status = source.message()
if status != oldstatus:
print(status)
oldstatus = status
sink.write(status)
except (KeyboardInterrupt, SystemExit):
raise
except Exception as e:
print("Error:" + str(e))
sink.write("...oops...error...")
sink.write(str(e))
sleep(interval)


def main():
source = TwitterTimeline()
sink = PiLiteBoard()
print("ready")
sink.write("ready ")
poll_for_updates(source, sink)
poll_for_updates(source, sink, repeat=False)


if __name__ == "__main__":
Expand Down
30 changes: 30 additions & 0 deletions Python_Examples/PiLiteWeather.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python
import urllib

from PiLiteLib import PiLiteBoard, poll_for_updates, JSONPoll


class WeatherPoll(JSONPoll):
def __init__(self, location, message_format=""):
default_format = "{name}: {weather[0][description]}, {main[temp_c]:.0f}C"
base_url = "http://api.openweathermap.org/data/2.5/weather?q=%s"
super(WeatherPoll, self).__init__(base_url%location,
message_format or default_format)

def mung_data(self,data):
""" Convert local temperature from K to C"""
data['main']['temp_c'] = data['main']['temp']-273.15
return super(WeatherPoll, self).mung_data(data)



def main():
source = WeatherPoll("London,uk")
sink = PiLiteBoard()
print("ready")
sink.write("ready ")
poll_for_updates(source, sink)


if __name__ == "__main__":
main()
17 changes: 1 addition & 16 deletions Python_Examples/PiLiteWorldTime.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
#!/usr/bin/env python
from collections import deque

import arrow

from PiLiteTwitter import PiLiteBoard, poll_for_updates
from PiLiteLib import PiLiteBoard, poll_for_updates, CyclingSources


class WorldTime(object):
Expand All @@ -15,19 +13,6 @@ def message(self):
now = arrow.utcnow().to(self.timezone)
return "{} : {}".format(self.label, now.format("HH:mm:ss"))


class CyclingSources(object):
def __init__(self, *sources):
self.sources = deque(sources)

def message(self):
message = self.sources[0].message()
self.sources.rotate(-1)
return message

def __len__(self):
return len(self.sources)


def main():
source = CyclingSources(WorldTime("London", "Europe/London"),
Expand Down
4 changes: 2 additions & 2 deletions Python_Examples/PiLiteXively.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ def __init__(self, feed):

def message(self):
feed = self.api.feeds.get(self.feedid)
value = feed.datastreams[0].current_value
return "%s"%value
stream = feed.datastreams[0]
return "%s %s %s %s"%(feed.title, stream.id, stream.current_value, stream.unit.label)


def main():
Expand Down