Saturday, February 11, 2012

Step Eight: Finalizing Google App Engine (Backend) Logic

Now that we have a crash course in how we can leverage Google App Engine and understand what kind of request the Arduino will be making, we can finalize the App Engine code.

Using the two previous posts, we can assemble the final main.py using the blocks of logic from the previous post. The complete file looks like this (see previous posts additional comments):


#!/usr/bin/env python
import os
import uuid
import cgi
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
import datetime
import time
class WeatherEntry(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
temperature = db.FloatProperty()
humidity = db.FloatProperty()
other = db.FloatProperty()
class DailyWeatherEntry(db.Model):
date = db.IntegerProperty()
temp_entry = db.TextProperty()
humidity_entry = db.TextProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
self.redirect('http://apartmentarduino.blogspot.com/')
class Weather(webapp.RequestHandler):
def get(self):
temp = str(float(cgi.escape(self.request.get('t')))/100)
humidity = str(float(cgi.escape(self.request.get('h')))/100)
strS = str(cgi.escape(self.request.get('s')))
if strS == 'my_secret': #secret added since I don't want just anyone to pollute my weather data!
rightNow = int(time.time())
dayAgo = rightNow-86400
recent_record = DailyWeatherEntry.gql("WHERE date > :1 ORDER BY date DESC",dayAgo)
rightNow = str(rightNow)
if recent_record.count()!=0: #update entry
dayObj = recent_record[0]
dayObj.temp_entry = dayObj.temp_entry + '['+rightNow+','+temp+'],'
dayObj.humidity_entry = dayObj.humidity_entry + '['+rightNow+','+humidity+'],'
dayObj.put()
else: #create entry
newEntry = DailyWeatherEntry(
date = int(time.time()),
temp_entry = '['+rightNow+','+temp+'],',
humidity_entry = '['+rightNow+','+humidity+'],'
)
newEntry.put()
self.response.headers.add_header("X-Arduino-Data", temp +','+ humidity )
else:
self.error(500)
class ShowWeather(webapp.RequestHandler):
def get(self):
the_weather = db.GqlQuery(
"SELECT * FROM DailyWeatherEntry ORDER BY date DESC LIMIT 1")
template_values = {
'weather' : the_weather
}
path = os.path.join(os.path.dirname(__file__), 'weather.html')
self.response.out.write(template.render(path, template_values))
def main():
application = webapp.WSGIApplication([('/', MainHandler),
('/weather/.?',Weather),
('/w',ShowWeather)],
debug=False)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
view raw main.py hosted with ❤ by GitHub



Hopefully you have some understanding of the Django-like templating engine App Engine supports. There is an excellent hello-world tutorial in Google's official docs.

Next we'll visualize the data using a javascript based graphing library Flot!

No comments:

Post a Comment