####################################### bug_motion.py ###################################

import sys
mypath=sys.path[0]
if mypath.find('my_python') == -1:       #If true, then "my_python" could not be found
  print "Sorry.  You need to be in my_python for Halverson's program to work."
  print "(That''s because I am assuming that the tgraphlix.py and ezu3.py libraries are there.)"
  exit()
sys.path[0]=mypath[0:mypath.find('my_python')]+'my_python'

from accurate_sleep import *
from recent_avglib_yy import *
import u3
from ezu3 import *
from oscopegraphlib import *
import pyaudio          # For beeps

def get_sensor_data(LJU3):
  sensor_data=[ain0(LJU3),ain1(LJU3)]
  return sensor_data

#Setup beep
stream=pyaudio.PyAudio().open(format=pyaudio.paInt8,channels=1,rate=32000,output=True)

LJU3 = u3.U3() # Opens the first LabJackU3 found on the USB
u3setup(LJU3,['ain','ain','din','din','ain','ain','ain','ain'])

sample_period = 0.1     # seconds, rate to check to bugs
record_every_n_samples = 10    # Record motions once every this many samples
recording_period=sample_period*record_every_n_samples
data_length=20
sensor_change_tolerance = 0.1    # Volts

motions_so_far = 0
#   def setup_lists(data_length,starting_values):
sensor_data=get_sensor_data(LJU3)
number_of_sensors=len(sensor_data)
setup_lists(data_length,sensor_data)

save_to_file=(raw_input("Do you want to save the data to a file? y/n: ")=="y")
print "Press button [Now its 2, but later it will be 0] to stop"
n_loops=0
motions_this_record_period=0
while True:
  accurate_sleep(sample_period)
  sensor_data=get_sensor_data(LJU3)
  update_multiple_lists(sensor_data)
  averages=find_multiple_averages()
  #print averages
  motion = False
  for i in range(0,number_of_sensors):
    if abs(sensor_data[i]-averages[i]) > sensor_change_tolerance:
      motions_so_far = motions_so_far + 1
      motions_this_record_period = motions_this_record_period + 1
      #Beep
      for n in range(0,100,1): stream.write("\x00\x30\x5a\x76\x7f\x76\x5a\x30\x00\xd0\xa6\x8a\x80\x8a\xa6\xd0")
      print "Bug moved!   Sensor ",i," noticed it.  It went from ",averages[i], \
         " to ",sensor_data[i]," Volts, motions_so_far=",motions_so_far
      setup_lists(data_length,sensor_data)   
  if n_loops % record_every_n_samples == 0:
    #def oscope(user_y,smallest_y=0.0,biggest_y=2.5,sample_period=0.1,samples_per_sweep=20,
    #    record_for_xgraph=False,use_seconds_since_midnight=False):
    oscope(motions_this_record_period,0,5,recording_period,60,save_to_file,True) 
    motions_this_record_period=0
  n_loops=n_loops+1
  if din2(LJU3):
    quit=raw_input("Do you want to quit (y/n)?  ")
    if quit == "y":
      break
print "Have a nice day!"
# shut down beep
stream.close()
pyaudio.PyAudio().terminate()
      
      


