LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-22-2014, 08:16 PM   #1
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Rep: Reputation: Disabled
How to build a simple LED RESTful service in Raspberry PI?


Hi guys, I would like to seek advise or help on how to build a simple LED RESTful service in Raspberry PI. I need to be able to get my LED to light up or off whenever I type localhost:3000/GET/1/1 or something. New to it and hope you guys could help me out with it as soon as possible, thanks in advance, guys.
 
Old 07-23-2014, 01:48 AM   #2
a4z
Senior Member
 
Registered: Feb 2009
Posts: 1,727

Rep: Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742
http://lmgtfy.com/?q=raspberry+pi+rest+server
 
Old 07-23-2014, 09:52 PM   #3
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by a4z View Post
Thanks for link, a4z.

I would like to seek help on my LED REST API. My issue is my other 2 LED never light up when I execute GET and PUT method for it. I have 3 LED - Red, Blue and Green but whenever I node my LED REST API and execute GET and PUT method, only my Red LED in pin 7 light up. The strange thing is there is no error for all my pins and I'm lost now.

Hardware I'm using is Raspberry PI.

I have done npm install and npm install pi.gpio.

This is my led_rest_api.js:
Code:
var express = require('express');
var bodyParser = require('body-parser');
var gpio = require('pi-gpio');

var app = express();
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);

app.get('/:pin', function(req, res){
  var pin = req.params.pin;

  gpio.open(pin, 'input', function(err) {
    gpio.read(pin, function(err, value) {
      res.send(200, {value: value});
      gpio.close(pin);
    });
  });
});

app.put('/:pin', function(req, res) {
  var pin = req.params.pin;
  var value = req.body.value;

  gpio.open(pin, 'output', function(err) {
    gpio.write(pin, value, function(err) {
      res.send(200);
      gpio.close(pin);
    });
  });
});

var server = app.listen(app.get('port'), function() {
  console.log('Listening on port %d', server.address().port);
});
Hope you guys could help me out with it as soon as possible, thanks in advance, guys
 
Old 07-24-2014, 01:07 AM   #4
a4z
Senior Member
 
Registered: Feb 2009
Posts: 1,727

Rep: Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742
https://github.com/PhiKapJames/PiLedRestService
it's python. but possible help you
there is also a vid
http://www.youtube.com/watch?v=8bezhluzufc

use curl to test rest apis

did you work through this
http://thefloppydisk.wordpress.com/2...in-javascript/

and all the other tutorials on this side?
 
Old 07-24-2014, 01:22 AM   #5
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by a4z View Post
https://github.com/PhiKapJames/PiLedRestService
it's python. but possible help you
there is also a vid
http://www.youtube.com/watch?v=8bezhluzufc

use curl to test rest apis

did you work through this
http://thefloppydisk.wordpress.com/2...in-javascript/

and all the other tutorials on this side?
https://github.com/PhiKapJames/PiLedRestService[/URL] & http://www.youtube.com/watch?v=8bezhluzufc are not what I'm looking for.
I have tried out http://thefloppydisk.wordpress.com/2...in-javascript/ but is an outdated API and it is not meant for controlling GPIO but just hard code the value whether is it switch on or off, a4z
 
Old 07-24-2014, 01:38 AM   #6
a4z
Senior Member
 
Registered: Feb 2009
Posts: 1,727

Rep: Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742Reputation: 742
Quote:
Originally Posted by aoiregion View Post
https://github.com/PhiKapJames/PiLedRestService[/URL] & http://www.youtube.com/watch?v=8bezhluzufc are not what I'm looking for.
I have tried out http://thefloppydisk.wordpress.com/2...in-javascript/ but is an outdated API and it is not meant for controlling GPIO but just hard code the value whether is it switch on or off, a4z
you missed the 'other tutorials on the page' I mentioned
http://thefloppydisk.wordpress.com/2...in-javascript/
so this is not about GPIO?
and this is outdated?
https://github.com/rakeshpai/pi-gpio
 
Old 07-24-2014, 01:49 AM   #7
273
LQ Addict
 
Registered: Dec 2011
Location: UK
Distribution: Debian Sid AMD64, Raspbian Wheezy, various VMs
Posts: 7,680

Rep: Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373
What is the format of the number sent to res.send()? Jut guessing looking at the code I would expect that sending "200" is lighting the red LED to level 2 (whatever that is) and to set the level for green to 2 you would send "020" etc.. Have you tried this?
 
Old 07-24-2014, 03:18 AM   #8
shell.albert
LQ Newbie
 
Registered: Jul 2014
Distribution: OpenSuse
Posts: 5

Rep: Reputation: Disabled
Are you using Raspberry Pi? I don't touch it.Two years before,I'm a electronic engineer,do work with schematic design,pcb layout,write device driver codes & applications.But now,I employ a new company for coding.Coding everything,I hate this life style.
I hope someday I can play and research Raspberry Pi as usual.
 
