[Sugar-devel] [PATCH ImageViewer] Use the accelerometer to rotate images

Agustin Zubiaga aguz at sugarlabs.org
Mon Aug 27 21:07:05 EDT 2012


This patch only affects the operation on the XO 1.75

Signed-off-by: Agustin Zubiaga <aguz at sugarlabs.org>
---
 ImageView.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 52 insertions(+), 1 deletion(-)

diff --git a/ImageView.py b/ImageView.py
index 39556d7..13eb1b0 100644
--- a/ImageView.py
+++ b/ImageView.py
@@ -62,6 +62,11 @@ class ImageViewer(Gtk.DrawingArea):
         self._temp_pixbuf = None
         self._image_changed_flag = True
         self._optimal_zoom_flag = True
+        self._lock_accelerometer = False
+
+        self._accelerometer = AccelerometerDevice()
+        if self._accelerometer.has_accelerometer:
+            GObject.timeout_add(2000, self._update_accelerometer_rotation)
 
         self.connect('draw', self.draw)
 
@@ -131,11 +136,12 @@ class ImageViewer(Gtk.DrawingArea):
         self._optimal_zoom_flag = False
         self._set_zoom(zoom)
 
-    def set_angle(self, angle):
+    def set_angle(self, angle, lock_accelerometer=True):
         self._image_changed_flag = True
         self._optimal_zoom_flag = True
 
         self.angle = angle
+        self._lock_accelerometer = lock_accelerometer
 
         if self.props.window:
             alloc = self.get_allocation()
@@ -243,6 +249,51 @@ class ImageViewer(Gtk.DrawingArea):
 
         return pixbuf
 
+    def _update_accelerometer_rotation(self):
+        if not self._lock_accelerometer:
+            x, y, z = self._accelerometer.read()
+            if x <= -700:
+                self.set_angle(270, False)
+            elif x >= 700:
+                self.set_angle(90, False)
+            elif y <= -700:
+                self.set_angle(180, False)
+            else:
+                self.set_angle(0, False)
+
+            return True
+        else:
+            return False
+
+
+class AccelerometerDevice(object):
+    # http://wiki.laptop.org/go/Accelerometer
+    ACCELEROMETER_DEVICE = '/sys/devices/platform/lis3lv02d/position'
+
+    def __init__(self, acceleration=0.05):
+        try:
+            self._device = open(self.ACCELEROMETER_DEVICE, 'r')
+            self.has_accelerometer = True
+        except IOError:
+            self.has_accelerometer = False
+
+    def reseek(self):
+        self._device.seek(0)
+
+    def read(self):
+        self.reseek()
+        x, y, z = self.parse(self._device.read())
+        return x, y, z
+
+    def parse(self, data):
+        # discard parentheses from the data
+        data = data[1:-2]
+        x, y, z = map(int, data.split(','))
+        return x, y, z
+
+    def close(self):
+        self._device.close()
+
 
 def update(view_object):
     #return view_object.zoom_out()
-- 
1.7.11.4



More information about the Sugar-devel mailing list