'''

Author: Federica Lionetto
Date: July 27th, 2015

Description:
It moves the laser to the desired position along x and z.
After each movement, a new entry is written into a text file, to keep track of the command that has been sent and of the new absolute position of the laser.

Parameters:
- <sensor>, the type of sensor;
- <x>, the desired x position;
- <z>, the desired z position.

How to run it:
python ElectronicMonkeyMovement.py --s <sensor> --x <x> --z <z>

For example:
python ElectronicMonkeyMovement.py --s ATLAS --x 0 -z 0

Arduino device ID:
DEVICE ID 2341:0042 on Bus 001 Address 045, Communications Device (in hexadecimal)

To get some information on the device:
lsusb -v -d 2341:0042

'''

import argparse
import subprocess
import os

import serial

import time

import sys
sys.path.insert(0,'../Tools')
from SendEmail import *

import numpy as np

parser = argparse.ArgumentParser(description='Define the parameters of the automated movement of the laser.')

parser.add_argument('--s',help='type of sensor',required=True)
parser.add_argument('--x',type=int,help='desired x position',required=True)
parser.add_argument('--z',type=int,help='desired z position',required=True)

args = parser.parse_args()

# Parameters and configuration.
sensor = args.s
desiredx = args.x
desiredz = args.z

print 'Type of sensor: ', sensor
print 'Desired x position: %i steps' % desiredx
print 'Desired z position: %i steps' % desiredz

# Find Arduino.
ser = serial.Serial('/dev/ttyACM0',9600)

folder = '/disk/groups/hep/flionett/TestStand/Data'
filename = folder+'/'+sensor+'/'+'MovementHistory.dat'
# Create the folder if it does not already exist.
if not os.path.exists(folder+"/"+sensor):
    os.makedirs(folder+"/"+sensor)
# Header to be written in the output text file.
header = 'Date&Time Absolute x (steps) Absolute z (steps) Command for x (steps) Command for z (steps)\n'

# Move the laser to the desired position along x and z.
print 'Move the laser to the desired position along x and z.'
# +10 if desiredx is positive, +20 if desiredx is negative, desiredx times.
for xcounter in range(abs(desiredx)) :
    print 'Step along x %i of %i' % (xcounter,desiredx)
    if (desiredx > 0) :
        ser.write('+10')
    elif (desiredx < 0) :
        ser.write('+20')
    time.sleep(1)
# +01 if desiredz is positive, +02 if desiredz is negative, desiredz times.
for zcounter in range(abs(desiredz)) :
    print 'Step along z %i of %i' % (zcounter,desiredz)
    if (desiredz > 0) :
        ser.write('+01')
    elif (desiredz < 0) :
        ser.write('+02')
    time.sleep(1)

print "================================================================================================"
print "Writing into output text file: "
print filename
print "================================================================================================"

file = open(filename,"a")
# Write the header only if the file is empty.
filesize = os.path.getsize(filename)
if (filesize == 0) :
    file.write(header)
    oldx = 0
    oldz = 0
else :
    ax, az = np.loadtxt(filename,delimiter=' ',skiprows=1,usecols=(5,6),unpack=True)
    print ax
    print az
    if (ax.size == 1) :
        oldx = ax
        oldz = az
    else :
        oldx = ax[-1]
        oldz = az[-1]

currentTime = time.ctime()
newx = oldx+desiredx
newz = oldz+desiredz
# header = 'Date&Time Absolute x (steps) Absolute z (steps) Command for x (steps) Command for z (steps)\n'
row = currentTime + " " + "%i" % newx + " " + "%i" % newz + " " + "%i" % desiredx + " " + "%i" % desiredz + "\n"
print row
file.write(row)

# Close output text file.
file.close()

print 'Laser successfully positioned!'

# Send email.
sender = 'federica.lionetto@cern.ch'
receiver = 'federica.lionetto@cern.ch'
# receiver = 'philipp.gloor@gmail.com'
message = 'End of the automated movement of the laser! Go to switch off the stepper motors ;)'
subject = 'End of the automated movement of the laser!'
send_email(sender,receiver,message,subject)