Old 07-24-2014, 04:34 AM   #9
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by 273 View Post
What is the format of the number sent to res.send()? Jut guessing looking at the code I would expect that sending "200" is lighting the red LED to level 2 (whatever that is) and to set the level for green to 2 you would send "020" etc.. Have you tried this?
res.send(200) is when a Number is given without any of the previously mentioned bodies, then a response body string is assigned for you. For example 200 will respond will the text "OK", and 404 "Not Found" and so on.

Quote:
Originally Posted by shell.albert View Post
Are you using Raspberry Pi? I don't touch it.Two years before,I'm a electronic engineer,do work with schematic design,pcb layout,write device driver codes & applications.But now,I employ a new company for coding.Coding everything,I hate this life style.
I hope someday I can play and research Raspberry Pi as usual.
Yes, I'm using Raspberry PI.
Thanks anyway, shell.albert xD
Hope you can hands on to Raspberry PI as soon as possible cause it's fun and also help me out(Kidding xD) xD
 
Old 07-24-2014, 04:40 AM   #10
273
LQ Addict
 
Registered: Dec 2011
Location: UK
Distribution: Debian Sid AMD64, Raspbian Wheezy, various VMs
Posts: 7,680

Rep: Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373
So where is the code to light the LEDs?
 
Old 07-24-2014, 04:45 AM   #11
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by 273 View Post
So where is the code to light the LEDs?
Is in my node_modules, 273 xD

This is the pi-gpio.js:
Code:
"use strict";
var fs = require("fs"),
	path = require("path"),
	exec = require("child_process").exec;

var gpioAdmin = "gpio-admin",
	sysFsPath = "/sys/devices/virtual/gpio";

var rev = fs.readFileSync("/proc/cpuinfo").toString().split("\n").filter(function(line) {
	return line.indexOf("Revision") == 0;
})[0].split(":")[1].trim();

rev = parseInt(rev, 16) < 3 ? 1 : 2; // http://elinux.org/RPi_HardwareHistory#Board_Revision_History

var pinMapping = {
	"3": 0,
	"5": 1,
	"7": 4,
	"8": 14,
	"10": 15,
	"11": 17,
	"12": 18,
	"13": 21,
	"15": 22,
	"16": 23,
	"18": 24,
	"19": 10,
	"21": 9,
	"22": 25,
	"23": 11,
	"24": 8,
	"26": 7,

	// Model B+ pins
	"29": 5,
	"31": 6,
	"32": 12,
	"33": 13,
	"35": 19,
	"36": 16,
	"37": 26,
	"38": 20,
	"40": 21
};

if(rev == 2) {
	pinMapping["3"] = 2;
	pinMapping["5"] = 3;
	pinMapping["13"] = 27;
}

function isNumber(number) {
	return !isNaN(parseInt(number, 10));
}

function noop(){}

function handleExecResponse(method, pinNumber, callback) {
	return function(err, stdout, stderr) {
		if(err) {
			console.error("Error when trying to", method, "pin", pinNumber);
			console.error(stderr);
			callback(err);
		} else {
			callback();
		}
	}
}

function sanitizePinNumber(pinNumber) {
	if(!isNumber(pinNumber) || !isNumber(pinMapping[pinNumber])) {
		throw new Error("Pin number isn't valid");
	}

	return parseInt(pinNumber, 10);
}

function sanitizeDirection(direction) {
	direction = (direction || "").toLowerCase().trim();
	if(direction === "in" || direction === "input") {
		return "in";
	} else if(direction === "out" || direction === "output" || !direction) {
		return "out";
	} else {
		throw new Error("Direction must be 'input' or 'output'");
	}
}

function sanitizeOptions(options) {
	var sanitized = {};

	options.split(" ").forEach(function(token) {
		if(token == "in" || token == "input") {
			sanitized.direction = "in";
		}

		if(token == "pullup" || token == "up") {
			sanitized.pull = "pullup";
		}

		if(token == "pulldown" || token == "down") {
			sanitized.pull = "pulldown";
		}
	});

	if(!sanitized.direction) {
		sanitized.direction = "out";
	}

	if(!sanitized.pull) {
		sanitized.pull = "";
	}

	return sanitized;
}

