Need help on my REST API

92 views
Skip to first unread message

Chia Yee Han

unread,
Jul 25, 2014, 12:58:27 AM7/25/14
to nod...@googlegroups.com

Hi guys, I would like to seek help on my LED REST API. I have finished constructed my basic REST API for my Raspberry PI. What I'm trying to do now is allow my LED to light up whenever I key localhost:3000/7/1 and key localhost:3000/7/0 to switch off. But my problem now is my REST API can't works and hope you guys could help me out with it as soon as possible, thanks in advance, guys.

This is my led_rest_api.js:

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);



Maximilian Brosnahan

unread,
Jul 26, 2014, 3:41:50 AM7/26/14
to nod...@googlegroups.com
Currently as it stands the request is not being closed after the state of the gpio pin has been changed. You need to call something like res.send('gpio pin: 7 is now on') after it is closed

You can also simplify what you have down to something like

var allowedPins = ['7','11', '16'];
app.post('/:pin/:state', function(req, res) {
  var pin = req.params.pin;
  var state = req.params.state;

  if (allowedPins.indexOf(pin) != -1 && state === '0' || state == '1'){
    gpio.open(pin, 'output', function(err){
      if (err) {
        res.send(err);
        return;
      }
      gpio.write(pin, 1, function() {
          gpio.close(pin);
          res.send('success')
      });
    });
  } else {
    res.send('error')
  }
});
Reply all
Reply to author
Forward
0 new messages