import dropbox
import pygame.camera
import os
import time

APP_ACCESS_TOKEN = '**********'
THERMOMETER_FILE = '/sys/bus/w1/devices/28-**********/w1_slave'

def poll_parameter(dbx, param):
    '''Parses the title of given Dropbox parameter file'''
    try:
        sch = dbx.files_list_folder('', True)
    except:
        print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + 'files_list_folder() exception in poll_parameter() with param = ' + str(param)
        return
    for match in sch.entries:
        if match.name.find(param + '=') != -1:
            try:
                parsed_param = int(match.name.replace(param + '=', ''))
            except:
                return
            return parsed_param
    return

def set_parameter(dbx, param, value):
    '''Sets given Dropbox parameter file to given value'''
    try:
        sch = dbx.files_list_folder('', True)
    except:
        print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + 'files_list_folder() exception in set_parameter() with param = ' + str(param) + ' and value = ' + str(value)
        return
    for match in sch.entries:
        if match.name.find(param + '=') != -1:
            old_filename = match.path_lower
            new_filename = match.path_lower.split('=', 1)[0] + '=' + str(value)
            if old_filename == new_filename:
                return
            try:
                dbx.files_move(old_filename, new_filename)
            except:
                print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + 'files_move() exception in set_parameter() with param = ' + str(param) + ' and value = ' + str(value)

def set_latest_temp(dbx):
    '''Parses and uploads the DS18B20 temperature reading'''
    try:
        therm_file = open(THERMOMETER_FILE, 'r')
    except:
        print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + 'open() exception in set_latest_temp()'
        return
    lines = therm_file.readlines()
    therm_file.close()
    if lines[0].strip()[-3:] != 'YES':
        return
    equals_pos = lines[1].find('t=')
    if equals_pos == -1:
        return
    temp_string = lines[1][equals_pos + 2:]
    set_parameter(dbx, 'temperature', float(temp_string)/1000.0)

if __name__ == '__main__':
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    main_dbx = dropbox.Dropbox(APP_ACCESS_TOKEN)
    pygame.camera.init()
    cam_list = pygame.camera.list_cameras()
    if len(cam_list) > 0:
        cam = pygame.camera.Camera(cam_list[0], (864, 480))
        while True:
            set_latest_temp(main_dbx)
            if poll_parameter(main_dbx, 'imagerequest') == 1:
                set_parameter(main_dbx, 'imagerequest', 0)
                cam.start()
                image = cam.get_image()
                pygame.image.save(image, 'image.jpg')
                data_file = open('image.jpg', 'rb')
                data = data_file.read()
                try:
                    main_dbx.files_upload(data, '/image.jpg', dropbox.files.WriteMode.overwrite)
                except:
                    print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + 'files_upload() exception in main loop'
                data_file.close()
                cam.stop()
                print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + '**Image requested**'
            if poll_parameter(main_dbx, 'exitprogram') == 1:
                set_parameter(main_dbx, 'exitprogram', 0)
                break
            try:
                time.sleep(poll_parameter(main_dbx, 'delay'))
            except:
                time.sleep(10)
    else:
        print '**No cameras detected**'
    print time.strftime('%d/%m/%y %H:%M:%S: ', time.localtime(time.time())) + '**Execution ended**'