var gpio = {
	rev: rev,
	
	open: function(pinNumber, options, callback) {
		pinNumber = sanitizePinNumber(pinNumber);

		if(!callback && typeof options === "function") {
			callback = options;
			options = "out";
		}

		options = sanitizeOptions(options);

		exec(gpioAdmin + " export " + pinMapping[pinNumber] + " " + options.pull, handleExecResponse("open", pinNumber, function(err) {
			if(err) return (callback || noop)(err);

			gpio.setDirection(pinNumber, options.direction, callback);
		}));
	},

	setDirection: function(pinNumber, direction, callback) {
		pinNumber = sanitizePinNumber(pinNumber);
		direction = sanitizeDirection(direction);

		fs.writeFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/direction", direction, (callback || noop));
	},

	getDirection: function(pinNumber, callback) {
		pinNumber = sanitizePinNumber(pinNumber);
		callback = callback || noop;

		fs.readFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/direction", "utf8", function(err, direction) {
			if(err) return callback(err);
			callback(null, sanitizeDirection(direction.trim()));
		});
	},

	close: function(pinNumber, callback) {
		pinNumber = sanitizePinNumber(pinNumber);

		exec(gpioAdmin + " unexport " + pinMapping[pinNumber], handleExecResponse("close", pinNumber, callback || noop));
	},

	read: function(pinNumber, callback) {
		pinNumber = sanitizePinNumber(pinNumber);

		fs.readFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/value", function(err, data) {
			if(err) return (callback || noop)(err);

			(callback || noop)(null, parseInt(data, 10));
		});
	},

	write: function(pinNumber, value, callback) {
		pinNumber = sanitizePinNumber(pinNumber);

		value = !!value?"1":"0";

		fs.writeFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/value", value, "utf8", callback);
	}
};

gpio.export = gpio.open;
gpio.unexport = gpio.close;

module.exports = gpio;
 
Old 07-25-2014, 01:06 AM   #12
273
LQ Addict
 
Registered: Dec 2011
Location: UK
Distribution: Debian Sid AMD64, Raspbian Wheezy, various VMs
Posts: 7,680

Rep: Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373Reputation: 2373
Unfortunately since I don't have the same setup that doesn't make much sense to me -- the pin map seems an on obfuscation but I'm srue it makes sense in context.
What I was getting at is that led_rest_api.js obviously works as it is calling pi-gpio.js adn an LED is lighting. So, can you for example modify pi-gpio.js so that another LED lights every time? Or could you hard-code led_rest_api.js to output whatever pi-gpio.js is expecting for a colour other than red? If I could make sense of the code I could be of more help but on the surface this looks to me like you may just have made a small syntax error.
 
Old 07-25-2014, 01:17 AM   #13
aoiregion
LQ Newbie
 
Registered: Jul 2014
Posts: 11

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by 273 View Post
Unfortunately since I don't have the same setup that doesn't make much sense to me -- the pin map seems an on obfuscation but I'm srue it makes sense in context.
What I was getting at is that led_rest_api.js obviously works as it is calling pi-gpio.js adn an LED is lighting. So, can you for example modify pi-gpio.js so that another LED lights every time? Or could you hard-code led_rest_api.js to output whatever pi-gpio.js is expecting for a colour other than red? If I could make sense of the code I could be of more help but on the surface this looks to me like you may just have made a small syntax error.
I have re-edited my led_rest_api.js and they should actually works but quite a few error.
Needed help for it.

This is my re-edited led_rest_api.js:
Code:
var express = require('express');
var bodyParser = require('body-parser');
var gpio = require('pi-gpio');
var app = express();

app.use(bodyParser.json());
app.set('port', process.env.PORT || 3030);

app.post('/:pin/1', function(req, res)
{
  var pin = req.params.pin;

  gpio.open(pin, 'output', function(err){
	if (pin === 7){
		//Set pin 7 high (1)
    		gpio.write(7, 1, function() 
		{ 
        		gpio.close(7);
  		}
		return gpio;
	} if (pin === 11){
		//Set pin 11 high (1)
    		gpio.write(11, 1, function() 
		{ 
        		gpio.close(11);
  		}
		return gpio;
	} if (pin === 16){
		//Set pin 16 high (1)
    		gpio.write(16, 1, function() 
		{ 
        		gpio.close(16);
  		}
		return gpio;
	}
  }
});

app.post('/:pin/0', function(req, res)
{
  var pin = req.params.pin;

  gpio.open(pin, 'output', function(err){
	if (pin === 7){
		//Set pin 7 low (0)
    		gpio.write(7, 0, function() 
		{ 
        		gpio.close(7);
  		}
		return gpio;
	} if (pin === 11){
		//Set pin 11 low (0)
    		gpio.write(11, 0, function() 
		{ 
        		gpio.close(11);
  		}
		return gpio;
	} if (pin === 16){
		//Set pin 16 low (0)
    		gpio.write(16, 0, function() 
		{ 
        		gpio.close(16);
  		}
		return gpio;
	}
  }
});


var server = app.listen(app.get('port'), function() {
  console.log('Listening on port %d', server.address().port);
 
  


Reply

Tags
gpio, raspberry pi



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: LED candle with Raspberry Pi LXer Syndicated Linux News 0 06-13-2014 11:21 AM
LXer: Take Raspberry Pi, build your own private cloud LXer Syndicated Linux News 0 06-10-2014 12:14 AM
LXer: Build your own supercomputer out of Raspberry Pi boards LXer Syndicated Linux News 0 05-23-2013 11:51 PM
Raspberry pi red LED on solidly with flashing green led. darkstarbyte Linux - Hardware 19 01-05-2013 06:54 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:09 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration