#!/usr/bin/python
#
# arch-tag: read NPC ADC channel
# Time-stamp: <2005-06-23 20:32:15 mike>
#
"""
Usage:  adcread.py [options] board:channel [N]

  options:
      --counts          -  return values in counts rather than volts
      --host NAME:PORT  -  NPC hostname and port (default mars-npc2:4242)
      
Read N values from the specified NPC A/D channel

"""
import sys
import getopt
from pmacs import NPCData

def tovolts(x):
    return x*5./32768.

try:
    opts,args = getopt.getopt(sys.argv[1:], 'h:c', ['host=', 'counts',
                                                    'cal='])
except getopt.GetoptError, e:
    print str(e)
    print __doc__
    sys.exit(1)

host = 'mars-npc1'
port = 4242
only_counts = 0

for opt,arg in opts:
    if opt in ('-h', '--host'):
        host,port = arg.split(':')
    elif opt in ('-c', '--counts'):
        only_counts = 1
        
try:
    board,channel = [int(s) for s in args[0].split(':')]
except:
    print __doc__
    sys.exit(1)

try:
    N = int(args[1])
except:
    N = 10

byte,elem = NPCData.adc_offset([board, channel])
dsrc = NPCData.NPCData(host, port=int(port))
accum = 0
if only_counts:
    f = lambda x: x
else:
    f = tovolts
    
try:
    for i in range(N):
        rec = dsrc.next()
        x = f(rec[elem])
        print '%.5g' % x
        accum += x
except StopIteration:
    pass
if only_counts:
    units = 'counts'
else:
    units = 'volts'
print >> sys.stderr, '%d:%d: %.5g %s' % (board, channel, accum/float(N), units)
