net module write sending string only

Posted on
  • I there any way to send other data types? I want to send with my Espruino Pico float (it's bytes), but it's always sending as text.

    I know how to handle the text, it's just that would take less bytes to send if it were always 8 bytes from it's float data type.

  • Yes, socket.write expects a string (or does a simple toString on whatever data type you give it). The simplest way around it is to use E.toString(...), for instance:

    >E.toString([0,1,2,3,4])
    ="\x00\x01\x02\x03\x04"
    

    If you did socket.write(E.toString([0,1,2,3,4])) you'd send just the 5 bytes 0..4.

    You could use String.fromCharCode(...) which is standard JS, but E.toString is a bit easier and more efficient when dealing with arrays.

    Sending floats is a bit more tricky, but you have 2 main options:

    Typed Arrays

    var a = new Float32Array(1); // one element array
    a[0]=564654.24245
    xyz.write(E.toString(a.buffer))
    

    DataView

    This got added as of 1v92, and it lets you store and read all kinds of data really conveniently:

    http://www.espruino.com/Reference#DataVi­ew

    var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer
    d.setFloat32(0/*byte offset*/, 765.3532564);
    d.setInt8(4, 42); 
    // etc..
    xyz.write(E.toString(d.buffer))
    
  • This would be good information to add to the net module documentation!

  • Thanks! Yes, I'll add a note to do that.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

net module write sending string only

Posted by Avatar for dh. @dh.

Actions