#! /usr/bin/python

import serial
import sys
import os
import time

# Note: in Python (but not in C!) strings must be
# preceded by "b" to ensure that each character
# is just one 8-bit byte.  Without it, each character
# may be several 8-bit bytes (UTF-8 format?)


# ----------------------------------------------------------------------
def ser_readchar():
    'Reads one character from the serial port. Complains if fail.'
    c = ser.read()
    if len(c) != 1:
        sys.stderr.write('\n  [** ser.read() = ' + c + (' (len = %d)]\n' % len(c)));
    return c

def wait_OK():
    'Waits for a "0" command return code from the serial channel\n' + \
    'If receives a "#", ignores everything up to and including the EOL' + \
    'Otherwise, if the return code is not "0", aborts with error.'
    ser.flush()
    s = ser_readchar()
    while s == b'#':
        # Skip all data to end-of-line:
        sys.stderr.write('[Arduino:] ');
        while s != b'\r' and s != b'\n':
            sys.stderr.write(s);
            s = ser_readchar();
        s = ser_readchar()
        while s == b'\r' or s == b'\n':
            sys.stderr.write('[!! chr(' + ('%03d' % ord(s)) + ')]')
            s = ser_readchar()
        sys.stderr.write('\n');
    sys.stderr.write('[Arduino:]  [' + s + ']\n')
    if s != b'0':
        sys.stderr.write('** Invalid return code from Arduino: [' + s + ']\n')
        sys.exit(1)
    return 0

def turn_led(k, v):
    'Turns led {k} (0 to 5) on if {v=="+"}, off if {v=="-"}.\n' + \
    'The parameter {v} bust be a {bytes} string.'

    # Name of led {k}:
    c = chr(ord('A') + k)

    # Turn led {c} to state {v}:
    ser.write(v);
    ser.write(c);
    wait_OK()
        
# ----------------------------------------------------------------------
ser = serial.Serial \
    ( '/dev/ttyUSB0', 9600,
      bytesize=serial.EIGHTBITS,
      parity=serial.PARITY_NONE,
      stopbits=serial.STOPBITS_ONE )

time.sleep(2)


# Turn on all the leds:
for k in range(6):
    turn_led(k,b'+')
    time.sleep(1)

# Define the distance between Z positions:
ser.write('4+280')
wait_OK()

# Turn off all the leds:
for k in range(6):
    turn_led(k,b'-')

for i in range(25):
    for k in range(6):
        # Turn led {c} on:
        turn_led(k,b'+')

        # Grab the image:
        name = 'frame_%05d_%02d.jpg' % (i, k)
        sys.stderr.write('writing %s \n' % name)
        res = os.system('uvccapture -S40 -C30 -G80 -B20 -x2560 -y2048 -o%s -v' % name)
        if res != 0:
            sys.stderr.write('** {fswebcam} command returned with nonzero status\n')
            sys.exit(res)

        # Turn led {k} off:
        turn_led(k,b'-');

    # Advance microscope to next Z position:
    ser.write(b'5')
    wait_OK()




#create folder
for t in range(6):
    res = os.system('mkdir LED%01d' % t)

#change pictures folder
for d in range(99):	
   for e in range(6):
    		res = os.system('mv frame_%05d_%02d.jpg LED%01d' % (d,e,e))



        
