DmhCppClient - a DMH Client Library for Multi-Threaded C++

The DmhCppClient is a message system client library that provides high-level methods for sending and receiving binary or text messages, with either send-and-reply synchronous-style interactions, or higher performance asynchronous-style interactions.  Additional threads are used to implement buffered sending, as well as asynchronous receiving, so there is not a need for the application to support an event loop, or a need to integrate the library code into an event loop.  The DmhCppClient is designed for modern C++ applications,  and uses STL classes in order to provide convenient, automatic memory management.

The DmhCppClient library is available for Windows 32 bit and 64 bit applications, as well as POSIX platforms such as Linux.  The Windows version uses an open source POSIX threads library which is distributed per the terms of the GNU Library License, and source code is available at http://sourceware.org/pthreads-win32/ or from Hume Integration.

Message exchanges are typically directed to application servers such as the Hume Integration Datahub, or the dmh_SQLsrv persistent database interface.  The DMH message system is remarkably easy to use with these DMH server processes because the messages are typically SQL or Tcl text commands that are directly interpreted by the receiver.   To extend this ease of use to the C++ client, functions are provided to parse Tcl list text strings,  or to create Tcl list text strings from string elements.  The library can also be used to exchange binary messages which can be useful for equipment controller and device integration.

Feature Summary


User Guide


The DmhCppClient library builds on the Hume DMH Multi-Threaded C library which is described separately.   The DmhCppClient library is provided as source code files which are added to your application, where they are compiled with the release or debug configurations of your project.  This approach prevents having problems with STL template based data items or C++ objects being passed across DLL boundaries.

The DmhCppClient source code files include:

The DmhCppClient files are distributed with the Hume C++ SECS Equipment .zip archive named  SecsEquipCpp<xxx>.zip. where <xxx> has values such as Win32, Win64, Linux_i686, or Linux_x86_64 to indicate the platform.  If you received the DMH software on CDROM, this archive is in the subdirectory LAN_IMAGE.   The distributions also contain DLLs for the DMH Multi-Threaded C library and the Pthreads library.  The Win64 distribution has example project files and 32bit and 64bit DLLs built with Visual Studio 2010, and the Win32 distribution has project files for VS2005 and 32 bit binaries that are built with VS2005.

The library is a client library that connects to a DMH message system server such as Hume's Tcl/Tk Datahub application, or the Java Datahub.   The library is is designed to successfully interoperate with versions of the DMH software running on a wide variety of platforms which provides the ability to easily bridge computer systems, application processes, and programming languages.

Installation

For development you will want the have the Hume Datahub SDK installed on your computer system or on an easily accessible host.  This provides you with the Datahub program to run as your DMH server.  The SDK installation also installs the documentation you are now reading.   A developer will typically unzip the downloaded DMH85 SDK .zip archive in a temporary place, and run the setup program accepting the SDK installation defaults.

Installation of the DmhCppClient consists of extracting files in the SecsEquipCpp<xxx> archive to a directory or directories of your choice.   If you are interested in using the DMH message system, but not using the C++ SECS features, you will typically unzip the archive in a temporary location, and copy just above mentioned files into your project source code directories.  A Windows developer edits his project:
  1. Add the DmhClientCpp.h, and .cpp files to the project 
  2. Add the dmh.h file as a project source file, or tell the C Preprocessor where to find it. 
  3. Add the dmh.lib or dmh64.lib to the project link dependencies.
  4. Copy the dmh and pthread DLLs from the SecsEquipCpp/release or release64 directory to your project release and debug directories.  Release versions of the DMH and Pthreads library are used for both debug and release application builds.

Development

Your design will typically use one instance of a DMH client connection per process.  A single client connection is used for sending and receiving with multiple mailboxes simultaneously from multiple threads.  More than one instance of a client connection per process is only needed if you wish to communicate directly with multiple DMH servers.  You should not use multiple connection instances within a single process to communicate with a single DMH server.

If you are not familiar with the DMH message system, you may want to read the mbx document which is usually installed at /usr/local/htm85/mann/mbx.html.  Your application acts a DMH message system client, and attaches to a running DMH server.  Once you are connected to the DMH system, you can exchange messages with the server and other attached client processes.

To get started, you only need to know the hostname where the DMH server is running, and the DMH Groupname that has been assigned to the server.   If you execute a Datahub process on your system from the command line, for example:

     $ /usr/local/bin/datahub eof &
you will start a DMH server running on your host, with the default DMH groupname of "mbx".  The Windows and Linux Datahub SDK installations feature Start Menu program items for running a Datahub as a DMH server with the default DMH groupname of "mbx" and the SQL command mailbox of "DATAHUB".

