ptolemy.actor.lib.io.comm
Class SerialComm

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.actor.lib.io.comm.SerialComm
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class SerialComm
extends TypedAtomicActor

Send and receive bytes via the serial port. The serial port and baud rate are specified by parameters.

This actor requires that the RXTX serial port API be installed from http://rxtx.qbang.org/wiki/index.php/Download.

This actor can be used in most domains, but the parameters must be chosen carefully to match the domain semantics. This actor sets up a listener to the serial port, and when input data appears on the serial port, it calls fireAtCurrentTime() on the director. This behavior is useful in the DE domain, for example (although you will likely have to set the stopWhenQueueIsEmpty parameter of the director false).

Some domains, however, such as SDF, ignore the fireAtCurrentTime() call. Such domains, will typically fire this actor when its outputs are needed. Consequently, for use in such domains, you will likely want to set the blocking parameter of this actor to true. When this parameter is true, the fire() method first reads data on its input port (if any) and writes it to the serial port, and then blocks until sufficient input data are available at the serial port. It then reads that data from the serial port and packages it as a byte array to produce on the output of this actor.

The inputs and outputs of this actor are unsigned byte arrays. The minimumOutputSize parameter specifies the minimum number of bytes that are produced on the output in each firing. The maximumOutputSize parameter specifies the maximum number of bytes that are produced on the output on each firing. If these two numbers are equal, then when a firing produces data, it will always produce the same amount of data. Otherwise, the amount of data produced is nondeterministic.

The discardOldData parameter, if true, indicates that the fire() method may discard bytes. In particular, if there are more than maximumOutputSize bytes available on the serial port, then all but the most recent maximumOutputSize will be discarded.

For example, if you wish for this actor to produce only the most recent byte read on the serial port each time it fires, set discardOldData to true, blocking to true, and both minimumOutputSize and maximumOutputSize to 1.

If after firing there are additional data available on the input port, then the fire() method will call fireAtCurrentTime() on the director before returning.

FIXME: This actor has some key limitations.

Since:
Ptolemy II 2.0
Version:
$Id: SerialComm.java 57040 2010-01-27 20:52:32Z cxh $
Author:
Winthrop Williams, Joern Janneck, Xiaojun Liu, Edward A. Lee (Based on my RxDatagram, and on the IRLink class writen by Xiaojun Liu)
See Also:
Serialized Form
Accepted Rating:
red (winthrop)
Proposed Rating:
red (winthrop)

Nested Class Summary
private static class SerialComm.PortListener
          The SerialPort class allows only one listener
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  boolean _blocking
           
private  boolean _directorFiredAtAlready
           
private  boolean _discardOldData
           
private  int _maximumOutputSize
           
private  int _minimumOutputSize
           
private static gnu.io.SerialPort _serialPort
           
private static SerialComm.PortListener _serialPortListener
           
 Parameter baudRate
          The baud rate of the serial port, such as 19200 (the default), 19200, or 115200, for the serial port.
 Parameter blocking
          Indicator of whether fire method is blocking.
 TypedIOPort dataReceived
          The output port for data that has been received by the serial port.
 TypedIOPort dataToSend
          The input port for data to be sent to the serial port.
 Parameter discardOldData
          Indicator of whether to discard old data.
 Parameter maximumOutputSize
          The maximum number of bytes produced in each firing on the output.
 Parameter minimumOutputSize
          The minimum number of bytes that will be read from the serial port and produced on the output.
 StringParameter serialPortName
          Attribute giving the serial port to use.
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
SerialComm(CompositeEntity container, java.lang.String name)
          Construct a SerialComm actor with the given container and name.
 
Method Summary
 void attributeChanged(Attribute attribute)
          If the parameter changed is serialPortName, then hope the model is not running and do nothing.
 void fire()
          If input data is available at the serial port, read it and produce it as a byte array at the output port of this actor; if a token is available at the input port of this actor, consume it and send the bytes contained by this token to the serial port.
 void preinitialize()
          Perform resource allocation for this actor.
 void stop()
          Override the base class to stop waiting for input data.
 void stopFire()
          Override the base class to stop waiting for input data.
 void wrapup()
          Close the serial port.
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, clone, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, initialize, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, postfire, prefire, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, terminate
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, postfire, prefire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, initialize, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

baudRate

