#!/usr/bin/python
#
# Program to read 8 channels of TS-9700 ADC card
#
# License:      GNU General Public License
# Author:       Chris Gallienne
#

import os,sys

pc104base = 0x11E00000
coeff = 0.00246
offset = 0.00

def read_ts9700reg(addr):
   os.system("peekpoke 8 %d > /tmp/op.txt" %addr)
   for line in file('/tmp/op.txt').readlines():
      word = line.split(None, sys.maxint)
      value = word[0]
   return value

def write_ts9700reg(addr, chan):
   os.system("peekpoke 8 %d %d > /dev/null" %(addr, chan))

def find_ts9700():
   offsets = [0x160, 0x168, 0x180, 0x188, 0x250, 0x258, 0x260, 0x268]
   for offset in offsets:
      addr=pc104base+offset+1
      value = read_ts9700reg(addr)
      if value == "0x97":
          return offset
   return 0

def get_data_value(addr, offset, chan):
   write_ts9700reg(addr, chan)
   status = 0 
   while status==0:
      value = read_ts9700reg(addr)
      status = int(value, 16)&0x80
   addr=pc104base+offset+3                                
   value = read_ts9700reg(addr)
   data = int(value, 16) << 8
   addr=pc104base+offset+2
   data = data + int(read_ts9700reg(addr), 16)
   volts = str(coeff*data)
   return volts

def read_ts9700data():
   """Read 8 channels of the TS9700 ADC Converter board.
   Returns string of 8 ASCIIvoltage values."""

   offset = find_ts9700()
   if offset:
      print ("TS9700 found at offset 0x%x" %offset)
      addr=pc104base+offset
      values = []
      for chan in range(0, 8):    
         values.add(get_data_value(addr, offset, chan))
   else:                                                  
      return 0                 

if __name__ == "__main__":
   values = read_ts9700data()     