The usual application design, and the one that provides the best performance,  is to connect to the DMH server during initialization, and to use this connection during the life of the application.  Construct an instance of the DmhCppClient class to have a DMH connection. The init( ) function is subsequently used to connect to the server.  The server's hostname and groupname are provided as arguments to the init( ) method.  If the application disconnects from the server, the init( ) command can be used again to restore the connection.

Error Handling

A long running program such as an automation application needs to handle intermittent errors with network outages or server shutdowns.

Here is a summary of the kinds of errors that the DMH functions will report.  When you make a method call that requires a DMH server connection, and you do not have one, the method call will return "No DMH server connection".  If you use an improper mailbox name such as one with whitespace in it, the method call will return a string such as, "mailbox name must contain only ASCII letters, digits, -, _, ., !, :, or @".   These are the two main errors when initiating a method call.   Most of the DMH  method calls are then processed asynchronously.  In other words, your method call returns, and the message communication you initiated happens as events are processed.  An error that occurs during event processing results in an Error event occurring.  You do not need to write an Error event handler,  but you probably should to communicate to the users of your program if an error occurs.  When the Error event occurs, in most cases, the Disconnected event will also occur.  You can place logic in your Disconnected( ) event handler to initiate recovery and resume logic, exit the program, etc.

Sending and Receiving - Basics

The programming model of the DMH message system is that you send a message to a destination mailbox.  When sending the message, you can optionally specify the name of a second mailbox for the recipient to send a reply message to.  Usually you send a message to an application logic server such as a Datahub.  The message is usually SQL,  Tcl, or VFEI command text that the recipient executes.  If the sender has designated a reply mailbox, the result of executing the command is sent to the reply mailbox.

Lets discuss sending without asking for replies using the send( ) method  or its equivalent, the put( ) method .  These methods are used to send text messages, and the binsend() method is used in a similar fashion to send binary messages.  For example,  suppose you are integrating a barcode reader.  When data is read from the barcode reader device, your code is supposed to update a record in a Datahub table.  You will send messages without asking for reply messages - if there is a system shutdown or communication failure, your application will know from the Disconnected event.  This is more efficient than asking for a reply message at every barcode read.

// update the latest barcode input record in table barcode_reader at the Datahub
char *HUB="DATAHUB";
char message[200];
sprintf(message, "update barcode_reader set data_in='%s' where device_id='%s'",
           newdata, myID);
dmh.send(dmh, HUB, message);

When you send a message without waiting for a reply, it is referred to as an asynchronous send.

Often, you will want to send a message to obtain reply data.  The most convenient method to use for text messages is the doXact( ) method.  The binXact() method is similar and is used for binary messages.  This method will take care of specifying and using a unique mailbox for your reply message, and it will take care of managing a timer in case a reply message is not forthcoming.

Sending and Receiving - Advanced

If your application needs to receive unsolicited messages from other processes, you use the whenever( ) method to setup asynchronous receiving of text messages, and the binWhenever() method for binary messages.  When an unsolicited message is received, your specified Whenmsg event handler or binary message event handler is called.   By convention you should use mailbox names for receiving that end in _SQL if SQL messages are expected, and _RPC if Tcl messages are expected.   There is no limit to the number of mailboxes that you use for receiving, but the design convention is that you use unique names based on the server function(s) provided.  There should be only one receiving process per mailbox name in a DMH group.  You may wish to create a unique mailbox name for receiving by basing the name on your hostname - see the method hostname( ).

The whenever( ) and the binWhenever() methods are used for ongoing receiving - your application will continue to receive the messages that are sent to your specified mailbox.  The disarm( ) method can be used to stop asynchronous receiving.

The whenmsg( ) and the binWhenmsg() methods are similar to the whenever( ) methods except that they receive only a single message.  If whenmsgAgain( ) is executed from your receiving event handler, then the software is re-armed to receive the next message.  So the combination of whenmsg( ) with whenmsgAgain( ) called in the receiving event handler is equivalent to using the whenever( ) method.

Lets revisit the doXact( ) method.  In some situations, you may want higher performance by sending messages and collecting the replies asynchronously, instead of waiting for each reply before sending the next message.  You do this by setting up one or more reply mailboxes and arming them for receiving using the whenmsg( ) or whenever( ) methods.  Instead of using doXact( ) use the send( ) command and specify the reply mailbox argument.  Typically a high performance application will create a small number of unique mailbox names for replies, and re-use them.  If you are creating unique mailboxes for each reply message, use the closeMailbox( ) method when you are done with each one, to recover resource usage.

