clojureunsigned

Writing unsigned bytes with Clojure


I'm pushing color data to a serial port to drive LEDs. The protocol here is a "command" -- in this case 'h' -- followed by the byte data representing hues.

What I have is working, but feels very clunky between needing DataOutputStream just to write the (int \h) and then ByteArrayOutputStream to write the bytes. Have I missed a more concise way to accomplish this?

 (with-open [b (new ByteArrayOutputStream)
             w (new DataOutputStream (io/output-stream "/dev/ttyACM0"))]
      (.writeInt w (int \h))
      (.writeBytes b (byte-array (map unchecked-byte (map to-hsv pixelarray))))
      (.writeTo b w))

Solution

  • You can avoid having to use ByteArrayOutputStream by using the write(byte[]) method of DataOutputStream:

    (with-open [w (new DataOutputStream (io/output-stream "/dev/ttyACM0"))]
      (.writeInt w (int \h))
      (.write w (byte-array (map unchecked-byte (map to-hsv pixelarray)))))
    

    And it doesn't seem that you actually need DataOutputStream - you can probably just use the stream returned by io/output-stream directly:

    (with-open [^OutputStream w (io/output-stream "/dev/ttyACM0")]
      (.write w (int \h))
      (.write w (byte-array (map unchecked-byte (map to-hsv pixelarray)))))