Last active
December 16, 2018 15:12
-
-
Save opichals/8f74cc494a3e2d7cf122c6013e8935cf to your computer and use it in GitHub Desktop.
Simple Espruino Graphics webGraphics over websocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wrapInstance(g, args) { | |
var width = g.getWidth(); | |
var height = g.getHeight(); | |
var page = `<script> | |
var ws; | |
setTimeout(function(){ | |
ws = new WebSocket("ws://" + location.host + "/webGraphics", "protocolOne"); | |
ws.onmessage = function (event) { | |
if (event.data.length > 40) { | |
// base64 -> Uint8Array | |
// from https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string | |
var buffer = new Uint8Array(atob(event.data).split("").map(c => c.charCodeAt(0))); | |
// console.log("MSG:"+buffer.length); | |
var cg = document.getElementById("g"); | |
var ctx = cg.getContext("2d"); | |
ctx.imageSmoothingEnabled = false; | |
var myImageData = ctx.createImageData(${width}, ${height}); | |
// make RGBA | |
var data = []; | |
buffer.forEach(b => data.push(b === 0 ? [255,255,255,255] : b === 5 ? [0,0,255,255] : [0,0,0,255])); | |
myImageData.data.set([].concat.apply([], data), 0); | |
ctx.scale(5, 5); | |
ctx.putImageData(myImageData, 0, 0); | |
} | |
}; | |
ws.onopen = function() { | |
console.log("OPEN"); | |
setTimeout(function() { | |
ws.send("Hello to Espruino!"); | |
}, 1000); | |
}; | |
},100); | |
</script><canvas id="g" width="${width}px" height="${height}px" style="border: 1px solid lightgrey;" />`; | |
function onPageRequest(req, res) { | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
res.end(page); | |
} | |
function startServer(onRequest, cb) { | |
var server = require('ws').createServer(onRequest); | |
server.listen(8000); | |
server.on("websocket", function(ws) { | |
ws.on('message',function(msg) { print("[WS] "+ msg); }); | |
cb(ws); | |
}); | |
} | |
startServer(onPageRequest, (ws) => { | |
g.ws = ws; | |
g.flip = function() { | |
// Espruino ws doesn't support binary (yet), so convert to base64 | |
ws.send(btoa(g.buffer)); | |
}; | |
ws.send(JSON.stringify(args)); | |
}); | |
} | |
function add(G) { | |
const GcreateArrayBuffer = G.createArrayBuffer; | |
G.createArrayBuffer = function(width, height, bpp, opts) { | |
// override bpp and options to capture <canvas> rendering below | |
const g = GcreateArrayBuffer(width, height, 8, {}); | |
wrapInstance(g, arguments); | |
return g; | |
}; | |
} | |
exports.add = add; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment