]> git.aero2k.de Git - sirius.git/commitdiff
Test and fix image coding.
authorTom Hunger <tehunger@gmail.com>
Thu, 15 Jan 2015 15:13:02 +0000 (15:13 +0000)
committerTom Hunger <tehunger@gmail.com>
Thu, 15 Jan 2015 16:02:50 +0000 (16:02 +0000)
sirius/coding/encoders.py
sirius/coding/image_encoding.py
sirius/coding/test_image_coding.py [new file with mode: 0644]
sirius/protocol/protocol_loop.py

index 1e78e85185a9406e552df1655a2bcd127a4430eb..19a056b2301fe2a562992cd3534213774bfc69a7 100644 (file)
@@ -53,9 +53,10 @@ def _encode_printer_message(command, pixel_count, rle_image, print_id):
     return entire_payload
 
 
-def encode_bridge_command(command, command_id, timestamp):
+def encode_bridge_command(bridge_address, command, command_id, timestamp):
     """Encodes a BridgeCommand into a dict that can be serialized as json.
 
+    :param bridge_address: The hex bridge address.
     :param command: A command from messages.py
     :param command_id: A unique id that is used to ack the command.
     :param timestamp: unix timestamp. Unclear why this is necessary.
@@ -63,7 +64,7 @@ def encode_bridge_command(command, command_id, timestamp):
     def make(extra):
         base = {
             'type': 'BridgeCommand',
-            'bridge_address': command.bridge_address,
+            'bridge_address': bridge_address,
             'command_id': command_id,
             # Apparently in ISO format?
             'timestamp': timestamp,
@@ -83,14 +84,20 @@ def encode_bridge_command(command, command_id, timestamp):
         })
 
     elif type(command) == messages.SetDeliveryAndPrint:
-        pixel_count, pixels = image_encoding.rle(command.pixels)
-        return make({'binary_payload': _encode_printer_message(
-            0x1, pixel_count, pixels, command_id)})
+        pixel_count, pixels = image_encoding.rle_image(command.pixels)
+        return make({
+            'binary_payload': _encode_printer_message(
+                0x1, pixel_count, pixels, command_id),
+            'type': 'DeviceCommand',
+        })
 
     elif type(command) == messages.SetDelivery:
-        pixel_count, pixels = image_encoding.rle(command.pixels)
-        return make({'binary_payload': _encode_printer_message(
-            0x2, pixel_count, pixels, command_id)})
+        pixel_count, pixels = image_encoding.rle_image(command.pixels)
+        return make({
+            'binary_payload': _encode_printer_message(
+                0x2, pixel_count, pixels, command_id),
+            'type': 'DeviceCommand',
+        })
 
     else:
         assert False, "unknown command type: {}".format(command)
index 24006818f155ba4df1c747138edfc5451093593f..0ae6cd98639263ca73a4bb29531e7ac53b3f2a5a 100644 (file)
@@ -3,6 +3,7 @@ from itertools import groupby
 import struct
 import io
 import time
+import tempfile
 
 WHITE = 0
 BLACK = 1
@@ -50,12 +51,12 @@ def rle(lengths):
                     yield 0
                     yield remainder
 
-def rle_image(image_fn):
-    im = Image.open(image_fn)
-    return _rle_image(im)
 
-def _rle_image(im):
-    # get image pixels
+def rle_image(im):
+    """
+    :param im: A python PIL image.
+    :returns: A 2-tuple of (number of pixels, RLE-encoded pixel data)
+    """
     im = im.convert('RGBA')
     pixels = im.getdata()
 
@@ -77,7 +78,7 @@ def _rle_image(im):
     lengths = [g[1] for g in groups]
     x = bytearray(rle(lengths))
     compressed_data = struct.pack("<%dB" % len(x), *x)
-    
+
     # package up with length as header
     # first byte is compressed type, always 1
     output = struct.pack("<BL", 0x01, len(compressed_data)) + compressed_data
@@ -85,58 +86,26 @@ def _rle_image(im):
     # return (number of pixels, output)
     return len(pixels), output
 
-def rle_html(html):
+
+def html_to_png(html):
        """ This works:
        <html><body style="width: 384px; margin: 0;">
        <img src="https://dl.dropboxusercontent.com/u/165957/Escher.gif">
        </body></html>
        """
        from selenium import webdriver
-       driver = webdriver.PhantomJS('phantomjs')
-       driver.set_window_size(384, 5)
-       #driver.get("http://www.google.com")
-       
-       driver.get("about:blank")
-       html = html.replace('"', '\\"')
-       html = html.replace("\n", " ")
-       html = html.replace("\t", " ")
-       html = html.replace("\r", " ")
-       driver.execute_script("""document.write("%s")""" % html)
-       # @TODO good grief, I can't just go putting sleeps around the place.
-       # how else to tell when the document.write has finished rendering, and
-       # all the images have loaded?
-       # maybe I need to inject something like this and look for an alert?
-       # http://imagesloaded.desandro.com
-       time.sleep(2)
-       
-       #p = driver.get_screenshot_as_file("/Users/matt/Desktop/test5.png")
-       p = driver.get_screenshot_as_png()
-       im = Image.open(io.BytesIO(p))
-       return _rle_image(im)
-
-# ~~~~
-# Test
-# ~~~~
-
-if __name__ == '__main__':
-    # just see whether the output results in the same number of
-    # pixels as the input
-    TEST_PNG_FN = '/Users/matt/Documents/dev-unversioned/sirius2/iconrethink.png'
-    pixel_count, rle_encoded = rle_image(TEST_PNG_FN)
-
-    output_length = 0
-    length_codes = {}
-    for length, code in TRANSLATE:
-        length_codes[code] = length
-    
-    for b in rle_encoded[3:]: # jump the header bytes
-        length = ord(b)
-        if length in length_codes.keys():
-            length = length_codes[length]
-        output_length += length
-    
-    # Good, it matches
-    print "Input length: %d" % pixel_count
-    print "Output length: %d" % output_length
-
-        
\ No newline at end of file
+        try:
+            driver = webdriver.PhantomJS('phantomjs')
+            driver.set_window_size(384, 5)
+
+            # note that the .html suffix is required to make phantomjs
+            # pick up the mime-type and render correctly.
+            with tempfile.NamedTemporaryFile(suffix='.html') as f:
+                f.write(html)
+                f.flush()
+                driver.get('file://' + f.name)
+                p = driver.get_screenshot_as_png()
+
+            return Image.open(io.BytesIO(p))
+        finally:
+            driver.quit()
diff --git a/sirius/coding/test_image_coding.py b/sirius/coding/test_image_coding.py
new file mode 100644 (file)
index 0000000..fd8fcd4
--- /dev/null
@@ -0,0 +1,19 @@
+import unittest
+
+from sirius.coding import image_encoding
+
+class ImageCase(unittest.TestCase):
+
+    def test_normal_text(self):
+        image = image_encoding.html_to_png('')
+        self.assertEquals(image.size[0], 384)
+
+    def test_normal_height(self):
+        image = image_encoding.html_to_png(
+            '<html><body style="margin: 0px; height: 100px;"></body></html>')
+        self.assertEquals(image.size[1], 100)
+
+    def test_rle(self):
+        image = image_encoding.html_to_png('')
+        n_bytes, _ = image_encoding.rle_image(image)
+        self.assertEquals(n_bytes, 3072)
index 2205b1483e2f9440274682817c9b041739c9e864..925a45b9359b623f4f92761df0e580ef3f372710 100644 (file)
@@ -52,6 +52,7 @@ def send_message(device_address, message):
 
     # Send data through the websocket.
     command = encoders.encode_bridge_command(
+        bridge_state.address,
         message,
         bridge_state.next_command_id,
         '0',