org.mbari.siam.core
Class BaseInstrumentService

java.lang.Object
  extended by java.rmi.server.RemoteObject
      extended by java.rmi.server.RemoteServer
          extended by java.rmi.server.UnicastRemoteObject
              extended by org.mbari.siam.core.DeviceService
                  extended by org.mbari.siam.core.BaseInstrumentService
All Implemented Interfaces:
java.io.Serializable, java.rmi.Remote, ScheduleOwner, Device, DeviceServiceIF, Instrument
Direct Known Subclasses:
PolledInstrumentService, StreamingInstrumentService

public abstract class BaseInstrumentService
extends DeviceService
implements Instrument, DeviceServiceIF, ScheduleOwner

BaseInstrumentService is the base class of an "application framework" for instruments which communicate through a serial port

The application framework is a semi-complete application, providing data and behavior which are common to all instrument services. To complete the implementation of a specific instrument service, the programmer extends the base BaseInstrumentService class, and implements or overrides several base class methods.

BaseInstrumentService provides the following as built-in features:

Access to instrument serial port: BaseInstrumentService contains a java.io.OutputStream for output to the instrument's CommPort, and a java.io.InputStream for input from the instrument's CommPort. Subclasses can use these stream objects to communicate with the instrument. Note that these objects should NOT be accessed from your subclass constructor, as they haven't been created yet at construction time.

Power management: Your subclass must implement methods initCommunicationPowerPolicy(), and initInstrumentPowerPolicy(), which should return one of the following values defined in interface org.mbari.isi.interfaces.Instrument: PowerPolicy.NEVER (for self-powered instruments), PowerPolicy.ALWAYS, or PowerPolicy.WHEN_SAMPLING. The subclass needn't do any further power management, as the base automatically manages instrument power through its DPA port based on the "power policy" specified by your subclass.

The base class provides default values for a number of attributes (member variables); see comments on the DEFAULT_ fields (below). These default values can be overridden using the "set" methods provided for each attribute (e.g. setMaxSampleTries()). For some attributes, no reasonable default value is known, and must be provided by your subclass. These values are specified by implementing the abstract "init" member functions defined by the base class (e.g. initCommunicationPowerPolicy()).

To implement a specific instrument service, complete the following steps:

1. Extend StreamingInstrumentService or PolledInstrumentService to create your service's subclass

2. Implement any abstract methods (see documentation below for specific methods)

3. If necessary, override base class initializeInstrument() method, where service- and instrument-specific initialization should be done. If necessary, change values of base class attributes here, using "set" methods provided.

4. If necessary, override other base class methods

5. If necessary, add any additional attributes/methods needed to implement your instrument's service. NOTE: Service implementations should AVOID catching InterruptedException, since infrastructure relies on thread interruption to quickly shutdown a service.

Author:
Tom O'Reilly, Kent Headley, Bill Baugh
See Also:
Serialized Form

Field Summary
protected  ScheduleTask _defaultSamplerTask
          Default sampler task
protected  java.lang.String _defaultSampleScheduleName
          Name of default sample schedule
protected  MessageCache _errorCache
          Error message cache
protected  InstrumentServiceAttributes _instrumentAttributes
          Basic instrument service attributes.
protected  DevicePacket _lastPacket
          Most recent DataPacket sent (of any kind)
protected  SensorDataPacket _lastSensorDataPacket
          Most recent SensorDataPacket sent
protected static org.apache.log4j.Logger _log4j
          Log4j logger
protected  int _maxSampleBytes
          Maximum number of bytes in a data sample read from instrument.
protected  DeviceMessagePacket _messagePacket
          DeviceMessagePacket.
protected  int _nPowerRequests
          Number of times power has been applied to instrument.
protected  int _nWakeRequests
          Number of times instrument wakeup has been requested
protected  FilteredDeviceLog _packetLog
          Sensor log for persistent packet storage.
protected  long _recordType
           
protected  boolean _running
          Set to false until run() is successful.
protected  long _samplerWakeupTime
           
protected  Scheduler.ScheduleKey _scheduleKey
          Unique key used to access Scheduler entries
protected  java.util.Vector _schedules
          ScheduleTask container (schedules)
protected  SensorDataPacket _sensorDataPacket
          SensorDataPacket to be returned to clients.
protected  Turbinator _turbinator
           
protected static long MAX_BASE_RECORDTYPE
           
protected static long RECORDTYPE_DEFAULT
           
protected static long RECORDTYPE_METADATA
           
protected static long RECORDTYPE_UNDEFINED
          Default record type
 
Fields inherited from class org.mbari.siam.core.DeviceService
_fromDevice, _instrumentPort, _nodeProperties, _parentNode, _regEntry, _sandBox, _serviceCachePath, _serviceName, _servicePropertiesPath, _serviceXMLPath, _toDevice, CACHED_PROPERTIES_FILENAME, PROPERTIES_FILENAME, XML_FILENAME
 
Fields inherited from class java.rmi.server.RemoteObject
ref
 
Fields inherited from interface org.mbari.siam.distributed.Device
ERROR, INITIAL, INSTRUMENT_STATE, MDATA_ALL, OK, SAFE, SAMPLING, SERVICE_ATTRIBUTES, SERVICE_CACHE, SERVICE_PROPERTIES, SERVICE_XML, SHUTDOWN, SLEEPING, SUSPEND, UNKNOWN
 
Constructor Summary
BaseInstrumentService()
          Constructor.
 
