import appuifw, e32, sensor, math
from sensor import *

fps = 10

canvas = appuifw.Canvas()
appuifw.app.body = canvas
x1, y1 = canvas.size
x1 -= 1
y1 -= 1
xm = x1 / 2
ym = y1 / 2

g = 60

def calibrate():
    # detect gravity value
    # for this, cell phone is expected to over a table,
    # perfectly horizontal, and steady
    global g
    e32.ao_sleep(.5)
    g = accel.z
    print "gravity = %d" % g

def paint():
    canvas.rectangle([0, 0, x1, y1], fill=0)
    # calculate gravity vector for each axis
    # which basically depends on the other axis
    rx, ry, rz = math.radians(rot.x), math.radians(rot.y), math.radians(rot.z)
    if rx < 0 or ry < 0 or rz < 0:
        # spurious
        timer.after(1.0 / fps, paint)
        return
    ax, ay, az = accel.x, accel.y, accel.z
    gz = g * math.sin(rx) * abs((-math.cos(ry)))
    gx = g * math.sin(ry) * abs(math.sin(rz))
    gy = g * math.cos(rx) * abs(math.cos(rz))
    # detect acceleration and discount gravity
    ax = (ax - gx) * 3 
    ay = (ay - gy) * 3
    az = (az - gz) * 3
    if ax > 0:
        canvas.rectangle([xm, ym-20, xm + ax, ym+20], fill=0x00FFFF)
    else:
        canvas.rectangle([xm + ax, ym-20, xm, ym+20], fill=0x00FFFF)
    if ay > 0:
        canvas.rectangle([xm-20, ym, xm+20, ym+ay], fill=0x00FF00)
    else:
        canvas.rectangle([xm-20, ym+ay, xm+20, ym], fill=0x00FF00)
    if az > 0:
        canvas.rectangle([xm, y1-20, xm + az, y1], fill=0xFF0000)
        canvas.rectangle([xm, 0, xm + az, 20], fill=0xFF0000)
    else:
        canvas.rectangle([xm + az, y1-20, xm, y1], fill=0xFF0000)
        canvas.rectangle([xm + az, 0, xm, 20], fill=0xFF0000)
    timer.after(1.0 / fps, paint)

timer = e32.Ao_timer()
lock = e32.Ao_lock()

def bye():
    lock.signal()

appuifw.app.exit_key_handler = bye

accel = AccelerometerXYZAxisData()
accel.start_listening()
rot = RotationData()
rot.start_listening()
calibrate()

timer.after(1.0 / fps, paint)
lock.wait()
timer.cancel()

accel.stop_listening()

