Update LEDborg node to use RPi.GPIO

Fix to Close #93
This commit is contained in:
dceejay 2015-01-30 08:43:55 +00:00
parent 9170cc6282
commit 1d90f7006f
5 changed files with 314 additions and 26 deletions

View File

@ -1,5 +1,5 @@
<!--
Copyright 2013 IBM Corp.
Copyright 2013,2015 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -25,15 +25,15 @@
<script type="text/x-red" data-help-name="ledborg">
<p>PiBorg LedBorg LED output node. Expects a <b>msg.payload</b> with a three digit rgb triple, from <b>000</b> to <b>222</b>.</p>
<p>See <i><a href="http://www.piborg.com/ledborg/install" target="_new">the PiBorg site</a></i> for more information.</p>
<p>You can also use a <b>msg.payload</b> in the standard hex format "#rrggbb". The clip levels are :</p>
<p><pre>0x00 - 0x57 = off<br/>0x58 - 0xA7 = 50%<br/>0xA8 - 0xFF = fully on</pre></p>
<p>You can also use a <b>msg.payload</b> in the standard hex format "#rrggbb".</p>
<p>You can also use the @cheerlight colour names - red, amber, green, blue, cyan, magenta, yellow, orange, pink, purple,
white, warmwhite, black</p>
<p>You may also supply a comma seperated rrr,ggg,bbb where the value can be between 0 and 255.</p>
</script>
<script type="text/javascript">
RED.nodes.registerType('ledborg',{
category: 'Rapsberry Pi',
category: 'Raspberry Pi',
color:"GoldenRod",
defaults: {
name: {value:""}

View File

@ -1,5 +1,5 @@
/**
* Copyright 2013 IBM Corp.
* Copyright 2013,2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,33 +16,63 @@
module.exports = function(RED) {
"use strict";
var util = require('util');
var util = require("util");
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var fs = require('fs');
// check if /dev/ledborg exists - if not then don't even show the node.
if (!fs.existsSync("/dev/ledborg")) {
throw "Info : PiBorg hardware : LedBorg not found";
var gpioCommand = __dirname+'/nrgpio';
if (!fs.existsSync("/dev/ttyAMA0")) { // unlikely if not on a Pi
//util.log("Info : Ignoring Raspberry Pibrella specific node.");
throw "Info : Ignoring Raspberry Pibrella specific node.";
}
if (!fs.existsSync("/usr/share/doc/python-rpi.gpio")) {
util.log("[rpi-pibrella] Info : Can't find RPi.GPIO python library.");
throw "Warning : Can't find RPi.GPIO python library.";
}
if ( !(1 & parseInt ((fs.statSync(gpioCommand).mode & parseInt ("777", 8)).toString (8)[0]) )) {
util.log("[rpi-pibrella] Error : "+gpioCommand+" needs to be executable.");
throw "Error : nrgpio must to be executable.";
}
// GPIO pins 11 (R), 13 (G), 15 (B).
function LedBorgNode(n) {
RED.nodes.createNode(this,n);
var p1 = /^[0-2][0-2][0-2]$/
var p2 = /^\#[A-Fa-f0-9]{6}$/
var node = this;
this.on("input", function(msg) {
RED.nodes.createNode(this,n);
this.pin = n.pin;
this.set = n.set || false;
this.level = n.level || 0;
this.out = n.out || "out";
var node = this;
var p1 = /^[0-2][0-2][0-2]$/
var p2 = /^\#[A-Fa-f0-9]{6}$/
var p3 = /^\d+,\d+,\d+$/
function inputlistener(msg) {
var rgb = "000";
if (p1.test(msg.payload)) {
fs.writeFile('/dev/ledborg', msg.payload, function (err) {
if (err) { node.warn(msg.payload+" : No LedBorg found"); }
});
rgb = msg.payload;
rgb = Number(rgb[0])*50+","+Number(rgb[1])*50+","+Number(rgb[2])*50;
}
else if (p2.test(msg.payload)) {
var r = Math.floor(parseInt(msg.payload.slice(1,3),16)/88).toString();
var g = Math.floor(parseInt(msg.payload.slice(3,5),16)/88).toString();
var b = Math.floor(parseInt(msg.payload.slice(5),16)/88).toString();
fs.writeFile('/dev/ledborg', r+g+b, function (err) {
if (err) { node.warn(r+g+b+" : No LedBorg found"); }
});
var r = Math.floor(parseInt(msg.payload.slice(1,3),16)*100/256).toString();
var g = Math.floor(parseInt(msg.payload.slice(3,5),16)*100/256).toString();
var b = Math.floor(parseInt(msg.payload.slice(5),16)*100/256).toString();
rgb = r+","+g+","+b;
}
else if (p3.test(msg.payload)) {
var c = msg.payload.split(",");
var r = Math.floor(parseInt(c[0])*100/256).toString();
var g = Math.floor(parseInt(c[1])*100/256).toString();
var b = Math.floor(parseInt(c[2])*100/256).toString();
rgb = r+","+g+","+b;
}
else {
// you can add fancy colours by name here if you want...
@ -50,16 +80,59 @@ module.exports = function(RED) {
var colors = {"red":"200","green":"020","blue":"002","cyan":"022","white":"222","pink":"201",
"warmwhite":"221","purple":"101","magenta":"202","yellow":"220","amber":"220","orange":"210","black":"000"}
if (msg.payload.toLowerCase() in colors) {
var c = colors[msg.payload.toLowerCase()];
fs.writeFile('/dev/ledborg', c, function (err) {
if (err) { node.warn(msg.payload+" : No LedBorg found"); }
});
rgb = colors[msg.payload.toLowerCase()];
rgb = Number(rgb[0])*50+","+Number(rgb[1])*50+","+Number(rgb[2])*50;
}
else {
node.warn("Invalid LedBorg colour code");
}
}
if (RED.settings.verbose) { node.log("out: "+msg.payload); }
if (node.child !== null) { node.child.stdin.write(rgb+"\n"); }
else { node.warn("Command not running"); }
node.status({fill:"green",shape:"dot",text:msg.payload});
}
node.child = spawn(gpioCommand, ["borg","11"]);
node.running = true;
node.status({fill:"green",shape:"dot",text:"OK"});
node.on("input", inputlistener);
node.child.stdout.on('data', function (data) {
if (RED.settings.verbose) { node.log("out: "+data+" :"); }
});
node.child.stderr.on('data', function (data) {
if (RED.settings.verbose) { node.log("err: "+data+" :"); }
});
node.child.on('close', function (code) {
node.child = null;
node.running = false;
node.status({fill:"red",shape:"circle",text:""});
if (RED.settings.verbose) { node.log("closed"); }
if (node.done) { node.done(); }
});
node.child.on('error', function (err) {
if (err.errno === "ENOENT") { node.warn('Command not found'); }
else if (err.errno === "EACCES") { node.warn('Command not executable'); }
else { node.log('error: ' + err); }
});
node.on("close", function(done) {
node.status({fill:"red",shape:"circle",text:""});
if (node.child != null) {
node.done = done;
node.child.stdin.write(" close 11");
node.child.kill('SIGKILL');
}
else { done(); }
});
}
RED.nodes.registerType("ledborg",LedBorgNode);
}

16
hardware/LEDborg/nrgpio Executable file
View File

@ -0,0 +1,16 @@
#
# Copyright 2014 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BASEDIR=$(dirname $0)
sudo python -u $BASEDIR/nrgpio.py $@

199
hardware/LEDborg/nrgpio.py Executable file
View File

@ -0,0 +1,199 @@
#!/usr/bin/python
#
# Copyright 2014 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Import library functions we need
import RPi.GPIO as GPIO
import sys
bounce = 20 # bounce time in mS to apply
if len(sys.argv) > 1:
cmd = sys.argv[1].lower()
pin = int(sys.argv[2])
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
if cmd == "pwm":
#print "Initialised pin "+str(pin)+" to PWM"
GPIO.setup(pin,GPIO.OUT)
p = GPIO.PWM(pin, 100)
p.start(0)
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup(pin)
sys.exit(0)
p.ChangeDutyCycle(float(data))
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup(pin)
sys.exit(0)
except Exception as ex:
print "bad data: "+data
elif cmd == "buzz":
#print "Initialised pin "+str(pin)+" to Buzz"
GPIO.setup(pin,GPIO.OUT)
p = GPIO.PWM(pin, 100)
p.stop()
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup(pin)
sys.exit(0)
elif float(data) == 0:
p.stop()
else:
p.start(50)
p.ChangeFrequency(float(data))
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup(pin)
sys.exit(0)
except Exception as ex:
print "bad data: "+data
elif cmd == "out":
#print "Initialised pin "+str(pin)+" to OUT"
GPIO.setup(pin,GPIO.OUT)
if len(sys.argv) == 4:
GPIO.output(pin,int(sys.argv[3]))
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup(pin)
sys.exit(0)
data = int(data)
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup(pin)
sys.exit(0)
except:
data = 0
if data != 0:
data = 1
GPIO.output(pin,data)
elif cmd == "in":
#print "Initialised pin "+str(pin)+" to IN"
def handle_callback(chan):
print GPIO.input(chan)
if len(sys.argv) == 4:
if sys.argv[3].lower() == "up":
GPIO.setup(pin,GPIO.IN,GPIO.PUD_UP)
elif sys.argv[3].lower() == "down":
GPIO.setup(pin,GPIO.IN,GPIO.PUD_DOWN)
else:
GPIO.setup(pin,GPIO.IN)
else:
GPIO.setup(pin,GPIO.IN)
print GPIO.input(pin)
GPIO.add_event_detect(pin, GPIO.BOTH, callback=handle_callback, bouncetime=bounce)
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup(pin)
sys.exit(0)
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup(pin)
sys.exit(0)
elif cmd == "byte":
#print "Initialised BYTE mode - "+str(pin)+
list = [7,11,13,12,15,16,18,22]
GPIO.setup(list,GPIO.OUT)
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup()
sys.exit(0)
data = int(data)
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup()
sys.exit(0)
except:
data = 0
for bit in range(8):
if pin == 1:
mask = 1 << (7 - bit)
else:
mask = 1 << bit
GPIO.output(list[bit], data & mask)
elif cmd == "borg":
#print "Initialised BORG mode - "+str(pin)+
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
r = GPIO.PWM(11, 100)
g = GPIO.PWM(13, 100)
b = GPIO.PWM(15, 100)
r.start(0)
g.start(0)
b.start(0)
while True:
try:
data = raw_input()
if data == "close":
GPIO.cleanup()
sys.exit(0)
c = data.split(",")
r.ChangeDutyCycle(float(c[0]))
g.ChangeDutyCycle(float(c[1]))
b.ChangeDutyCycle(float(c[2]))
except EOFError: # hopefully always caused by us sigint'ing the program
GPIO.cleanup()
sys.exit(0)
except:
data = 0
elif cmd == "rev":
print GPIO.RPI_REVISION
elif cmd == "ver":
print GPIO.VERSION
elif cmd == "mouse": # catch mice button events
file = open( "/dev/input/mice", "rb" )
oldbutt = 0
def getMouseEvent():
global oldbutt
global pin
buf = file.read(3)
pin = pin & 0x07
button = ord( buf[0] ) & pin # mask out just the required button(s)
if button != oldbutt: # only send if changed
oldbutt = button
print button
while True:
try:
getMouseEvent()
except:
file.close()
sys.exit(0)
else:
print "Bad parameters - {in|out|pwm} {pin} {value|up|down}"

View File

@ -1,6 +1,6 @@
{
"name" : "node-red-node-ledborg",
"version" : "0.0.2",
"version" : "0.0.3",
"description" : "A Node-RED node to control a PiBorg LedBorg board for a Raspberry Pi.",
"dependencies" : {
},