Method Summary
protected abstract  SensorDataPacket acquire(boolean logSample)
          Acquire data sample from instrument, process it, and put data into output.
 SensorDataPacket acquireSample(boolean logPacket)
          Acquire data sample from instrument, process it, log it, and return it to caller.
 void addDefaultPacketFilters(PacketFilter[] filters)
          Add default packet filters for data retrieval.
protected  int addSchedule(ScheduleTask schedule, boolean overwrite)
          Add the specified schedule task.
 int addSchedule(java.lang.String name, java.lang.String schedule, boolean overwrite)
          Add/replace instrument schedule
 void annotate(byte[] annotation)
          Put annotation into device data stream.
 void assertSamplingState()
          Do overhead tasks needed to prepare for sample cycle.
 void cacheProperties(byte[] note)
          Cache service properties on the "instrument host" node, such that current service property values will be restored next time service is created on current port of current node.
 void callDataListeners(SensorDataPacket packet)
          Call any DataListeners that have registered for dataCallbacks, for the given SensorDataPacket
 boolean canSummarize()
          A check method to indecate if this instrument service can produce summary packets.
protected  void checkInputProperties(java.util.Properties properties)
          Check that all specified properties are allowed to be set on-the-fly.
 void cleanupServiceState()
          Do overhead tasks needed to clean up after sample cycle.
 void clearDefaultPacketFilters()
          Clear default packet filters for data retrieval.
 void clearPropertiesCache(byte[] note)
          Clear properties cache.
protected abstract  ScheduleSpecifier createDefaultSampleSchedule()
          Return default sampling schedule.
protected  void createPacketLog()
          Create device packet log.
 ScheduleTask createTask(java.lang.String name, ScheduleSpecifier schedule, ScheduleOwner owner)
          createTask is a factory method to make new schedule tasks by name.
protected  void createTurbinators()
          Helper function to create the Turbinators
 void disableSummary()
          Disable data summary generation.
abstract  void doScheduledTask(ScheduleTask task)
          Execute the scheduled task, as part of ScheduleOwner implementation.
 void enableSummary()
          Enable data summary generation.
protected  void endDeviceAccess()
          Remove from list of threads that are accessing instrument device.
 java.util.Collection getAllSchedules()
          Return a vector of ScheduleTask objects Part of ScheduleOwner interface.
 Device[] getChildren()
          Return child Devices.
protected  PowerPolicy getCommunicationPowerPolicy()
          Get instrument communication power policy.
protected  int getCurrentLimit()
          Get power channel's current limit.
 PacketFilter[] getDefaultPacketFilters()
          Get default packet filters for data retrieval.
 ScheduleTask getDefaultSampleSchedule()
          Get the default schedule
 java.lang.String getDefaultSampleScheduleName()
          Get default sample schedule name
 DevicePacketParser getDevicePacketParser()
          Get instruments' DevicePacketParser, which returns JDDAC records.
 byte[] getFileBytes(java.lang.String file)
          Get the contents of a file and return them as a byte array
protected  PowerPolicy getInstrumentPowerPolicy()
          Get instrument power policy.
 InstrumentServiceBlock getInstrumentServiceBlock()
          Retrive the FunctionBlock used for specialized processing of acquired samples.
protected  int getInstrumentStartDelay()
          Get instrument startup time
protected  byte[] getInstrumentStateMetadata()
          Get instrument 'metadata' from device itself.
 SensorDataPacket getLastSample()
          Get last sample packet.
protected  int getMaxSampleBytes()
          Get maximum number of bytes in a data sample read from instrument.
protected  int getMaxSampleTries()
          Get maximum number of tries when retrieving sample from instrument.
 MetadataPacket getMetadata(byte[] cause, int components, boolean logPacket)
          Create, return and optionally log a metadata packet
protected  MetadataPacket getMetadata(byte[] cause, int components, java.lang.String[] attributeNames, boolean logPacket)
          Create, return, and optionally log metadata packet; if service attributes are requested, then include only specified attributes.
 byte[] getMetadataPayload(int components, java.lang.String[] attributeList)
          Get requested metadata state components in a byte array containing serialized State and StateAttribute objects.
 DevicePacketSet getPackets(long startTime, long stopTime)
          Return all logged data packets having creation time within specified time window.
 DevicePacketSet getPackets(long startTime, long stopTime, PacketFilter[] filters, boolean excludeStale)
          Return all logged data packets having creation time within specified time window, that pass specified packet filters.
 Device getParent()
          Return parent Device.
 PacketParser getParser()
          Get instrument's parser.
 byte[] getPortDiagnostics(boolean logPacket)
          Get diagnostics message from device's port and optionally log it.
 byte[] getPortDiagnosticsSummary(boolean logPacket)
          Get diagnostics summary message from device's port and optionally log it.
protected  byte[] getPromptString()
          Get instrument's "prompt" character(s).
 java.util.Vector getProperties()
          Get Vector of instrument properties; each Vector element consists of byte array with form "key=value".
 byte[] getProperty(byte[] key)
          Get value of specified service property.
protected  byte[] getSampleBuf()
          Get raw sample buffer.
 byte[] getSampleSchedule()
          Return byte-string representation of instrument sampling schedule.
protected  byte[] getSampleTerminator()
          Get sample terminator
protected  long getSampleTimeout()
          Get sampling timeout (millisec)
 ScheduleTask getSchedule(java.lang.String name)
          Get a schedule by name
 Scheduler.ScheduleKey getScheduleKey()
          Return the schedule key, as part of ScheduleOwner implementation.
 java.util.Vector getSchedules()
          Return a vector of ScheduleTask objects Part of Instrument interface.
 byte[] getServicePropertiesBytes()
          Get Service Properties file, returned as a byte array
