Skip to content

Commit

Permalink
Merge pull request #1 from naztronaut/saveStatus
Browse files Browse the repository at this point in the history
Save status
  • Loading branch information
naztronaut authored Oct 21, 2019
2 parents ea0cc8f + c6fa373 commit 9f43097
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 10 deletions.
44 changes: 40 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,31 @@ need the library in our venv, so while activated inside your virtual environment
pip install pigpio
```

Now when we run our `pigpio` commands, we won't get an error.
Now when we run our `pigpio` commands, we won't get an error.

### The Stack

#### JavaScript - Script.js - Frontend

The `script.js` has jQuery that calls the Flask app using simple AJAX calls. They assume that the path for the flask app is `/api/lr` -
if you use another path, change this in the JavaScript to avoid getting 404s on your AJAX calls. You can also modify the API endpoints in `rgbw.py`.

The script also utilizes [Pickr](https://github.com/Simonwep/pickr) for the color picker. If updates are needed, feel free to look at that repo and grab the latest.

##### Configurable options

This config object in `script.js` allows you to configure the URL for your Pi. The default is an ip address but if you can access your Pi via a hostname or domain name,
just chnage the url properly to reflect the address:
```javascript
let config = {
url: 'http://{{ip_addr}'
};
```

##### Cache Busting

I use a basic cache busting system in the JavaScript by looking at the current time for the request and appending it to the AJAX request looking for `status.txt` because
I've noticed that browsers love to store this in memory, especially mobile browsers. This ensures that we don't have to worry about caching.

#### Apache and WSGI - Web Server

Expand Down Expand Up @@ -136,26 +160,38 @@ using a color picker.
These parameters are optional. If they are not sent, they will automatically be given a value of 0. For example, the following request:

```
/api/lr?red=255&white=150
/api/lr?red=255&blue=150
```

Will return this:

```json
{
"blue": 0,
"blue": 150,
"green": 0,
"red": "255",
}
```

Sending no values will turn the lights off.

#### `/api/lr/white?white&blue=255`
#### `/api/lr/white?white=255`

The white lights were separated for simplicity. Since the frontend color picker only produces Red, Green, and Blue color codes, the white was left out. For simplicity,
I've separated it so it can be turned on and off with a button instead. I will apply a brightness option later.

#### `/api/lr/getStatus?colors=rgb/white'

The states of the lights are held in two different JSON files. `rgb.json` which houses the Red, Green, and blue Color statuses. And `white.json` which houses the on/off
status of the white light. You can pass in the query parameter `colors` and either `rgb` or `white` as a value to get the different states.

This data is used when the page is refreshed or loaded for the first time, then you know what color your lights are on.

**Note**: `rgbw.py` needs to state the full path to the JSON files. It is currently set to `/var/www/html/rgbw/*.json` - if you need to host this elsewhere, change this.
The user Pi needs to be able to write to these files as well.

I include these files in the repo because if they don't exist, the app throws a 500 Internal Server Error. By default, all values are 0.

### Crontab
When the Pi first boots, `pigpiod` is not automatically started. To ensure that it starts properly, I'd recommend entering this into your crontab. First edit crontab with this:

Expand Down
File renamed without changes
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<head>
<head>
<title>Easy Programming - Control Kitchen Cabinet Lights</title>
<title>Easy Programming - RGBW Lights</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="includes/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/classic.min.css"/>
Expand Down
5 changes: 5 additions & 0 deletions rgb.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"blue": 0,
"green": 0,
"red": 0
}
14 changes: 14 additions & 0 deletions rgbw.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from flask import Flask, request, jsonify
import pigpio
import json


app = Flask(__name__)
Expand All @@ -20,13 +21,26 @@ def led():
# pi.set_PWM_dutycycle(18, white)

# return jsonify({"red": red, "green": green, "blue": blue, "white": white})
with open('/var/www/html/rgbw/rgb.json', 'w') as f:
json.dump({"red": red, "green": green, "blue": blue}, f)
return jsonify({"red": red, "green": green, "blue": blue})


# Separated white button for now so it can be controlled separately
# Reading/writing to JSON file: https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
@app.route('/white', methods=['GET'])
def white():
white = int(request.args.get('white')) if (request.args.get('white')) else 0

pi.set_PWM_dutycycle(18, white)
with open('/var/www/html/rgbw/white.json', 'w') as f:
json.dump({"white": white}, f)
return jsonify({"white": white})


@app.route('/getStatus', methods=['GET'])
def get_status():
colors = str(request.args.get('colors'))

with open('/var/www/html/rgbw/' + colors + '.json', 'r') as f:
return json.load(f)
31 changes: 26 additions & 5 deletions script.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@ let config = {
let whiteStatus = 0;

$(document).ready(function() {
btnStatus();
// Cache buster added because caching was a big problem on mobile
let cacheBuster = new Date().getTime();

// btnStatus();
getLEDStatus('rgb');
getLEDStatus('white');

const pickr = Pickr.create({
el: '.color-picker',
theme: 'classic', // or 'monolith', or 'nano'
Expand All @@ -19,7 +23,7 @@ $(document).ready(function() {
'rgba(255, 0, 0, 1)',
'rgba(0, 255, 0, 1)',
'rgba(0, 0, 255, 1)',
// 'rgba(255, 250.0, 0, 1)', // yellow broken
'rgba(255, 255, 0, 1)', // yellow broken
'rgba(255, 0, 255, 1)',
'rgba(0, 255, 255, 1)',
'rgba(255, 255, 255, 1)',
Expand Down Expand Up @@ -47,8 +51,9 @@ $(document).ready(function() {
}
});

pickr.on('swatchselect', e => {
pickr.off().on('swatchselect', e => {
sendData(e);
pickr.setColor(e.toRGBA().toString(0));
});
pickr.on('save', e => {
sendData(e);
Expand All @@ -60,10 +65,9 @@ $(document).ready(function() {
let green = Math.floor(obj[1]);
let blue = Math.floor(obj[2]);
let queryBuilder = `red=${red}&green=${green}&blue=${blue}`;
console.log(queryBuilder);

$.ajax({
url: `${config.url}/api/lr?${queryBuilder}&${cacheBuster}`,
url: `${config.url}/api/lr/?${queryBuilder}&${cacheBuster}`,
method: 'GET',
dataType: 'json',
cache: false,
Expand Down Expand Up @@ -105,4 +109,21 @@ $(document).ready(function() {
}
}

// Get RGB Status so Color Picker in UI is set to that color on page load
function getLEDStatus(color) {
$.ajax({
url: `${config.url}/api/lr/getStatus?colors=${color}&${cacheBuster}`,
method: 'GET',
success: function(result) {
if(color == 'rgb') {
let colors = `rgb(${result.red}, ${result.green}, ${result.blue})`;
pickr.setColor(colors);
} else {
whiteStatus = result.white;
btnStatus();
}
},
});
}

});
3 changes: 3 additions & 0 deletions white.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"white": 0
}

0 comments on commit 9f43097

Please sign in to comment.