In the previous article, we discussed how to get up and running with Johnny Five and the ESP8266 micro-controller. If you are not sure how to get set up I recommend you read that article first.
Previously we created a simple script that allowed us to control the onboard LED with our keyboard. This required us to install the package and listen in . This is not a bad approach but there is a better one.
Johnny Five comes packaged with a REPL. A REPL (read-eval-print-loop) is an interactive language shell giving a simple interactive interface to the Johnny Five API. We can control our robots with the REPL but there is some set up first.
Setting up the REPL
We need to make the REPL aware of our hardware by injecting the of the hardware into our script. We are using the script from before but with the keyboard code stripped out:
1const { EtherPortClient } = require("etherport-client")2const { Board, Led, Pin } = require("johnny-five")34const board = new Board({5 port: new EtherPortClient({6 host: "192.168.1.109",7 port: 3030,8 }),9 repl: false,10})1112const LED_PIN = 21314board.on("ready", () => {15 console.log("Board ready")16 var led = new Led(LED_PIN)17})
Now, let's add the REPL code. Update the board ready callback to look like this:
1[...]2board.on("ready", function() {3 /*4 Initialize pin 2, which5 controls the built-in LED6 */7 var led = new Led(LED_PIN);89 /*10 Injecting object into the REPL11 allow access while the program12 is running.1314 Try these in the REPL:1516 led.on();17 led.off();18 led.blink();1920 */21 board.repl.inject({22 led: led23 });24});
With this simple addition, we now have access to all the functions available on the LED object.
Limiting access
But what if we don't want to give our users unfettered access? What if we only want to give access to specific functions or write functions that do more than just control the hardware. Maybe we want to add logging or provide more appropriate function names. Well, we can write our own functions that are available in the REPL and inject those instead.
1[...]2board.on("ready", function() {3 /*4 Initialise pin 2, which5 controls the built-in LED6 */7 var led = new Led(LED_PIN);89 board.repl.inject({10 // Allow limited on/off control access to the11 // Led instance from the REPL.12 on: function() {13 led.on();14 },15 off: function() {16 led.off();17 },18 flash: function () {19 led.blink();20 },2122 });23});
This script will make , and functions available in the REPL.
And that is it. A nice, short intro to the Johnny Five REPL. Until you start hooking your scripts up to WebSockets or a REST API, I think this is one of the better ways to control your robots.