Event Handling Notes

Your application should not "live" inside of your event handling code.  There are some rules concerning what your application can do in a receiving callback. In general, your application does not receive new asynchronous messages while your receiving callback logic is executing. So the usual application design for the callback logic is to return fairly quickly without performing lengthy computation. If your callback logic executes doXact(), binXact(), or timedReceive() then receiving of asynchronous messages is resumed during the execution of your callback. As your callback continues to execute, in the general case, there will not be re-entrant execution of your callback for receiving another message to the same mailbox. In other words, the whenever() and whenmsgAgain() logic guard against re-entrant execution of your callback logic for receiving to the same mailbox as the currently executing callback. It is possible to bypass the re-entrancy safeguard by calling whenmsg() from your callback to re-arm the callback. This is not a recommended practice.

A summary of the above paragraph; if you cause asynchronous receiving to be resumed during callback execution by using doXact() or similar methods, you should only be using whenever() or whenmsgAgain() to re-register the executing callback for the next reception. Otherwise you will have re-entrant execution of your callback.

Be careful with the Trace event.  If you turn on a lot of tracing and are exchanging long messages, your application will be manipulating huge amounts of string data.

International Character Sets

Multibyte UTF-8 character sequences are used by the DMH to represent International characters.  The API for the DMH software uses these character sequences since they are compatible with the usual single character ASCII strings used by most applications.  UTF-8 strings can be manipulated with all the usual C language functions because they do not use the null character as data.  Instead, the byte sequence 0xC0 0x80 is used to represent an imbedded NULL.

When declaring database tables to hold international text, base the VARCHAR( ) sizes on UTF-8 byte counts, not on the number of characters.  In the most conservative case,  you need to allow 3 bytes per displayed character.

Datahub table varchar fields are compatible with UTF-8 sequences representing ordinary International text.  There are issues with storing UTF-8 sequences of arbitrary binary data which can be avoided or worked around:

Signal Handling for non-Windows Systems

The DMH software creates a sending thread and a receiving thread. These threads are masked from the asynchronous signals SIGUSR1, SIGUSR2, SIGINT, SIGALM, and SIGHUP. Your application can use or ignore these signals without worrying about integration with the DMH software. The DMH software does not change the signal handling status of any thread making a library call. When your software is executing in a DMHWhenmsgProc as a result of a message being received, it is the DMH receiving thread that is executing your callback method. If you change the signal handling status of this thread in your callback logic, you should restore its original state before returning.

Termination

When your application is shutting down, you may call the disconnect() method or just destroy your DmhCppClient instance(s). The destructor will disconnect gracefully from the DMH server and free resources used by your connection.  Practically speaking the DMH server routinely takes care of situations where clients leave ungracefully, but proper software manners are encouraged.

Miscellaneous Notes

An actual network connection to the DMH server is not attempted until init() is called.

The programming model is that you will not have more than one connection to a particular DMH server.  It is typical to have only one DMH connection per application process and to use it for the life of the application.  Communication across DMH groups can be accomplished by using multiple connection instances, each connected to a different DMH Group.

There should be only one reader per mailbox name in a given DMH group.

The library software is able to use and resolve DMH groupname aliases as described in the online Tcl documentation.  Groupname aliases are resolved at the DMH server and not at the client.

Mailbox Naming rules:



DmhCppClient API Reference

 
DmhCppClient "Properties"
Property Access Description
const char *getClientID(void) The DMH server assigns a unique string to each client for identification purposes. This value is a readonly runtime value providing the server's ID string or an empty string if a connection has not been established. 
int getDefaultTimeout(void)

int setDefaultTimeout(int)

The default timeout interval for send and reply transactions, or timed receive invocations.   In seconds - the default value is 30.  Settable range: 1 - 86399.
const char *getDescription(void)

void setDescription(const char *)

One of the features of the Tcl/Tk DMH Status Window is to provide an action for identifying connected clients. The default description provided for a C++ DMH client is similar to "<hostname>: C DMH client". You are able to provide your own description string for your application.
const char *getMhGroup(void) The MhGroup property is a readonly runtime value indicating the hostname:port  of the DMH server when connected, else NULL.  Hostname is the server's idea of his hostname which may be different from the hostname that was specified at the client.


int getState(void)

 
 
 
 
 

 

