Commits

Ashley Felton committed b6f7487

Implement basic views to switch LEDs.

  • Participants
  • Parent commits c7a4f4f

Comments (0)

Files changed (4)

temper/__init__.py

 CACHE_TYPE = 'simple'
 CACHE_DEFAULT_TIMEOUT = 60 * 5  # Cache for 5 minutes by default.
 CACHE_THRESHOLD = 20
+TEMP_LOGS = '/var/log/temps'
+GPIO_PINS = [17, 18, 21]
 
 app = Flask(__name__)
 cache = Cache(app)

temper/templates/leds.html

 <div class="row-fluid">
     <div class="span12">
         <h1>LED Controller</h1>
-        <label for="gpio17-toggle-button">GPIO pin 17:</label>
-        <div id="gpio17-toggle-button" data-gpio="17">
-            <input id="checkbox-gpio17" type="checkbox" value="gpio17" checked="checked">
-        </div>
+        <table class="table" style="width:auto;">
+            {% for g in gpio_config %}
+            <tr>
+                <td>
+                    GPIO pin {{ g.id }}:
+                </td>
+                <td>
+                    <div class="gpio-toggle" id="toggle-button-gpio{{ g.id }}" data-gpio="{{ g.id }}">
+                        <input type="checkbox"{% if g.mode %} checked="checked"{% endif %}>
+                    </div>
+                </td>
+            </tr>
+            {% endfor %}
+        </table>
     </div>
 </div>
 {% endblock %}
 {% block extra_js %}
 <script src="/static/js/jquery.toggle.buttons.js"></script>
 <script type="text/javascript">
-    $('#gpio17-toggle-button').toggleButtons({
+{% for g in gpio_config %}
+    $('#toggle-button-gpio' + {{ g.id }}).toggleButtons({
         onChange: function ($el, status, e) {
-            //console.log($el, status);
+            //console.log(status);
             //console.log($($el).parent().data("gpio"));
-            $.post("/gpio_mode", {gpio: 17, mode: 0},
+            var pinmode;
+            if (status==true) {
+                pinmode = 1
+            }
+            else {
+                pinmode = 0
+            };
+            $.post("/gpio_mode", {gpio: {{ g.id }}, mode: pinmode},
                 function(data) {
                     console.log(data);
                 }
             )
         }
     });
+{% endfor %}
 </script>
 {% endblock %}
 import subprocess
 import time
 from datetime import datetime, date
-
-
-TEMP_LOGS = '/var/log/temps'
+from temper import app
 
 
 def read_onewire_temp():
     Log a temperature reading to a file with a timestamp.
     '''
     # Open a file with today's date in /var/log/temps, write the temp to it.
-    logfile = '/'.join([TEMP_LOGS, 'temps_{0}.log'.format(datetime.strftime(datetime.now(), '%Y%m%d'))])
+    logfile = '/'.join([app.config['TEMP_LOGS'], 'temps_{0}.log'.format(datetime.strftime(datetime.now(), '%Y%m%d'))])
     f = open(logfile, 'a')
     f.write('{0},{1}\n'.format(datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%M:%S'), read_onewire_temp()))
     f.close()
     # log_date should be a valid Python date object.
     if log_date:
         # Test to see if a log file exists for the nominated date.
-        logfile = '/'.join([TEMP_LOGS, 'temps_{0}.log'.format(datetime.strftime(log_date, '%Y%m%d'))])
+        logfile = '/'.join([app.config['TEMP_LOGS'], 'temps_{0}.log'.format(datetime.strftime(log_date, '%Y%m%d'))])
     else:
         # Try using today's date instead.
-        logfile = '/'.join([TEMP_LOGS, 'temps_{0}.log'.format(datetime.strftime(date.today(), '%Y%m%d'))])
+        logfile = '/'.join([app.config['TEMP_LOGS'], 'temps_{0}.log'.format(datetime.strftime(date.today(), '%Y%m%d'))])
     if os.path.exists(logfile):
         # Open the logfile and iterate over it. Return a list of tuples:
         # (datetime_string, float)
     '''
     Read n number of temperature log files (or all files if n is None).
     '''
-    logs = sorted(os.listdir(TEMP_LOGS))
+    logs = sorted(os.listdir(app.config['TEMP_LOGS']))
     temps = []
     if n and len(logs) > n:
         # Only return n logs.
     return sorted(temps)
 
 
+import json
+def gpio_config():
+    print os.path.dirname(os.path.abspath(__file__))
+
+
 if __name__ == "__main__":
     log_temp()
+#!/usr/bin/python
 import json
+import subprocess
 from flask import request, render_template, jsonify
 from temper import app, utils, cache
 from datetime import datetime
 
 @app.route('/leds')
 def led_controller():
-    return render_template('leds.html')
+    # Read in the current GPIO pin config and pass it to the template.
+    # Temporarily just make something up:
+    gpio_config = [{'id': 17, 'mode': 0}, {'id': 18, 'mode': 0}, {'id': 21, 'mode': 0}]
+    return render_template('leds.html', gpio_config=gpio_config)
 
 
 @app.route('/gpio_mode', methods=['POST'])
     # Read the GPIO and mode arguments from the POST request.
     gpio = int(request.form['gpio'])
     mode = int(request.form['mode'])
-    return jsonify({'gpio': gpio, 'mode': mode})
-#if gpio and mode:  # NOTE: mode == 0 evaluates to False. Duh!
-    #    return jsonify({'gpio': gpio, 'mode': mode})
-    #else:
-    #    return '{}'
+    if gpio in [17, 18, 21] and mode in [0, 1]:  # NOTE: mode == 0 evaluates to False. Duh!
+        subprocess.call('gpio -g write {0} {1}'.format(gpio, mode), shell=True)
+        return jsonify({'gpio': gpio, 'mode': mode})
+    else:
+        return '{}'