protected abstract  PowerPolicy initCommunicationPowerPolicy()
          Return initial value of instrument communication power policy.
protected abstract  int initCurrentLimit()
          Return DPA current limit (milliamp).
 void initialize(NodeProperties nodeProperties, Parent parent, InstrumentPort port, ServiceSandBox sandBox, java.lang.String serviceXMLPath, java.lang.String servicePropertiesPath, java.lang.String cachedServicePath)
          Initialize service parameters.
 void initializeDriverDefaults()
          Load defaults for member variables using abstract methods.
protected  void initializeInstrument()
          Do instrument- and service-specific initialization.
protected  void initializePooledResources(long id, int len)
          initialize a set of reusable data packet objects Base class creates only one.
protected abstract  PowerPolicy initInstrumentPowerPolicy()
          Return initial value of instrument power policy.
protected abstract  int initInstrumentStartDelay()
          Return instrument startup time in millisec.
protected abstract  int initMaxSampleBytes()
          Return maximum number of bytes in a instrument data sample.
protected abstract  byte[] initPromptString()
          Return instrument's "prompt" characters.
protected abstract  byte[] initSampleTerminator()
          Return instrument's sample terminator characters.
protected  void interruptDeviceAccess(int waitMsec)
          Interrupt any threads that are accessing the device, optionally wait specified time for thread to die after interrupt.
 void logPacket(DevicePacket devicePacket)
          Centralized packet logging logic
protected  void managePowerSleep()
          Return instrument to lowest possible power state between samples
protected  void managePowerWake()
          Prepare instrument for sampling; connect comms and turn on power.
 int nPowerRequests()
          Return number of power-on requests issued so far
protected  void postSample()
          Called after sample has been acquired, processed and logged.
 int powerOff()
          Turn off instrument power.
protected  void powerOffCallback()
          Called after power is removed from instrument.
 int powerOn()
          Turn on instrument power.
protected  void powerOnCallback()
          Called after power is applied to instrument; return when instrument is ready for use.
 void prepareToRun()
          Initialize service and instrument, sampling schedule.
protected  void prepareToSample()
          Prepare the device for sampling; called before requestSample().
protected  void printData(byte[] buf)
          Print instrument data contained in input buffer.
protected  SensorDataPacket processSample(byte[] sample, int nBytes)
          Process raw sample bytes, return TimeStampedData object.
protected  int readSample(byte[] sample)
          Read raw sample bytes from serial port into buffer, return number of bytes read.
 int removeAllSchedules()
          Remove all schedules.
 int removeSchedule(java.lang.String name)
          Remove specified schedule.
 void resetPortDiagnostics()
          Reset port diagnostics.
 void resume()
          Put service in OK state.
 int resumeSchedule(java.lang.String schedule)
          Resume specified schedule.
 boolean running()
          Indicates if run() has been successful.
 void setAttributes(ServiceAttributes attributes)
          Set the ServiceAttributes object for this service.
 void setClock()
          Set device's clock to current time; can throw NotSupportedException.
 void setClock(long t)
          Set device's clock to specified time.
protected  void setCommunicationPowerPolicy(PowerPolicy policy)
          Set instrument communication power policy.
protected  void setCurrentLimit(int milliamps)
          Set power channel's current limit.
 void setDefaultSampleScheduleName(java.lang.String name)
          Set default sample schedule name
protected  void setInstrumentPowerPolicy(PowerPolicy policy)
          Set instrument power policy.
 void setInstrumentServiceBlock(InstrumentServiceBlock instrumentServiceBlock)
           
protected  void setInstrumentStartDelay(int millisec)
          Set instrument startup time
protected  void setMaxSampleBytes(int maxBytes)
          Set maximum number of bytes in a raw data sample read from instrument.
protected  void setMaxSampleTries(int maxTries)
          Set maximum number of tries when retrieving sample from instrument.
protected  void setPromptString(byte[] promptString)
          Set instrument's "prompt" character(s).
 void setProperty(byte[] propertyStrings, byte[] unused)
          Set value of specified instrument service properties.
protected  void setRecordType(long type)
          Set _recordType field
protected  void setSampleTerminator(byte[] sampleTerminator)
          Set sample terminator.
protected  void setSampleTimeout(long timeout)
          Set sampling timeout (millisec).
 byte[] shutdown()
          Stop the service.