The state property is a read-only value available at runtime.  The value can be read to determine if a healthy communication connection exists, etc.    Applications will ordinarily use event methods and not poll the state property value.  The transient and error states do not last long, so testing for the values DmhCppClient::DMHSTATE_DISCONNECTED or DmhCppClient::DMHSTATE_CONNECTED is the most common scenario. 
  DMHSTATE_DISCONNECTED=0            disconnected
  DMHSTATE_RESOLVINGHOSTNAME=4       hostname is being resolved
  DMHSTATE_CONNECTION_SETUP=6        connection setup in progress 
  DMHSTATE_CONNECTED=7               healthy connection exists
  DMHSTATE_CLOSE_IN_PROGRESS=8       connection close in progress
  DMHSTATE_ERROR_CLEANUP=9           a communication error has occurred  
DMHSTATE_PROTOCOL_SETUP=(DMHSTATE_CONNECTED | 0x100);       DMH protocol setup in progress 
int getTracebits(void)

int setTracebits(int)

The Tracebits property controls output of diagnostic data to the Trace event.  This value is used as a bitfield with the bit values controlling the following categories of output:
TRACE_READS=01        data reads 
TRACE_WRITES=02       data writes
TRACE_RECV=04         message receiving
TRACE_SEND=08         message sending
TRACE_LOGIC=16       logic tracing


 
DmhCppClient Callback Events
Event Callback  and Set Method  Description
All callback methods - NOTES
 
 
 
 
 

 

You write your own callback method consistent with the typedef of the callback defined in dmh.h which is the header for the underlying C API.  Then you register it using your DmhCppClient instance.  When the event happens, your callback method is called.  You use the DMHClient callback argument value and the dmh_getClientData() function to get a pointer to your DmhCppClient instance.  To avoid having to manage memory allocations manually, you should not use the DMHClient argument value for any other dmh_*() function calls - use your DmhCppClient instance instead.

class MyClass {

  void someMethod() {
     ...
     dmh->whenever("RECEIVE_MAILBOX", myReceive, this);
     }

  // receiving callback - signature defined in dmh.h
  static void myReceive(DMHClient dc, const char *destbox, const char *replybox, const char *msg, void *clientdata) {
      DmhCppClient *dmh = (DmhCppClient *)dmh_getClientData(dc);
      MyClass instance = (MyClass *)clientdata;

      instance->someOtherMethod();
      dmh->reply("Handled the message in myReceive logic");
      }
};

The above example code is copied from the comments at the end of the DmhCppClient.h file.

void (DMHBinmsgProc) (DMHClient, 
   const char *destinationMailbox,
   const char *replyMailbox, 
   const unsigned char *data, 
   int datalen, 
   void *clientData);
This is the callback signature for receiving binary messages.  A callback that you write is executed by the receiving thread when a  message has arrived.  You can register different callback methods for each destination mailbox using the binWhenmsg or binWhenever methods, described in the next table. 

The destinationMailbox parameter is a mailbox name that your application has specified when initiating receiving.  If the sender of the message indicated a reply mailbox, it is passed as the argument, replyMailbox.  If no reply mailbox has been specified, the replyMailbox argument is an empty string.  The data argument indicates a buffer holding the data of the sent message.  The datalen argument indicates the number of bytes in the buffer.  It is possible to send and receive messages that are 0 length.  The DMH client logic protects you from receiving another message for the destinationMailbox, and re-entering your handler logic until you have returned from the current callback execution. 

When you call the binWhenmsg() method or binWhenever( ) method to setup receiving,  you can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to  pass a pointer to a C++ object, so your receive callback can use the pointer to call a class method. 

void (DMHConnectedProc) (DMHClient)

void connectedProcSet(DMHConnectedProc *);

The Connected event happens after successfully connecting to the DMH server in the wake of the init() method invocation. 
void (DMHDisconnectedProc) (DMHClient)

void disconnectedProcSet(DMHDisconnectedProc *)

The Disconnected event happens when the DMH connection has been closed from any circumstance such as remote closure, communication failure, error, or invocation of the disconnect method.  This event is similar to the Tcl lostserver procedure invocation.  The event may happen more than once if multiple errors are being processed.

void (DMHErrorProc) (DMHClient, int errnum, const char *text)
   

void errorProcSet(DMHErrorProc *)
 
 

The Error event happens when the init() method fails, or there has been communication failure.  In most cases when the Error event happens, the control state will transition to the disconnected state, and the Disconnected event will occur shortly.

Broken connection errors include:

10051  the network is unreachable
10060  Connection has timed out
11053  Connection is aborted due to timeout or other failure
10054  Connection is reset by remote system
10058  Connection has been shutdown
void (DMHShutdownProc) (DMHClient, int *StayAlive)

