Skip to content

Commit

Permalink
updates to rpc, webclock, etc
Browse files Browse the repository at this point in the history
adjusted models a bit
more work on rpc interfaces. made post interface of learndata work
finished und cleaned up the javascript stats display. you can now edit the supposed point so the heuristic can learn from it.
etc :-)
  • Loading branch information
poelzi committed Jul 4, 2010
1 parent b9515f4 commit f3aa942
Show file tree
Hide file tree
Showing 10 changed files with 321 additions and 90 deletions.
23 changes: 19 additions & 4 deletions api/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,25 @@ class SessionEntriesHandler(BaseHandler):
# return ('session_entries_handler', ['session'])

class SessionLearnHandler(BaseHandler):
allowed_methods = ('GET','POST', 'PUT', 'DELETE')
allowed_methods = ('GET', 'POST', 'DELETE')
exclude = ('session',)
model = LearnData

# @staticmethod
# def resource_uri():
# return ('session_learn_handler', ['session'])
def read(self, request, session=None):
return Session.objects.get(id=session).learndata

def create(self, request, *args, **kwargs):

session = Session.objects.get(id=kwargs["session"])
ld = session.learndata

for key in ["wake", "lights", "start", "stop"]:
if key in request.POST:
if session.entry_set.filter(id=request.POST[key]).count():
setattr(ld, "%s_id" %key, request.POST[key])
else:
setattr(ld, "%s_id" %key, None)

ld.save()

return ld
5 changes: 2 additions & 3 deletions api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@


urlpatterns = patterns('',
#url(r'^docs/', show_docs),
url(r'^docs/', documentation_view),
url(r'^session/(?P<session>[^/]+)/learndata/', session_learn_handler, name="session_learn_handler"),
url(r'^session/(?P<session>[^/]+)/entries/', session_entries_handler, name="session_entries_handler"),
url(r'^session/(?P<id>[^/]+)/', session_handler, name="session_handler"),
url(r'^session/', session_list_handler, name="session_list_handler"),
url(r'^session/(?P<id>[^/]+)/$', session_handler, name="session_handler"),
url(r'^session/$', session_list_handler, name="session_list_handler"),
)
49 changes: 45 additions & 4 deletions db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,46 @@ class Session(models.Model):
"""
One Sleep Session
"""
start = models.DateTimeField("Start", null=False, auto_now_add=True, db_index=True)
stop = models.DateTimeField("Stop", null=False, auto_now_add=True, db_index=True)
start = models.DateTimeField("Start", null=False, auto_now_add=True, editable=False)
stop = models.DateTimeField("Stop", null=False, auto_now_add=True, editable=False)
user = models.ForeignKey(User, null=True)
detector = models.ForeignKey(Detector, null=True)
typ = models.IntegerField("Type", default=0, choices=SESSION_TYPES)
wakeup = models.DateTimeField("Wakeup", null=True)
rating = models.DecimalField("Rating", max_digits=1, decimal_places=0, null=True)
rating = models.IntegerField("Rating", null=True)
deleted = models.BooleanField("Deleted", default=False)
# Do we need this ?
#alone = models.BooleanField("Alone", null=True, default=True, help_text="Sleeping with someone else in the bed")

def save(self, *args, **kwargs):
super(Session, self).save(*args, **kwargs)
self.learndata

@property
def learndata(self):
if not self.id:
raise ValueError, "Session Object not saved"
try:
return self.learndata_set.all()[0]
except IndexError, e:
rv = LearnData(session=self)
rv.save()
return rv

@property
def week(self):
return self.start.isocalendar()[1]

def __repr__(self):
return "<Session %s %s-%s>" %(self.user, self.start, self.stop)

@property
def length(self):
s = (self.stop - self.start).seconds
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
return (hours, minutes, seconds)


class Entry(models.Model):
date = models.DateTimeField("Date", null=False, auto_now_add=True)
Expand All @@ -68,6 +91,24 @@ class Entry(models.Model):
def __repr__(self):
return "<Entry %s %d>" %(self.date, self.value)


class LearnData(models.Model):
"""
One Sleep Session
"""
session = models.ForeignKey(Session, null=False)
lights = models.ForeignKey(Entry, related_name="learn_lights",
help_text="Where the lights should start dimming", null=True)
wake = models.ForeignKey(Entry, related_name="learn_wake",
help_text="Perfect wakeup point", null=True)
start = models.ForeignKey(Entry, related_name="learn_start",
help_text="When sleeping began", null=True)
stop = models.ForeignKey(Entry, related_name="learn_stop",
help_text="When sleep stopped", null=True)
learned = models.BooleanField(default=False)



