0

I would like to seek help on my REST API. I have finished constructed my basic REST API for my Raspberry PI and able to work now, thanks to you guys. Now I would like to display mySQL database records in a table with loop so it can always display new records but it failed and prompt an error which I have screenshot it down and uploaded.

This is my led_rest_api.js:

var express = require('express');
var bodyParser = require('body-parser');
var gpio = require('pi-gpio');
var app = express();
var dateFormat = require('dateformat');
var mysql = require('mysql');
var http = require('http');

var now = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');

var conn = mysql.createConnection({
   host: 'localhost',
   user: 'user',
   password: 'password',
   database: 'sensor'
});

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

var display = conn.query('SELECT * FROM sensorInfo');

var table = ('<tr><th>Sensor ID</th><th>Sensor</th><th>On Log Time</th><th>Off Log Time</th></tr>');

foreach (display as row) {
        table. =
       "<tr><td>". $row['sensorId'] . "</td>". 
            "<td>". $row['sensors'] . "</td>".
       "<td>". $row['onLogTime'] . "</td>".
            "<td>". $row['offLogTime'] ."</td></tr>";
    });

var server = http.createServer(function(request, response) {
   response.writeHead(200, {"Content-Type": "text/html"});
   response.write("<!DOCTYPE html>");
   response.write("<html>");
   response.write("<head>");
   response.write("<title><H1 align="center">Sensor REST API</H></title>");
   response.write("</head>");
   response.write("<body>");
   response.write("<table border=1>table</table>");
   response.write("</body>");
   response.write("</html>");
   response.end();
});

app.put('/: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() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(1, "Red LED", current_timestamp(), NULL)', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(7);
        });
        return gpio;
    } if (pin === 11){
        //Set pin 11 high (1)
            gpio.write(11, 1, function() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(2, "Blue LED", current_timestamp(), NULL)', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(11);
        });
        return gpio;
    } if (pin === 16){
        //Set pin 16 high (1)
            gpio.write(16, 1, function() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(3, "Green LED", current_timestamp(), NULL)', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(16);  
        });
        return gpio;
    }
  }
});

app.put('/: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() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(1, "Red LED", NULL, current_timestamp())', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(7);
        });
        return gpio;
    } if (pin === 11){
        //Set pin 11 low (0)
            gpio.write(11, 0, function() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(2, "Blue LED", NULL, current_timestamp())', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(11);
        });
        return gpio;
    } if (pin === 16){
        //Set pin 16 low (0)
            gpio.write(16, 0, function() 
        {
                conn.query('INSERT INTO sensor(sensorId, sensors, onLogTime, offLogTime) VALUES(3, "Green LED", NULL, current_timestamp())', function(err){
            if (err) throw err;
                else res.send('success');
         });
                res.send(now);
                gpio.close(16);
        });
        return gpio;
    }
  }
});

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

This is the error screenshot:

enter image description here

  • You asked a similar question yesterday, and got no comment. If others, like me, have no idea what a "LED REST API" is, how you have you have connected your LED, or even what language the code is written in. you are unlikely to get much help. – Milliways Jul 25 '14 at 4:50
  • I connect my LED using gpio to Raspberry PI. I wrote the program language is node.js which also a java script. – user3127380 Jul 25 '14 at 4:57
1

Your express server is listening on port 3030 and not 3000 so the URL would be http://localhost:3030/7/1.

When testing your API you should not "key" the URL into a browser as this causes a GET request. Use something like curl to make a POST request instead.

Also consider changing your API to use PUT since multiple requests for an on or off switch has the same effect as a single request, better matching the semantics of the HTTP verb PUT (which is idempotent).

  • Thanks Hans Malherbe, I have changed already. Now I got an error now which I'm confused now, it asked me to remove if statement all that and I'm lost now. I have updated my thread and coding plus error screenshots. – user3127380 Jul 25 '14 at 6:30
1

You are not closing your gpio.write call

if (pin === 7){
    //Set pin 7 low (0)
    gpio.write(7, 0, function() 
    { 
            gpio.close(7);
        return gpio;
    } );    // <----
} if (pin === 11){
  • Wow, thanks alot, rob. It works like magic. But now, I want to display current date and time but it gave me weird output. – user3127380 Jul 27 '14 at 13:58
  • No problem. Open another specific question, probably not a raspberrypi.statckoverflow one. – rob Jul 29 '14 at 7:31
  • Thanks rob, I have sort of settle it now is mySQL INSERT method got error and I have change my question already. – user3127380 Jul 29 '14 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.