void shutdownProcSet(DMHShutdownProc *)

A remote request has been received to terminate the process.  If you do not set the StayAlive flag true, the software will cause the application to exit. 
void (DMHTraceProc) (DMHClient, const char *text)

void traceProcSet(DMHTraceProc *)

This event provides diagnostic and debug information per the Tracebit property setting.  Your application needs to avoid creating new DMH activity in the Trace event callback, that in turn causes Trace events.  A cycle of positive feedback is possible which will cause a software fission reaction.
void (DMHWhenmsgProc) (DMHClient, const char *destinationMailbox,  const char *replyMailbox, const char *Data, void *clientData)
 
 
 
 
 
 
 

 

The Whenmsg callback is executed when a  message has arrived.  You can register different callback methods for each destination mailbox using the whenmsg or whenever methods, described in the next table. 

The destinationMailbox parameter is a mailbox name that your application has specified when initiating receiving.  If the sender of the message indicated a reply mailbox, it is passed as the argument, replyMailbox.  If no reply mailbox has been specified, the replyMailbox argument is an empty string.  The data argument is the text of the sent message.  The DMH client logic protects you from receiving another message for the destinationMailbox, and re-entering your handler logic until you have returned from the current callback execution. 

When you call the whenmsg() method or whenever( ) method to setup receiving,  you can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to pass the this pointer to your C++ object, so your receive callback can use the pointer to call methods. 

DmhCppClient methods
METHODS DESCRIPTION
General Comments
 
 
 
 
 
 
 
 
 

 

Many of the method calls return NULL for the usual successful invocation, or an error message that could be logged or displayed to the user.  The most common error message is "No DMH server connection".  This message occurs when using a method that requires a connection and init( ) has not been called successfully, or the DMH connection has been lost.  The methods do not throw exceptions, and you do not need to use try and catch. 

If you use an improper mailbox name such as one with whitespace in it, the method call will return a string such as, "mailbox name must contain only ASCII letters, digits, -, _, ., !, :, or @".   Most of the DMH  method calls are then processed asynchronously.  In other words, your method call returns, and the message communication you initiated happens as events are processed.  An error that occurs during event processing results in the Error event occurring.

void abort(void) Any in-progress send-and-reply or modal wait transactions such as the init( ) method or doXact( ) calls are aborted with return values indicating TIMEOUT.  Invoking the abort method does not affect asynchronous receiving that is setup using the whenmsg( ) or whenever( ) methods.  Has no effect if not connected.
int bin2utf(const unsigned char *bindata, int datalen, 
  std::string &utf)

int utf2bin(const char *utf8, unsigned char *buffer, int buffsize)

These calls are simplified conversion methods for converting between binary codes 0x00 through 0xFF and the UTF-8 strings used by the DMH and Tcl.   The sequence 0xC0 0x80 is used to represent a binary null, so the UTF-8 string representation is compatible with runtime library methods that work with null terminated strings.  These calls are used internally to support the binary messaging features, and are also available for your use.

The call bin2utf converts a binary sequence into a null terminated UTF-8 string.  The return value is the string length (strlen()) plus one for the null terminator byte - in other words the storage needed for the UTF-8 string.  Byte values from 0x01 through 0x7F only need one byte for storage, and other bytes require two.  

