Permalink
Browse files

added a crontab action scheduler.

  • Loading branch information...
1 parent 4a50fe2 commit 408dd4ff8ab92a220518e3e246e4e9da75e3f4b3 @dandroid88 committed Nov 11, 2012
View
@@ -5,5 +5,6 @@ def after_install(options, home_dir):
subprocess.call([join(home_dir, 'bin', 'pip'), 'install', 'pyserial'])
subprocess.call([join(home_dir, 'bin', 'pip'), 'install', 'jsonrpclib'])
subprocess.call([join(home_dir, 'bin', 'pip'), 'install', 'beautifulsoup4'])
+ subprocess.call([join(home_dir, 'bin', 'pip'), 'install', 'python-crontab'])
"""))
print output
No changes.
@@ -0,0 +1,8 @@
+{
+ "authors":[
+ "Daniel Myers"
+ ],
+ "version":".1",
+ "name":"Scheduler",
+ "url":"/scheduler/"
+}
@@ -0,0 +1,85 @@
+from webmote_django.webmote.models import *
+from django.db import models
+from django.contrib.auth.models import User
+from django.forms import ModelForm
+from django import forms
+from django.forms.widgets import *
+from crontab import CronTab
+
+###########
+# Schedules
+###########
+
+class Schedules(models.Model):
+ name = models.CharField(max_length=100, blank=True)
+ active = models.BooleanField()
+ class Meta:
+ app_label = 'webmote'
+
+ def delete(self, *args, **kwargs):
+ for schedlet in self.schedlet_set.all():
+ schedlet.delete()
+ super(Schedules, self).delete(*args, **kwargs)
+
+class Schedule_Form(ModelForm):
+ name = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'e.g. AC, Heat, Lights, etc.'}))
+ class Meta:
+ model = Schedules
+ app_label = 'webmote'
+ exclude = ('active',)
+##########
+# Schedlet
+##########
+
+class Schedlet(models.Model):
+ schedule = models.ForeignKey(Schedules)
+ action = models.ForeignKey(Actions, related_name='schedlet_action')
+ time = models.TimeField()
+ sunday = models.BooleanField()
+ monday = models.BooleanField()
+ tuesday = models.BooleanField()
+ wednesday = models.BooleanField()
+ thursday = models.BooleanField()
+ friday = models.BooleanField()
+ saturday = models.BooleanField()
+ class Meta:
+ app_label = 'webmote'
+
+ def save(self, *args, **kwargs):
+ super(Schedlet, self).save(*args, **kwargs)
+ # the port number here should be obtained dynamically
+ cmd = 'wget http://localhost:8081/scheduler/runSchedlet/' + str(self.id) + '/'
+ tab = CronTab()
+ job = tab.new(command=cmd, comment='Generated by Webmote')
+ job.minute.on(self.time.minute)
+ job.hour.on(self.time.hour)
+ days = (
+ self.sunday,
+ self.monday,
+ self.tuesday,
+ self.wednesday,
+ self.thursday,
+ self.friday,
+ self.saturday
+ )
+ for (num, day) in enumerate(days):
+ if day:
+ job.dow.on(num)
+ tab.write()
+
+ def delete(self, *args, **kwargs):
+ # the port number here should be obtained dynamically
+ cmd = 'wget http://localhost:8081/scheduler/runSchedlet/' + str(self.id) + '/'
+ tab = CronTab()
+ job = tab.find_command(cmd)
+ if job:
+ tab.remove_all(cmd)
+ tab.write()
+ super(Schedlet, self).delete(*args, **kwargs)
+
+class Schedlet_Form(ModelForm):
+ time = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'e.g. 15:30, 1:30, etc.'}))
+ class Meta:
+ model = Schedlet
+ app_label = 'webmote'
+ exclude = ('schedule',)
@@ -0,0 +1,13 @@
+$('.schedule-active').change(function() {
+ id = $(this).attr('id').split('-')[2];
+ data = $(this).find("option:selected").val()
+ $.ajax({
+ url: '/scheduler/editActive/' + id +'/',
+ type: 'POST',
+ contentType: 'application/json; charset=utf-8',
+ data: JSON.stringify(data),
+ dataType: 'text',
+ success: function(result) {}
+ });
+});
+
@@ -0,0 +1,52 @@
+{% extends "base.html" %}
+{% comment %}
+{% extends "jqm/simple.html" %}
+{% endcomment %}
+
+{% block title %}
+ Webmote - Example
+{% endblock %}
+
+{% block page_title %}
+ Webmote - Schedular
+{% endblock %}
+{% block content %}
+ <div data-role="content">
+ <h2>{{ schedule.name }}</h2>
+ {% if schedule.schedlet_set %}
+ <div class="ui-grid-a" id="schedlet_grid_fields">
+ <div class="ui-block-a">
+ <div class="ui-bar ui-bar-a" style="height:30px">Action</div>
+ </div>
+ <div class="ui-block-b">
+ <div class="ui-bar ui-bar-a" style="height:30px">Delete</div>
+ </div>
+ </div>
+ {% for s in schedule.schedlet_set.all %}
+ <div class="ui-grid-a" id="schedlet_grid_row_{{ s.id }}">
+ <div class="ui-block-a">
+ <div class="ui-bar ui-bar-a" style="height:30px">
+ {{ s.action.name }}
+ </div>
+ </div>
+ <div class="ui-block-b">
+ <div class="ui-bar ui-bar-a" style="height:30px">
+ <form method="post" action="">{% csrf_token %}
+ <input type="submit" name="deleteSchedlet" value="Delete" onclick="this.value='{{ s.id }}';this.form.post()"/>
+ </form>
+ </div>
+ </div>
+ </div>
+ {% endfor %}
+ {% else %}
+ <h3>Currently there are no schedlets in this schedule...</h3>
+ {% endif %}
+ <div id="ScheduleForm">
+ <h2>Add a Schedlet</h2>
+ <form name="newSchedlet" method="POST">{% csrf_token %}
+ {{ schedletForm.as_table }}
+ <input type="submit" name="newSchedlet" value="Add Schedlet" />
+ </form>
+ </div>
+ </div>
+{% endblock %}
@@ -0,0 +1,69 @@
+{% extends "base.html" %}
+{% comment %}
+{% extends "jqm/simple.html" %}
+{% endcomment %}
+
+{% block title %}
+ Webmote - Example
+{% endblock %}
+
+{% block page_title %}
+ Webmote - Schedular
+{% endblock %}
+{% block content %}
+ <div data-role="content">
+ <script type="text/javascript" src="{{ STATIC_URL }}Scheduler.js"></script>
+ <h2>Schedules</h2>
+ {% if schedules %}
+ <div class="ui-grid-b" id="schedules_grid_fields">
+ <div class="ui-block-a">
+ <div class="ui-bar ui-bar-a" style="height:30px">Name</div>
+ </div>
+ <div class="ui-block-b">
+ <div class="ui-bar ui-bar-a" style="height:30px">Active</div>
+ </div>
+ <div class="ui-block-c">
+ <div class="ui-bar ui-bar-a" style="height:30px">Delete</div>
+ </div>
+ </div>
+ {% for s in schedules %}
+ <div class="ui-grid-b" id="schedules_grid_row_{{ s.id }}">
+ <div class="ui-block-a">
+ <div class="ui-bar ui-bar-a" style="height:30px">
+ <a href="/scheduler/schedule/{{ s.id }}">{{ s.name }}</a>
+ </div>
+ </div>
+ <div class="ui-block-b">
+ <div class="ui-bar ui-bar-a" style="height:30px">
+ <select class="schedule-active" name="flip-min" id="flip-min-{{ s.id }}" data-role="slider">
+ {% if s.active %}
+ <option value="False">Off</option>
+ <option value="True" selected="selected">On</option>
+ {% else %}
+ <option value="False" selected="selected">Off</option>
+ <option value="True">On</option>
+ {% endif %}
+ </select>
+ </div>
+ </div>
+ <div class="ui-block-c">
+ <div class="ui-bar ui-bar-a" style="height:30px">
+ <form method="post" action="">{% csrf_token %}
+ <input type="submit" name="deleteSchedule" value="Delete" onclick="this.value='{{ s.id }}';this.form.post()"/>
+ </form>
+ </div>
+ </div>
+ </div>
+ {% endfor %}
+ {% else %}
+ <h3>Currently there are no schedules...</h3>
+ {% endif %}
+ <div id="ScheduleForm">
+ <h2>Add a Schedule</h2>
+ <form name="newSchedule" method="POST">{% csrf_token %}
+ {{ scheduleForm.as_table }}
+ <input type="submit" name="newSchedule" value="Add Schedule" />
+ </form>
+ </div>
+ </div>
+{% endblock %}
@@ -0,0 +1,8 @@
+from django.conf.urls.defaults import patterns, include, url
+
+urls = patterns('',
+ url(r'^scheduler/schedule/(?P<id>\d+)/$', 'Scheduler.views.schedule'),
+ url(r'^scheduler/editActive/(?P<id>\d+)/$', 'Scheduler.views.editActive'),
+ url(r'^scheduler/runSchedlet/(?P<id>\d+)/$', 'Scheduler.views.runSchedlet'),
+ url(r'^scheduler/$', 'Scheduler.views.schedules'),
+)
View
@@ -0,0 +1,54 @@
+from django.contrib.auth.decorators import login_required
+from django.shortcuts import render_to_response, redirect
+from django.template import RequestContext
+from django.http import HttpResponse
+from django.utils import simplejson
+from Scheduler.models import *
+
+@login_required
+def schedules(request):
+ context = {}
+ if request.method == 'POST':
+ if 'newSchedule' in request.POST:
+ newSchedule = Schedule_Form(request.POST)
+ if newSchedule.is_valid():
+ newSchedule = newSchedule.save(commit=False)
+ newSchedule.active = True
+ newSchedule.save()
+ if 'deleteSchedule' in request.POST:
+ Schedules.objects.filter(id=request.POST['deleteSchedule'])[0].delete()
+ context['schedules'] = Schedules.objects.all()
+ context['scheduleForm'] = Schedule_Form()
+ return render_to_response('scheduler.html', context, context_instance=RequestContext(request))
+
+@login_required
+def schedule(request, id="0"):
+ context = {}
+ if request.method == 'POST':
+ if 'newSchedlet' in request.POST:
+ newSchedlet = Schedlet_Form(request.POST)
+ if newSchedlet.is_valid():
+ schedlet = newSchedlet.save(commit=False)
+ schedlet.schedule = Schedules.objects.filter(id=id)[0]
+ schedlet.save()
+ if 'deleteSchedlet' in request.POST:
+ Schedlet.objects.filter(id=request.POST['deleteSchedlet'])[0].delete()
+ context['schedule'] = Schedules.objects.select_related().filter(id=id)[0]
+ context['schedletForm'] = Schedlet_Form()
+ return render_to_response('schedule.html', context, context_instance=RequestContext(request))
+
+@login_required
+def editActive(request, id="0"):
+ if request.method == 'POST':
+ activeState = simplejson.loads(request.raw_post_data)
+ schedule = Schedules.objects.filter(id=id)[0]
+ schedule.active = 1 if "True" in activeState else 0
+ schedule.save()
+ return HttpResponse(simplejson.dumps(activeState), mimetype='application/javascript')
+
+def runSchedlet(request, id="0"):
+ if '127.0.0.1' in request.META['REMOTE_ADDR']:
+ Schedlet.objects.filter(id=id)[0].action.runAction()
+ return HttpResponse(simplejson.dumps(''), mimetype='application/javascript')
+
+

0 comments on commit 408dd4f

Please sign in to comment.