public Parameter baudRate
The baud rate of the serial port, such as 19200 (the default), 19200, or 115200, for the serial port. This has type integer and defaults to 19200.


blocking

public Parameter blocking
Indicator of whether fire method is blocking. If true, fire() waits until minimumOutputSize bytes have arrived. The type is boolean with default false.


dataToSend

public TypedIOPort dataToSend
The input port for data to be sent to the serial port. This port has type unsigned byte array.


dataReceived

public TypedIOPort dataReceived
The output port for data that has been received by the serial port. This port has type unsigned byte array.


discardOldData

public Parameter discardOldData
Indicator of whether to discard old data. If this is true, then the fire() method will read all available data, but produce no more than maximumOutputSize bytes on the output, discarding the rest. This is a boolean that defaults to false.


maximumOutputSize

public Parameter maximumOutputSize
The maximum number of bytes produced in each firing on the output. This is an integer that defaults to MaxInt. It is required to be at least as large as minimumOutputSize


minimumOutputSize

public Parameter minimumOutputSize
The minimum number of bytes that will be read from the serial port and produced on the output. This is required to be a strictly positive integer, and it defaults to 1.


serialPortName

public StringParameter serialPortName
Attribute giving the serial port to use. This is a string with the default being the first serial port listed by the javax.comm.CommPortIdentifier class. If there are no serial ports available (meaning probably that the javax.comm package is not installed properly), then the value of the string will be "no ports available".


_serialPort

private static gnu.io.SerialPort _serialPort

_serialPortListener

private static SerialComm.PortListener _serialPortListener

_maximumOutputSize

private int _maximumOutputSize

_minimumOutputSize

private int _minimumOutputSize

_discardOldData

private boolean _discardOldData

_blocking

private boolean _blocking

_directorFiredAtAlready

private boolean _directorFiredAtAlready
Constructor Detail

SerialComm

public SerialComm(CompositeEntity container,
                  java.lang.String name)
           throws NameDuplicationException,
                  IllegalActionException
Construct a SerialComm actor with the given container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the actor cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
If the parameter changed is serialPortName, then hope the model is not running and do nothing. Likewise for baudRate.

Overrides:
attributeChanged in class NamedObj
Parameters:
attribute - The attribute that changed.
Throws:
IllegalActionException - Not thrown in this base class.

fire

public void fire()
          throws IllegalActionException
If input data is available at the serial port, read it and produce it as a byte array at the output port of this actor; if a token is available at the input port of this actor, consume it and send the bytes contained by this token to the serial port. If blocking is true, then after writing the input data to the serial port, stall the calling thread until there are input data available at the serial port. The minimumOutputSize specifies the minimum number of bytes that must be available.

Before returning, if data is sent to the serial port, this method calls flush(). However, the flush() method does not wait for the hardware to complete the transmission, as this might take many milliseconds (roughly 1mS for every 10 bytes at 115200 baud). Consequently, the data will not have been completely produced on the serial port when this returns.

If data is still available on the serial port when this returns, then before returning it calls fireAtCurrentTime() on the director.

Before this method exits, it will either call fireAtCurrentTime() on the director (if there is already enough input data on the serial port to be able to fire again and produce the requisite number of outputs), or it will start a thread that will wait until there is enough data and then call fireAtCurrentTime().

Specified by:
fire in interface Executable
Overrides:
fire in class AtomicActor
Throws:
IllegalActionException - Not thrown in this base class.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Perform resource allocation for this actor. Specifically, open the serial port (setting the baud rate and other communication settings) and then activate the serial port's event listening resource, directing events to the serialEvent() method of this actor.

Specified by:
preinitialize in interface Initializable
Overrides:
preinitialize in class AtomicActor
Throws:
IllegalActionException - Not thrown in this base class.

stop

public void stop()
Override the base class to stop waiting for input data.

Specified by:
stop in interface Executable
Overrides:
stop in class AtomicActor

stopFire

public void stopFire()
Override the base class to stop waiting for input data.

Specified by:
stopFire in interface Executable
Overrides:
stopFire in class AtomicActor

wrapup

public void wrapup()
            throws IllegalActionException
Close the serial port. This method is invoked exactly once per execution of an application. None of the other action methods should be be invoked after it.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class AtomicActor
Throws:
IllegalActionException - Not thrown in this base class.