class DBWriter(ez_chronos.CommandDispatcher):

def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -108,7 +149,7 @@ def smpl_0x03(self, data):
#FIXME add device & user
self.session[device] = session = Session(start=now, stop=now)
session.save()
logging.debug("start new session: %s" %session.id)
logging.debug("start new session: %s @ %s" %(session.id, session.start))
else:
session = self.session[device]
self.last_msg[device] = now
Expand Down
27 changes: 26 additions & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os.path

DEVELOPMENT_MODE = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG

Expand Down Expand Up @@ -78,7 +79,8 @@
)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'piston.middleware.ConditionalMiddlewareCompatProxy',
'piston.middleware.CommonMiddlewareCompatProxy',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
Expand All @@ -99,12 +101,14 @@
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.markup',
# 'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'uberclock.db',
'uberclock.webclock',
'piston',
'uberclock.api',
)


Expand All @@ -119,9 +123,30 @@

CLOCK_SESSION_TIMEOUT = 60*5

PISTON_STREAM_OUTPUT = True

CHUMBY_URLS = {
'default' : '<embed width="800" height="480" quality="high" bgcolor="#FFFFFF" wmode="transparent" name="virtualchumby" type="application/x-shockwave-flash" src="http://www.chumby.com/virtualchumby_noskin.swf" FlashVars="_chumby_profile_url=http%3A%2F%2Fwww.chumby.com%2Fxml%2Fvirtualprofiles%2FE8E34C1E-726B-11DF-BA50-001B24F07EF4&amp;baseURL=http%3A%2F%2Fwww.chumby.com" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>'
}

import os

if not os.path.exists(os.path.expanduser("~/.uberclock")):
os.mkdir(os.path.expanduser("~/.uberclock"))

try:
from settings_local import *
except ImportError:
import sys
sys.stderr.write('Unable to read settings_local.py\n')

if DEVELOPMENT_MODE:
DATABASE_ENGINE = DATABASES['default']['ENGINE'].split('.')[-1]
INSTALLED_APPS += ('django_evolution',)

try:
INSTALLED_APPS += ADDITIONAL_APPS
except NameError:
pass

#PISTON_DISPLAY_ERRORS = DEBUG
3 changes: 2 additions & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@

</style>

<script type="text/javascript" src="/static/js/jquery/jquery-1.3.2.min.js"></script>
<!--<script type="text/javascript" src="/static/js/jquery/jquery-1.3.2.min.js"></script>-->
<script type="text/javascript" src="/static/js/jquery/jquery-1.3.2.js"></script>

{% block header_base %}{% endblock %}
{% block header %}{% endblock %}
Expand Down
1 change: 1 addition & 0 deletions urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),

(r'^api/', include('uberclock.api.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'', include('uberclock.webclock.urls')),
Expand Down
24 changes: 21 additions & 3 deletions webclock/templates/stats.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
{% extends "base.html" %}
{% load webclock %}

{% block menuextra %}
<li class="toplink">
<form id="stats_type_form">
<select id="stats_type" name="typ">
<option value="png" {%if "png" == current%}selected="1"{%endif%}>Image</option>
<option value="js" {%if "js" == current%}selected="1"{%endif%}>Interactive</option>
</select>
</form>
</li>
{% endblock %}


{% block content %}
Expand All @@ -8,10 +20,16 @@
{% else %}
{% ifchanged session.week%}<h3>Week {{ session.start|date:"W" }}</h3>{% endifchanged %}
{% endif %}
<a href="/stats/{{ session.id }}/">{{ session.start|date:"DATETIME_FORMAT" }} - {{ session.stop|date:"DATETIME_FORMAT" }}</a><br/>


<a href="/stats/{{ session.id }}/" class="stats_detail">{{ session.start|date:"DATETIME_FORMAT" }} - {{ session.stop|date:"DATETIME_FORMAT" }} ({{session.length|timelengh}})</a><br/>
{% endfor %}

{% block js_footer %}
<script type="text/javascript">
$('#stats_type').change(function() {
$('#stats_type_form').submit();
});
</script>
{% endblock %}


{% endblock %}
Loading

0 comments on commit f3aa942

Please sign in to comment.