#!/usr/bin/env python
"""
Script for logging data to FTP server.
"""

import os

try:
    import RPi.GPIO as GPIO
except ImportError:
    print 'WARNING: USING DUMMY GPIO MODULE. PLEASE INSTALL RPi.GPIO!'
    from dummy import GPIO
import struct
import time
import zlib
from ftpstream import FTPStream

PORTC = [21, 19, 15, 13, 11, 7, 5, 3]
PORTB7 = 23


class FTPLogger(object):

    def __init__(self, ftpstream, cycle_duration=300):
        self.ftpstream = ftpstream
        self.cycle_duration = cycle_duration
        self.num_channels = 2
        FTPLogger.setup()

    def __del__(self):
        print 'Cleaning up GPIO...'
        GPIO.cleanup()

    @staticmethod
    def _read_PORTC():
        v = 0
        for p in PORTC:
            v <<= 1
            if GPIO.input(p):
                v += 1
        return v

    @staticmethod
    def setup():
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(PORTC, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(PORTB7, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    def start(self):
        while True:
            start_time = None
            end_time = None
            scheduled_end_time = None
            samples = bytearray()
            while start_time is None or end_time < scheduled_end_time:
                GPIO.wait_for_edge(PORTB7, GPIO.FALLING)
                v0 = FTPLogger._read_PORTC()
                GPIO.wait_for_edge(PORTB7, GPIO.RISING)
                v1 = FTPLogger._read_PORTC()
                end_time = time.time()
                if start_time is None:
                    start_time = end_time
                    scheduled_end_time = start_time + self.cycle_duration
                # print '%5d %5d' % (v0, v1)
                samples.append(v0)
                samples.append(v1)
            print start_time, end_time, len(samples)
            data = bytearray(struct.pack('d', start_time) +
                             struct.pack('d', end_time) +
                             struct.pack('B', self.num_channels) +
                             struct.pack('i', len(samples) / self.num_channels))
            data.extend(samples)
            compressed = zlib.compress(bytes(data))
            # import binascii
            # print binascii.hexlify(compressed)
            fname = time.strftime('%Y-%m-%d-%H%M%S.log', time.gmtime())
            print 'Saving %s...' % fname
            self.ftpstream.enqueue(fname, compressed)


if __name__ == '__main__':
    ftpstream = FTPStream(host=os.environ['FTP_SERVER'],
                          user=os.environ['FTP_USER'],
                          password=os.environ['FTP_PASS'])
    ftpstream.start()
    logger = FTPLogger(ftpstream)
    logger.start()
