2

I want to control my Arduino from a web interface, so I've created the client side in ReactJS and the server side in ExpressJS (Johnny-Five included).

I just want to update the interval of a blinking led in real time, based on the user input. Here is my server code:

const express = require('express');
const bodyParser = require('body-parser');
const five = require('johnny-five');

const app = express();
const board = new five.Board();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

board.on('ready', function () {
  app.post("/api/led-flash", function (req, res) {
    let led = new five.Led(13);
    led.blink(req.body.interval);
  });
});

app.listen("5000", () => {
  console.log("App listening on port 5000");
});

The code seems to work only for a few requests at the beginning. What is the correct way of doing this?

Andrei Rosu
  • 1,169
  • 2
  • 10
  • 26

1 Answers1

1

You'll want to start the server after the board is ready. So something like the following:

const express = require('express');
const bodyParser = require('body-parser');
const five = require('johnny-five');

const app = express();
const board = new five.Board();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/led-flash", function (req, res) {
    // perform some initial cleanup work if needed like resetting LEDs.
    // ...


    let led = new five.Led(13);
    led.blink(req.body.interval);

    res.json({ message: 'success!'})

    // Some additional work after success
    // ...
});

function startServer() {
    app.listen("5000", () => {
        console.log("App listening on port 5000");
    });
}

board.on('ready', startServer);

The above is untested, but post a solution if you find one!

Cisco
  • 20,972
  • 5
  • 38
  • 60
  • Good point! Though, it seems that the previous blinking values are not ignored. It just looks like the new interval values are added on the "stack". – Andrei Rosu May 07 '18 at 18:26
  • You'll probably want to do some "cleanup" _before_ and _after_ execution. – Cisco May 07 '18 at 18:53
  • 1
    The problem was that my requests never ended, by using res.end() or res.json() etc. Thank you very much for your help. – Andrei Rosu May 07 '18 at 19:04