#!/usr/bin/python
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <ducklord@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. Anders Lauritsen 
# ----------------------------------------------------------------------------


import time, cwiid


cacheTime = 1.0

cache = []

initialTime = time.time()


def wiimoteCallback(alist):
    global cache
    for tuple in alist:
        whichCommand, arg = tuple
        text = ''
        text += str(time.time()-initialTime)
        for value in arg:
            text += ' '
            text += str(value)
        text += '\n'
        cache.append(text)



def writeCacheToFile(cache):
    file = open('seimsmograph_data.csv', 'a')
    for line in cache:
        file.write(line)
    file.close()
    return

def recordData():
    global cache
    while True:
        time.sleep(cacheTime)
        writeCacheToFile(cache)
        cache = []




print "Press 1+2 on the wiimote"

try:
    wiimote = cwiid.Wiimote()
    wiimote.mesg_callback = wiimoteCallback
    wiimote.rumble = 1
    time.sleep(.2)
    wiimote.rumble = 0
    wiimote.led = 1
    wiimote.enable(cwiid.FLAG_MESG_IFC)
    wiimote.rpt_mode = cwiid.RPT_ACC
    print "connected"

    file = open('seimsmograph_data.csv', 'a')
    file.write('#time X Y Z\n')
    file.close()

    recordData()
except:
    print "Faild to connect to wiimote"