protected  java.lang.String shutdownInstrument()
          Perform any instrument-specific shutdown actions and optionally return a human-readable message (e.g.
 long sleepingUntil(ScheduleTask task)
          If execution thread of specified task is sleeping, return time at which it will resume; otherwise return 0.
protected  void snooze(int seconds)
          Put thread to sleep for specified seconds, in such a way that cpu is guaranteed to be awake when the thread is done sleeping.
protected  void startDeviceAccess()
          Add to list of threads that are accessing instrument device.
 boolean summaryEnabled()
          Return true if summary generation is enabled.
 void suspend()
          Put service in SUSPEND state.
 int suspendSchedule(java.lang.String schedule)
          Suspend specified schedule.Return integer code defined by Scheduler.
protected  int sync(long delayMillis)
          Sync default sample schedule
 int syncSchedule(java.lang.String schedule, long delayMillis)
          "Synchronize" specified schedule.
protected  void validateSample(byte[] sampleBuf, int nBytes)
          This method can optionally be overriden so the sub-class can determines the validity of the sampled bytes.
 
Methods inherited from class org.mbari.siam.core.DeviceService
addDataListener, advertiseService, createRegistryEntry, getAttributes, getCommPortName, getFrameworkVersion, getId, getInstrumentPort, getLocation, getName, getRemoteSerialPort, getRemoteSerialPort, getSamplingCount, getSamplingErrorCount, getSamplingRetryCount, getSerialPortParameters, getStatus, host, incRetryCount, initializePropertyDefaults, registryEntry, registryName, removeDataListener, setInstrumentPort, setNodeProperties, setParent, setSerialPort, setStatusError, setStatusInitial, setStatusOk, setStatusSafe, setStatusSampling, setStatusShutdown, setStatusSuspend
 
Methods inherited from class java.rmi.server.UnicastRemoteObject
clone, exportObject, exportObject, exportObject, unexportObject
 
Methods inherited from class java.rmi.server.RemoteServer
getClientHost, getLog, setLog
 
Methods inherited from class java.rmi.server.RemoteObject
equals, getRef, hashCode, toString, toStub
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.mbari.siam.distributed.Device
getCommPortName, getFrameworkVersion, getId, getLocation, getName, getSamplingCount, getSamplingErrorCount, getSamplingRetryCount, getStatus, host, test
 
Methods inherited from interface org.mbari.siam.distributed.DeviceServiceIF
getName
 

Field Detail

_log4j

protected static org.apache.log4j.Logger _log4j
Log4j logger


_running

protected boolean _running
Set to false until run() is successful.


_errorCache

protected MessageCache _errorCache
Error message cache


_defaultSamplerTask

protected ScheduleTask _defaultSamplerTask
Default sampler task


_messagePacket

protected DeviceMessagePacket _messagePacket
DeviceMessagePacket.


_samplerWakeupTime

protected long _samplerWakeupTime

_maxSampleBytes

protected int _maxSampleBytes
Maximum number of bytes in a data sample read from instrument.


_sensorDataPacket

protected SensorDataPacket _sensorDataPacket
SensorDataPacket to be returned to clients.


_lastSensorDataPacket

protected SensorDataPacket _lastSensorDataPacket
Most recent SensorDataPacket sent


_lastPacket

protected DevicePacket _lastPacket
Most recent DataPacket sent (of any kind)


_packetLog

protected FilteredDeviceLog _packetLog
Sensor log for persistent packet storage.


RECORDTYPE_UNDEFINED

protected static final long RECORDTYPE_UNDEFINED
Default record type

See Also:
Constant Field Values

RECORDTYPE_METADATA

protected static final long RECORDTYPE_METADATA
See Also:
Constant Field Values

RECORDTYPE_DEFAULT

protected static final long RECORDTYPE_DEFAULT
See Also:
Constant Field Values

MAX_BASE_RECORDTYPE

protected static final long MAX_BASE_RECORDTYPE
See Also:
Constant Field Values

_recordType

protected long _recordType

_turbinator

protected Turbinator _turbinator

_nPowerRequests

protected int _nPowerRequests
Number of times power has been applied to instrument.


_nWakeRequests

protected int _nWakeRequests
Number of times instrument wakeup has been requested


_schedules

protected java.util.Vector _schedules
ScheduleTask container (schedules)


_defaultSampleScheduleName

protected java.lang.String _defaultSampleScheduleName
Name of default sample schedule


_scheduleKey

protected Scheduler.ScheduleKey _scheduleKey
Unique key used to access Scheduler entries


_instrumentAttributes

protected InstrumentServiceAttributes _instrumentAttributes
Basic instrument service attributes.

Constructor Detail

BaseInstrumentService

public BaseInstrumentService()
                      throws java.rmi.RemoteException
Constructor.

Throws:
java.rmi.RemoteException
Method Detail

running

public boolean running()
Indicates if run() has been successful.


getPromptString

protected final byte[] getPromptString()
Get instrument's "prompt" character(s).


setPromptString

protected final void setPromptString(byte[] promptString)
Set instrument's "prompt" character(s).

Parameters:
promptString - instrument's prompt string

getSampleTerminator

protected final byte[] getSampleTerminator()
Get sample terminator


setSampleTerminator

protected final void setSampleTerminator(byte[] sampleTerminator)
Set sample terminator.

Parameters:
sampleTerminator - instrument sample termination string

getSampleTimeout

protected final long getSampleTimeout()
Get sampling timeout (millisec)


setSampleTimeout

protected final void setSampleTimeout(long timeout)
                               throws RangeException
Set sampling timeout (millisec).

Parameters:
timeout - sampling timeout in millisec
Throws:
RangeException

getMaxSampleTries

protected final int getMaxSampleTries()
Get maximum number of tries when retrieving sample from instrument.


setMaxSampleTries

protected final void setMaxSampleTries(int maxTries)
                                throws RangeException
Set maximum number of tries when retrieving sample from instrument.

Parameters:
maxTries - maximum number of times to attempt sample retrieval; must be greater than 0
Throws:
RangeException

getMaxSampleBytes

protected final int getMaxSampleBytes()
Get maximum number of bytes in a data sample read from instrument.


setMaxSampleBytes

protected final void setMaxSampleBytes(int maxBytes)
                                throws RangeException
Set maximum number of bytes in a raw data sample read from instrument. Allocates sample buffer (retrieved by getSampleBuf()).

Parameters:
maxBytes - maximum number of bytes in a raw sample
Throws:
RangeException

getSampleBuf

protected final byte[] getSampleBuf()
Get raw sample buffer.


getLastSample

public final SensorDataPacket getLastSample()
                                     throws NoDataException
Get last sample packet.

Specified by:
getLastSample in interface Instrument
Throws:
NoDataException

getCurrentLimit

protected final int getCurrentLimit()
Get power channel's current limit.


setCurrentLimit

protected final void setCurrentLimit(int milliamps)
                              throws RangeException
Set power channel's current limit. Breaker will trip if limit is exceeded.

Parameters:
milliamps - current limit in milliamps
Throws:
RangeException

getInstrumentPowerPolicy

protected final PowerPolicy getInstrumentPowerPolicy()
Get instrument power policy.


setInstrumentPowerPolicy

protected final void setInstrumentPowerPolicy(PowerPolicy policy)
Set instrument power policy.


getCommunicationPowerPolicy

protected final PowerPolicy getCommunicationPowerPolicy()
Get instrument communication power policy.


setCommunicationPowerPolicy

protected final void setCommunicationPowerPolicy(PowerPolicy policy)
Set instrument communication power policy.


getInstrumentStartDelay

protected final int getInstrumentStartDelay()
Get instrument startup time


setInstrumentStartDelay

protected final void setInstrumentStartDelay(int millisec)
                                      throws RangeException
Set instrument startup time

Parameters:
millisec - instrument startup delay in milliseconds
Throws:
RangeException

initializeDriverDefaults

public void initializeDriverDefaults()
                              throws InitializeException
Load defaults for member variables using abstract methods. Values specified in service.properties may override some of these.

Throws:
InitializeException

initializePooledResources

protected void initializePooledResources(long id,
                                         int len)
initialize a set of reusable data packet objects Base class creates only one. subclasses may override to support larger pool for different types


prepareToRun

public void prepareToRun()
                  throws InitializeException,
                         java.lang.InterruptedException
Initialize service and instrument, sampling schedule. This method must be invoked by outside entity before data acquisition starts.

Specified by:
prepareToRun in interface Device
Overrides:
prepareToRun in class DeviceService
Throws:
InitializeException
java.lang.InterruptedException

createTurbinators

protected void createTurbinators()
Helper function to create the Turbinators


prepareToSample

protected void prepareToSample()
                        throws java.lang.Exception
Prepare the device for sampling; called before requestSample(). By default this method does nothing, and may be overridden in the subclass.

Throws:
java.lang.Exception

postSample

protected void postSample()
Called after sample has been acquired, processed and logged. By default this method does nothing, an may be overridden in the subclass.


acquireSample

public final SensorDataPacket acquireSample(boolean logPacket)
                                     throws NoDataException
Acquire data sample from instrument, process it, log it, and return it to caller.

Specified by:
acquireSample in interface Instrument
Throws:
NoDataException

assertSamplingState

public void assertSamplingState()
                         throws NoDataException
Do overhead tasks needed to prepare for sample cycle. It is broken out into a separate method to allow other methods (e.g., when a service wants to override acquire()) to use the same code without cutting and pasting.

Throws:
NoDataException

cleanupServiceState

public void cleanupServiceState()
Do overhead tasks needed to clean up after sample cycle. It is broken out into a separate method to allow other methods (e.g., when a service wants to override acquire()) to use the same code without cutting and pasting.


managePowerWake

protected void managePowerWake()
Prepare instrument for sampling; connect comms and turn on power. Uses _powerPolicy to determine appropriate action. Instrument and comms power are lumped together (no immediate need to have separate power policy for comms); may need to change.

Overrides:
managePowerWake in class DeviceService

powerOn

public int powerOn()
Turn on instrument power. If override is true, don't check with parent first.

Specified by:
powerOn in interface Device

managePowerSleep

protected void managePowerSleep()
Return instrument to lowest possible power state between samples

Overrides:
managePowerSleep in class DeviceService

powerOff

public int powerOff()
Turn off instrument power.

Specified by:
powerOff in interface Device

nPowerRequests

public int nPowerRequests()
Return number of power-on requests issued so far


readSample

protected int readSample(byte[] sample)
                  throws TimeoutException,
                         java.io.IOException,
                         java.lang.Exception
Read raw sample bytes from serial port into buffer, return number of bytes read. Reads characters from serial port until sample terminator string is encountered.

Parameters:
sample - output buffer
Throws:
TimeoutException
java.io.IOException
java.lang.Exception

validateSample

protected void validateSample(byte[] sampleBuf,
                              int nBytes)
                       throws InvalidDataException
This method can optionally be overriden so the sub-class can determines the validity of the sampled bytes. If an error is detected an InvalidDataException is thrown.

Parameters:
sampleBuf - sample buffer containing data to validate
nBytes - Number of bytes of data to validate
Throws:
InvalidDataException - thrown if data is found to be invalid

processSample

protected SensorDataPacket processSample(byte[] sample,
                                         int nBytes)
                                  throws java.lang.Exception
Process raw sample bytes, return TimeStampedData object. By default, raw sample is encapsulated in TimeStampedData object, and no additional processing is done.

Parameters:
sample - raw sample
nBytes - number of bytes in raw sample
Throws:
java.lang.Exception

callDataListeners

public void callDataListeners(SensorDataPacket packet)
Call any DataListeners that have registered for dataCallbacks, for the given SensorDataPacket


getServicePropertiesBytes

public byte[] getServicePropertiesBytes()
Get Service Properties file, returned as a byte array


getMetadataPayload

public byte[] getMetadataPayload(int components,
                                 java.lang.String[] attributeList)
                          throws java.rmi.RemoteException,
                                 java.lang.Exception
Get requested metadata state components in a byte array containing serialized State and StateAttribute objects.

Throws:
java.rmi.RemoteException
java.lang.Exception

getMetadata

public MetadataPacket getMetadata(byte[] cause,
                                  int components,
                                  boolean logPacket)
                           throws java.rmi.RemoteException
Create, return and optionally log a metadata packet

Specified by:
getMetadata in interface Device
Specified by:
getMetadata in class DeviceService
Throws:
java.rmi.RemoteException

getMetadata

protected MetadataPacket getMetadata(byte[] cause,
                                     int components,
                                     java.lang.String[] attributeNames,
                                     boolean logPacket)
                              throws java.rmi.RemoteException,
                                     java.lang.Exception
Create, return, and optionally log metadata packet; if service attributes are requested, then include only specified attributes.

Parameters:
cause -
components -
attributeNames -
logPacket -
Returns:
metadata (MetadataPacket)
Throws:
java.rmi.RemoteException
java.lang.Exception

getFileBytes

public byte[] getFileBytes(java.lang.String file)
                    throws java.io.FileNotFoundException,
                           java.io.IOException,
                           java.lang.NullPointerException
Get the contents of a file and return them as a byte array

Throws:
java.io.FileNotFoundException
java.io.IOException
java.lang.NullPointerException

getInstrumentStateMetadata

protected byte[] getInstrumentStateMetadata()
                                     throws java.lang.Exception
Get instrument 'metadata' from device itself. By default, this method does nothing, and can be overridden. This method should return any available configuration information that is available from the instrument device. Note that this method should NOT power-manage the device, as that is the responsibility of the caller.

Throws:
java.lang.Exception

initializeInstrument

protected void initializeInstrument()
                             throws InitializeException,
                                    java.lang.Exception
Do instrument- and service-specific initialization. By default, this method does nothing, and may be overridden.

Throws:
InitializeException
java.lang.Exception

annotate

public void annotate(byte[] annotation)
Put annotation into device data stream. Annotation will be automatically time-tagged by host.

Specified by:
annotate in interface Instrument

getSampleSchedule

public final byte[] getSampleSchedule()
Return byte-string representation of instrument sampling schedule.

Specified by:
getSampleSchedule in interface Instrument

getParent

public Device getParent()
                 throws NoParentException
Return parent Device.

Specified by:
getParent in interface Device
Throws:
NoParentException

getChildren

public Device[] getChildren()
                     throws NoChildrenException
Return child Devices.

Specified by:
getChildren in interface Device
Throws:
NoChildrenException

initialize

public void initialize(NodeProperties nodeProperties,
                       Parent parent,
                       InstrumentPort port,
                       ServiceSandBox sandBox,
                       java.lang.String serviceXMLPath,
                       java.lang.String servicePropertiesPath,
                       java.lang.String cachedServicePath)
                throws MissingPropertyException,
                       InvalidPropertyException,
                       PropertyException,
                       InitializeException,
                       java.io.IOException,
                       gnu.io.UnsupportedCommOperationException
Initialize service parameters. Called immediately after service is instantiated.

Overrides:
initialize in class DeviceService
Throws:
MissingPropertyException
InvalidPropertyException
PropertyException
InitializeException
java.io.IOException
gnu.io.UnsupportedCommOperationException

createPacketLog

protected void createPacketLog()
                        throws MissingPropertyException,
                               InvalidPropertyException,
                               java.io.FileNotFoundException,
                               java.io.IOException
Create device packet log.

Throws:
MissingPropertyException
InvalidPropertyException
java.io.FileNotFoundException
java.io.IOException

powerOnCallback

protected void powerOnCallback()
                        throws java.lang.Exception
Called after power is applied to instrument; return when instrument is ready for use. By default, sleeps for 'instrumentStartDelay' milliseconds.

Throws:
java.lang.Exception

powerOffCallback

protected void powerOffCallback()
Called after power is removed from instrument. By default this method does nothing, and may be overridden.


suspend

public void suspend()
Put service in SUSPEND state. Release resources (e.g. serial port) for use by other applications. Note that this method should NOT be synchronized, since must be able to suspend a service that is currently sampling.

Specified by:
suspend in interface Device
Overrides:
suspend in class DeviceService

resume

public void resume()
Description copied from class: DeviceService
Put service in OK state. Re-acquire resources (e.g. serial port).

Specified by:
resume in interface Device
Overrides:
resume in class DeviceService

getPackets

public DevicePacketSet getPackets(long startTime,
                                  long stopTime)
                           throws NoDataException
Return all logged data packets having creation time within specified time window.

Specified by:
getPackets in interface Instrument
Throws:
NoDataException

getPackets

public DevicePacketSet getPackets(long startTime,
                                  long stopTime,
                                  PacketFilter[] filters,
                                  boolean excludeStale)
                           throws NoDataException
Return all logged data packets having creation time within specified time window, that pass specified packet filters.

Specified by:
getPackets in interface Instrument
Throws:
NoDataException

clearDefaultPacketFilters

public void clearDefaultPacketFilters()
Clear default packet filters for data retrieval.

Specified by:
clearDefaultPacketFilters in interface Instrument

addDefaultPacketFilters

public void addDefaultPacketFilters(PacketFilter[] filters)
Add default packet filters for data retrieval.

Specified by:
addDefaultPacketFilters in interface Instrument

getDefaultPacketFilters

public PacketFilter[] getDefaultPacketFilters()
Get default packet filters for data retrieval.

Specified by:
getDefaultPacketFilters in interface Instrument

getProperty

public byte[] getProperty(byte[] key)
                   throws MissingPropertyException
Get value of specified service property.

Specified by:
getProperty in interface Instrument
Throws:
MissingPropertyException

setProperty

public final void setProperty(byte[] propertyStrings,
                              byte[] unused)
                       throws java.rmi.RemoteException,
                              InvalidPropertyException
Set value of specified instrument service properties. Input consists of one or more 'key=value' pairs. Each key=value pair is separated from the next pair by newline ('\n').

Specified by:
setProperty in interface Instrument
Throws:
java.rmi.RemoteException
InvalidPropertyException

checkInputProperties

protected void checkInputProperties(java.util.Properties properties)
                             throws InvalidPropertyException
Check that all specified properties are allowed to be set on-the-fly. Throw PropertyException if any disallowed properties have been specified.

Throws:
InvalidPropertyException

getProperties

public java.util.Vector getProperties()
Get Vector of instrument properties; each Vector element consists of byte array with form "key=value".

Specified by:
getProperties in interface Instrument

cacheProperties

public void cacheProperties(byte[] note)
                     throws java.lang.Exception
Cache service properties on the "instrument host" node, such that current service property values will be restored next time service is created on current port of current node.

Specified by:
cacheProperties in interface Instrument
Throws:
java.lang.Exception

clearPropertiesCache

public void clearPropertiesCache(byte[] note)
                          throws java.rmi.RemoteException,
                                 java.lang.Exception
Clear properties cache.

Specified by:
clearPropertiesCache in interface Instrument
Throws:
java.rmi.RemoteException
java.lang.Exception

sync

protected int sync(long delayMillis)
Sync default sample schedule


printData

protected void printData(byte[] buf)
Print instrument data contained in input buffer. By default does nothing, and may be overridden.


getPortDiagnostics

public byte[] getPortDiagnostics(boolean logPacket)
                          throws java.rmi.RemoteException
Get diagnostics message from device's port and optionally log it.

Specified by:
getPortDiagnostics in interface Instrument
Throws:
java.rmi.RemoteException

setRecordType

protected void setRecordType(long type)
Set _recordType field


logPacket

public void logPacket(DevicePacket devicePacket)
Centralized packet logging logic


getPortDiagnosticsSummary

public byte[] getPortDiagnosticsSummary(boolean logPacket)
                                 throws java.rmi.RemoteException
Get diagnostics summary message from device's port and optionally log it.

Specified by:
getPortDiagnosticsSummary in interface Instrument
Throws:
java.rmi.RemoteException

resetPortDiagnostics

public void resetPortDiagnostics()
Reset port diagnostics.

Specified by:
resetPortDiagnostics in interface Instrument

getParser

public PacketParser getParser()
                       throws NotSupportedException
Get instrument's parser. Not supported, by default.

Specified by:
getParser in interface Instrument
Throws:
NotSupportedException

getDevicePacketParser

public DevicePacketParser getDevicePacketParser()
                                         throws NotSupportedException
Get instruments' DevicePacketParser, which returns JDDAC records. Not supported by default

Throws:
NotSupportedException

getScheduleKey

public final Scheduler.ScheduleKey getScheduleKey()
Return the schedule key, as part of ScheduleOwner implementation.

Specified by:
getScheduleKey in interface ScheduleOwner

doScheduledTask

public abstract void doScheduledTask(ScheduleTask task)
Execute the scheduled task, as part of ScheduleOwner implementation. Subclass will actually implement

Specified by:
doScheduledTask in interface ScheduleOwner

getSchedules

public final java.util.Vector getSchedules()
                                    throws java.rmi.RemoteException
Return a vector of ScheduleTask objects Part of Instrument interface.

Specified by:
getSchedules in interface Instrument
Throws:
java.rmi.RemoteException

getAllSchedules

public final java.util.Collection getAllSchedules()
Return a vector of ScheduleTask objects Part of ScheduleOwner interface.

Specified by:
getAllSchedules in interface ScheduleOwner

getDefaultSampleSchedule

public ScheduleTask getDefaultSampleSchedule()
Get the default schedule


getSchedule

public ScheduleTask getSchedule(java.lang.String name)
Get a schedule by name


getDefaultSampleScheduleName

public java.lang.String getDefaultSampleScheduleName()
Get default sample schedule name


addSchedule

public int addSchedule(java.lang.String name,
                       java.lang.String schedule,
                       boolean overwrite)
Add/replace instrument schedule

Specified by:
addSchedule in interface ScheduleOwner
Parameters:
name - Schedule name
schedule - Representation of schedule
overwrite - If true, replace existing schedule
Returns:
Scheduler.UNDEFINED, Scheduler.INVALID_SCHEDULE

addSchedule

protected int addSchedule(ScheduleTask schedule,
                          boolean overwrite)
Add the specified schedule task.


removeAllSchedules

public int removeAllSchedules()
Remove all schedules. Return integer code defined by Scheduler.

Specified by:
removeAllSchedules in interface ScheduleOwner

removeSchedule

public int removeSchedule(java.lang.String name)
Remove specified schedule. Return integer code defined by Scheduler.

Specified by:
removeSchedule in interface ScheduleOwner

suspendSchedule

public int suspendSchedule(java.lang.String schedule)
Suspend specified schedule.Return integer code defined by Scheduler.

Specified by:
suspendSchedule in interface ScheduleOwner

resumeSchedule

public int resumeSchedule(java.lang.String schedule)
Resume specified schedule. Return integer code defined by Scheduler.

Specified by:
resumeSchedule in interface ScheduleOwner

syncSchedule

public int syncSchedule(java.lang.String schedule,
                        long delayMillis)
"Synchronize" specified schedule. Return integer code defined by Scheduler.

Specified by:
syncSchedule in interface ScheduleOwner

setDefaultSampleScheduleName

public void setDefaultSampleScheduleName(java.lang.String name)
Set default sample schedule name


createTask

public ScheduleTask createTask(java.lang.String name,
                               ScheduleSpecifier schedule,
                               ScheduleOwner owner)
createTask is a factory method to make new schedule tasks by name. Subclasses may add new types of schedules by overriding createTask, calling super, and checking the return for null (return value if not null) before checking the name argument for one of the new added types.


setAttributes

public void setAttributes(ServiceAttributes attributes)
Set the ServiceAttributes object for this service.

Specified by:
setAttributes in interface DeviceServiceIF
Overrides:
setAttributes in class DeviceService

enableSummary

public void enableSummary()
Enable data summary generation.

Specified by:
enableSummary in interface Instrument

disableSummary

public void disableSummary()
Disable data summary generation.

Specified by:
disableSummary in interface Instrument

summaryEnabled

public boolean summaryEnabled()
Return true if summary generation is enabled.

Specified by:
summaryEnabled in interface Instrument

shutdown

public byte[] shutdown()
Stop the service. Note that this method should NOT be synchronized, since must be able to shut down a service that is currently being sampled.

Specified by:
shutdown in interface Device
Overrides:
shutdown in class DeviceService

startDeviceAccess

protected void startDeviceAccess()
                          throws java.lang.Exception
Add to list of threads that are accessing instrument device. This thread list will be accessed by shutdown() and suspend() in order to quickly terminate threads that are interacting with the device.

Throws:
java.lang.Exception

endDeviceAccess

protected void endDeviceAccess()
Remove from list of threads that are accessing instrument device.


interruptDeviceAccess

protected void interruptDeviceAccess(int waitMsec)
Interrupt any threads that are accessing the device, optionally wait specified time for thread to die after interrupt. caller is responsible for setting service state.


shutdownInstrument

protected java.lang.String shutdownInstrument()
                                       throws java.lang.Exception
Perform any instrument-specific shutdown actions and optionally return a human-readable message (e.g. noting caveats, status, etc); the returned message is purely for human operator.

Throws:
java.lang.Exception

sleepingUntil

public final long sleepingUntil(ScheduleTask task)
If execution thread of specified task is sleeping, return time at which it will resume; otherwise return 0.

Specified by:
sleepingUntil in interface ScheduleOwner

snooze

protected final void snooze(int seconds)
                     throws java.lang.InterruptedException
Put thread to sleep for specified seconds, in such a way that cpu is guaranteed to be awake when the thread is done sleeping. Throw InterruptedException if the thread is interrupted during Thread.sleep().

Throws:
java.lang.InterruptedException

setClock

public void setClock(long t)
              throws NotSupportedException
Set device's clock to specified time. DEPRECATED - use setClock() with no arguments.

Specified by:
setClock in interface Instrument
Throws:
NotSupportedException

setClock

public void setClock()
              throws NotSupportedException
Set device's clock to current time; can throw NotSupportedException.

Specified by:
setClock in interface Instrument
Throws:
NotSupportedException

acquire

protected abstract SensorDataPacket acquire(boolean logSample)
                                     throws NoDataException
Acquire data sample from instrument, process it, and put data into output.

Throws:
NoDataException

initInstrumentPowerPolicy

protected abstract PowerPolicy initInstrumentPowerPolicy()
Return initial value of instrument power policy.


initCommunicationPowerPolicy

protected abstract PowerPolicy initCommunicationPowerPolicy()
Return initial value of instrument communication power policy.


initInstrumentStartDelay

protected abstract int initInstrumentStartDelay()
Return instrument startup time in millisec.


initCurrentLimit

protected abstract int initCurrentLimit()
Return DPA current limit (milliamp).


initSampleTerminator

protected abstract byte[] initSampleTerminator()
Return instrument's sample terminator characters.


initPromptString

protected abstract byte[] initPromptString()
Return instrument's "prompt" characters.


initMaxSampleBytes

protected abstract int initMaxSampleBytes()
Return maximum number of bytes in a instrument data sample.


createDefaultSampleSchedule

protected abstract ScheduleSpecifier createDefaultSampleSchedule()
                                                          throws ScheduleParseException
Return default sampling schedule.

Throws:
ScheduleParseException

getInstrumentServiceBlock

public InstrumentServiceBlock getInstrumentServiceBlock()

Retrive the FunctionBlock used for specialized processing of acquired samples. By default it will return a SummaryBlock if the following conditions are met:

Returns:
The JDDAC FunctionBlock used for specialized processing of aquired samples.

setInstrumentServiceBlock

public void setInstrumentServiceBlock(InstrumentServiceBlock instrumentServiceBlock)
Parameters:
instrumentServiceBlock - The JDDAC FunctionBlock used for specialized processing of aquired samples.

canSummarize

public boolean canSummarize()
A check method to indecate if this instrument service can produce summary packets. This is a bit of hack but should work for the MTM4 deployment.

Returns:
true if the BaseInstrumentService can produce SummaryPackets. false otherwise.


Copyright © 2003 MBARI.

The Monterey Bay Aquarium Research Institute (MBARI) provides this documentation and code "as is", with no warranty, express or implied, of its quality or consistency. It is provided without support and without obligation on the part of MBARI to assist in its use, correction, modification, or enhancement.