Skip to content

Instantly share code, notes, and snippets.

@carloscarvallo
Created September 11, 2017 03:45
Show Gist options
  • Save carloscarvallo/2b6bbc76373ace7f5d19a3bdc1e2de21 to your computer and use it in GitHub Desktop.
Save carloscarvallo/2b6bbc76373ace7f5d19a3bdc1e2de21 to your computer and use it in GitHub Desktop.
controls rodi from nodejs
const request = require('request')
const requestStream = require('request-stream');
const EventEmitter = require('events');
const intervalManager = require('./intervals-manager')
var speed = 100;
var loop = 100;
class Rodi extends EventEmitter {
constructor( url ) {
super();
this.url = url;
this.blink = 1;
this.sense = 2;
this.move = 3;
this.sing = 4;
this.see = 5;
this.pixel = 6;
this.senseLight = 7;
this.led = 8;
// don't support
this.imu = 9;
}
forward( speed ) {
request.get(this.url + this.move + `/${speed}/${speed}`);
this.emit('forward');
}
back( speed ) {
request.get(this.url + this.move + `/-${speed}/-${speed}`);
this.emit('back');
}
right( speed ) {
request.get(this.url + this.move + `/${speed}/-${speed}`);
this.emit('right')
}
left( speed ) {
request.get(this.url + this.move + `/-${speed}/${speed}`);
this.emit('left')
}
stop() {
request.get(this.url + this.move + '/0/0');
this.emit('stop');
}
frontView() {
var self = this
// TODO: little hack because of rodi-web I think
requestStream(this.url + this.see, function( err, res ) {
if (err)
self.emit('error', err)
var chunks = [];
res.on("data", ( chunk ) => { chunks.push(chunk) });
res.on("end", () => { self.emit('distance', Buffer.concat(chunks)) });
res.on("error", function( err ) {
self.emit('error', err)
})
});
}
}
var rodibot = new Rodi('http://192.168.4.1:1234/');
var frontViewIntervalId = null;
var i = 0;
var loopFn = function() {
rodibot.frontView();
};
rodibot.on('forward', () => {
console.log("RODI GO!");
frontViewIntervalId = intervalManager.make(loopFn, loop);
})
rodibot.on('distance', (value) => {
console.log("distance", value.toString());
var val = value.toString();
if (val <= 25) {
rodibot.stop();
intervalManager.clear(frontViewIntervalId)
}
})
rodibot.on('right', () => {
console.log("RODI ROTATES")
setTimeout(() => {
rodibot.stop();
rodibot.forward(speed)
}, 700)
})
rodibot.on('left', () => {
console.log("RODI ROTATES")
setTimeout(() => {
rodibot.stop();
rodibot.forward(speed)
}, 800)
})
rodibot.on('stop', () => {
console.log('RODI STOPPED')
i++
if (i % 2 !== 0)
rodibot.left(speed)
})
rodibot.on('error', ( err ) => {
rodibot.stop();
throw new Error(err)
})
rodibot.forward(speed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment