Header Definition:  DigioBs2Api.h
/*******************************************************************/
/*                                                                 */
/* File Name:   DigioBs2Api.h                                      */
/*                                                                 */
/* Description:                                                    */
/*                                                                 */
/*    This DLL provides a simple interface for accessing           */
/*    a Parallax BS2 Stamp device over a RS-232 link.  (The device */
/*    must be preprogrammed with special firmware from Kadtronix.) */
/*                                                                 */
/*    The DLL exports methods for reading and writing command      */
/*    strings.                                                     */
/*                                                                 */
/*    Client applications use the exported methods from the        */
/*    CDigioBs2Api class to identify and access external           */
/*    BS2 device(s).  A new instance of the class must             */
/*    be created for each device being accessed.                   */
/*                                                                 */
/*    Communication to the BS2 target device is implemented via    */
/*    message packets.  A command packet has the following format: */
/*                                                                 */
/*                                                                 */
/*      Command Message Format (from PC to target):                */
/*                                                                 */
/*        Name  Size  Description                                  */
/*        ----  ----  -----------                                  */
/*        Len    1    Number of bytes to follow                    */
/*         ID    1    Command identifier                           */
/*        Cmd    n    Message contents (n = Len - 1)               */
/*                                                                 */
/*                                                                 */
/*      Response Message Format (from target to PC):               */
/*                                                                 */
/*        Name  Size  Description                                  */
/*        ----  ----  -----------                                  */
/*         ID    1    Response identifier (= cmd.ID + 20)          */
/*        Rsp    n    Message contents (no. bytes = Len)           */
/*                                                                 */
/*                                                                 */
/*    (Note:  The BS2 device echoes each received character back   */
/*    to the PC.  Receive handling in the DLL automatically        */
/*    attempts to "filter" these extra characters from the data    */
/*    stream, relieving the host application from having to        */
/*    perform this additional processing.                          */
/*                                                                 */
/*                                                                 */
/*                                                                 */
/* Revision History:                                               */
/*                                                                 */
/*    Name              Date       Description                     */
/*    ----              ----       -----------                     */
/*    K.Delahoussaye    06/20/04   Initial version                 */
/*                                                                 */
/*******************************************************************/
#ifndef DIGIOBS2
#define DIGIOBS2
#include "windows.h"
//
// Notes:
// -----
// 
// This DLL provides the client application an easy method for accessing
// a BS2 Stamp device over RS-232 link, while hiding the details
// of the implementation.
//
// The module was built using Microsoft Visual C++, 6.0 as a Win32, 
// non-MFC DLL.  Since there is no dependence on the Microsoft 
// Foundation Class (MFC), there is no need to copy additional MFC 
// DLLs to your Windows system folder.  Also, no dependence on MFC
// means the size of the DLL itself is minimal.  (Although the DLL
// does not internally use the MFC, the client application is not
// restricted.  Exported functions in the DLL may be called by either
// MFC or non-MFC applications.)
//
// The client application may link implicitly or explicitly with the
// DLL.  In explicit linking, the client application makes function 
// calls to explicitly load and unload the DLL's exported functions.
// In implicit linking, the application links to an import library
// (UsbHidApi.lib) and makes function calls just as if the functions 
// were contained within the executable.
//
#define DIGIOBS2API_DLL_NAME "DigioBs2Api.dll"

// The following ifdef block is the standard way of creating macros which make exporting 
// from a DLL simpler. All files within this DLL are compiled with the DIGIOBS2API_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see 
// DIGIOBS2API_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
#ifdef DIGIOBS2API_EXPORTS
#define DIGIOBS2API_API __declspec(dllexport)
#else
#define DIGIOBS2API_API __declspec(dllimport)
#endif
 

// This structure defines an entry in a device list
// The list describes the parameters associated with
// a device.  It is mainly used with the GetList()
// function. 
typedef struct {
 int     nCommPort;         // CommPort      (e.g., COM1)
 bool bDeviceDetected;   // TRUE => an active device exists
    char    sDeviceName[20];   // Device name   (e.g., STAMP)
    char    sManufacturer[20]; // Manufacturer  (e.g., PARALLAX)
 char    sModel[20];        // Model number  (e.g., BS2-IC)
    char    sSerialNumber[20]; // Serial number (e.g., 012345689)
} mdeviceList;
 

// Define target commands.  (Note that commands are even numbered.
// This is because the response is expected to be an odd value eual
// to the command value plus one.)
#define DEV_UNDEFINED 0x00 // Undefined
#define DEV_CFG_PORT 0x01 // Set port signal directions (input/output)
#define DEV_READ_PORT 0x02 // Read the port signal(s)
#define DEV_WRITE_PORT 0x03 // Write the port signal(s)
#define DEV_SET_BIT  0x04 // Set/clear a discrete output (high/low)
#define DEV_SPI_MSTR 0x05 // Issue a SPI (master) write/read command
#define DEV_USER_CMD 0x06    // User-defined command

// Define the amount of time (in mS) to wait after each write 
// to the device.  This is to ensure we don't overrun the target
// controller's limited buffering capacity.  (The BS2-IC in fact
// has no buffering capability.)
#define WRITE_DELAY_MS  10

// This designation indicates an unassigned comm port
#define COMM_NONE       16  // No specified comm.port
 

// This class is exported from the DigioBs2Api.dll
class DIGIOBS2API_API CDigioBs2Api  {
public:

   // Constructor
 CDigioBs2Api(void);

   // Destructor
   ~CDigioBs2Api(void);

   //////////////////////////////////////////////////////////
   //
   // Open()
   //
   // Description:
   //
   //     Opens a BS2 device at the specified comm port. Provides
   //     status to a supplied string (csErr).  Returns 0
   //     on success;  non-zero on failure.
   //////////////////////////////////////////////////////////
   int  Open(int, char *sErr);
 

   //////////////////////////////////////////////////////////
   //
   // Close()
   //
   // Description:
   //
   //     Closes device communication
   ////////////////////////////////////////////////////////// 
   void Close(void);
 

   ////////////////////////////////////////////////////////////
   // Initialize the SPI parameters. 
   // Returns TRUE on success or FALSE on failure.
   // (The SPI in the BS2-IC runs at ~16kHz.)
   // 
   //  Phase: (for SHIFTIN): control the bit order and clock-phase: 
   //
   //    0 = data is msb-first, sample bits before clock pulse, 
   //    1 = data is lsb-first, sample bits before clock pulse,
   //    2 = data is msb-first, sample bits after clock pulse,
   //    3 = data is lsb-first, sample bits after clock pulse,
   //
   //  Width: (for SHIFTOUT / SHIFTIN): data width (bytes)
   //
   //    1 to 4 bytes
   //
   //  (Note:  At present, mode and freq parameters are unused.)
   // 
   ////////////////////////////////////////////////////////////
   bool SpiInit(int mode, int freq, int phase, int width);
 

   //////////////////////////////////////////////////////////
   //
   // Detect()
   //
   // Description:
   //
   //     This function determines if a BS2 device
   //     is present.  Returns TRUE on success and
   //     FALSE on failure.
   //////////////////////////////////////////////////////////
   bool Detect(void);
 

   //////////////////////////////////////////////////////////
   //
   // ConfigPort()
   //
   // Description:
   //
   //     This function sets up 16-bit digital I/O 
   //     as inputs and/or outputs.
   //     The specified parameter value indicates
   //     whether the signals are input or output. 
   //     [HIGH(1)=output;  LOW(0)=Input]
   //     Returns TRUE on success or FALSE on failure.
   //     (If using SPI, config any desired I/O pin(s) using
   //     this function, then perform SPI init.)
   //////////////////////////////////////////////////////////
   bool ConfigPort(unsigned short dir);
 

   //////////////////////////////////////////////////////////
   //
   // SpiMasterWriteRead()
   //
   // Description:
   //
   //     Write SPI value to BS2 and read a response value.
   //     Can be used for reading and/or writing a SPI device.
   //     (Note: The BS2 must perform a SHIFTOUT for nWidth bytes
   //     and follow it with a SHIFTIN for nWidth bytes.  This
   //     is our convention for writing to a device and/or reading
   //     return data (if any).  Returns a 16-bit read value.
   // 
   //     (Note: You must call SpiInit() prior to calling this
   //     function.)
   //////////////////////////////////////////////////////////
   unsigned int SpiMasterWriteRead(unsigned int val, int nWidth);
 

   //////////////////////////////////////////////////////////
   //
   // WritePort()
   //
   // Description:
   //
   //     Set specified output bits on digital I/O ports.
   //     (The port bits must have been configured prior
   //     to making this call.)  The function accepts a
   //     16-bit value and writes it to the device.
   //     Any pin(s) not configured as outputs remain
   //     unaffected.  Returns TRUE on success
   //     or FALSE on failure.
   //////////////////////////////////////////////////////////
   bool WritePort(unsigned short val);
 

   //////////////////////////////////////////////////////////
   //
   // ReadPort()
   //
   // Description:
   //
   //     Gets the states of the 16 I/O port signals.
   //     (The port bits must have been configured prior
   //     to making this call.)  The function retrieves a
   //     16-bit value.  Returns TRUE on success or
   //     FALSE on failure.
   //////////////////////////////////////////////////////////
   bool ReadPort(unsigned short *val);
 

   //////////////////////////////////////////////////////////
   //
   // UserWrite()
   //
   // Description:
   //
   //     Writes a user-defined command array and retrieves
   //     a response. Up to 8 user bytes may be
   //     issued. (Implementation requires firmware source
   //     code modification for your application.)  Returns 
   //     the number of bytes received or negative result on error.
   // 
   //     (Note:  On successful completion, the first byte contained 
   //      in the response buffer will be the response ID.  This
   //      value will be equal to the original command ID plus 20.
   //      Also, be aware that the BS2 will echo the data stream
   //      bytes back to the PC.  For proper filtering by the read
   //      handler, the BS2 is expected to return 9 bytes (including
   //      the response ID.)
   //////////////////////////////////////////////////////////
   int UserWrite(UCHAR *pCmd, int nCmdLen, UCHAR *pResp);
 

   //////////////////////////////////////////////////////////
   //
   // SetDiscrete()
   //
   // Description:
   //
   // This function sets/clears the specified digital 
   // output signal.  Returns TRUE on success;  FALSE
   // otherwise.
   //////////////////////////////////////////////////////////
   bool SetDiscrete(int signal, bool bEnable);
 

   //////////////////////////////////////////////////////////
   //
   // ReverseByte()
   //
   // Description:
   //
   // This function returns the "inverse" of the specified byte.
   //////////////////////////////////////////////////////////
   unsigned char ReverseByte(unsigned char val);
 

   //////////////////////////////////////////////////////////
   // 
   // GetList()
   //
   // Description:
   //
   //    Get list of devices and their availability.  The 
   //    caller must supply a pointer to a buffer that will 
   //    hold the list of structure entries. Must also supply 
   //    an integer representing maximum no. of entries
   //    the buffer can hold. Returns total devices found.
   //////////////////////////////////////////////////////////
   int GetList(mdeviceList  *pList,        // Caller's array for storing matching device(s) 
            int          nMaxDevices);  // Size of the caller's array list (no.entries)

   //////////////////////////////////////////////////////////
   //
   // Write()
   //
   // Description:
   //
   // This function sends the specified buffer.  Returns
   // 1 on success; 0 otherwise.  (This low-level function
   // should only be used if building your own message handlers.
   // Otherwise, you should use one of the high-level functions
   // listed above.)
   //////////////////////////////////////////////////////////
   int Write(unsigned char *buf, int n);
 

   //////////////////////////////////////////////////////////
   //
   // Read()
   //
   // Description:
   //
   // This function awaits a received message.  Returns
   // 1 on success; 0 otherwise.  (This low-level function
   // should only be used if building your own message handlers.
   // Otherwise, you should use one of the high-level functions
   // listed above.)
   //////////////////////////////////////////////////////////
   int Read(unsigned char *buf, int n);
 

protected:

   // Member variables
   int  m_nWidth;      // SPI data width (1 to 4) bytes
   int  m_nBitOrder;   // SPI bit order: msb or lsb
   int  m_nPhase;      // SPI phase 
   int  m_nMosiPort;   // SPI data output port  (0 to 15)
   int  m_nMisoPort;   // SPI data input port   (0 to 15)
   int  m_nClockPort;  // SPI clock output port (0 to 15)
   int  m_nReadBytes;

    //////////////////////////////////////////////////////////
    //  Communications members and methods
    //////////////////////////////////////////////////////////
    HANDLE  ComHandle;
    WORD    CurrentBaud;

    int     OpenComms(char    sPort[10],  // Comm port (eg., COM1)
                DWORD   Baud,       // Baud rate (eg., CBR_57600)
       BYTE    Parity,     // Parity    (eg., NOPARITY)
       BYTE    Stop,       // Stop Bits (eg., ONESTOPBIT)
       char    sErr[50]);  // Returned error/status string
    BOOL    CheckComms(void);
    BOOL    CheckBaud(BYTE bBaud);
    BOOL    WriteDevice(BYTE *Buffer,DWORD dwLen,DWORD *dwWritten);
    BOOL    ReadDevice(BYTE *Buffer,DWORD *dwRead,int nMaxBytes,int MaxWait);
 void    ClearComm(bool bTx, bool bRx);
    void    CloseComms(void);
};

#endif

 

Back to Main Page