#!/usr/bin/python
#
# arch-tag: NPC sensors module
# Time-stamp: <2005-06-03 10:42:23 mike>
#
from NPCData import adc_offset, dio_offset
from io import ADC
from elementtree import ElementTree
import xmlenc as xml

__version__ = '1.5'

#
# Calibration coefficients for each sensor types.  The coefficients are
# for the linear equation:
#
#   units = c[0] + c[1]*volts
#
CALS = {'temp' : [0., 100.],
        'humidity' : [0., 1.],
        'pressure' : [-5.556, 22.22],
        'volts' : [0., 1.]}

class Sensor(object):
    def __init__(self, desc):
        self.__dict__.update(desc)
        self.type = self.name.split('/')[0]
        self.__dict__.setdefault('cal', CALS[self.type])
        self.adc = ADC(**self.adc)
        
    def _to_phys(self, v):
        """Convert A/D voltage to the physical units of the sensor"""
        return self.cal[0] + v*self.cal[1]

    def status(self, record):
        d = {}
        d['value'] = self._to_phys(self.adc.read(record))
        d['units'] = self.units
        d['name'] = self.name
        return d
    
    def as_xml(self):
        """Return the XML description of the sensor as an ElementTree
        object"""
        return xml.sensor(self.type, self.adc, name=self.name,
                          units=self.units, cal=self.cal)
