 1Content-type: application/x-Unknown; charset=UTF8package nmc.sidekick;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.lang.Exception;

import nmc.common.*;

//(klh)
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import com.ajile.jem.rawJEM;

public class SKHumidity extends StdEnvironmentalSensorDriver {
double _m;// conversion slope
double _b;// conversion intercept
static final int RH_POWER_ON = (1<<6);
int _RHSensorWarmup; // Sensor Warmup time (ms)
Adc adc = Adc.getInstance();
int _samplesToAverage =10;

    SKHumidity (int adc_channel ) {
	_adcChannel                 = adc_channel;
	_name			= "TheSKHumiditySensorDriverRev1.0";
	_RHSensorWarmup       = 10000;
	_m                                = 1.0; 
	_b                                 = 0; 
	_timeout		= 15000;
	_maxTries		= 3;
	_maxAttnBytes		= 250;
	_maxSampleBytes	= 1000;
	_initMaxTries		= 3;
	_maxSkipBytes		= 512;
	_cfgBufSize		= 512;
	_samplesToAverage       = 10;
    }
	
    public void initialize(){
	super.initialize();
	DebugMessage.println("SKHumidity Initializing RHPowerOn");
	initRHPowerOn();
    }


    public void initRHPowerOn(){
       synchronized(adc){

        sensorPowerOff();
    // The following is NOT THREAD-SAFE
    // If anything else is doing a read-modify-write of regE at the same time,
    // Heisenbugs are likely to appear
        // now enable the output driver on the pin connected to RH_POWER_ON (E6)
        //int regEEn  = rawJEM.getInt(AjileAddr.GPIOE_OER);
        //regEEn |= RH_POWER_ON;
        //rawJEM.set(AjileAddr.GPIOE_OER, regEEn);
        
        DebugMessage.println("SKHumiditySensor.sensorPowerOn() (REG_E_OER 6.1)");
        
        // This SHOULD be THREAD-SAFE
        rawJEM.setField(1,AjileAddr.GPIOE_OER,6,1);
        }
    }

    /** Read a data sample from device communications interface. */
    //public TimestampedData poll() throws Exception {
    public void poll(PollCmd m) throws Exception{
        int tries = 0;
        TimestampedData retVal;

        while (tries < _maxTries) {
            tries++;
            try {
                byte[] theSample = getSKHumiditySample();
                TimestampedData retval = new TimestampedData(theSample);
	        // Now we put the message into an outbound MessageQ, 
	        // instead of returning the TimestampedData.
	        // We may need some Message packetizing here...
                
                PolledDataReply pdr = new PolledDataReply(m,retval);
                _outbound.put(pdr);

                return;

            } catch (TimeoutException e) {
                DebugMessage.println("Driver: '"
                                   + _name
                                   + "' got timeout");
            } // other Exceptions fly past into the caller
        }
        
        throw new Exception("Retry limit exceeded (retries=" + tries + ")");
    }//end poll()

    private byte[] getSKHumiditySample() throws Exception {
       int counts=0;
       double humidity=0.0; 
       sensorPowerOn();	
       synchronized(adc){
 	DebugMessage.println("getSKHumiditySample() Reading adc...");
 	DebugMessage.println("Before Power on Ajile time "+System.currentTimeMillis());
    	//counts=adc.getReading(_adcChannel);
            //humidity = (double)counts*_m+_b;
            DebugMessage.println("Before Loop Start Ajile time "+System.currentTimeMillis());
            int i=0;
            int sum=0;
            int reading=0;
             for( i=0;i<_samplesToAverage;i++){
    	  reading=adc.getReading(_adcChannel);
    	  sum+=reading;
	  DebugMessage.println("adc reading "+i+" counts = "+reading+" sum = "+sum);
            }
            counts=(sum/_samplesToAverage);
	DebugMessage.println("Average of "+i+" readings is "+counts);
            DebugMessage.println("After "+i+" loops Ajile time "+System.currentTimeMillis());
       }
       DebugMessage.println("getSKHumiditySample() Turning sensor power off ");
       sensorPowerOff();
       DebugMessage.println("After Sensor power down Ajile time "+System.currentTimeMillis());
       
      // copy the sample into the exactly-right-sized byte array
      byte[] retval = (new Integer(counts)).toString().getBytes();	
      DebugMessage.println(_name+"getSKHumiditySample() Returning..."+retval);
      
      return retval;
    }//end getSKHumiditySample()

    //public TimestampedData configure(byte[] cfgData) throws Exception {
    public void configure(ConfigurationCmd m) throws Exception{
        DebugMessage.println("We are in the driver \""
                           + _name
                           + "\" with configuration data="
                           + new String(m.data));
	  // The SKHumiditySensor has no configuration and does not return
	  // and status/meta data...
        byte[] result = "SKHumiditySensor has no configurable options".getBytes();
        TimestampedData retval = new TimestampedData( result );

         // Now we put the message into an outbound MessageQ, 
         // instead of returning the TimestampedData.
         // We may need some Message packetizing here...   
         ConfigurationReply cr=new ConfigurationReply(m,retval);
        _outbound.put(cr);
      
         return;
    }
    

    public void sensorPowerOn(){
        DebugMessage.println("SKHumiditySensor Powering ON ");
    // The following is NOT THREAD-SAFE
    // If anything else is doing a read-modify-write of regE at the same time,
    // Heisenbugs are likely to appear
        // set the value of RH_POWER_ON to 1 (RH Power On)
        // int regEOut = rawJEM.getInt(AjileAddr.GPIOE_OR);
        // regEOut |= RH_POWER_ON;
        // rawJEM.set(AjileAddr.GPIOE_OR, regEOut);  
       DebugMessage.println("SKHumiditySensor.sensorPowerOn (REG_E_OR 6.1)");
         
        // This SHOULD be THREAD-SAFE
        rawJEM.setField(1,AjileAddr.GPIOE_OR,6,1);  
        DebugMessage.println("sensorPowerOn() Warming up sensor....");
        delay(_RHSensorWarmup);
    }
    
    public void sensorPowerOff(){
        DebugMessage.println("SKHumiditySensor Powering OFF");
    // The following is NOT THREAD-SAFE
    // If anything else is doing a read-modify-write of regE at the same time,
    // Heisenbugs are likely to appear
        // set the value of RH_POWER_ON to 0 (RH Power Off)
        //int regEOut = rawJEM.getInt(AjileAddr.GPIOE_OR);
        //regEOut &= ~RH_POWER_ON;
        //rawJEM.set(AjileAddr.GPIOE_OR, regEOut);    
        DebugMessage.println("SKHumiditySensor.sensorPowerOff() (REG_E_OR 6.0)");

        // This SHOULD be THREAD-SAFE
        rawJEM.setField(0,AjileAddr.GPIOE_OR,6,1);
    }

}