The call utf2bin converts a null terminated UTF-8 string into a sequence of bytes.  The conversion is aborted if the input string has invalid UTF-8 sequences, or has sequences that would map outside of the 0x00 through 0xFF range.  The return value is the number of bytes successfully converted.  In general, the output buffer size needs to be as big as the string length (strlen()) of the UTF-8 string.  The method is able to convert a UTF-8 string in place if the string buffer argument is repeated as the second argument.  (You will typically need to cast the argument type, eg., (unsigned char *).

const char *binsend(const char *destinationMailbox, 
  const unsigned char *message, int msglen, const char *replyMailbox)
The binsend method is used to send binary messages.  It is similar to the send method described below which is intended for UTF-8 text messages.

Sends a binary message to a mailbox, optionally with a reply mailbox indicated.   By convention, when a reply mailbox is indicated for a command message sent to a Datahub mailbox or equipment interface mailbox, the command is processed, and a reply message is sent to the reply mailbox. 

Specifying the reply mailbox as a NULL pointer, an empty string, or as the literal text "NULL" is equivalent to not specifying a reply mailbox.

Returns NULL on success, or an error message.  You must be connected to use this call.

const char *binWhenever(const char *receiveMailbox, DMHBinmsgProc *, void *clientData) Registers to receive all messages directed to the specified mailbox.  The messages are passed to the user written callback as binary data.  When the DMHBinmsgProc callback returns, the software re-arms for receiving the next message directed to the specified mailbox.  The disarm( ) method can be used to stop receiving. 

You can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to pass the this pointer of your C++ object, so your receive callback can use the pointer  to call methods. 

You must be connected to use this call.

const char *binWhenmsg(const char *receiveMailbox, DMHBinmsgProc *, void *clientData) Registers for receiving the next available message directed to the specified mailbox as binary data. Calling whenmsgAgain( ) in the BinmsgProc( ) event handling code re-arms the receive registration for the next message.

You can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to pass the this pointer of your C++ object, so your receive callback can use the pointer  to call methods. 

Returns NULL on success, or an error message.  You must be connected to use this call.

int binXact(const char *destinationMailbox, const unsigned char *sendData, 
 int sendDatalen, std::vector<unsigned char> &replyData, int timeoutSeconds = 0, const char *replyMailbox = NULL)
Performs a complete send and reply binary transaction with timeout management.  The reply data is set into the passed by reference replyData vector starting at index 0.  The method creates and manages a unique reply mailbox for the send and reply transaction if the replyBox argument is passed as NULL.  If the timeoutSeconds argument is specified as 0, the DefaultTimeout value is used.  The integer return value is negative for a TIMEOUT or error condition.  Otherwise, it is the number of bytes received in the reply which may be 0.

You can have multiple instances of binXact(), doXact( ) or timedReceive( ) active at a time but not more than one instance for a specified reply mailbox. 

If you specify a replyMailbox, you need to insure that the name you specify is only used by your application.  It is usual to create a unique reply mailbox name, perhaps based on the hostname and process ID, assign it to a variable, and use it repeatedly.

If you are not connected when using this call, the reply value of -1 is returned immediately.  Trace event information can be used to distinguish failure modes.

const char *closeMailbox(const char *boxname) Stop using a mailbox - disarm() receiving if listening, flush() if not empty,  and remove from existence if it exists.  

Returns NULL on success, or an error message.  You must be connected to use this call.

const char *count(const char *boxname, long &ctSent, long &ctRead, long &ctPending)

Returns three numbers, the total count of messages that have been sent to the mailbox, the total count of messages that have been consumed from the mailbox, and last, the current count of pending messages.  A pending message is one that exists in the queue associated with the mailbox, and has not been consumed by reading or flushing.

Returns NULL on success, or an error message.  You must be connected to use this call.

void disarm(, const char *boxname) Un-register the listener from a specified  mailbox.  This call may be used to cancel an earlier whenever( ) or whenmsg( ) call.  If called with a NULL boxname argument, all whenever( ) and whenmsg( ) receiving registrations are canceled.  The abort( ) method will cancel in-progress doXact( ) calls.  Has no effect if not connected.
void disconnect() The counterpart of init( ), disconnects from the DMH server.  The sendFlush( ) method gets called to complete any in-progress sends.  The abort( ) method gets called to end any in-progress transactions.  The disarm( ) method gets called to cancel all receiving.  A thread that was used for listening is caused to exit. A sending thread will be kept alive and possibly re-used. Has no effect if not connected.

DmhCppClient(int traceBits = 0);

virtual ~DmhCppClient(void)

Constructor and Destructor

Use the constructor to create and initialize a DMH connection client instance.  You may optionally pass an initial value for the Tracebits property.  There is no attempt to connect to a DMH server until the init() method is called.

The destructor disconnects gracefully from the server if connected, and then deallocates the memory, threads, and resources used by the connection.
std::string doXact(const char *destinationMailbox, const char *message, int timeoutSeconds = 0, const char *replyMailbox = NULL)
 
 
 
 
 

 

Performs a complete send and reply text message transaction with timeout management.  Creates and manages a unique reply mailbox for the send and reply transaction if the replyMailbox argument is passed as NULL.  If the timeoutSeconds argument is specified as 0, the DefaultTimeout value is used.  The usual reply is the text of the reply message. The string value "TIMEOUT" is returned in case of failure.  You can have multiple instances of doXact( ) or timedReceive( ) active at a time but not more than one instance for a specified reply mailbox.  

If you specify a replyMailbox, you need to insure that the name you specify is only used by your application.  It is usual to create a unique reply mailbox name, perhaps based on the hostname, assign it to a variable, and use it repeatedly.

If you are not connected when using this call, the "TIMEOUT" string value is returned immediately.  Trace event information can be used to show the cause.

const char *flush(, const char *boxname)

 

Empties a mailbox of any pending messages.  A pending message is one that has been sent to the mailbox but has not been consumed.  In other words, a pending message is waiting in a queue associated with the  mailbox name.  Messages are consumed by reading or flushing.

Returns NULL on success, or an error message.  You must be connected to use this call.

int groupnamePort(const char *Groupname)
Used to determine the TCP/IP socket port number that is used by the DMH server to listen for client connections.  Most applications will not have a use for this method since the server socket port is managed by the DMH software. 
const char *hostname(void)
Returns the TCP/IP hostname of the computer that the client software is executing on.  The name is guaranteed to be stripped of domain information, and imbedded white spaces which are not valid in hostnames, are seen as delimiters of the first token.

 
 

  const char *init(
const char *groupname = NULL,
const char *serverHostname = NULL)
 
 
 
 
 
 
 

 

Performs the initial connection to the DMH message server.  The default groupname is "mbx" and the default server hostname or IP Address string is the computer system that the client software is running on.  The connection will be setup or an error result will be obtained before returning.

init errors include

10051  the network is unreachable
10060  Connection has timed out. This error indicates that the remote host may not be online.
10061  Connection attempt is refused. 
10061  Connection is forcefully rejected.
The remote host is online and reachable, but there is not a DMH server at the specified group or port. 
11001  Hostname not found (DNS authoritative).  This error may indicate an improperly spelled hostname, or a hostname that is not known to your name server.
11002  Hostname not found (non-authoritative name resolution).  This error may indicate that your name server is down.
If the connection succeeds, the return value is NULL, otherwise an error message is returned  indicating why the initialization failed. 

When the initialization is successfully completed, the Connected event is fired.  If init fails, depending on how the init call fails, the Error event may fire. 

If the connection to the DMH server is ever lost, the Disconnected event is fired.

Returns NULL on success, or an error message. 

static void listAppend(std::string &list,
const char *e1,
const char *e2 = NULL,
const char *e3 = NULL,
const char *e4 = NULL,
const char *e5 = NULL,
const char *e6 = NULL);

Append one to 6 elements to string text formatted as a list which is passed by reference.   The result output uses whitespace or {surrounding braces} to delimit elements of the list.
 
static std::string listElement(const char *listText, int index1, int index2 = -1, int index3 = -3);

static std::string listElement(const string &listText, int index1, int index2 = -1, int index3 = -3);


static int listElement(const char *listText, std::string &element, int index1, int index2 = -1, int index3 = -1)

static int listElement(const string &listText, std::string &element, int index1, int index2 = -1, int index3 = -1)
This method is similar to the lindex command of Tcl.  It will parse listText and return the specified element.  Arguments index2 and index3 may be used to indicate that parsing of the list should continue up to two additional levels as a nested list structure.   If a specified index is out of bounds, an empty string is returned. 

The first call signature returns the element text as a string or if an invalid list is parsed, an empty string is returned.  

The second form of the method uses a string value passed by reference to return the element text.  The integer return value is 0 for success and negative if the input list cannot be parsed.
static std::string listJoin(int argc, const char *argv[]);

static std::string listJoin(std::vector<std::string> &sv);
Joins together strings as list elements forming a result string that is a list.  Braces are added as needed to delimit empty elements, or to delimit special character sequences involving backslashes , square brackets, etc. 
static int listSplit(const char *listText, std::vector<std::string> &elements)

static int listSplit(const string &listText, std::vector<std::string> &elements)
The listSplit( ) class method parses a string formatted as a list into a vector of string elements.  The method understands the usage of quotes, braces and backslash sequences.  Not all strings are valid lists.  The return value is 0 on success.  Failure occurs when there are unmatched braces, unmatched quotes, or non-whitespace following braces or quotes in which case the return value is negative.
const char *product() If this API is implemented for another product, a different string should be returned in case the using software needs to know the difference. The Hume DMH software returns a two element list with "DMH" as the first element, and a Copyright message as the second element.
const char *put(const char *destinationMailbox, const char *message) The put( ) method is equivalent to send( ) when specifying NULL as the replyMailbox
Returns NULL on success, or an error message. 
const char *putr(const char *destinationMailbox, const char *replyMailbox, const char *message) The putr( ) method is equivalent to send( ) with specifying a replyMailbox.
Returns NULL on success, or an error message. 
std::string receiveList(void); Returns a list of the mailboxes for which there are waiting receivers.  The return value does not show mailbox names that have in-progress whenmsg callbacks.  This command may be useful for debugging, and it is not used in a typical application.  The result is an empty string when you are not connected.
const char *reply(const char *message); An enhanced performance send for the scenario of sending a reply to an inbound message to the reply mailbox specified with the received message from within the message handling callback code.  In most circumstances, there is only a very slight performance benefit to be gained by using this call.  The reply and the indication to continue receiving are sent to the DMH server in the same network packet after the receiving callback returns.  Returns NULL for success.
const char *send(const char *destinationMailbox, const char *message, const char *replyMailbox = NULL);
 
 

 

Send a message to a mailbox, optionally with a reply mailbox indicated.   By convention, when a reply mailbox is indicated for a command message sent to a Datahub mailbox or equipment interface mailbox, the command is processed, and a reply message is sent to the reply mailbox. 

Specifying the reply mailbox as a NULL pointer, an empty string, or as the literal text "NULL" is equivalent to not specifying a reply mailbox.

Sending to the mailbox name "TRACE" sends the message to the DMH Server Trace Facility.

The send method corresponds to the Tcl mbx put and mbx putr commands. 

Returns NULL on success, or an error message.  You must be connected to use this call.

void sendFlush(void) When you send messages, the calls return immediately and the messages are queued for sending. Since TCP/IP is relatively fast, the messages are transferred into the network layer fairly quickly. If you want to block until all of the pending send data is written to the network layer by the sending thread, call sendFlush.
std::string serverStatus(void)
 
 
 
 
 

 

Returns a list containing the information presented in the Tcl DMH status window.  The information can be parsed by the application to determine status information on every mailbox that is currently in use.  This command may be useful for debugging, and is not used by ordinary applications.

The first element of the list is a list of 5 elements:
{ hostname:port messagesReceived messagesSent messagesQueued tcl_version }

Subsequent elements in the list are lists of four or five elements:
{ mailboxname countIn countOut countPending [readerHandle] }

Additional elements may exist in the list if there are DMH clients that are not currently waiting to receive messages.  These elements are formatted as:
{{{no whenmsg pending}} - - - readerClientID}

You must be connected to use this call.

std::string timedReceive(const char *receiveMailbox, int timeoutSeconds = 0);
Waits for a message to be received in the specified mailbox.  If the call succeeds,  the return value is the message data.  If the call fails, the return value is the literal string "TIMEOUT".   If you are not connected, the call fails immediately with the return value "TIMEOUT".  Trace event information can be used to show the TIMEOUT cause.  If the timeoutSeconds argument is passed as 0, the DefaultTimeout value is used.
const char *version(void) Returns a two element list consisting of the DMH protocol version, and the library component configuration management Id string. Current software returns the "1.3" to  as the first element to indicate compatibility with DMH protocol version 1.3.
const char *whenever(const char *receiveMailbox, DMHWhenmsgProc *, void *clientData = NULL)
Registers to receive all messages directed to the specified mailbox.  When the DMHWhenmsgProc callback returns, the software re-arms for receiving the next message directed to the specified mailbox.  The disarm( ) method can be used to stop receiving. 

You can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to pass the this pointer of your C++ object, so your receive callback can use the pointer  to call methods. 

You must be connected to use this call.

const char *whenmsg(const char *receiveMailbox, DMHWhenmsgProc *, void *clientData);
Register for receiving the next available message directed to the specified mailbox.  Calling whenmsgAgain( ) in the DMHWhenmsgProc( ) event handling code re-arms the receive registration for the next message.

You can optionally specify the clientData argument to be saved and passed  to your callback at the time a message arrives.  A typical use would be to pass the this pointer of your C++ object, so your receive callback can use the pointer  to call methods. 

Returns NULL on success, or an error message.  You must be connected to use this call.

const char *whenmsgAgain(void) The whenmsg( ) method methods as a one-shot.  In other words, receiving is stopped after receiving one message.  Calling the whenmsgAgain() method from the receive handler re-registers to receive the next message.

Returns NULL on success, or an error message.  You must be connected to use this call.


 


License Terms

Subject to Change Without Notice

This is licensed and supported software.
©Copyright 2011, Hume Integration Software
All Rights Reserved

The Hume C++ DMH client software is licensed for development and runtime use at no additional charge for computers that are licensed for development use of the Hume Integration Datahub SDK or runtime use of the Hume C++ SECS libraries.   Hume Integration is also pleased to offer separate runtime licenses for using the C++ DMH client software on other computer systems .

Document Version

Date of last revision: $Date: 2011/04/27 19:01:46 $