Skip to content

Instantly share code, notes, and snippets.

@bjpirt
Created April 30, 2014 12:29
Show Gist options
  • Save bjpirt/790d1f69e8b02e209a7f to your computer and use it in GitHub Desktop.
Save bjpirt/790d1f69e8b02e209a7f to your computer and use it in GitHub Desktop.
A quick proxy script to bridge between Scratch and Mirobot.
{
"author": "Ben Pirt",
"name": "mirobot-scratch-proxy",
"description": "A simple Scratch to Mirobot proxy",
"version": "0.0.1",
"dependencies": {
"ws": "0.4.31"
}
}
#!/usr/bin/env node
var net = require('net');
var WebSocket = require('ws');
var Mirobot = function(ready){
this.ready = ready;
this.init();
};
Mirobot.prototype = {
init: function(){
var self = this;
this.conn = net.connect({host: '192.168.1.82', port: 8899}, function() {
console.log("Mirobot connected");
if(self.ready){
self.ready();
}
});
this.conn.on('data', function(data){ self.handleData(data) });
this.conn.on('end', function() {
console.log('mirobot disconnected');
});
this.conn.on('error', function(e) {
console.log(e);
});
},
action: function(cmd, arg, cb){
var msg = {cmd: cmd}
if(arg){ msg.arg = arg }
this.send(msg, cb);
},
handleData: function(data){
lines = data.toString().trim().split("\r\n");
for(var i in lines){
line = lines[i];
line = JSON.parse(line);
if(line.status === 'complete' && this.cbs[line.id]){
this.cbs[line.id]();
delete this.cbs[line.id];
}else{
console.log("no callback");
}
}
},
cbs: [],
send: function(msg, cb){
msg.id = Math.random().toString(36).substr(2, 9)
if(cb){
this.cbs[msg.id] = cb;
}
console.log(JSON.stringify(msg));
this.conn.write(JSON.stringify(msg) + "\r\n");
}
}
var mirobotClient = new Mirobot(function(){
mirobotClient.action('penup');
});
var scratchClient = net.connect({host: '192.168.1.81', port: 42001}, function() {
var broadcast = function(msg){
msg = 'broadcast "' + msg + '"'
console.log("sending: " + msg);
var len = msg.length;
var buf = new Buffer(4);
buf.writeUInt32BE(len, 0);
buf = Buffer.concat([buf, new Buffer(msg)]);
scratchClient.write(buf);
}
scratchClient.on('data', function(data) {
var len = data.readUInt32BE(0);
var msg = data.slice(4, len + 4).toString();
console.log("received: " + msg);
var match = msg.match(/broadcast \"mirobot-([^-]*)-?(.*)?"/)
if(match){
mirobotClient.action(match[1], match[2], function(){
broadcast('mirobot-ready');
});
}
});
});
scratchClient.on('end', function() {
console.log('scratchClient disconnected');
});
scratchClient.on('error', function(e) {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment