Home
SCADAPack 300 & 4203 C++ Tools
Contents
1. typedef enum dlogStatus_ type DLOGS_ SUCCESS operation was successful DLOGS_FAILURE operation failed DLOGS_INPROGRESS operation in progress DLOGS EXISTS data log exists DLOGS DIFFERENT data log configuration differs DLOGS_ INVALID data log configuration invalid DLOGS NOMEMORY failed due to lack of memory DLOGS_BADID data log ID is not valid DLOGS WRONGPARAM wrong parameter except dlogID DLOGS BUFFERFULL data log buffer is full DLOGS COMPLETE operation is complete dlogStatus dlogTransferStatus Type The dlogTransferStatus enumerated type indicates the status of the current or recent auto transfer operation The transfer status only makes sense for data logs configured to perform autocopy or automove transfers when an external USB media is inserted The transfer status for data logs without auto transfer capabilities is defaulted to DLOGS_TRANSFER_DONE_ALL typedef enum dlogTransferStatus_ type Document Version 1 61 5 19 2011 591 Structures and Types DLOGS TRANSFER INPROGRESS Auto transfer is not done or in progress DLOGS_TRANSFER_DONE_ALL Auto transfer is done with files transferred DLOGS_TRANSFER_DONE NO WORK Auto transfer is done with no files transferred DLOGS_TRANSFER_DONE_ INVALID TOKEN Auto transfer is done because of invalid token DLOGS_TRANSFER_NOT_USED Auto transfer not configured or not started dlogT
2. See ele ee eee ae A ee Se ee ENE int main void TASKINFO taskStatus struct pconfig portSettings struct prot _ settings protSettings portSettings baud BAUD9600 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATAT portSettings stop bits STOP1 portSettings flow rx RFC_NONE portSettings flow tx TFC_NONE portSettings type RS232 portSettings timeout 600 set_port com2 amp portSettings get_protocol com2 amp protSettings protSettings station 1 protSettings type MODBUS_ ASCII set_protocol com2 amp protSettings Configure Register Assignment clearRegAssignment addRegAssignment DIN generic8 0 10017 0 0 0 addRegAssignment DIAG protocolStatus 1 31000 0 0 0 Install Exit Handler getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR myshutdown Install Modbus Handler request resource IO SYSTEM installModbusHandler myModbusHandler Document Version 1 61 5 19 2011 649 Example Programs release resource IO SYSTEM while TRU a release processor Install Serial Port Handler Example SCADAPack 350 C Application Main Program Copyright 2006 Control Microsystems Inc wh include lt ctools h gt include nvMemory h define CHAR RECEIVED 11 aA void signal serial INT32 port INT32 c
3. UINT16 forwardStation forwarding station address SF TRANSLATION IP_ADDRESS forwardIPAddress forwarding IP address slavelnterface is the communication interface which receives the slave command message Valid interface types are 1 com1 2 com2 3 coms 4 com4 100 Etherneti Document Version 1 61 5 19 2011 627 Structures and Types slaveStation is the station address used in the slave command message Valid address range is 0 to 255 in standard Modbus 0 to 65534 in extended Modbus 65535 entry cleared This station address must be different from the station address assigned to the slavelnterface forwardIinterface is the communication interface from which to forward the command message as master Valid interface types are 1 com1 2 com2 3 com3 4 com4 100 Modbus TCP network 101 Modbus RTU over UDP network 102 Modbus ASCII over UDP network forwardStation is the station address of the remote slave device to forward the command message to Valid address range is 0 to 255 in standard Modbus 0 to 65534 in extended Modbus 65535 entry cleared This station address must be different from the station address assigned to the forwardinterface forward lPAddress is the IP address of the remote slave device to forward a Modbus IP command message to Set to zero if not applicable SF_TRANSLATION_EX The SF_TRANSLATION_EX structure contains Store and Forward
4. Document Version 1 61 5 19 2011 481 Function Specifications release_processor Release Processor to other Tasks Syntax include lt ctools h gt void release processor void Description The release_processor function releases control of the CPU to other tasks Other tasks of the same priority will run Tasks of the same priority run in a round robin fashion using a time slicing mechanism release_processor puts the task explicitely at the end of the round robin queue Notes Calling release_processor in all idle loops is not necessary anymore In contrary it reduces the fair share of CPU time because the CPU is given up before the end of the time slice The function release_processor still makes sense if the calling task does not have anything to do for the moment Release all resources in use by a task before releasing the processor Refer to the Real Time Operating System section for more information on tasks and task scheduling See Also request_resource Document Version 1 61 5 19 2011 482 Function Specifications release_resource Release Control of a Resource Syntax include lt ctools h gt void release resource UINT32 resource Description The release_resource function releases control of the resource specified by resource If other tasks are waiting for the resource the highest priority of these tasks is given the resource and is made ready to execute If no tas
5. EXCEPTION FUNCTION 24 EXCEPTION ADDRESS 257 EXCEPTION VALUE De Document Version 1 61 5 19 2011 616 Structures and Types MM _QUEUE_FULL Sn MM STATIONS ARE EQUAL 28 MM EXCEPTION DEVICE FAILURE 29 MM EXCEPTION DEVICE BUSY 30 MODBUS_CMD_ STATUS e MM_SENT returns a valid command has been sent e MM_RECEIVED returns response was received e MM_NO_MESSAGE returns no message was sent e MM _BAD_ FUNCTION returns invalid function code used e MM _BAD_SLAVE returns invalid slave station address used e MM _BAD_ ADDRESS returns invalid database address used e MM_BAD_LENGTH returns invalid message length e MM_PROTOCOL_NOT_SUPPORTED returns selected protocol is not supported e MM_CONNECTING returns connecting to slave IP address e MM CONNECTED returns connected to slave IP address e MM _CONNECT_TIMEOUT returns timeout while connecting to slave IP address e MM_SEND_ERROR returns TCP IP error has occurred while sending message e MM_RSP_TIMEOUT returns timeout has occurred waiting for response e MM_RSP_ERROR returns slave has closed connection incorrect response or incorrect response length e MM_DISCONNECTING returns disconnecting from slave IP address is in progress e MM DISCONNECTED returns connection to slave IP address is disconnected e MM BAD C
6. get process input ioReadAin4 0 ainData pidData pv ainData 0 execute the PID block xecuted pidExecute amp pidData if the output changed if executed write the output to analog output module aoutData 0 pidData output ioWriteAout4 0 aoutData ioRequest MT Aout4 0 release processor to other priority 254 tasks release processor Document Version 1 61 5 19 2011 450 Function Specifications pidinitialize Initialize PID controller data Syntax include lt ctools h gt void pidInitialize PID DATA pData Description This function initializes the PID algorithm data The function has one parameter pData is a pointer to a structure containing the PID data and outputs The function should be called once before calling the pidExecute function for the first time The structure pointed to by pData must contain valid values for sp pv and manualOutput before calling the function The function has no return value See Also pidExecute Example See the Example for pidExecute Document Version 1 61 5 19 2011 451 Function Specifications pollABSlave Poll DF1 Slave for Response Syntax include lt ctools h gt UINT16 pollABSlave FILE stream UINT16 slave Description The pollABSlave function is used to send a poll command to the slave station specified by slave in the DF1 Half Duplex protocol configured for the spec
7. cccccceesceceeeceeeeeeeeeeeseeeeeseaeeesaeeeeeeeeaas 650 Install Clock Handler Example c ccccccceeeeeeeeeeeseeeeeeeaeeeeneeseeeeeseaeeeeaeeeeneeeaas 651 Install Database Handler Example ecceceeecceeeeeseeeeeeeeaeeeeeeaeeeeeeaeeeeeenaeeeeee 653 Memory Allocation Example cccccceeeeeeeeeeeeeeeeeeeseneeeeeseneeeeeseeeeeeeseneaeeeteneaees 658 Master Message Example Using Modbus Protocol 0 c cceeeeeeeeeeeeeeeeeeeeeees 659 Master Message Example Using serialModbusMastet ccccseceeeeeenees 661 Master Message Example Using mTcpMasterMessage 665 Modem Initialization Example 0 0 0 eecceceseeeeeeeeeeeeeeeeeeeeeseeeeeeeseeeeeeseneaeereeenaees 668 Real Time Clock Program Example cccccceeecceceeeeeeeeeeeeeseeeeeseaeeeeaeeeeneesaas 669 Start Timed Event Example cccccceceeeceeseeceeeeeceaeeeeeaeeeeeeeseeeesaeeesaeeeeneeenaees 670 Porting Existing C Tools Applications eeeeeeeeeeeees 672 Porting SCADAPack 32 C Applications to the SCADAPack 350 and 4203 672 Partially Supported C Tools FUNCTIONS c ccceeeeeeeeeeeeeeeceeeeeseeeesaeeeeeeeeees 674 Unsupported C Tools Functions 0 ccceeeeceeeeeeeeeeeeeeeeeeeeeeseeeeesaeeeeneeseeneees 677 Porting SCADAPack C Applications to the SCADAPack 350 and 4203 679 Document Version 1 61 5 19 2011 12 Index of Figures Figure 1 Figure 2 Figure 3 Figure 4
8. Document Version 1 61 5 19 2011 55 Real Time Operating System Execution Point 4 Execution Point 5 Execution Point 6 Figure 3 Queue Status after Creation of echoData Task This point occurs just after the echoData task waits for event 10 It has been placed on the event queue for event 10 The highest priority task on the ready queue was the main task It is now running On the next instruction it will create another task at the same priority as main Event 10 Queue echoData Figure 4 Queue Status After echoData Task Waits for Event This point occurs just after the creation of the auxiliary task This task is the same priority as the main task Therefore the main task remains the running task The auxiliary task is ready to run and it is placed on the Ready queue Event 10 Queue echoData Figure 5 Queue Status after Creation of auxiliary Task This point occurs just after the main task releases the processor but before the next task is selected to run The main task is added to the end of the priority 1 list in the Ready queue On the next instruction the RTOS will select the highest priority task in the Ready queue Document Version 1 61 5 19 2011 56 Real Time Operating System Ready Queue Event 10 Queue echoData 100 auxiliary H main 100 255 null 255 Figure 6 Queue Status After main Task Releases Processor E
9. UINT32 stationAddress UINT32 ipAddress UINT16 portNumber UCHAR protocol COMM ENDPOINT CONNECTION_TYPE The CONNECTION_TYPE enumerated type defines connection types supported by the connection pool typedef enum ipConnection t CT Unused 0 CT_ Slave slave task connection CT MasterIEC 61131 1 master task connection created for an TEC 61131 1 masterip FB CT MasterCApp master task connection created fora C application CT_MasterSF master task connection created for store and forward CONNECTION TYPE e Only the connection type CT_MasterCApp may be used in C applications DATALOG_CONFIGURATION The data log configuration structure holds the configuration of the data log Each record in a data log may hold up to eight fields The typesOfFields entry in the structure specifies the types of the fields Not all the fields are used if fewer than eight elements are declared in this array The amount of memory used for a record depends on the number of fields in the record and the size of each field Use the datalogRecordSize function to determine the memory needed for each record Document Version 1 61 5 19 2011 585 Structures and Types typedef struct datalogConfig type UINT16 records of records UINT16 fields of fields per record a DATALOG VARIABLE typesOfFields MAX NUMBER OF FIELDS DATALOG_ CONFIGURATION
10. Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables Document Version 1 61 5 19 2011 566 Function Specifications For better performance use the variable s network address and the setdbase function The lO_SYSTEM system resource needs to be requested before calling this function Example This program writes the message Warning to the message variable named TextData TextData has a maximum length of 10 bytes and a current length of 7 bytes include lt ctools h gt int main void BOOLEAN status unsigned char msg 13 10 To pz e DPED a Q PRFROMAIDAORWNHEO ll N OOO OO Bo Bee H e request_resource IO SYSTEM status writeMsgVariable TextData msg release resource IO SYSTEM Document Version 1 61 5 19 2011 567 Function Specifications writeTimerVariable Write to IEC 61131 1 Timer Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN writeTimerVariable UCHAR varName UINT32 value Description This function write
11. Document Version 1 61 5 19 2011 370 Function Specifications insert code to handle wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT check status of last scan if io0Status MT 4203DROutputs insert code to handle else if io status commStatus insert code to handle release processor for 100ms sleep processor 100 the failure here 0 amp io status the failure here the failure here Document Version 1 61 5 19 2011 371 Function Specifications ioWrite4203DSOutputs Write 4203 DS Outputs Syntax include lt ctools h gt BOOLEAN ioWrite4203DSOutputs UCHAR amp doutData Description This function writes data to the I O table for the digital outputs of the 4203 DS I O Data is written to the module when an I O request for the module is processed doutData is a reference to a UCHAR variable Digital data for the outputs is read from this variable One bit in the array represents each output point The function returns TRUE if the supplied data was written to the I O table FALSE is returned if the data could not be written to the I O table See Also ioRead4203DSInputs Example This program turns on the digital outputs on the 4203 DS include lt ctools h gt define MY EVENT 1 int main void UCHAR doutData IO_ STATUS io_status main loop
12. Document Version 1 61 5 19 2011 603 Structures and Types dnpCounterInput holdTimeClass3 is the maximum period to hold Class 3 events before reporting HoldCountClass3 is the maximum number of Class 3 events to hold before reporting EnableUnsolicitedOnStartup enables or disables unsolicited reporting at start up SendUnsolicitedOnStartup sends an unsolicited report at start up level2Compliance reports only level 2 compliant data types excludes floats AO 32 MasterAddressCount is the number of master stations masterAddress 8 is the number of master station addresses MaxEventsInResponse is the maximum number of change events to include in read response PSTNDialAttempts is the maximum number of dial attempts to establish a PSTN connection PSTNDialTimeout is the maximum time after initiating a PSTN dial sequence to wait for a carrier signal PSTNPauseTime is the pause time between dial events PSTNOnlinelnactivity is the maximum time after message activity to leave a PSTN connection open before hanging up PSTNDialType is the dial type tone or pulse dialling modem nitString 64 is the initialization string to send to the modem The dnpCounterlnput type describes a DNP counter input point This type is used for both 16 bit and 32 bit points typedef struct dnpCounterInput_type eis UINT16 modbusAddress UCHAR class UINT32 threshold dnpCountertInput modbusAddress is the address of
13. GNU Compiler Options The GNU C compiler is installed with the C Tools The build bat file included in the sample C application uses the following command line for compiling ccarm 03 mapcs 32 mlittle endian march armv4 ansi fno builtin DARMEL I SCTOOLS PATH DCPU ARMARCH4 DTOOL_ FAMILY gnu DTOOL gnu std c99 c main cpp These compiler options are described in the table below The complete list of compiler options is may be found in the document Using the GNU Compiler Collection GCC which is installed with the compiler at C Program Files Control Microsystems CTools Arm7 gcc pdf Option Description i O Level 3 optimization mapcs 32 Generate code for a processor running with a 32 bit program counter and conforming to the function calling standards for the APCS 32 bit option mlittle endian Generate code for a processor running in little endian mode march armv4 Specifies the name of the target ARM architecture as armv4 ansi std c99 ISO C99 language standard for C fno builtin Don t recognize built in functions not begining with builtin as prefix Predefine name as a macro with the definition 1 Dname zdefinition Predefine name as a macro with definition Compile or assemble the source files but not link them Add the directory dir to the head of the list of directories to be searched for header files If you use more than one I option the directories are scanned in left t
14. data from 16 Din points data from 8 Ain points data written to Dout points initialize custom i o database initializeDatabase main loop while TRUE 0 write data to Out ioWrite56010utputs d add I O requests ioRequest M1 ioRequest M1 T 5601Inp T 56010ut put tables outData to the I O System queue uts 0 puts 0 this event signals completion of preceding i o requests ioNotification SCAN EVENT NO wait for your event to be signalled when all your I O requests hav wait _event SCAN_EVEN been processed T NO get the data read from Input modules ioRead5601Inputs dinData ainData request resource IO _ SYSTEM copy Ain data to the database for index 0 index lt 8 index setdbase MODBUS 31001 index ainData index copy Din data to the database for index 0 index lt 16 index if dinData amp 0x01 else setdbase MODBUS 11001 index 1 Document Version 1 61 5 19 2011 657 Example Programs setdbase MODBUS 11001 index 0 dinData gt gt 1 get 12 DOUT points from the database for index 0 index lt 12 index doutData lt lt 1 if dbase MODBUS 1012 index doutData 1 release resource IO SYSTEM release processor to other priority 254 tasks release pr
15. dnpMasterClassPoll Send DNP Class Poll Syntax BOOLEAN dnpMasterClassPoll UINT16 slaveAddress UINT16 classFlags Description The dnpMasterClassPoll function sends a Class Poll message in DNP to request the specified data classes from a DNP slave slaveAddress specifies the DNP station address of the slave classFlags specifies the classes of data to request It can contain any combination of the following values if multiple values are used they should be ORed together CLASSO_FLAG request Class 0 Data CLASS1_FLAG request Class 1 Data CLASS2_FLAG request Class 2 Data CLASS3_FLAG request Class 3 Data The DNP slave slaveAddress needs to be configured in the DNP Master Poll Table prior to calling this function The function returns TRUE if the DNP class poll message was successfully triggered It returns FALSE if the specified slave address has not been configured in the DNP Routing Table or the DNP configuration has not been created Notes This function is only available on the SCADAPack 32 SCADAPack 350 and 4203 DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 191 Function Specifications dnpMasterClockSync Send DNP Clock Synchronization Syntax BOOLEAN dnpMasterClockSync UINT16 slaveAddress Description The dnpMasterClockSync function sends a Clock Synchroniza
16. getclock Read the Real Time Clock Syntax include lt ctools h gt void getclock TIME time Description The getclock function reads the time and date from the real time clock hardware The getclock function copies the time and date information to the TIME structure pointed to by time Notes The time format returned by the getclock function is not compatible with the standard UNIX style functions The IO_SYSTEM resource needs to be requested before calling this function See Also getClockTime setclock Example This program displays the current date and time include lt ctools h gt main void TIME now request resource IO SYSTEM getclock amp now read the clock release resource IO SYSTEM fprintf com1 2d 2d 2d now day now month now year fprintf coml S2d 2d r n now hour now minute Document Version 1 61 5 19 2011 244 Function Specifications getClockAlarm Read the Real Time Clock Alarm Settings Syntax include lt ctools h gt ALARM SETTING getClockAlarm void Description The getClockAlarm function returns the alarm setting in the real time clock Notes The IO_SYSTEM resource needs to be requested before calling this function See Also setClockAlarm Document Version 1 61 5 19 2011 245 Function Specifications getClockTime Read the Real Time Clock Syntax include lt ctools h gt void getClockTi
17. DATALOG_STATUS The data log status enumerated type is used to report status information typedef enum DLS CREATED 0 data log created DLS_BADID invalid log ID DLS EXISTS log already exists DLS _NOMEMORY insufficient memory for log DLS BADCONFIG invalid configuration DATALOG STATUS DATALOG_VARIABLE DialError The data log variable enumerated type is used to specify the type of variables to be recorded in the log typedef enum DLV_UINT16 0 16 bit unsigned integer x i DLV_INT16 16 bit signed integer f DLV_UINT32 32 bit unsigned integer f DLV_INT32 32 bit signed integer x x DLV_FLOAT 32 bit floating point x DLV_CMITIME 64 bit time DLV DOUBLE 64 bit floating point x i DLV_NUMBER_OF_ TYPES DATALOG VARIABLE The DialError enumerated type defines error responses from the dial up modem functions and may have one of the following values enum DialError DE NoError 0 Document Version 1 61 5 19 2011 586 Structures and Types DialState E BadConfig E NoModem E InitError E NoDialTone E BusyLine _CallAborted _FailedToConnect _CarrierLost E NotInControl E CallCut DI DI D DI DI DI DI DI DI DI my E E E E E E B DE_NoError returns no error has occurred DE_BadConfig retur
18. Document Version 1 61 5 19 2011 337 Function Specifications if ioRequest MT 5606Inputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioRead5606Inputs 5 dinData ainData check status of last scan if ioStatus MT 5606Inputs 5 amp io status status FALSE else if io status commStatus status FALSE print data if done fprintf coml status u Dins 0 to 7 X Ain 4 status dinData 0 ainData done TRUE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 338 Function Specifications ioRead5606Outputs Read 5606 Outputs Syntax include lt ctools h gt BOOLEAN ioRead56060utputs UINT16 moduleAddress UCHAR amp doutData 2 INT16 amp aoutData 2 UINT16 amp inputType 8 UINT16 amp inputFilter UINT16 amp scanFrequency UINT16 amp outputType Description This function reads buffered data from the digital and analog outputs of a 5606 I O module Buffered data are written using the ioWrite5606Outputs function moduleAddress is the address of the 5606 module Valid values are 0 to 7 doutData is a reference to an array of two UCHAR variables Digital data for the 16 outputs are written to this array O
19. SO_REUSEADDR indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses SO_KEEPALIVE enables the periodic transmission of messages every 2 hours on a connected socket If the connected party fails to respond to these messages the connection is considered broken SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities Instead messages are directed to the appropriate network interface according to the network portion of the destination address SO_LINGER controls the action taken when unsent messages are queued on a socket and a close on the socket is performed If the socket promises reliable delivery of data and SO_LINGER is set the system will block the process on the close of the socket attempt until it is able to transmit the data or until it decides it is unable to deliver the information a timeout period termed the linger interval is specified in the setsockopt call when SO_LINGER is requested If SO_LINGER is disabled and a close on the socket is issued the system will process the close of the socket in a manner that allows the process to continue as quickly as possible The option SO BROADCAST requests permission to send broadcast datagrams on the socket With protocols that support out of band data the SO_OOBINLINE option requests that out of band data be placed in the normal data input queue as received it will then be accessible with re
20. binary input AI16 POINT 16 bit analog input AI32_ POINT 32 bit analog input AISF_ POINT short float analog input AILF POINT long float analog input CI16 POINT 16 bit counter output CI32_POINT 32 bit counter output BO POINT binary output AO16 POINT 16 bit analog output AO32 POINT 32 bit analog output AOSF_ POINT short float analog output AOLF POINT long float analog output e Document Version 1 61 5 19 2011 606 Structures and Types dnpProtocolStatus The dnpPrototocolStatus structure contains status information for DNP message transactions struct dnpPrototocolStatus dnpRoutingTableEx UINT16 successes failures failuresSinceLastSuccess formatErrors framesReceived framesSent messagesReceived messagesSent U U U U U U HHHHHHH JH HH DDDDAAOD U successes is the number of successful DNP message transactions failures is the total number of failed DNP message transactions failuresSinceLastSuccess is the number of failures since last the success formatErrors is the number of messages received with bad message data framesReceived is the number of DNP frames message packets received framesSent is the number of DNP frames message packets sent messagesReceived is the number of DNP messages received messagesSent is the number of DNP messages sent command
21. dnpGetBIConfig Reads the configuration of a DNP binary input point dnpGetBIConfigEx Reads the configuration of an extended DNP Binary Input point dnpGetBOConfig Reads the configuration of a DNP binary output point dnpGetCl16Config Reads the configuration of a DNP 16 bit counter input point dnpGetCl32Config Reads the configuration of a DNP 32 bit counter input point dnpGetConfiguration Reads the DNP protocol configuration dnpGetConfigurationEx Reads the extended DNP configuration parameters dnpGetRuntimeStatus Reads the current status of DNP change event buffers dnpinstallConnectionHandler Configures the connection handler for DNP dnpMasterClassPoll Sends a Class Poll message in DNP to request the specified data classes from a DNP slave DnpMasterClockSync sends a Clock Synchronization message in DNP to a DNP slave dnpPortStatus Returns the DNP message statistics for the specified communication port dnpReadAddressMappingTableEntry Reads an entry from the DNP address mapping table dnpReadAddressMappingTableSize Reads the total number of entries in the DNP address mapping table dnpReadMasterPollTableEntry Reads an entry from the DNP master poll table dnpReadMasterPollTableEntryEx Reads an extended entry from the DNP master poll table dnpReadPMasierPollTableSize Reads the total number of entries in the DNP master poll table dnpReadRoutingTableEntry Reads an entry from the routing table dnpReadRou
22. number of 16 bit analog input events events UINT16 eventCountAI32 number of 32 bit analog input UINT16 eventCountAISF number of short floating point analog input events UINT16 eventCountClass1 number of class 1 events UINT16 eventCountClass2 number of class 2 events UINT16 eventCountClass3 number of class 3 events DNP_RUNTI E STATUS eventCountBI is number of binary input events eventCountCl16 is number of 16 bit counter events eventCountCl32 is number of 32 bit counter events eventCountAl16 is number of 16 bit analog input events eventCountAl32 is number of 32 bit analog input events EventCountAISF is number of short floating point analog input events eventCountClass1 is the class 1 event counter eventCountClass2 is the class 2 event counter eventCountClass3 is the class 3 event counter The envelope type is a structure containing a message envelope Envelopes are used for inter task communication Document Version 1 61 5 19 2011 608 Structures and Types HART_COMMAND HART_DEVICE typedef struct envelope type UINT32 source sender task ID UINT32 destination destination task ID UINT32 type type of message UINT32 data the message data envelope e link is a pointer to the next envelope in a queue This field is used by the RTOS It is of no interest to an application program e source is the task ID of t
23. Document Version 1 61 5 19 2011 625 Structures and Types pstatus READSTATUS The pstatus structure contains serial port status information struct pstatus UINT16 framing parity c_ overrun b_ overrun rx_buffer size rx_buffer_used tx buffer size tx buffer used io_ lines HHHHHHHH JH HHHHHHAH DDDDDADD m C 5 C C C C C ce framing is the number of received characters with framing errors parity is the number of received characters with parity errors c_overrun is the number of received character overrun errors b_overrun is the number of receive buffer overrun errors rx_buffer_size is the size of the receive buffer in characters rx_buffer_used is the number of characters in the receive buffer tx_buffer_size is the size of the transmit buffer in characters tx_buffer_used is the number of characters in the transmit buffer io_lines is a bit mapped field indicating the status of the I O lines on the serial port The values for these lines differ between serial ports see tables below ANDing can isolate the signals with the SIGNAL_CTS SIGNAL_DCD SIGNAL_OH SIGNAL_RING or SIGNAL_VOICE macros The READSTATUS enumerated type indicates the status of an C bus message read and may have one of the following values enum ReadStatus RS_ success RS_selectFailed typedef enum ReadStatus READSTATUS RS_success returns read was successful RS_selectFailed returns slave dev
24. Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it Add a call to modemNotification when writing a custom protocol Extended addressing is available on the Modbus RTU and Modbus ASCII protocols only See the TeleBUS Protocols User Manual for details Example This code fragment sets protocol parameters for the com2 serial port include lt ctools h gt PROTOCOL SETTINGS settings settings type MODBUS_RTU settings station 1234 settings priority 250 settings SFMessaging FALSE settings mode AM extended Document Version 1 61 5 19 2011 526 Function Specifications request _resourc setProtocolSettings com2 release resourc IO_SYS7 p p IO_SYS7 EM amp settings EM Document Version 1 61 5 19 2011 527 Function Specifications setProtocolSettingsEx Sets extended protocol settings for a serial port Syntax include lt ctools h gt BOOLEAN setProtocolSettingsEx FILE stream PROTOCOL SETTINGS EX pSettings Description The setProtocolSettingsEx function sets protocol parameters for a serial port This function supports extended addressing and Enron Modbus parameters The function has two arguments e port specifies the serial port It is one of com1 com2 or coms e pSettings is a pointer to a PROTOCOL_SETTINGS_EX structure Refer to the description of t
25. by this application See manual for details Document Version 1 61 5 19 2011 32 C Program Development UINT32 applicationGroup 0 Pointer to static non volatile data Define the structure NV_ MEMORY in nvMemory h NV_MEMORY pNvMemory NULL Size of structure in static non volatile memory UINT32 nvMemorySize is 0 UINT32 applicationType UCHAR limit the number of executabl Default limit is 0 which applicationTypeLimit mainPRiority Valid values for applicationType are 0 to 65535 0 sizeof NV_MEMORY applicationType and applicationTypeLimit may be used to limit instances of this application Default type Valid values for applicationTypeLimit are 0 to 32 no limit valid types valid limits 0 to 65535 0 0 to 32 0 no The variable mainPriority selects the priority for the task main The task main is declared in the file main cpp There are 255 priority levels and the highest priority task has a priority of 0 The table below lists the recommended priority values to use with the SCADAPack 350 and 4203 The logic application executes in a continuous loop at priority 100 This means that a task selected with priority gt 100 will not be given the CPU Priority 100 is suitable for C Applications Document Version 1 61 5 19 2011 33 C Program Development Recomme nded Use Not recomme nded
26. parameter The poll interval is set in seconds Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns TRUE if successful FALSE otherwise Document Version 1 61 5 19 2011 164 Function Specifications dnpCreateRoutingTable Create Routing Table Syntax include lt ctools h gt BOOLEAN dnpCreateRoutingTable UINT16 size Description This function destroys any existing DNP routing table and allocates memory for a new routing table according to the size parameter Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns TRUE if successful FALSE otherwise Example See the example in the dnoGetConfiguration section Document Version 1 61 5 19 2011 165 Function Specifications dnpGenerateChangeEvent Generate DNP Change Event Syntax BOOLEAN dnpGenerateChangeEvent DNP_ POINT TYPE pointType UINT16 pointAddress Description The dnpGenerateChangeEvent function generates a change event for the DNP point specified by pointType and pointAddress pointType specifies the type of DNP point Allowed values are BI_POINT binary input Al16_POINT 16 bit analog input Al32_POINT 32 bit analog input AISF_POINT short float analog input Cl16_ POINT 16 bit counter output CI32_POINT 32 bit counter output pointAddress specifies the DNP
27. BOOLEAN status BOOLEAN done main loop while TRUE read output data from I O table status ioRead56070utputs 5 doutData aoutData inputType inputFilter scanFrequency outputType print data fprintf com3 status u Douts 0 to 7 X Aout 0 d r n status doutData 0 aoutData 0 release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 344 Function Specifications ioReadAin4 Read Data From 4 point Analog Input Module Syntax include lt ctools h gt BOOLEAN ioReadAin4 UINT16 moduleAddress INT16 amp data 4 Description This function reads buffered data from the 4 point analog input module at the specified module address Buffered data are updated when an I O request for the module is processed The function has two parameters the module address and a reference to an array of four INT16 variables If the moduleAddress is valid analog input data are copied to the array The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 345 Function Specifications ioReadAin8 Read Data From 8 point Analog Input Module Syntax include lt ctools h gt BOOLEAN ioReadAin8 UINT16 moduleAddress INT16 amp data 8 Description This function reads buffered data from the 8 point analog
28. Configure 32 Bit Counter Input Points Pear Raa eee teas aS Se ar se Wea ae Sr ne eo ae ae eee for index 0 index lt configuration CI32 number index counterInput modbusAddress 30001 index 2 counterInput eventClass CLASS 3 counterInput threshold 1 dnpSaveC132Config configuration CI32 startAddress index amp counterInput Document Version 1 61 5 19 2011 644 Example Programs main loop while TRUE add remainder of program here release processor to other priority 254 tasks release processor Get Program Status Example This program stores a default alarm limit into the I O database the first time it is run On subsequent executions it uses the limit in the database The limit in the database can be modified by a communication protocol during execution include lt ctools h gt define HI ALARI 41000 define ALARM OUTPUT 1026 define SCAN EVENT 0 int main void if getProgramStatus FUNCPTR main NEW PROGRAM Set default alarm limit request resource IO SYSTEM setdbase MODBUS HI ALARM 4000 release resource IO SYSTEM Use values in database from now on setProgramStatus FUNCPTR main PROGRAM EXECUTED while TRUE INT16 ain 8 analog input module data Scan ain module ioRequest MT Ain8 0 ioNotification SCAN EVENT wait event SCAN_EVENT ioReadAi
29. Document Version 1 61 5 19 2011 34 C Program Development Recomme nded Use Document Version 1 61 5 19 2011 35 C Program Development Recomme nded Use Serial protocol tasks IP protocol tasks or other Document Version 1 61 5 19 2011 36 C Program Development Recomme nded Use blocking task e g wait_even t called each loop Document Version 1 61 5 19 2011 37 C Program Development Recomme nded Use continuou sly running loop e g O processin g Document Version 1 61 5 19 2011 38 C Program Development Recomme nded Use Document Version 1 61 5 19 2011 39 C Program Development mainStack applicationGroup The variable mainStack selects the stack space for the task main At least 5 stack blocks are needed when the main task calls the function fprintf The heap size is not configurable The C application has access to the entire system heap The variable applicationGroup is assigned with a unique value by the operating system to identify each user defined C application The variable applicationGroup should be used for the parameter type when calling the function create_task When an application is stopped or deleted tasks created by the same application group will be stopped pNvMemory and nvMemorySize The variables pNvMemory and nvMemorySize are declared next and changes are not required The struct
30. If the function returns NORMAL then the protocol driver sends the response message in the buffer pointed to by pResponse If the function returns an exception response protocol driver returns the exception response to the caller The buffer pointed to by pResponse is not used Example This program installs a simple handler function include lt ctools h gt UINT16 commandHand1ler INT16 length HAR pCommand T16 responseSize T16 pResponseLength HAR pResponse C I I S OE C C C C UCHAR command UINT16 result if a command byte was received if length gt 1 get the command byte Document Version 1 61 5 19 2011 233 Function Specifications command pCommand 0 J switch command read unit status command case 7 if the response buffer is large enough if responseSize gt 2 build the response header pResponse 0 pCommand 0 set the unit status pResponse 1 17 set response length pResponseLength 2 indicate the command worked result NORMAL else buffer is to small to respond result ILLEGAL FUNCTION break add cases for other commands here default command is invalid result ILLEGAL FUNCTION else command is too short so return error result ILLEGAL FUNCTION return result This function unhooks the protocol
31. Real Time Operating System ioDatabaseReset ledSetDefault master_message mTcpSetinterfaceEx mTcpSetProtocol reset the database set the default LED state send a master message poll configure the Modbus TCP interface configure the Modbus TCP protocol mTcpMasterMessage send a Modbus TCP master message overrideDbase readintVariable readMsgVariable readRealVariable readTimerVariable resetClockAlarm setclock setClockAlarm setdbase setForceFlag set_port set_protocol setProtocolSettings force the database value read an integer variable read a message variable read a real variable read a timer variable reset the clock alarm set the system clock set the clock alarm set a database register set the forcing flag set the serial port set the protocol for an interface set the protocol settings setProtocolSettingsEx set the protocol settings setSFTranslation setSFTranslationEx writeBoolVariable writelntVariable writeRealVariable writeMsgVariable writeTimerVariable DYNAMIC_MEMORY Resource configure Store and Forward translation configure Store and Forward translation write a Boolean variable write an Integer variable write a Real variable write a Message variable write a Timer variable The DYNAMIC_MEMORY resource regulates access to memory allocation functions These functions allocate memory from the system heap The heap is shared amongst tasks The allocation functions are non reentrant The
32. UCHAR amp flashMemoryRecord logData FALSE else logData TRUE else Turn off FORCE LED if DIN1 is OFF forceLed LED OFF Suspend DINI OFF or resume DIN1 ON loging if dinlCurrentState dinlPreviousState if dinlCurrentState dlogStatusInfo dlogResume dlogidNumber dlogStatusInfo dlogSuspend dlogidNumber dinlPreviousState dinlCurrentState Document Version 1 61 5 19 2011 640 Example Programs DNP Configuration Example SCADAPack 350 C Application Main Program Copyright 2001 2004 Control Microsystems Inc The following program demonstrates how to configure DNP for operation on com3 of the SCADAPack 350 extern C add prototypes here UINT32 mainPriority 100 UINT32 mainStack 4 UINT32 applicationGroup 0 UINT16 index loop index PROTOCOL CONFIGURATION protocolSettings protocol settings dnpConfiguration configuration configuration settings dnpBinaryOutput binaryOutput binary output settings dnpBinaryInput binaryInput as binary input settings dnpAnalogInput analogInput FL analog input settings dnpAnalogOutput analogOutput analog output settings dnpCounterInput counterInput conter input settings Document Version 1 61 5 19 2011 641 Example Programs pr eS So See ea a re eee O
33. amp analogInput Configure 16 Bit Analog Output Points for analogOutput modbusAddress dnpSaveAOl1 6Config index index O index lt configuration AO16 number index 40001 index amp analogOutput Configure 32 Bit Analog Output Points for analogOutput modbusAddress dnpSaveA032Config index index 0 index lt configuration AO32 number index 40101 index 2 amp analogOutput Configure 16 Bit Counter Input Points for index 0 index lt configuration CI16 number index Document Version 1 61 5 19 2011 181 Function Specifications here ay counterInput modbusAddress 30001 index counterInput class CLASS 3 counterInput threshold 1 dnpSaveC1I16Config index amp counterInput Configure 32 bit Counter Input Points for index 0 index lt configuration CI32 number index counterInput modbusAddress 30001 index 2 counterInput class CLASS 3 counterInput threshold 1 dnpSaveCI32Config index amp counterInput add additional initialization code for your application loop forever while TRUE add additional code for your application here allow other tasks of this priority to execute release processor return Document Version 1 61 5 19 2011 182 Function Specifications dnpGetConfigurationEx Read DNP Extend
34. amp configuration Start DNP protocol on com port 2 get_protocol com2 amp settings settings type DNP set_protocol com2 amp settings Save port settings so DNP protocol will automatically start request resource IO SYSTEM save EEPROM RUN release resource IO SYSTEM Configure Binary Output Points for index 0 index lt configuration BO number index Document Version 1 61 5 19 2011 180 Function Specifications binaryOutput modbusAddressl 1 index binaryOutput modbusAddress2 1 index binaryOutput controlType NOT PAIRED dnpSaveBOConfig index amp binaryOutput Configure Binary Input Points for index 0 index lt configuration BI number indext binaryInput modbusAddress 10001 index binaryInput class CLASS 1 binarylInput eventTyp COS dnpSaveBIConfig index amp binaryInput Configure 16 Bit Analog Input Points for index 0 analogInput modbusAddress index lt configuration AI16 number index 30001 index analogInput class CLASS 2 analogInput deadband 1 dnpSaveAI16Config index amp analogInput Configure32 Bit Analog Input Points for index 0 analogInput modbusAddress analogInput class analogInput deadband index lt configuration AI32 number index t 30001 index 2 CLASS 2 1 dnpSaveAl32Config index
35. dlogResume Resume writing to a suspended data log file Syntax include lt ctools h gt dlogStatus dlogResume UINT32 dlogID Parameters The function has these parameters e dlogID is the ID of the data log The function returns e DLOGS_SUCCESS if logging was resumed e DLOGS_BADID if the data log ID is invalid Description This function resumes writing to a previously suspended data log If external media is configured for the data log the first connected drive name is retrieved If data log configuration files are not present they are created immediately The data log file is created when the first data log record is written from the log buffer A dlogResume call on an already active data log has no impact See Also dlogSuspend Document Version 1 61 5 19 2011 157 Function Specifications dlogSpace Return the space available in the data log buffer Syntax include lt ctools h gt dlogStatus dlogSpace UINT32 dlogID UINT32 pBufferRecords Parameters The function has these parameters e dlogID is the ID of the data log e pBufferRecords is a pointer a variable to hold the number of records in the buffer The function returns e DLOGS_ SUCCESS if the number of records was returned e DLOGS_BADID if the data log ID is invalid e DLOGS_WRONGPARANM if an error due to wrong parameter happened e DLOGS_FAILURE if an unexpected error happened Description This function returns the num
36. fprintf coml Point Value for point 0 point lt 32 pointtt fprintf coml n r d point Document Version 1 61 5 19 2011 353 Function Specifications putchar dinData amp 0x0001 1 0 dinData gt gt 1 Document Version 1 61 5 19 2011 354 Function Specifications ioReadDin8 Read Data From 8 point Digital Input Module Syntax include lt ctools h gt BOOLEAN ioReadDin8 UINT16 moduleAddress UCHAR amp data Description This function reads buffered data from the 8 point digital input module at the specified module address Buffered data are updated when an I O request for the module is processed The function has two parameters the module address and a reference to an UCHAR variable If the moduleAddress is valid digital input data are copied to the variable The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 355 Function Specifications ioReadDout16 Read Data From 16 point Digital Output Module Syntax include lt ctools h gt BOOLEAN ioReadDout16 UINT16 moduleAddress UINT16 amp data Description This function reads buffered data used for the 16 point digital output module at the specified module address Buffered data are written using the ioWriteDout16 function The function has two parameters the module address and a poin
37. other processing code Allow other tasks to execute release processor Install Database Handler Example This program assumes that the pointer pAllocatedMem has been declared in nvMemory h This is a sample IEC 61131 1 application for the installDbaseHandler and installSetdbaseHandler functions This sample program demonstrates database handlers for the Modbus registers 1001 to 1100 11001 to 11100 31001 to 31100 41001 to 41100 This database is allocated in non volatile memory When the handlers are installed calls to the functions dbase setdbase databaseRead and databaseWrite for these Modbus registers will call these handlers This is true as long as the register is not already assigned to an IEC 61131 1 variable Note that these database access functions are used by C applications and by all protocols include lt ctools h gt include lt string h gt include nvMemory h define SA PLE SIZE 100 define SCAN _EVENT_NO 0 custom Modbus database structure struct myDatabase e BOOLEAN coilDbase SAMPLE SIZE BOOLEAN statusDbase SAMPLE SIZE INT16 inputDbase SAMPLE SIZE INT16 holdingDbase SAMPLE SIZE define ME SIZE sizeof struct myDatabase This is the dbase handler Document Version 1 61 5 19 2011 653 Example Programs static BOOL UINT INT
38. 0 Lot ANERE R E AE E A AT E AE T E E er cere rr 145 Dbase Handler Function esnatua E E E EE 147 Aeallocate_ONnvelope ea a a E AEEA ER R 148 oele AREE E R E AE E EE AE T 149 OlOG Delete eaa a cave T E 151 GlOGDeleteAll css i a E EE EN 152 alaala E a APE E E E A E 153 Document Version 1 61 5 19 2011 dlogGetStatus drii ai aea eee ee ln Ba 154 ClO g Distt aie ee ee Ae T ee ie ee 155 ClOgNewFile c tei a tatseiiie ceive dai Anes dite tiene ei 156 CIOGRESUMO nw ied eeiee AiGid cain eve ie dine ieee ei 157 Cl6gSpace oie ave a ee ad dia a eaei ridado 158 dlogS spend jessie ere A Gad aire adi vie aes 159 CIOQW rite vice shaves inten navies itive inves setiiee dienes Mined edinebes tities ives diiieee iy 160 dnpClearEventlogs i ascended ieee iiaa aeia eiiiai ieni 161 AnpConnectionEvent 1 cists ea kinin iioi dariana alten dteah 162 dnpCreateAddressMapping Table ccccccceesceceeeeeceeeeeseeseeeeeseaeesseaeeneneessaees 163 dnpCreateMasterPollTable ccccceccecceeeeeeeeeeeeceeeeeeaeeeeaaeeeeeeeseaeeesaaeseeneeesaees 164 AnpCreateRoutingT able iisas aii anartan adaa aaa aaiae iaa pia ateena 165 dnpGenerateChangeEvent cccccceceeeceeeeeceeeeeceeeeeseaeeeeaaeseeeeeseeeesaeseeneessaees 166 AnpGenerateEVentl og iiinis anaran aae aa aa aiae iaaa paa dence 167 dnPGetAlT ECON iOi ra ani iranran iasan aa a anaa aiaia aas pa abies 168 dNPGetAlS2CON O iiaeaa anaran aa a aa aa aaiae diet ateei 169 AnpGetAl
39. 16 DOUT_ generic 8 SCADA Pack_A OUT Document Version 1 61 5 19 2011 92 Function Specifications CNFG_prot SCADA ocolSetting Pack_lo s werlO CNFG_real SCADA TimeClock Pack_u pperlO CNFG_sav SCADA eTOoEEPRO Pack_L M PIO CNFG_setS SCADA erialPortDT Pack_2 R IO CNFG_stor SCADA eAndForwa Pack_1 rd 0010 SCADASE SCADA NSE_4203 _ Pack_5 DR 60610 CNTR_520 SCADA xCounterlIn SENSE puts _ 4203 _ DS SCADAPac k_33xlO moduleAddress specifies a unique address for the module For the valid range for moduleAddress refer to the list of modules in the chapter Register Assignment Reference of the Telepace Ladder Logic Reference and User Manual For module addresses com1 com2 com3 or com4 specify 0 1 2 or 3 respectively for moduleAddress For module address Ethernet1 specify 4 for moduleAddress For module types that have no module address e g CNFG_LEDPower specify 1 for moduleAddress For SCADAPack module types that have a module address fixed at 0 specify 0 for moduleAddress startingRegister1 specifies the first register of any unused block of consecutive registers Refer to the list of modules in the Register Assignment Reference for the type and number of registers required for this block Data read from or written to the module is stored in this block of registers If the module type specified has more than one type of I O use startingRegister2 startingRegister3 and startingRegister4 as applicable Each sta
40. Figure 5 Figure 6 Figure 7 Figure 8 Figure 9 Queue Status before Execution of Main Task cccccccccceesssseeseeeeees 55 Queue Status at Start of MAIN TASK cecccceeccceeeeeceeseeeeeeeeeaeeeeeeees 55 Queue Status after Creation of echoData Task ccceeceeseeeeeeeeees 56 Queue Status After echoData Task Waits for Event ccce 56 Queue Status after Creation of auxiliary TaSK eeeeeeeeeeeeeee 56 Queue Status After main Task Releases Processor c cccceeeeees 57 Queue Status at Start of auxiliary Task ccccccceeeeeeeeeeeeeeeeeeeeeeteeee 57 Queue Status after Character Received ccccceseecceeeeeeeeeeeeeeeeeeees 58 Queue Status after echoData Waits for Event cccceeceeeeeeeeeeeees 58 Document Version 1 61 5 19 2011 13 Safety Information Read these instructions carefully and look at the equipment to become familiar with the device before trying to install operate or maintain it The following special messages may appear throughout this documentation or on the equipment to warn of potential hazards or to call attention to information that Clarifies or simplifies a procedure A The addition of this symbol to a Danger or Warning safety label indicates that an electrical hazard exists which will result in personal injury if the instructions are not followed A This is the safety alert symbol It is used to alert y
41. Function Specifications hartStatus Return Status of Last HART Command Sent Syntax include lt ctools h gt BOOLEAN hartStatus UINT16 module HART RESULT status UINT16 code Description This function returns the status of the last HART command sent by a 5904 module 0 to 3 Use this function to determine if a response has been received to acommand sent The function has three parameters the module number of the 5904 module a pointer to the status variable and a pointer to the additional status code variable The status and code variables are updated with the following information HART interface HR_NoModuleResponse not used module is not communicating Command ready HR_CommandPending not used to be sent Command sent to HR_CommandSent current attempt number device oe HR_Response response code from HART oe device see Notes No valid response HR_NoResponse O no response from HART received after all device attempts made Other error response code from HART device see Notes HART interface HR_WaitTransmit not used module is not ready to transmit The function returns TRUE if the status was read The function returns FALSE if the module number is invalid Notes The response code from the HART device contains communication error and status information The information varies by device but there are some common values e f bit 7 of the high byte is set the high byte contains
42. If the Modbus TCP server is currently running 1 is returned If the server is not running 0 is returned Document Version 1 61 5 19 2011 429 Function Specifications mTcpGetinterface Get Modbus IP Interface Settings Syntax include lt ctools h gt BOOLEAN mTcpGetInterface COM INTERFACE ifType MTCP_IF SETTINGS pSettings Description The mTcpGetlnterface function is used to obtain the interface settings for Modbus IP protocols on the specified interface If the selected interface is invalid FALSE is returned otherwise TRUE is returned and the settings are copied to the structure pointed to by pSettings The valid value for iffype is CIF_Ethernet1 The enumeration type COM_INTERFACE and the structure MTCP_IF_SETTINGS are described in the Structures and Types section Document Version 1 61 5 19 2011 430 Function Specifications mTcpGetinterfaceEx Get Modbus IP Interface Extended Settings Syntax include lt ctools h gt BOOLEAN mTcpGetInterfaceEx COM_INTERFACE ifType MTCP_IF SETTINGS EX pSettings Description This function returns the interface settings used for Modbus IP protocols including Enron Modbus settings The function has two parameters e ifType specifies the interface The valid value is CIF_Ethernet1 e pSettings is a pointer to a Modbus IP interface extended settings structure The settings are copied to this structure
43. MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes If the specified register is currently forced the I O database remains unchanged When writing to LINEAR digital addresses value is a bit mask which writes data to 16 1 bit registers at once If any of these 1 bit registers is currently forced only the forced registers remain unchanged The I O database is not modified when the controller is reset It is a permanent storage area which is maintained during power outages Refer to the Functions Overview section for more information The IO_SYSTEM resource needs to be requested before calling this function Example include lt ctools h gt int main void request resource IO SYSTEM setdbase MODBUS 40001 102 Turn ON the first 16 coils setdbase LINEAR START COIL 255 Write to a 16 bit register setdbase LINEAR 3020 240 Document Version 1 61 5 19 2011 511 Function Specifications Write to the 12th holding register setdbase LINEAR START HOLDING 330 Write to the 12th holding register setdbase LINEAR START HOLDING 330 release resource IO SYSTEM Document Version 1 61 5 19 2011 512 Function Specifications Setdbase Handler Function User Defined Setdbase Handler Function The setdbase handler f
44. Macro stdout is Disabled The macro stdout is disabled in the SCADAPack C Tools Instead use the serial port macros com1 com2 or com3 This means that the following functions that use stdout do not work printf putc getc Use the replacement functions listed below iprint Task Creation Function The task priorities have changed with the SCADAPack 350 and 4203 There are now 255 priority levels and the highest priority task has a priority of 0 Existing calls to create_task will need to be modified to account for a lower number being a higher priority The table below contains the recommended priority values to use when porting to the SCADAPack 350 and 4203 Priority Description Equivalent Priority Priority Value for Value for SCADAPack SCADAPack 32 350 and 4203 Fn a e o o Coe e o The argument used for application type in existing calls to create_task must be replaced with the global variable applicationGroup The operating system assigns a unique value to applicationGroup when it is defined in appStart cpp Please see the documentation for create_task in the Function Specifications section for more details Controller I O Functions The following functions are no longer supported The replacement function is indicated for each Each function is documented in the Function Specifications section Replaced wit interruptinput no replacement function interruptCounter no replacement function ioReadCounterSP2 re
45. Structures and Types MTCP_IF_SETTINGS The Modbus IP Interface Settings structure defines the interface settings when using any Modbus IP protocol on the specified interface typedef struct st_MTcpIfSettings UINT16 station UCHAR addrMode BOOLEAN sfMessaging MTCP_IF_ SETTINGS e station is the Modbus station address for the specified communication interface Valid values are 1 to 255 in standard Modbus 1 to 65534 in extended Modbus Default value is 1 e addrMode is the addressing mode AM_standard or AM_extended Default value is AM_ standard e SFMessaging is the enable Store and Forward messaging control flag Enable store and forward when set to TRUE Disable store and forward when set to FALSE Default value is FALSE MTCP_IF_SETTINGS_EX The Modbus IP Interface Extended Settings structure defines the interface settings when using any Modbus IP protocol on the specified interface This structure includes Enron Modbus support typedef struct st_MTcpIfSettingsEx type UINT16 station UCHAR addrMode BOOLEAN sfMessaging BOOLEAN enronEnabled UINT16 enronStation MTCP_IF_ SETTINGS EX e station is the Modbus station address for the specified communication interface Valid values are 1 to 255 in standard Modbus 1 to 65534 in extended Modbus Default value is 1 e addrMode is the addressing mode AM_standard or AM_extended Default value is AM_standard e SFM
46. Syntax include lt ctools h gt UINT16 getStatusBit UINT16 bitMask Description The getStatusBit function returns the values of the bits indicated by bitMask in the controller status code See Also setStatusBit clearStatusBit Document Version 1 61 5 19 2011 275 Function Specifications getTaskinfo Get Information on a Task Syntax include lt ctools h gt BOOLEAN getTaskInfo INT32 taskID TASKINFO pTaskInfo Description The getTaskInfo function returns information about the task specified by taskiD If taskID is 0 the function returns information about the current task The function copies task information to the TASKINFO structure pointed to by pTaskinfo FALSE is returned if the task specified by task D doesn t exist otherwise TRUE is returned and the data is copied Refer to the Structures and Types section for a Description of the fields in the TASKINFO structure Example See the Get Task Status Example in the Examples section Document Version 1 61 5 19 2011 276 Function Specifications getVersion Get Firmware Version Information Syntax include lt ctools h gt VERSION getVersion void Description The getVersion function obtains firmware version information It returns a VERSION structure Refer to the Structures and Types section for a Description of the fields in the VERSION structure Notes The version information can be used to adapt a program to
47. The function returns TRUE if the specified interface is valid and FALSE otherwise The enumeration type COM_INTERFACE and the structure MTCP_IF_SETTINGS_EX are described in the Structures and Types section Document Version 1 61 5 19 2011 431 Function Specifications mTcpGetProtocol Get Modbus IP Protocol Settings Syntax include lt ctools h gt BOOLEAN mTcpGetProtocol IP PROTOCOL TYPE type IP PROTOCOL SETTINGS pSettings Description The mTcpGetProtocol function copies the settings for a specific Modbus IP or DNP IP protocol to the structure pointed to by pSettings The protocol type is selected with the type argument and it may be set to any of the following IPP_ModbusTcp IPP_ModbusRtuOverUdp IPP_ModbusAsciiOverUdp IPP_DnpOverTcp or IPP_DnpOverUdp If the protocol type is valid the settings are copied and TRUE is returned If the protocol type is invalid FALSE is returned and nothing is copied The structure IP_PROTOCOL_SETTINGS is described in the Structures and Types section See Also mTcpSetProtocol mTcpGetInterfaceEx Document Version 1 61 5 19 2011 432 Function Specifications mTcpSetConfig Set Modbus TCP Protocol Settings Syntax include lt ctools h gt BOOLEAN mTcpSetConfig MTCP_ CONFIGURATION pSettings Description The mTcpSetConfig function is used to configure settings common to all connections using the Modbus TCP protocol Existing connections are mai
48. Use make clean to start over from a clean slate and compile files again If you add additional types of output files you will need to modify this section PHONY clean clean del o del out The gnu C compiler is a command line compiler To build the application e Open a command prompt from a shortcut or use this procedure o Click Start gt Run o In Open type cmd and click OK e Switch to the folder containing the project o For example type cd c projects sp350 hello e Type make and press Enter Make will compile the two cpp files then link them into a single output file named myApp out If errors occur they will be displayed on the command line Document Version 1 61 5 19 2011 26 Getting Started Loading and Executing the C Application Using Telepace Controller Initialization Connect to Controller The Telepace C C Program Loader transfers executable files from a PC to the controller and controls execution of programs in the controller The controller should be initialized when beginning a new programming project or when it is desired to start from default conditions It is not necessary to initialize the controller before every program load To completely initialize the controller perform a Cold Boot When the controller starts in the cold boot mode e The default serial communication parameters are used e The Telepace Ladder Logic application program is erased e The C C program is erased
49. half duplex version of the protocol resetAllABSlaves Clears responses from the response buffers of half duplex slave controllers setABConfiguration Defines DF1 protocol configuration parameters TCP IP Communications The SCADAPack 350 and SCADAPack 357 controllers have one 10 100BaseT Ethernet port TCP IP Functions The ctools h file defines the following TCP IP related functions Refer to the Function Specification section for details on each function listed ethernetGetIP Get the Ethernet controller TCP IP settings ethernetSetIP Set the Ethernet controller TCP IP settings ethernetGetMACAddress Returns Ethernet controller MAC address ipGetConnectionSummary Returns the number of connections master slave or unused ipGetInterfaceType Returns the interface that is configured to the specified local IP address Modbus IP Protocol Modbus IP is an extension of serial Modbus which defines how Modbus messages are encoded within and transported over TCP IP based networks Modbus IP protocols are just as simple to implement and flexible to apply as serial Modbus Complete information for Modbus IP and serial Modbus may be found on line at www modbus org Document Version 1 61 5 19 2011 78 Overview of Programming Functions These functions are supported on the SCADAPack 350 controllers Modbus IP Functions The ctools h file defines the following Modbus IP related functions Refer to the Function Specification sec
50. is given the processor and executes Ready Queue Event 10 Queue Running Task main 50 echoData 100 auxiliary 255 null Figure 9 Queue Status after echoData Waits for Event Document Version 1 61 5 19 2011 58 Overview of Programming Functions Overview of Programming Functions This section of the User Manual provides an overview of the Functions Macros Structure and Types available to the user The Functions Macros Structure and Types overview is separated into sections of related functions Refer to the Function Specification C Tools Macros and C Tools Structures and Types sections of this manual for detailed explanations of the Functions Macros Structure and Types described here Controller Operation Start Up Functions Start Up Macros This section of the manual provides an overview of the functions relating to controller operation The following functions are called by the application startup function appstart They are for use only in the context of appstart Refer to the Function Specification section for details on each function listed startup_task Returns the address of the system start up routine runBackgroundlO Starts or stops the Background I O task runTarget Starts or stops the run time engine task initializeApplicationVariables Initializes user application variables runlOSystem Starts or stops the I O system start_protocol Starts serial pro
51. nothing is done and FALSE is returned The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name must be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the setdbase function The lO_SYSTEM system resource needs to be requested before calling this function Example This program writes the value 120 000 to the integer variable named Pressure include lt ctools h gt int main void BOOLEAN status request_resource IO SYSTEM status writeIntVariable Pressurel 120000 release resource IO SYSTEM Document Version 1 61 5 19 2011 564 Function Specifications writeRealVariable Write to IEC 61131 1 Real Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN writeRealVariable UCHAR varName float value Description This function writes to the specified real i e floating point variable The variable is specified by its name expressed as a character strin
52. while TRUE write data to output tables for next scan doutData 0x03 ioWrite4203DSOutputs doutData add module scan to queue if ioRequest MT_4203DSOutputs 0 insert code to handle the failure here wait for scan to complete ioNotification MY EVENT Document Version 1 61 5 19 2011 372 Function Specifications wait event MY_ EVENT check status of last scan if ioStatus MT 4203DSOutputs insert code to handle else if io status commStatus insert code to handle release processor for 100ms sleep processor 100 0 amp io status the failure here the failure here Document Version 1 61 5 19 2011 373 Function Specifications ioWrite52100utputs Write SCADAPack 330 coniroller board outputs Syntax include lt ctools h gt BOOLEAN ioWrite52100ututs UCHAR amp doutData Description This function writes buffered data to the digital outputs of a SCADAPack 330 controller board Data are written to the module when an I O request for the module is processed doutData is a reference to a variable holding the digital output values e Bit 0 of this variable is written to the USB LED control e Bit 1 of this variable is written to the com3 HMI power control e Bits 2 to 7 are not used The function returns TRUE as no I O errors are possible See Also ioRead52100utputs Exa
53. 1 61 5 19 2011 476 Function Specifications select may be used to determine when more data arrives or and when out of band data arrives Parameters socketDescriptor bufferPtr bufferLength flags The socket descriptor to receive data from The buffer to put the received data into The length of the buffer area that bufferPtr points to See below The flags parameter is formed by ORing one or more of the following MSG_DONTWAIT MSG_OOB MSG_PEEK Returns gt 0 0 1 recv will fail if EBADF ENOBUFS EMSGSIZE EWOULDBLOCK ESHUTDOWN EINVAL ENOTCONN Don t wait for data but rather return immediately Read any out of band data present on the socket rather than the regular in band data Peek at the data present on the socket the data is returned but not consumed so that a subsequent receive operation will see the same data Number of bytes actually received from the socket EOF An error occurred The socket descriptor is invalid There was insufficient user memory available to complete the operation The socket requires that message be received atomically and bufferLength was too small The socket is marked as non blocking or the MSG_DONTWAIT flag is used and no data is available to be read or the MSG_OOB flag is set and the out of band data has not arrived yet from the peer The remote socket has closed the connection and there is no more data to be received TCP sock
54. 15 release resource IO SYSTE wait for response com2 10 1 10009 8 Allow other tasks to execute release processor Master Message Example Using serialModbusMaster This program sends master messages on com2 demonstrating two methods using the function serialModbusMaster SCADAPack 350 C Application Main Program Copyright 2001 2004 Control Microsystems Inc include lt ctools h gt function prototypes Document Version 1 61 5 19 2011 661 Example Programs static void master2 void JR weececsse see sesh Ses oS ee oho eae ete esl eee Modular variables eee a a ce ea ad I nd OE ds declare session as modular to reduce stack space usage static MODBUS SESSION masterSessionl static MODBUS_ SESSION masterSession2 JR edtesaccsohee teh se tse Stes e aoe eee See main The main function sets up serial port then sends commands to a Modbus slave This task monitors the command status to check when the response is received This method is useful when other processing can be done while waiting for the response UINT32 mainPriority 100 UINT32 mainStack 4 UINT32 applicationGroup 0 int main void MASTER MESSAGE message BOOLEAN status UINT16 good bad struct prot settings settings struct pconfig portset request resource IO SYSTEM enable Modbus protocol on com2 settings type MODBUS_RTU settings station 1 se
55. 323 Function Specifications check status of last scan if ioStatus MT _5414Inputs 0 amp io status status FALSE else if io _status commStatus status FALSE print data fprintf coml status u Dins 0 to 7 X r n status dinData 0 release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 324 Function Specifications ioRead5415Inputs Read 5415 module inputs Syntax include lt ctools h gt BOOLEAN ioRead5415Inputs UINT16 moduleAddress UCHAR amp dinData Description This function reads buffered data from the digital inputs relay coil power status and power jumper position of the 5415 relay output module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5415 module Valid values are 0 to 15 dinData is a reference to a UCHAR variable Digital data from the 2 inputs are written to this array Bit O holds the relay coil power status Bit 1 holds the relay power jumper position See Also ioWrite5415Outputs ioRead54150utputs Example This Example reads the digital inputs on the 5415 I O module include lt ctools h gt include nvMemory h define MY EVENT 1 void main void UCHAR dinData 1 IO_ STATUS io_status BOOLEAN status main loop while TRUE add module scan to queue if ioRequest MT
56. 32767 aoutData 1 32767 set analog input types to 4 20 mA inputType 0 3 inputType 1 3 inputType 2 35 inputType 3 3 inputType 4 3 inputType 5 3 inputType 6 3 inputType 7 3 set filter and frequency inputFilter 3 minimum filter scanFrequency 0 60 Hz set analog output type to 4 20 mA outputType 1 Document Version 1 61 5 19 2011 387 Function Specifications inputType status ioWrite56070utputs 5 doutData aoutData inputFilter scanFrequency outputType add module scan to queue if ioRequest MT_56070utputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT check status of last scan if io0Status MT _56070utputs 5 amp io status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 388 Function Specifications ioWriteAout2 Write Data to 2 Point Analog Output Module Syntax include lt ctools h gt BOOLI EAN ioWriteAout2 UINT16 moduleAddress INT16 amp data 2 Description This function writes data to the I O tables for the 2 point analog output module at the specified module address Data are written to the module when an I O request for
57. 5 30pm Australian Eastern Standard Time Toll free within North America 1 888 226 6876 Direct Worldwide 61 3 9249 9580 Email au Support controlmicrosystems com Document Version 1 61 5 19 2011 18 Getting Started Getting Started This section of the C Tools User Manual describes the installation of C Tools and includes a Program Development Tutorial The Program Development Tutorial leads the user through the steps involved in writing compiling linking and loading a C application program SCADAPack C Tools Installation The SCADAPack C Tools install a gnu C compiler and controller header and support files Framework applications for Telepace and IEC 61131 1 firmware are provided Any standard Editor may be used to create C applications Telepace IEC 61131 1 or Realflo applications are used to load applications into the SCADAPack controllers These installations are described in the following sections Installing SCADAPack C Tools To install the SCADAPack C Tools e Insert the SCADAPack C Tools CD into your CD drive and follow the on screen instructions The C Tools is a command line compiler Two system properties need to be set for the compiler to work To modify system properties e From the Start menu or the Desktop right click on My Computer e Select the Advanced tab e Click Environment Variables e Inthe System Variables section at the bottom add a variable as follows
58. B8 is the message checksum include lt ctools h gt static UINT16 myModbusHandler UCHAR message UINT16 messageLength UCHAR response UINT16 responseLength Document Version 1 61 5 19 2011 647 Example Programs UCHAR pMessage UCHAR pResponse pMessage message if pMessage 71 Action for command data pMessagett if pMessage 0 request resource IO SYSTEM setdbase MODBUS 1 0 release resource IO SYSTEM pResponse response pResponse 71 pResponsett pResponse O pResponsett pResponse F pResponsett pResponse F pResponsett responseLength 4 return NORMAL else if pMessage 1 request resource IO SYSTEM setdbase MODBUS 1 1 release resource IO SYSTEM pResponse response pResponse 71 pResponsett pResponse O pResponsett pResponse N pResponsett responseLength 3 return NORMAL return FUNCTION NOT HANDLED Document Version 1 61 5 19 2011 648 Example Programs else return FUNCTION NOT HANDLED static void myshutdown void removeModbusHandler myModbusHandler This routine is the modbus slave application Serial port com2 is configured for Modbus ASCII protocol Register Assignment is configured The modbus handler is installed The exit handler is installed pa
59. DNP_MASTER configuration rtuAddress DEFAULT DNP_RTU configuration datalinkConfirm TRUE configuration datalinkRetries EFAULT DLINK RETRIES configuration datalinkTimeout EFAULT DLINK TIMEOUT J J configuration operateTimeout EFAULT OPERATE TIMEOUT configuration applicationConfirm TRUE configuration maximumResponse J DEFAULT MAX RESP_LENGTH configuration applicationRetries DEFAULT APPL RETRIES configuration applicationTimeout DEFAULT APPL TIMEOUT configuration timeSynchronization TIME SYNC configuration BI number 8 configuration BI_ cosBufferSize DEFAULT COS BUFF configuration BI_ soeBufferSiz DEFAULT SOE BUFF configuration BO number Oy configuration C1I16 number 24 configuration CI16 bufferSize 48 configuration CI32 number 12 configuration C132 bufferSize 24 configuration AI16 number 24 configuration AI16 reportingMethod CURRENT VALUE configuration AI16 bufferSize 24 configuration AI32 number 12 configuration AI32 reportingMethod CURRENT VALUE configuration AI32 bufferSize 12 configuration AO16 number 8 configuration AO32 number 87 configuration unsolicited TRUE configuration holdTime DEFAULT HOLD TIME J configuration holdCount DEFAULT_HOLD COUNT dnpSaveConfiguration
60. DYNAMIC_MEMORY resource needs to be obtained before using any of the following functions Document Version 1 61 5 19 2011 48 Real Time Operating System calloc allocates data space dynamically free frees dynamically allocated memory malloc allocates data space dynamically realloc changes the size of dynamically allocated space Inter task Communication The inter task communication functions pass information between tasks These functions can be used for data exchange and task synchronization Messages are queued by the RTOS until the receiving task is ready to process the data Inter task Communication Functions There are five RTOS functions for inter task communication Refer to the Function Specification section for details on each function listed send_message Send a message envelope to another task receive_message Read a received message from the task s message queue or wait if the queue is empty poll_ message Read a received message from the task s message queue Continue execution of the task if the queue is empty allocate_envelope Obtain a message envelope from free pool maintained by the RTOS or wait if none is available deallocate_envelope Return a message envelope to the free pool maintained by the RTOS Inter task Communication Structures Event Notification The ctools h file defines the structure Message Envelope Structure for inter task communication information Refer to the C Tools Struc
61. Dins 0 to 15 X Ain 3 f r n status dinData ainData 3 done TRUE r release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 330 Function Specifications ioRead5505Outputs Read 5505 Configuration Syntax include lt ctools h gt BOOLEAN ioRead55050utputs UINT16 moduleAddress UINT16 amp inputType 4 UINT16 amp inputFilter Description This function reads configuration data from the I O Table for a 5505 I O module Configuration data are written using the ioWrite5505Outputs function moduleAddress is the address of the 5505 module Valid values are 0 to 15 inputType is a reference to an array of four UINT16 variables Analog input measurement types are written to this array Valid values are e 0 RTD in deg Celsius e 1 RTD in deg Fahrenheit e 2 RTD in deg Kelvin e 3 resistance measurement in ohms inputFilter is a reference to a UINT16 variable The input filter selection is written to this variable e 0 0 5s e q1 i1s e 2 2S8 e 3 4s The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5505 Inputs ioWrite55050utputs Example This program reads configuration data for the 5505 I O module at address 5 include lt ctools h gt int main void UINT16 inputType 4 Document Version 1 61 5 19 2011 331 Function Specifications UINT16
62. ENABLE or TFC_NONE DISABLE macro Setting this parameter to TFC_IGNORE_CTS causes the port to ignore the CTS signal Setting this parameter to TFC_NONE causes the port to use the CTS signal which is the default setting e type specifies the serial port type It is one of RS232 RS232_MODEM or RS485_ 2WIRE macros e timeout is not supported This setting is ignored and is fixed at 600ms for backwards compatibility PID DATA The PID_DATA structure contains data for a PID control calculation The structure contains input values calculation results and internal data that needs to be maintained from one execution to the next typedef struct pidData_type Document Version 1 61 5 19 2011 621 Structures and Types input values loat pv loat sp loat gain loat reset loat rate loat deadband loat fullScale loat zeroScale loat manualOutput T32 period BOOLEAN autoMode Fh Fh Fh Fh Fh Fh Fh Fh fh G m zZ calculation results float output BOOLEAN outOfDeadband historic data values float pvN1 float pvN2 float errorNl UINT32 lastTime PID DATA e pvis the process value e spis the set point e gain is the gain e reset is the reset time in seconds e rate is the rate time in seconds e deadband is the deadband e fullScale is the full scale output limit e zeroScale is the zero scale output limit e manualOutput is the manual output value e period
63. I O Module Write data to the I O table for the digital outputs of a 5601 I O Module Write to the digital and analog outputs of SCADAPack 5604 I O Module Write to the digital and analog outputs of a 5606 I O Module Write to the digital and analog outputs of a 5606 I O Module Write data to the I O tables for any 8 point Digital output module The controller supports internal counters and external counter modules The counter registers are 32 bits for a maximum count of 4 294 967 295 They roll over to 0 on the next count The counter inputs measure the number of rising Document Version 1 61 5 19 2011 64 Overview of Programming Functions inputs Refer to the SCADAPack 350 System Hardware Manual for further information on controller counter inputs and counter input modules There are three library functions related to counters Refer to the Function Specification section for details on each function listed ioReadCounter5232 Read buffered data from the 5232 counter inputs ioReadCounter4 Read buffered data from any 4 point Counter input module Status LED and Output Functions The status LED and output indicate alarm conditions The STAT LED blinks and the STATUS output opens when an alarm occurs The STAT LED turns off and the STATUS output closes when alarms clear The STAT LED blinks a binary sequence indicating alarm codes The sequences consist of long and short flashes followed by an off delay of 1 s
64. IEEE 754 standard for floating point number representation This type is used for 32 bit points typedef struct dnpAnalogInputShortFloat_type UINT16 modbusAddress UCHAR eventClass float deadband dnpAnalogInputShortFloat e modbusAddress is the address of the Modbus register number associated with the point e eventClass is the reporting class for the object It may be set to CLASS _1 CLASS_2 or CLASS _3 e deadband is the amount by which the analog input value needs to change before an event will be reported for the point The dnpAnalogOutput type describes a DNP analog output point This type is used for both 16 bit and 32 bit points typedef struct dnpAnalogOutput_type UINT16 modbusAddress dnpAnalogOutput e modbusAddress is the address of the Modbus register associated with the point The dnpBinarylnput type describes a DNP binary input point typedef struct dnpBinaryInput_type UINT16 modbusAddress UCHAR class dnpBinarylInput e modbusAddress is the address of the Modbus register associated with the point e class is the reporting class for the object It may be set to CLASS_1 CLASS_2 or CLASS _3 The dnpBinarylnputEx type describes an extended DNP Binary Input point typedef struct dnpBinaryInputEx type UINT16 modbusAddress Document Version 1 61 5 19 2011 593 Structures and Types dnpBinaryOutput UCHAR eventClass UCHAR debounce dnpBinarylInputEx modbusAddress is
65. MARTRE SUE Tete a a a a r shes a RSE 610 MRT SE TN OS e a aa a a aE a Es 611 HART VARA B E a a ee feta eaten a a a a ete too 611 IO GONFIG Stricture oere ekeren AAEE EAE AAE EAEE ANET 611 lJOSSTATUS Structure a aa 8 exe aa aa a Ta aaa ea Taaa aae hse seehenss bbiseeeees 612 RAD RE SSA a a aaa a a ue 612 IP_CONNECTION_SUMMARY 0 c ccccceeeeseeeeeeeeceeeeeseaeeeeaeeseeeeesaaeeeeaaeseeeeeeaas 612 IP_CONFIG_MODE Enumeration cc ccccsecceceeseeceeeesneeeeessneeeeessneeeeeesneeeenss 613 IP_PROTOCOL_SETTINGS 1 0 00 ccccceccceceeeeeeeeeeeeeeeceaeeeseaeeeeeeeseeeesaeeeseaeeeeneeeaas 613 P PROTOCOL TY PEE sossve ciecns bs ced ghachacktucdaeephaabe chil desc E a a a aa Akari 614 hea A AINE Siccreecha A eA ene cle acum Aer A peat eae es 614 ledControl tagisa edanean ea esas Mise eee 615 MASTER MESSAGE sa i inian a a aed ieee nee 615 MODBUS_CMD_STATUS niiina iaiaaeaia epa aiai aaa aaan 616 Modemi comorian denies eed icine inline AN EE 618 M demSetup irrin nrn a aa aia eed ee a 618 MTCP CONFIGURATION niiina oiana aria aaa aa aa i aaa 619 MTOP IF SETTINGS eii aieiaa eaaa aa aa aa tiene 620 Document Version 1 61 5 19 2011 11 PCONPIG cave didve okie eevee i a avidin a tei 621 PIDE DATA iniae sie nied Selendis eel dina See Gree eans 621 PROTOCOL SET TINGS i eisieaa ia ee iia ery einen 623 PROTOCOL_SETTINGS_EX Type cccccccsseeeeeeeeceeeeeeeaeeeeneeseeeeeseaeeseaeeeeeeeeeas 623 Prot SetlIngS cities cali eh ene ci
66. O hardware through user assigned registers in the I O database The Register Assignment assigns I O database registers to user assigned registers using I O modules An I O Module can refer to an actual I O hardware module e g 5407 Digital Inout Module or it may refer to a set of controller parameters such as serial port settings The chapter Register Assignment Reference of the Telepace Ladder Logic Reference and User Manual contains a description of what each module is used for and the register assignment requirements for the I O module Register assignments configured using the Telepace Register Assignment dialog may be stored in the Telepace program file or downloaded directly to the controller To obtain error checking that stops invalid register assignments use the Telepace Register Assignment dialog to initially build the Register Assignment The Register Assignment can then be saved in a Ladder Logic file e g filename lad and downloaded with the C program Register Assignment Functions There are several library functions related to register assignment Refer to the Function Specification section for details on each function listed clearRegAssignment Erases the current Register Assignment addRegAssignment Adds one I O module to the current Register Assignment getlOErrorindication Gets the control flag for the I O module error indication getOutputsInStopMode Gets the control flags for state of Outputs in Ladders Stop
67. Register Assignment Reference of the Telepace Ladder Logic Reference and User Manual For module addresses com1 com2 com3 or com4 specify 0 1 2 or 3 respectively for moduleAddress For module address Ethernet specify 4 for moduleAddress For module types that have no module address e g CNFG_LEDPower specify 1 for moduleAddress For SCADAPack module types that have a module address fixed at 0 specify 0 for moduleAddress startingRegister1 specifies the first register of any unused block of consecutive registers Refer to the list of modules in the Register Assignment Reference for the type and number of registers required for this block Data read from or written to the module is stored in this block of registers If the module type specified has more than one type of I O use startingRegister2 startingRegister3 and startingRegister4 as applicable Each start register specifies the first register of an unused block of consecutive registers for each type of input or output on the module Refer to the list of modules in the Register Assignment Reference for the module I O types Specify 0 for startingRegister2 startingRegister3 or startingRegister4 if not applicable parameters is an array of configuration parameters for the register assignment module Many modules do not use the parameters and a 0 needs to be specified for the parameters Use the addRegAssignment function to configure these modules Use parameters with the following modul
68. The ctools h file defines library functions for the I O database Refer to the C Tools Macros section for details on each macro listed AB Specifies Allan Bradley database addressing DB_BADSIZE Error code out of range address specified DB_BADTYPE Error code bad database addressing type specified DB_OK Error code no error occurred LINEAR Specifies linear database addressing MODBUS Specifies Modbus database addressing NUMAB Number of registers in the Allan Bradley database NUMCOIL Number of registers in the Modbus coil section NUMHOLDING Number of registers in the Modbus holding register section NUMINPUT Number of registers in the Modbus input registers section NUMLINEAR Number of registers in the linear database NUMSTATUS Number of registers in the Modbus status section START_COIL Start of the coil section in the linear database Document Version 1 61 5 19 2011 82 Overview of Programming Functions START_HOLDING Start of the holding registers section in the linear database START_INPUT Start of the input register section in the linear database START_STATUS Start of the status section in the linear database Register Assignment I O hardware that is used by the controller needs to be assigned to I O database registers in order for these I O points to be scanned continuously I O data may then be accessed through the I O database within the C program C programs may read data from or write data to the I
69. The function returns TRUE if the configuration was read and FALSE if an error occurred Notes This function needs to be used in conjunction with the dnpReadRoutingTableEntry function to read a complete entry in the DNP routing table Document Version 1 61 5 19 2011 199 Function Specifications dnpReadRoutingTableEntry Read Routing Table entry Syntax include lt ctools h gt BOO EAN dnpReadRoutingTable UINT r16 index routingTable pRoute Description Entry This function reads an entry from the routing table pRoute is a pointer to a table entry it is written by this function The return value is TRUE if pRoute was successfully written or FALSE otherwise Notes DNP needs to be enabled before calling this function in order to create the DNP conf See iguration Also dnpWriteRoutingTableEntry Document Version 1 61 5 1 9 2011 200 Function Specifications dnpReadRoutingTableEntryEx Read Routing Table entry Syntax include lt ctools h gt BOOLEAN dnpReadRoutingTableEntryEx UINT16 index dnpRoutingTableEx entry i Description This function reads an extended entry from the DNP routing table index specifies the index of the entry in the table Valid values are 0 to the size of the table minus 1 pEntry is a pointer to an extended DNP routing table entry structure The entry is written to this structure The functi
70. This program displays the values of the digital input and the analog input read from the 4203 DR I O include lt ctools h gt define MY EVENT 1 int main void UCHAR dinData INT16 ainData UINT32 cinData 2 BOOLEAN status IO_ STATUS io_status main loop while TRUE add module scan to queue if ioRequest MT_4203DRInputs 0 Document Version 1 61 5 19 2011 316 Function Specifications status FALSE else wait for scan to complete ioNotification MY EVENT wait event MY_EVENT read input data from last scan status ioRead4203DRInputs dinData ainData cinData check status of last scan if status FALSE insert code to handle the failure here else if ioStatus MT_4203DRInputs 0 amp io status insert code to handle the failure here else if io status commStatus insert code to handle the failure here else The last scan was successful so print the data ainData fprintf com2 status u Dins 0 X Ain d r n status dinData done TRUE sleep processor for 100ms sleep processor 100 Document Version 1 61 5 19 2011 317 Function Specifications ioRead4203DSInputs Read 4203 DS Inputs Syntax include lt ctools h gt BOOLEAN i0Read4203DSInputs UCHAR amp dinData INT16 amp ainData 3 UINT32 amp
71. a communication error summary This field is bit mapped The table shows the meaning of each bit Document Version 1 61 5 19 2011 293 Function Specifications as defined by the HART protocol specifications Consult the documentation for the HART device for more information ek Desetption e vericalpartyeror s foem a T iongtudinal pariy eror 2 reserved aways0 Go bufferoverow o o oema o e f bit 7 of the high byte is cleared the high byte contains a command response summary The table shows common values Other values may be defined for specific commands Consult the documentation for the HART device 32 Busy the device is performing a function that cannot be interrupted by this command 64 Command not Implemented the command is not defined for this device e The low byte contains the field device status This field is bit mapped The table shows the meaning of each bit as defined by the HART protocol specifications Consult the documentation for the HART device for more information st essrmion CS 6 T configuration changed 4 more status available use command 48 to read 0 primary variable out of imis See Also hartSetConfiguration Document Version 1 61 5 19 2011 294 Function Specifications hartGetConfiguration Read HART Module Settings Syntax include lt ctools h gt BOOLEAN hartGetConfiguration UINT16 module HART SETTINGS settings D
72. a specific type of controller or version of firmware For Example a bug work around could be executed only if older firmware is detected Example This program displays the version information include lt ctools h gt int main void struct prot_settings settings VERSION versionInfo Disable the protocol on serial port 1 settings type NO PROTOCOL settings station T settings priority 250 settings SFMessaging FALSE request resource IO SYSTEM set_protocol coml amp settings release resource IO SYSTEM Display the ROM version information versionInfo getVersion fprintf coml r nFirmware Information r n fprintf coml Controller type d r n versionInfo controller fprintf coml Firmware version d r n versionInfo version fprintf coml Creation date s r n versionInfo date fprintf coml Copyright s r n versionInfo copyright Document Version 1 61 5 19 2011 277 Function Specifications getWakeSource Gets Conditions for Waking from Sleep Mode Syntax include lt ctools h gt UINT32 getWakeSource void Description The getWakeSource function returns a bit mask of the active wake up sources Valid wake up sources are listed below e WS_RTC_ALARM e WS_COUNTER_1_OVERFLOW e WS_COUNTER_2_OVERFLOW e WS _COUNTER_3_OVERFLOW e WS_LED_POWER_SWITCH e WS_DIN_1_CHANGE e WS_COM3_VISION See Also setPowerM
73. a standards based communications protocol developed to achieve interoperability among systems in the electric utility oil amp gas and water waste water industries This robust flexible non proprietary protocol is based on existing open standards to work within a variety of networks The IEEE has recommended DNP for remote terminal unit to intelligent electronic device messaging DNP can also be implemented in any SCADA system for efficient and robust communications between substation computers RTUs IEDs and master stations over serial or LAN based systems DNP offers flexibility and functionality that go far beyond conventional communications protocols Among its robust and flexible features DNP 3 0 includes e Output options e Addressing for over 65 000 devices on a single link Document Version 1 61 5 19 2011 74 Overview of Programming Functions e Time synchronization and time stamped events e Broadcast messages e Data link and application layer confirmation DNP 3 0 was originally designed based on three layers of the OSI seven layer model application layer data link layer and physical layer The application layer is object based with objects provided for generic data formats The data link layer provides for several methods of retrieving data such as polling for classes and object variations The physical layer defines commonly a simple RS 232 or RS 485 interface DNP Communication Protocol Functions There are s
74. aed eee bane tan eae 274 Q tStatusBits ssie mAn ai ae a edie stealer ees 275 QetTasklntors edariei ei i eda eee eed TA E a ees 276 QOLVEIrSION E E E tbibes ieee driiyee din 277 QEtW ake SourGe a nozue ain ieii iiaa eiia eiiiai iioa 278 Handler FUNCION aati ninio eieiaeo iaeiae i eataa iiad 279 AN D OPE AA E E TE A ANA EE A E ETEN 282 MAMGOMMANG sess ereua era a eraa EEE EE A A EER AG ERRES 283 MartGommMandO eiee sE e ARE ETEEN AEEA EAS 285 barncommarndi ooe iee a a ai Ra ES EAE AT E ERa AGE ARRES 286 barComnmand2 uriene a ARE EAEE EEE ATE ER EAS 287 HaAMGOMMANGS sers erene aaa are ai Aaa ES EE ATIE ERa AGa ARRES 288 hartCommandi Tess reneis irer eie ARE ET EEE AE EAR ERAS 290 HaAMGOMMANASS seere aga ara ai ARa ES EEEE AT EE ERa AGE ARRAS 291 AMS tats ee a a a E e ARE EATE AEEA EEAS 293 hartGetConfiguratiO Nesenie itanran an ateena a aaraa n a naiean a a aE 295 NantSStConfiQuration keresete sneren anu utran neata aaan eataa aa kaS a anaa 296 NartPackStrinG PA T E 297 MaMUMPACK SUING ersari eaei araar onda rae dde Eadan kadi akS 298 WNL EE E E AE A TA E EEE 299 iOa Re ved ce daceteck coctecuadasnse E AS E EO sha seas E A 300 EE a TAE A coc A EE PEE T EE EA E EE E A E 301 EEI NANG e e r E ET E E AT ES 302 INStalICIOCKHANGAIEL aieas aara irea arana KRESAA ARAKAN TERR AAA ARAE ELAn 303 installDbaseHandler cecececeeeceeeeeceeeeeeeeeeeaeeeeeeeeeeecaaaaeeeeeeeeeseceaeaeeeeeeeseeeeaees 304 installSetdbaseHandler cccccceecceceeeee
75. always enabled The function copies the settings from the structure pointed to by pSettings to the settings of the specified protocol and returns TRUE The structure IP_PROTOCOL_SETTINGS is described in the Structures and Types section If there is an invalid setting FALSE is returned and the settings are not copied To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ RUN release resource FLASH MEMORY Notes The IO_SYSTEM resource needs to be requested before calling this function with Telepace firmware See Also mTcpGetProtocol mTcpSetInterfaceEx Document Version 1 61 5 19 2011 436 Function Specifications mTcpMasterClose Close Modbus IP Master Messaging Session Syntax include lt ctools h gt BOOLEAN mTcpMasterClose UINT32 connectID Description The mTcpMasterClose function returns the specified connectID to the pool of available connections so that it may be re used for other new connections FALSE is returned if the specified connectiD is invalid or if the connection has not been disconnected otherwise TRUE is returned and the connectiD is released After calling this function the function mTcpMasterStatus may no longer be called with this connectID The function mTcpMasterDisconnect needs to be called first before
76. application UINT16 version Description This function stores or removes an application ID in the device configuration data The device configuration appears in Modbus registers if the register mapping is enabled applicationType specifies the type of application It is one of DCAT_LOGIC1 DCAT_LOGIC2 or DCAT_C e DCAT_LOGIC1 Device configuration application type is the first logic application e DCAT_LOGIC2 Device configuration application type is the second logic application e DCAT_C Device configuration application type is a C application If DCAT_C is used the application ID is added to the table of C applications The applications don t appear in any fixed order in the C application table action specifies if the ID is to be added or removed Valid values are DCA_ADD and DCA_REMOVE e DCA ADD attempting to add a duplicate value matching companylID application and version will result in only one entry in the table The function will return TRUE indicating the data is in the table e DCA_REMOVE For logic applications the ID will be removed unconditionally For C applications the ID will be removed if it is found in the table matching companylD application and version companylD specifies your company Contact Control Microsystems to obtain a company ID 0 indicates an unused entry application specifies your application Valid values are 0 to 65535 You need to maintain unique values for you
77. are no longer function calls in appstart for starting various drivers as there were in the SCADAPack version These drivers are already running when a C Application is executed It is still possible to call these Document Version 1 61 5 19 2011 679 Porting Existing C Tools Applications Add Existing Program functions to disable functionality For example runTarget FALSE may still be called from appstart or main to stop the logic application Files to Framework e Copy all user written C files from the SCADAPack application to the framework directory created in the last section e Copy user written H files if any from the SCADAPack application to the framework directory Do NOT copy the SCADAPack ctools h file or any other C Tools header files e g older SCADAPack C Tools headers such as protocol h The new ctools h is already in the framework directory e For each user written H file copied to the framework directory in step 2 make sure that the following statements are included at the top of each header file ifdef cplusplus extern C endif And also make sure that the following statements are included at the bottom of each header file ifdef cplusplus fendif e Edit the SCADAPack application file that contains the function main Open this file and copy its contents beginning after the included headers and paste this into the framework file main cpp after the prototypes as shown b
78. are using on your PC to communicate with the controller Document Version 1 61 5 19 2011 30 Getting Started e Connect com to the PC serial port using an RS 232 serial communication cable This cable is a null modem or computer to computer cable Loading the Application To load the Hello C application into the controller e From the Controller menu select the C C Program Loader command e Select the Add button and use the Browse button to locate the application It is found at C Applications IEC 61131 1 Hello myApp out Add C C Program File Name Browse Ic SP2 Applications IS aGRAF Hello myApp out write Cancel ul e Select the Write button to download to the file to the controller Executing the Program e Connect a terminal to com2 on the controller It will display the output of the program Set the communication parameters to 9600 baud 8 data bits 1 stop bit and no parity e From the C C Program Loader dialog click on the Run button to execute the program The hello world message will be displayed on the terminal e When multiple C Applications are loaded and the controller is power cycled the C Applications are restarted in the order they were first loaded to the controller Document Version 1 61 5 19 2011 31 C Program Development C Program Development Program Architecture Application Startup This section of the manual describes the proce
79. as a normal serial port Station Number The TeleBUS protocol allows up to 254 devices on a network using standard addressing and up to 65534 devices using extended addressing Station numbers identify each device A device responds to commands addressed to it or to commands broadcast to every station The station number is in the range 1 to 254 for standard addressing and 1 to 65534 for extended addressing Address 0 indicates a command broadcast to every station and cannot be used as a station number Each serial port may have a unique station number Store and Forward Messaging Store and forward messaging allows the re transmission of messages received by a controller communication interface Messages may be re transmitted on any communication interface with or without station address translation A user defined translation table determines actions performed for each message Store and forward messaging may be enabled or disabled on each port It is disabled by default Serial Communication Protocol Functions There are several library functions related to TeleBUS communication protocol Refer to the Function Specification section for details on each function listed checkSFTranslationTable Check translation table for invalid entries clear_protocol_status Clears protocol message and error counters clearSFTranslationTable Clear store and forward translation table entries get_protocol Reads protocol parameters Document Ver
80. b dbase MODBUS 30002 setdbase MODBUS 40020 a b release resource IO SYSTEM Document Version 1 61 5 19 2011 634 Example Programs void task2 void while TRUE body of task 2 loop event handler wait event TIME TO PRINT fprintf coml It s time for a coffee break r n JE osteo toscease sell see ee se eet ee The myShutdown function stops the signalling of TIME TO PRINT events when application is stopped void myShutdown void endTimedEvent TIME TO PRINT int main void TASKINFO taskStatus continuos processing task at priority 100 create task taskl 100 applicationGroup 2 event handler needs larger stack for printf function create task task2 75 applicationGroup 4 set up task exit handler to stop signalling of events when this task ends getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR myShutdown start timed even startTimedEvent TIM to occur every 10 sec _TO_ PRINT 100 Fl ct while TRUE body of main task loop other processing code Document Version 1 61 5 19 2011 635 Example Programs DataLog Example KKEKKKK KK KK KK KK KK KK KK KK KK KK KK KK KK KKK KKK KK KK KK KK KKKKKKKKKKKK KK KK KKKK DISCLAIMER This program is an example to demonstrate one or more programming functions or met
81. be returned The function has four parameters e The message parameter is a pointer to the first character of the received message The first character of the message is the function code The format of the data after the function code is defined by the function code e The messageLength parameter is the number of characters in the message e The response parameter is a pointer to the first character of a buffer to hold the response The function should write the response into this buffer The buffer is 253 characters long The first character of the buffer is the function code of the message The format of the data after the function code is defined by the function code e The responseLength parameter is a pointer to the length of the response The function should set the length of the response using this pointer The length is the number of characters placed into the response buffer The function returns one of four values The first causes a normal response to be sent The others cause an exception response to be sent e NORMAL indicates the response and responseLength have been set to valid values The Modbus protocol will add the station address and checksum to this string and transmit the reply to the master station e ILLEGAL_FUNCTION indicates the function code in the message was understood but the function was deemed illegal Document Version 1 61 5 19 2011 279 Function Specifications e ILLEGAL_DATA_ADDRESS ind
82. changed The TCP_MAXSEG value cannot be set below 64 bytes Default value is IP MTU minus 40 bytes Set this option value to a non zero value to disable the Nagle algorithm that buffers the sent data inside the TCP Useful to allow client s TCP to send small packets as soon as possible like mouse clicks Default 0 The socket descriptor to set the options on The protocol to set the option on See below The name of the option to set See below and above The pointer to a user variable from which the option value is set User variable is of data type described below The size of the user variable It is the size of the option data type described below Socket level protocol IP level protocol TCP level protocol ProtocolLevel Option Name Option data Option type value SOL_SOCKET SO_DONTROUTE int Oor1 SO_KEEPALIVE int Oor1 SO_LINGER struct linger Document Version 1 61 5 19 2011 538 Function Specifications ProtocolLevel Option Name Option data Option type value SO_OOBINLINE int 0 or 1 SO_RCVBUF unsigned long SO_RCVLOWAT unsigned long SO_REUSEADDR int 0 or 1 SO_SNDBUF unsigned long SO_SNDLOWAT unsigned long IP_PROTOIP IP_TOS unsigned char IP_TTL unsigned char IP_MULTICAST_TTL unsigned char IP_MULTICAST_IF struct in_addr IP_PROTOTCP TCP_MAXSEG int TCP_NODELAY int 0 or 1 Returns 0 Successful set of option 1 An error occurred setsockopt will fail if EBADF The socket descriptor is invalid EINVAL O
83. com2 PPP connection IPConfig_GatewayOnCom3 configures IP settings from controller settings Default gateway is the com3 PPP connection IPConfig_GatewayOnCom4 configures IP settings from controller settings Default gateway is the com4 PPP connection IP_PROTOCOL_SETTINGS The Modbus IP Protocol Settings structure defines settings for one of the Modbus IP communication protocols typedef struct st_ipProtocolSettings UINT16 portNumber UINT32 masterIdleTimeout UINT32 serverIdleTimeout BOOLEAN serverEnabled Document Version 1 61 5 19 2011 613 Structures and Types IP PROTOCOL SETTINGS e portNumber is the TCP or UDP port number for the Modbus IP of DNP IP protocol Valid port numbers are 1 to 65535 e masterldleTimeout is the length of time in seconds that a master connection will wait for the user to send the next command before ending the connection This allows the slave device to free unused connections while the master application may retain the connection allocation Set to 0 to disable timeout and let the application close the connection Valid values are any 32 bit integer Default value is 10 seconds TCP protocols only Not used by UDP protocols e _serverldleTimeout is the length of time in seconds that a server connection will wait for a message before ending the connection Set to 0 to disable timeout and let remote client close connection Valid values are any 32 bit inte
84. configured IP address that will uniquely identify the outgoing interface for multicast datagrams sent on this socket A zero IP address parameter indicates that we want to reset a previously set outgoing interface for multicast packets sent on that socket The following options are recognized at the TCP level IP_PROTOTCP protocolLevel options Document Version 1 61 5 19 2011 537 Function Specifications TCP_MAXSEG TCP_NODELAY Parameters socketDescriptor protocolLevel optionName optionValuePtr optionLength ProtocolLevel SOL_SOCKET IP_PROTOIP IP_PROTOTCP Sets the maximum TCP segment size sent on the network The TCP_MAXSEG value is the maximum amount of data including TCP options but not the TCP header that can be sent per segment to the peer i e the amount of user data sent per segment is the value given by the TCP_MAXSEG option minus any enabled TCP option for example 12 bytes for a TCP time stamp option The TCP_MAXSEG value can be decreased or increased prior to a connection establishment but it is not recommended to set it to a value higher than the IP MTU minus 40 bytes for example 1460 bytes on Ethernet since this would cause fragmentation of TCP segments Setting the TCP_MAXSEG option will inhibit the automactic computation of that value by the system based on the IP MTU which avoids fragmentation and will also inhibit Path Mtu Discovery After the connection has started this value cannot be
85. controller Write to the outputs of a 4203 DS controller Write to the digital and analog outputs of a 5606 I O Module Write to the digital and analog outputs of a 5607 I O Module The controller supports internal digital inputs and external digital input modules Refer to the SCADAPack 350 System Hardware Manual for further information on controller digital inputs and digital input modules There are several library functions related to digital inputs and external digital input modules Refer to the Function Specification section for details on each function listed ioRead5606Inputs ioReadDin5232 ioReadCounter5232 ioRead5414Inputs ioWrite54140utputs ioReadDin16 ioReadDin32 ioRead5601Inputs ioRead5604Inputs ioRead5606Ouitputs ioRead56070utputs ioReadDin8 Read the digital and analog inputs from a 5606 I O Module Read buffered data from the 5232 digital inputs Read buffered data from the 5232 counter inputs Read buffered data from the 5414 Digital input module Write 5414 module configuration parameters Read buffered data from any 16 point Digital input module Read buffered data from any 32 point Digital input module Read buffered data from the digital and analog inputs of a 5601 I O module Read the digital and analog inputs from a SCADAPack 5604 I O Module Read the digital and analog outputs from a 5606 I O Module Read the digital and analog outputs from a 5607 I O Module Read buffer
86. controller board Bits 0 1 and 2 of the status code are used by the controller firmware Attempting to control these bits will result in indeterminate operation See Also getStatusBit Document Version 1 61 5 19 2011 540 Function Specifications setStatusMode Set Source for Status LED Syntax include lt ctools h gt void setStatusMode UINT16 mode Description The setStatusMode function controls wether APPLICATION or SYSTEM status bits are shown on the STAT LED The function has no return value Document Version 1 61 5 19 2011 541 Function Specifications setWakeSource Sets Conditions for Waking from Sleep Mode Syntax include lt ctools h gt void setWakeSource UINT32 enableMask Description The setWakeSource routine enables and disables sources that will wake up the processor It enables all sources specified by enableMask All other sources are disabled Valid wake up sources are listed below Multiple sources may be ORed together e WS_NONE e WS_ALL e WS_RTC_ALARM e WS _COUNTER_1_OVERFLOW e WS _COUNTER_2_ OVERFLOW e WS _COUNTER_3 OVERFLOW e WS_LED POWER_SWITCH e WS_DIN_1_CHANGE e WS_COM3_VISION Notes Specifying WS_NONE as the wake up source will keep the controller from waking except by a power on reset See Also getWakeSource setPowerMode Example The code fragments below show how to enable and disable wake up sources Wake up on all sources setWak
87. create the DNP configuration Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 203 Function Specifications dnpSaveAl32Config Save DNP 32 Bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAI32Config UINT32 point dnpAnalogInput pAnalogInput 7 Description The dnpSaveAl32Config function sets the configuration of a DNP 32 bit analog input point The function has two parameters the point number and a pointer to an analog input point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetAl32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 204 Function Specifications dnpSaveAlSFConfig Save Short Floating Point Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAISFConfig UINT16 point dnpAnalogInput pAnalogInput Description The dnpSaveAlSFConfig function sets the configuration of a DNP short floating point analog input point The function has two parameters the point number and a pointer to a configuration structure The functi
88. ctools h gt struct pconfig settings Document Version 1 61 5 19 2011 520 Function Specifications request resource IO SYSTEM set_port com2 get_port coml amp settings release resource IO SYSTEM Document Version 1 61 5 19 2011 521 Function Specifications setLoginCredentials Sets login credentials for a service Syntax include lt ctools h gt BOOLEAN setLoginCredentials UINT32 service UINT32 index UCHAR username UCHAR password Parameters service specifies the service for which the credentials are being set index specifies the index for the credentials Indices are service specific username specifies the username to grant access to password specifies the password that is valid with the username Description The setLoginCredentials function registers a username and password pair for the specified service Valid services are 0 FTP Maximum username and password length is 16 bytes Only index 0 is supported The valid values of index are service specific The username and password are both NULL terminated strings with a service defined maximum length True is returned if the credentials were set False is returned if the service rejected the credentials or if the service was unrecognized Notes Duplicate usernames are supported See Also getLoginCredentials clearLoginCredentials Document Version 1 61 5 19 2011 522 Function Specifi
89. data e checksum_errors is the number of messages received with bad checksums e cmd_received is the number of commands received e cmd_sent is the number of commands sent by the master_message function e rsp_received is the number of responses received by the master_message function e rsp_sent is the number of responses sent e command is the status of the last protocol command sent e task_id is the ID of the protocol task This field is used by the set_protocol function to control protocol execution e stored_messages is the number of messages stored for forwarding e forwarded_messages is the number of messages forwarded PORT_CHARACTERISTICS The PORT_CHARACTERISTICS type is a structure that contains serial port characteristics typedef struct portCharacteristics tag UINT16 dataflow UINT16 buffering UINT16 protocol UINT32 options PORT CHARACTERISTICS e dataflow is a bit mapped field describing the data flow options supported on the serial port ANDing can isolate the options with the PC_FLOW_RX_RECEIVE_STOP PC_FLOW_RX_XON_XOFF PC_FLOW_TX_IGNORE_CTS or PC_FLOW_TX_XON_XOFF macros e buffering describes the buffering options supported No buffering options are currently supported e protocol describes the protocol options supported The macro PC_PROTOCOL_RTU_FRAMING is the only option supported e options describes additional options supported No additional options are currently supported
90. data byte is provided with the TCP protocol when the SO_OOBINLINE option is not set If an out of band data byte is present recv with the MSG_OOB flag not set will not read past the position of the out of band data byte in a single recv request That is if there are 10 bytes from the current read position until the out of band byte and if we execute a recv specifying a bufferLength of 20 bytes and a flag value of 0 recv will only return 10 bytes This forced stopping is to allow us to determine when we are at the out of band byte mark When we are at the mark recv with the MSG_OOB flag set can read the out of band data byte The user needs to use select in order to know when out of band data has arrived or is arriving Out of band data when the SO_OOBINLINE option is set see setsockopt TCP protocol only If the SO_OOBINLINE option is enabled the out of band data is left in the normal data stream and is read without specifying the MSG_OOB More than one out of band data bytes can be in the stream at any given time The out of band byte mark corresponds to the final byte of out of band data that was received In this case the MSG_OOB flag cannot be used with recv The out of band data will be read in line with the other data Again recv will not read past the position of the out of band mark in a single recv request The user needs to use select in order to know when out of band data has arrived or is arriving Document Version
91. data is read from the log at a slower rate than it is logged it is possible that the sequence numbers of the records read will not be sequential This indicates that records were overwritten between calls to read data The sequence number rolls over after reaching its maximum value Document Version 1 61 5 19 2011 138 Function Specifications See Also See example DataLog program in the Example Programs section datalogReadStart datalogPurge datalogWrite Example See the example for datalogReadStart Document Version 1 61 5 19 2011 139 Function Specifications datalogReadStart Read Data Log Start Function Syntax include lt ctools h gt BOOLEAN datalogReadStart UINT16 ogID UINT32 pSequenceNumber Description This function returns the sequence number of the record at the start of the data log This is the oldest record in the log The function has two parameters og D specifies the data log The valid range is 0 to 15 pSequenceNumber is a pointer to a variable to hold the sequence number The function returns TRUE if the operation succeeded The function returns FALSE if the log ID is not valid or if the log has not been created Notes Use the datalogReadNext function to read records from the log The function will return a sequence number even if the log is empty In this case the next call to datalogReadNext will return no data See Also See example DataLog program in the Example Pr
92. delivery of data and SO_LINGER is set the system will block the process on the close of the socket attempt until it is able to transmit the data or decides it is unable to deliver the information A timeout period termed the linger interval is specified in the setsockopt call when SO_LINGER is requested If SO_LINGER is disabled and a close on the socket is issued the system will process the close of the socket in a manner that allows the process to continue as quickly as possible The option SO BROADCAST requests permission to send broadcast datagrams on the socket With protocols that support out of band data the SO_OOBINLINE option requests that out of band data be placed in the normal data input queue as received it will then be accessible with recv call without the MSG_OOB flag SO_SNDBUF and SO_RCVBUF are options that adjust the normal buffer sizes allocated for output and input buffers respectively The buffer size may be increased for high volume connections or may be decreased to limit the possible backlog of incoming data The Internet protocols place an absolute limit of 64 Kbytes on these values for UDP and TCP sockets in the default mode of operation The following options are recognized at the IP level IP_PROTOIP protocolLevel options IP_TOS IP type of service Default 0 IP_TTL IP Time To Live in seconds Default 64 IP_MULTICAST_TTL Change the default IP TTL for outgoing multicast datagrams IP_MULTICAST_IF Specify a
93. description of the structure for an explanation of the parameters The function returns TRUE if the settings were retrieved It returns FALSE if the stream is not valid Notes Extended addressing and the Enron Modbus station are available on the Modbus RTU and Modbus ASCII protocols only See the TeleBUS Protocols User Manual for details See Also setProtocolSettingsEx setProtocolSettings start_protocol get_protocol get_protocol_status set_protocol modemNotification Example This program displays the protocol configuration for com1 include lt ctools h gt int main void PROTOCOL SETTINGS EX settings if getProtocolSettingsEx coml amp settings fprintf coml Type d r n settings type fprintf com1 Station d r n settings station fprintf com1 Address Mode d r n settings mode fprintf coml SF Sd r n settings SFMessaging fprintf com1 Priority d r n settings priority fprintf com1 Enron Sd r n settings enronEnabled fprintf com1 Enron station d r n Document Version 1 61 5 19 2011 264 Function Specifications settings enronStation fprintf coml Serial port is not valid r n Document Version 1 61 5 19 2011 265 Function Specifications get_protocol_status Get Protocol Information Syntax include lt ctools h gt struct prot status get protocol status FILE stream Description The get_protoc
94. details The handler function has one parameter e event is DNP event that has occurred It may be one of DNP_CONNECTION_REQUIRED DNP_MESSAGE_COMPLETE or DNP_MESSAGE_TIMEOUT See the structure definition for the meaning of these events The handler function has no return value By default no connection handler is installed and no special steps are taken when DNP requires a connection receives a message confirmation or a timeout occurs See Also dnpConnectionEvent Document Version 1 61 5 19 2011 186 Function Specifications Example This example shows how a C application can handle the events and inform a logic application of the events The logic application is responsible for making and ending the dial up connection The program uses the following registers e 10001 turns on when a connection is requested by DNP for unsolicited reporting e 10002 turns on when the unsolicited report is complete e 10003 turns on when the unsolicited report is fails e The ladder logic program turns on register 1 when the connection is complete and turns off the register when the connection is broken JR sete eee Bo Bee Ae Be SU ea ee es Se eet ee dnp c Demonstration program for using the DNP connection handler Copyright 2001 Control Microsystems Inc Af JR Becht coe ee ee Se Se ee eo ee ee Ss Include Files Ay include lt ctools h gt PRs Se ae eee et ee Ses ee ee
95. e CI32_bufferSize is the number of events in the 32 bit counter change buffer Valid values are 0 to 9999 e CI32_wordOrder is the Word Order of CI32 points O LSW first 1 MSW first e Al16_number is the number of 16 bit analog input points Valid values are 0 to 9999 e Al16_startAddress is the DNP address of the first Al16 point e Al16_reportingMethod determines how 16 bit analog changes are reported e Set this to FIRST _VALUE to report the value of the first change event measured e Set this to CURRENT_VALUE to report the value of the latest change event measured e Al16_bufferSize is the number of events in the 16 bit analog input change buffer Valid values are 0 to 9999 e AI32_number is the number of 32 bit analog input points Valid values are 0 to 9999 e AI32_startAddress is the DNP address of the first Al32 point e AI32_reportingMethod determines how 32 bit analog changes are reported e Set this to FIRST _VALUE to report the value of the first change event measured e Set this to CURRENT_VALUE to report the value of the latest change event measured Document Version 1 61 5 19 2011 602 Structures and Types e Al32_bufferSize is the number of events in the 32 bit analog input change buffer Valid values are 0 to 9999 e Al32_wordOrder is the Word Order of Al32 points O LSW first 1 MSW first e AISF_number is the number of short float Analog Inputs e AISF_startAddress is the DNP address of first
96. e DLOGS_ SUCCESS if the write was successful e DLOGS_BUFFERFULL if the record could not be written because of a full buffer e DLOGS_BADID if the data log ID is not valid e DLOGS FAILURE if the record could not be written due to a run time error Description This function writes a record to the data log specified by dlogID Memory is copied from the pointer address to the data log buffer The data is packed as it is written to the buffer Gaps due to structure alignments are not written Packing is performed using the size and offset information specified during data log creation dlogWrite stores a record sequence number at the start of the record in the buffer A CRC16 value is computed for the data including the heading sequence number and stored at the end of the record The data log buffer is flushed regularly to data log files by the data log server task See Also dlogFlush Document Version 1 61 5 19 2011 160 Function Specifications dnpClearEventLogs Clear DNP Event Log Syntax include lt ctools h gt BOOLI FAN dnpClear Description EventLogs void The dnpClearEventLogs function deletes all change events from the DNP change event buffers for all point types Document Version 1 61 5 19 2011 161 Function Specifications dnpConnectionEvent Report a DNP connection event Syntax include lt ctools h gt void dnpConnectionEvent UINT16 dnpAddress DNP_CONNECTION
97. error can be retrieved by calling getErrorCode socketDescriptor select will fail if EBADF One of the socket descriptors is bad EINVAL A component of the pointed to time limit is outside the acceptable range tv_sec needs to be between 0 and 10 8 inclusive tv_usec needs to be greater than or equal to 0 and less than 10 6 Document Version 1 61 5 19 2011 497 Function Specifications send Syntax include lt ctools h gt int send int socketDescriptor char bufferPtr int bufferLength int flags Description send is used to transmit a message to another transport end point send may be used only when the socket is in a connected state socketDescriptor is a socket created with socket If the message is too long to pass atomically through the underlying protocol non TCP protocol then the error EMSGSIZE is returned and the message is not transmitted A return value of 1 indicates locally detected errors only A positive return value does not implicitly mean the message was delivered but rather that it was sent Blocking socket send if the socket does not have enough buffer space available to hold the message being sent send blocks Non blocking stream TCP socket send if the socket does not have enough buffer space available to hold the message being sent the send call does not block It can send as much data from the message as can fit in the TCP buffer and returns the length of the d
98. for declaring non volatile variables Consider the following C Application defined in the two files main cpp and file2 cpp The first version of these files defines which non volatile variables are required for each file Local and module variables would normally exist as well Document Version 1 61 5 19 2011 40 C Program Development Version 2 main cpp include ctools h Non volatile variables required by main cpp static UINT32 variablel static UCHAR array1l 20 static struct sample table 10 void main void variablel arrayl 0 table 0 index file2 cpp include ctools h Non volatile variables required by file2 cpp static UINT32 variable2 void functionl void variable2 This second version of these files shows how to declare these variables as non volatile To do this the declarations have been moved to the header file nvMemory h and are shown in bold below A template for nvMemory h is provided in the sample C Application This header file needs to be included in each file that accesses the non volatile variables The only undesirable effect of making certain variables non volatile is that these variables need to become global variables To access the non volatile variables in code use the pointer pNvMemory to the NV_MEMORY structure as shown below main cpp include ctools h include nvMemory h void main void pNvMemory
99. from flash A sum of more than one area may be selected If an unsupported flag is set the flag has no effect If there is no supported flag set e g areaFlags 0 nothing is done The function has no return value See the function flashSettingsSave for a list of valid flags Notes The FLASH_MEMORY resource needs to be requested before calling this function Document Version 1 61 5 19 2011 239 Function Specifications flashSettingsSave Save Controller Settings to Flash Syntax include lt ctools h gt BOOLEAN flashSettingsSave UINT32 areaFlags Description This function stores the controller settings in the indicated area or areas to flash memory Settings in other areas are not affected The function has one parameter areaFlags indicating which areas to store into flash A sum of more than one area may be selected The function returns TRUE if all the settings were stored and FALSE if there was an error writing to flash If an unsupported flag is set the flag has no effect If there is no supported flag set e g areaFlags 0 all current settings are saved again Valid flags are listed below and defined in ctools h Area Flag Loaded on Reset Controller Settings in this Area CS_ETHERNET Ethernet MAC address CS_OPTIONS Controller factory options CS_PERMANENT Saved settings loaded Controller type IP address on Service and Run Gateway Network mask IP Boot Configuration mode Lock
100. future use 2 At OFF channel 3 RTD is good ON channel 3 RTD is open or PWR input is off OFF channel 3 data in range O Ootame gata tetas O 14 OFF channel 3 RTD is using 3 wire measurement OM etann oe usna re measurement Reserved for future use ainData is a reference to an array of four floating point variables Analog data are written to this array The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5505Outputs ioWrite5505Outputs Example This program displays the values of the 16 internal digital inputs and the 4th analog input read from 5505 I O at address 5 include lt ctools h gt define MY EVENT 1 int main void UINT16 dinData float ainData 4 IO_ STATUS io_status BOOLEAN status BOOLEAN done main loop while TRUE add module scan to queue if ioRequest MT_5505Inputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_EVENT read input data from last scan Document Version 1 61 5 19 2011 329 Function Specifications status ioRead5505Inputs 5 dinData ainData check status of last scan if ioStatus MT 5505Inputs 5 amp io status status FALSE else if io status commStatus status FALSE print data if done fprintf coml status u
101. h gt define MY EVENT aL void main void UCHAR dinData 3 INT16 ainData 8 IO_ STATUS io_status BOOLEAN status main loop while TRUE add module scan to queue if ioRequest MT_5607Inputs 5 Document Version 1 61 5 19 2011 341 Function Specifications status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioRead5607Inputs 5 dinData ainData check status of last scan if ioStatus MT _5607Inputs 5 amp io status status FALSE else if io status commStatus status FALSE print data fprintf com3 status u Dins 0 to 7 X Ain 4 status dinData 0 ainData release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 342 Function Specifications ioRead5607 Outputs Read 5607 Outputs Syntax include lt ctools h gt BOOLEAN i0Read56070utputs UINT16 moduleAddress UCHAR amp doutData 2 INT16 amp aoutData 2 UINT16 amp inputType 8 UINT16 amp inputFilter UINT16 amp scanFrequency UINT16 amp outputType Description This function reads buffered data from the digital and analog outputs of a 5607 I O module Buffered data are written using the ioWrite5607Outputs function moduleAddress is the addr
102. handle responses this large e applicationRetries is the number of times the application layer will retry a transmission Valid values are 0 to 255 e applicationTimeout is the length of time the application layer will wait for a response before trying again or aborting the transmission The value is measured in milliseconds Valid values are 100 to 60000 in multiples of 100 milliseconds This value must be larger than the data link timeout e timeSynchronization defines how often the RTU will request a time synchronization from the master e Set this to NO_TIME_SYNC to disable time synchronization requests e Set this to STARTUP_TIME_SYNC to request time synchronization at start up only e Set this to 1 to 32767 to set the time synchronization period in seconds e Bl_number is the number of binary input points Valid values are 0 to 9999 e Bl_startAddress is the DNP address of the first Binary Input point e Bl_reportingMethod determines how binary inputs are reported either Change Of State or Log All Events e Bl_soeBufferSize is the Binary Input Change Event Buffer Size e BO_number is the number of binary output points Valid values are 0 to 9999 e BO_startAddress is the DNP address of the first Binary Output point e Cl16_number is the number of 16 bit counter input points Valid values are 0 to 9999 e Cl16_startAddress is the DNP address of the first C116 point e Cl16_reportingMethod determines how Cl16 inputs are r
103. handler has connected to the master station The application sends this event to DNP When DNP receives this event it will send unsolicited messages Document Version 1 61 5 19 2011 594 Structures and Types dnpConfiguration The DNP_DISCONNECTED event indicates that the handler has disconnected from the master station The application sends this event to DNP When DNP receives this event it will request a new connection before sending unsolicited messages The DNP_CONNECTION_ REQUIRED event indicates that DNP wishes to connect to the master station DNP sends this event to the application The application should process this event by making a connection The DNP_MESSAGE_COMPLETE event indicates that DNP has received confirmation of unsolicited messages from the master station DNP sends this event to the application The application should process this event by disconnecting In many applications a short delay before disconnecting is useful as it allows the master station to send commands to the slave after the unsolicited reporting is complete The DNP_MESSAGE_TIMEOUT event indicates that DNP has attempted to send an unsolicited message but did not receive confirmation after all attempts This usually means there is a communication problem DNP sends this event to the application The application should process this event by disconnecting The dnpConfiguration type describes the DNP parameters typedef struct dnpConfigur
104. handler when the main task ends void mainExitHandler void unhook the handler function enronInstallCommandHandler NULL int main void TASKINFO thisTask Document Version 1 61 5 19 2011 234 Function Specifications install handler to execute when this task ends thisTask getTaskInfo 0 installExitHandler thisTask taskID FUNCPTR mainExitHandler install handler for Enron Modbus enroninstallCommandHandler commandHandler infinite loop of main task while TRUE add application code here Document Version 1 61 5 19 2011 235 Function Specifications ethernetGetIP Get Ethernet Controller TCP IP Settings Syntax include lt ctools h gt void ethernetGetIP IP_SETTINGS pIPSettings Description The ethernetGetIP function copies the Ethernet controller TCP IP settings into the structure pointed to by p PSettings The structure IP_SETTINGS is described in the Structures and Types section See Also ethernetSetIP Document Version 1 61 5 19 2011 236 Function Specifications ethernetGetMAC Address Get Ethernet Controller MAC address Syntax include lt ctools h gt void ethernetGetMACAddress CHAR pMAC Description The ethernetGetMACAddress function copies the Ethernet controller MAC address to the array pointed to by pMAC pMAC must point to an array of 6 bytes Document Versi
105. in the ARM7 folder e C Tools header and support files are installed in o Controller IEC 61131 1 for IEC 61131 1 firmware applications o Controller Telepace for Telepace firmware applications e Framework applications are installed in Controller Framework Applications These are described further in the product development tutorial e Documentation shortcuts are on the Start menu You need to have found them if you re reading this so we won t say any more Program Development Tutorial Program development consists of three stages writing and editing compiling and linking and loading the program into the target controller Each step uses separate tools To demonstrate these steps a sample program will be prepared Traditionally the first program that is run on a new C compiler is the hello world program It prints the message hello world Hey who are we to be different Document Version 1 61 5 19 2011 20 Getting Started Create a New C Application Framework Any editor may be used to write and edit the application program for the SCADAPack controllers Copy C Application Framework Review appstart cpp Edit main cpp Begin by making a copy of the C application framework using the IEC 61131 1 sample application or the Telepace sample application By default the samples are installed at C program files Control Microsystems CTools Controller Framework Applications Make a copy of either the IEC 61131 1
106. in the original release of the Telepace C Tools They were supported for backward compatibility in later versions of the Telepace C Tools but did not allow access to all I O modules They are no longer compatible with the I O system architecture These functions are replaced with equivalent I O system functions The new functions provide access to all I O modules a rarer ition group fain functions inthe ioRead group__ _ Other I O Function Changes Jiffy Clock Functions The following C Tools I O functions are fully supported in the SCADAPack C Tools with the following difference Instead of executing the required I O operation immediately before returning from the function the I O operation is added to the I O System queue as an I O request and is performed by the I O System architecture in parallel with application program execution Notification of the completion of an I O request may be obtained using the ioNotification function hartlO Request a hart I O module scan The scan reads data from the 5904 interface module processes HART responses processes HART commands and writes commands and configuration data to the 5904 interface module Request all O points to be cleared The C Tools function jiffy is replaced with the readStopwatch function This function returns the time in milliseconds Existing programs need to be modified to call the new function and to convert any timing constants to millise
107. int lastConnectionState last state of connection register int currentConnectionState current state of connection register install DNP connection handler dnpInstallConnectionHandler sampleDNPHandler get the current connection state lastConnectionState dbase MODBUS CONNECTION STATUS loop forever while TRUE request resource IO SYSTEM get the current connection state currentConnectionState dbase MODBUS CONNECTION STATUS if the state has changed if currentConnectionState lastConnectionState if the connection is active if currentConnectionState Inform DNP that a connection exists xy dnpConnectionEvent DNP_CONNECTED clear the request flag setdbase MODBUS CONNECTION REQUIRED 0 else Inform DNP that the connection is closed dnpConnectionEvent DNP_DISCONNECTED clear the message flags Document Version 1 61 5 19 2011 189 Function Specifications setdbase MODBUS MESSAGE COMPLETE 0 setdbase MODBUS MESSAGE FAILED 0 save the new state lastConnectionState currentConnectionState the processor so other tasks can run releas release resource IO SYSTEM release processor 190 Document Version 1 61 5 19 2011 Function Specifications
108. is the execution period in milliseconds e autoMode is the auto mode flag TRUE auto FALSE manual e output is the last output value e outOfDeadband is the error is outside the deadband e pvN1 is the process value from n 1 iteration e pvN2 is the process value from n 2 iteration e errorN1 is the error from n 1 iteration e _lastTime is the time of last execution Document Version 1 61 5 19 2011 622 Structures and Types PROTOCOL_SETTINGS The Extended Protocol Settings structure defines settings for a communication protocol This structure differs from the standard settings in that it allows additional settings to be specified typedef struct protocolSettings t UCHAR type UINT16 station UCHAR priority UINT16 SFMessaging ADDRESS MODE mode PROTOCOL SETTINGS type is the protocol type It may be one of NO PROTOCOL MODBUS_RTU or MODBUS_ ASCII AB_FULL_BCC AB_FULL_CRC AB_HALF_BCC DNP or AB_HALF_CRC macros To set the remaining settings use the function mTcpSetInterfaceEx station is the station address of the controller Each serial port may have a different address The valid values are determined by the communication protocol This field is not used if the protocol type is NO PROTOCOL priority is the task priority of the protocol task This field is not used if the protocol type is NO_ PROTOCOL SFMessaging is the enable Store and Forward messaging control flag ADDRESS_ MODE is
109. logName strLogName strlen strLogName 1 Create the log dlogStatusInfo dlogCreate amp usbMemLogConfig amp dlogidNumber while TRUE Read RTC and I Os request resource IO SYSTEM databaseRead MODBUS 10001 amp dinlCurrentState getclock amp currentTime release resource IO SYSTEM m Turn on FORCE LED flashing and data logging if DIN1 is turned ON if dinlCurrentState if currentTime second rtcPreviousSecond rtcPreviousSecond currentTime second forceLed getForceLed Log data every 5 seconds if currentTime second 5 Document Version 1 61 5 19 2011 639 Example Programs if logData request resource IO SYSTEM Get RTC time stamp date time getClockTime amp flashMemoryRecord valuel days amp flashMemoryRecord valuel centiseconds Read AIN1 raw value databaseRead MODBUS 30001 amp flashMemoryRecord value2 release resource IO_ SYSTEM Scale AIN1 0 100 flashMemoryRecord value3 float flashMemoryRecord value2 16384 0 100 0 Write date to log file dlogStatusInfo dlogWrite dlogidNumber UCHAR amp flashMemoryRecord if dlogStatusInfo DLOGS_ BUFFERFULL dlogStatusInfo dlogFlush dlogIdNumber dlogStatusInfo dlogWrite dlogIdNumber
110. needs to be repeated at a fixed interval of time The timed event feature sets up a periodic event that is signaled by the operating system at a specified fixed interval Document Version 1 61 5 19 2011 689 Porting Existing C Tools Applications A main application task or an additional application task can be made to wait on a periodic event before executing a set of actions If the actions are completed before the next periodic event has been signaled the task is blocked while waiting for the event This blocked state allows the processor to execute other application or system tasks while it waits This is more efficient than executing a loop that checks for a timer to expire For an example using timed events see the function startTimedEvent Reading the System Stopwatch For one time actions and timed actions that need accuracy better that a tenth of a second the system clock may be read using the function readStopwatch This function returns the system time in milliseconds and has a resolution of 10 ms The stopwatch time rolls over to 0 when it reaches the maximum value for an unsigned long int i e a UINT32 4 294 967 295 ms or about 49 7 days For example startTime readStopwatch wait for 50 ms 10 ms while readStopwatch startTimed lt 50 release_processor Refer to the section describing the function readStopwatch for other timing examples using this function Modbus Handler Fu
111. o Click New o In Variable Name type CTOOLS_PATH o In Variable Value type C program files Control Microsystems CTools if you installed to a different path then substitute the correct path here o Click OK e Inthe System Variables section at the bottom modify the PATH variable as follows o Locate the PATH variable Document Version 1 61 5 19 2011 19 Getting Started Installing Telepace o Click Edit o In Variable Value add the following at the start of the text including the semi colon at the end of the string C Program Files Control Microsystems CTools Arm7 host x86 win32 bin if you installed to a different path then substitute the correct path here o Click OK e Click OK Install Telepace as described on the jewel case liner of the Telepace Installation CD Some virus checking software may interfere with Setup If you experience difficulties with the Setup disable your virus checker and run Setup again Installing IEC 61131 1 Workbench Install IEC 61131 1 as described on the jewel case liner of the IEC 61131 1 Installation CD Some virus checking software may interfere with Setup If you experience difficulties with the Setup disable your virus checker and run Setup again Viewing Installed Components The C Tools installs the following components All files are installed by default to C program files Control Microsystems CTools e gnu C compiler for Arm7 processor is installed
112. occurred This informs the modem handler not to disconnect an incoming call when an outgoing call is requested with modemDial This function is used with custom communication protocols The function is usually called when a message is received by the protocol although it can be called for other reasons The port_index indicates the serial port that received the message Notes The serial port type must be set to RS232_MODEM The dial up connection handler stops outgoing calls from using the serial port when an incoming call is in progress and communication is active If communication stops for more than five minutes then outgoing call requests are allowed to end the incoming call This keeps the modem or the calling application from permanently disabling outgoing calls The function is used with programs that dial out through an external modem using the modemDial function It is not required where the modem is used for dialing into the controller only Document Version 1 61 5 19 2011 428 Function Specifications mTcpGetConfig Get Modbus TCP Protocol Settings Syntax include lt ctools h gt UINT16 mTcpGetConfig MTCP_CONFIGURATION pSettings Description The mTcpGetConfig function copies the Modbus TCP protocol settings to the structure pointed to by pSettings The structure MTCP_CONFIGURATION is described in the Structures and Types section The settings are common to all connections using the Modbus TCP protocol
113. of status is determined by the requirements of the host computer Notes The specified result will be sent each time that the protocol command is received until a new result is specified The result is cleared when the controller is reset The application program needs to initialize the status each time it is run See Also master_message Document Version 1 61 5 19 2011 415 Function Specifications modbusSlavelD Set Response to Protocol Command Syntax include lt ctools h gt void modbusSlaveID UCHAR string UINT16 length Description The modbusSlavelD function is used in conjunction with the Modbus compatible communication protocol It sets the result returned in response to the Report Slave ID command This command is provided for compatibility with some Modbus protocol drivers for host computers string points to a string of at least length characters The contents of the string are determined by the requirements of the host computer The string is not NULL terminated and may contain multiple NULL characters The length specifies how many characters are returned by the protocol command length must be in the range 1 to REPORT _SLAVE_ID_SIZE If length is too large only the first REPORT_SLAVE_ID_SIZE characters of the string will be sent in response to the command Notes The specified result will be sent each time that the protocol command is received until a new result is specified The function copie
114. of this variable is written with the com3 HMI power control e Bits 2 to 7 are not used The function returns TRUE as no I O errors are possible See Also ioRead5210Inputs ioWrite52100utputs Document Version 1 61 5 19 2011 322 Function Specifications ioRead541 4Inputs Read 5414 module inputs Syntax include lt ctools h gt BOOLEAN ioRead5414Inputs UINT16 moduleAddress UCHAR amp dinData 2 Description This function reads buffered data from the digital inouts5414 module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5414 module Valid values are 0 to 15 dinData is a reference to an array of two UCHAR variables Digital data for the 16 inputs are written to this array One bit in the array represents each input point See Also ioWrite5414Outputs Example This program displays the values of the first 8 digital inputs include lt ctools h gt include nvMemory h define MY EVENT 1 void main void UCHAR dinData 2 IO_ STATUS io_status BOOLEAN status main loop while TRUE add module scan to queue if ioRequest MT_5414Inputs 0 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioRead5414Inputs 0 dinData Document Version 1 61 5 19 2011
115. out file which is loaded into the controller Generally no changes will ever be required in this section The compiler options affecting this that should be changed are defined in the CFLAGS setting above APPLICATION NAME out imImage o intermediate objects Process CPP constructors and destructors Document Version 1 61 5 19 2011 24 Getting Started echo GeChO S ee saorssace ost echo Building output file lecho sste SR SESS He sae Scs nmarm imImage o CTOOLS PATH Arm7 tcl bin tclsh84 exe S CTOOLS PATH Arm7 host x86 win32 bin munch tcl c arm gt ctdt c ccarm CFLAGS c fdollars in identifiers ctdt c o ctdt o Link downloadable application ccarm I r nostdlib Wl X Wl EL T S CTOOLS PATH Arm7 target h tool gnu ldscripts link OUT imImage o ctdt o o APPLICATION NAME out Clean up temporary files del ctdt c ctdt o The next sections describe how to make the intermediate objects and check that symbols will be resolved when the application is loaded into the controller Generally no changes will ever be required in this section rules for making intermediate objects imImage o objects Merge all object files into one ccarm I r nostdlib Wl X W1 EL Wl S objects o imImage o link with controller specific CTools library to check for unresolved externals MES E O E EEO E E OE imLink SCADAPack350 0 imImage o echo COChO SoS SSRs SSS
116. request queue an I O module scan request for the specified I O module The function has two arguments the module type and the module address Refer to the table below for valid I O module types and address ranges The function returns TRUE if the request was added The function returns FALSE if there is no room in the request queue or if an argument is invalid Document Version 1 61 5 19 2011 363 Function Specifications Document Version 1 61 5 19 2011 364 Function Specifications ioSetConfiguration Set I O Controller Configuration Syntax include lt ctools h gt BOOLEAN ioSetConfiguration const IO CONFIG amp settings Description This function sets the I O controller configuration and adds a request to write the settings to the I O controller The function has one argument a reference to an IO_CONFIG structure The function returns TRUE if the request was added The function returns FALSE if there is no room in the request queue or if there is an error in the settings Document Version 1 61 5 19 2011 365 Function Specifications ioStatus Read Status of Last Scan of Specified I O Module Syntax include lt ctools h gt BOOLEAN ioStatus IO TYPE moduleType UINT16 moduleAddress IO_ STATUS status Description This function reads the status of the last scan of the specified I O module The function has three arguments the module type the module address and a p
117. sestatsacses arses sate aS disse sess csass Configure 32 Bit Analog Input Points Lape Tea S eS se a aaa so eS reo Se es for index 0 index lt configuration AI32 number index analogInput modbusAddress 30001 index analogInput eventClass CLASS 2 analogiInput deadband 1 dnpSaveAI32Config configuration AI16 startAddress index amp analogInput pega aoa Sane a RS Sane ae Se a ee a ee Configure 16 Bit Analog Output Points CA xia adicicala ia ica deca kee ae al aT A for index 0 index lt configuration AO16 number index analogOutput modbusAddress 40001 index dnpSaveAOl16Config configuration AO16 startAddress index amp analogOutput A PSR SRS SSS SaaS eS aera Seo SS See e aS E Ss Configure 32 Bit Analog Output Points Lis OSs HS SSE SS es SS ee oe ge Se sree eee for index 0 index lt configuration AO32 number index analogOutput modbusAddress 41001 index 2 dnpSaveA032Config configuration A032 startAddress index amp analogOutput ifPne sense seas tats S Ges staa eS Sass hess er sa esses ass sse Configure 16 Bit Counter Input Points Pea SSRs a ee apa ge re en ee T for index 0 index lt configuration CI16 number index counterInput modbusAddress 30001 index counterInput eventClass CLASS 3 counterInput threshold 1 dnpSaveCI16Config configuration CI16 startAddress index amp counterInput fire eas SS ae er ee ee a eee eae eas
118. settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Example include lt ctools h gt int main void struct ledControl_tag ledControl request resource IO SYSTEM Turn LEDS off after 20 minutes ledControl time 20 ledControl state LED OFF ledSetDefault ledControl release resource IO SYSTEM the reset of the program Document Version 1 61 5 19 2011 409 Function Specifications listen Syntax include lt ctools h gt int listen int socketDescriptor int backLog Description To accept connections a socket is first created with socket a backlog for incoming connections is specified with listen and then the connections are accepted with accept The listen call applies only to sockets of type SOCK_STREAM The backLog parameter defines the maximum length the queue of pending connections may grow to If a connection request arrives with the queue full and the underlying protocol supports retransmission the connection request may be ignored so that retries may succeed For AF_INET sockets the TCP will retry the connection If the backlog is not cleared by the time the TCP times out connect will fail with ETIMEDOUT Parameters socketDescriptor The socket descriptor to liste
119. state Description The runLed function sets the run light LED to the specified state state may be one of the following values LED ON turn on run LED LED OFF turn off run LED The run LED remains in the specified state until changed or until the controller is reset Notes The ladder logic interpreter controls the state of the RUN LED If a ladder logic program is loaded and running in the controller the interpreter sets the RUN LED to ON In this situation if the C application turns the RUN LED to OFF a conflict occurs and the RUN LED will blink OFF and ON Example include lt ctools h gt int main void runLed LED ON program is running the rest of the code Document Version 1 61 5 19 2011 493 Function Specifications runMasterlpStartTask Run TCP IP Master Message Support Task Syntax include lt ctools h gt void runMasterIpStartTask BOOLEAN state Description The runMasterlpStartTask function is used to start or stop the TCP IP master message support task This task needs to be running to allow master messaging over a TCP IP network using the functions in the mTcpMaster group Calling the function with the argument state set to FALSE stops the task Calling the function with state set to TRUE starts the task This function should only be needed in the context of the startup function appstart See Also mTcpMasterMessage Document Version 1 61 5 19 2011 4
120. state and password I O Replaced with default System settings settings on Cold Boot Saved settings loaded Serial port settings Serial on Run Boot protocol settings Modbus TCP settings HART Default settings loaded O settings LED power on Service Boot settings Replaced with default settings on Cold Boot Notes The FLASH_MEMORY resource needs to be requested before calling this function Document Version 1 61 5 19 2011 240 Function Specifications forceLed Set State of Force LED Syntax include lt ctools h gt void forceLed UINT16 state Description The forceLed function sets the state of the FORCE LED state may be either LED_ON or LED_OFF Notes The FORCE LED is used to indicate forced I O Use this function with care in application programs Document Version 1 61 5 19 2011 241 Function Specifications freeMemory Free Non Volatile Dynamic Memory Syntax include lt ctools h gt void freeMemory void pMemory Description The freeMemory function returns the specified memory to the system memory pool The specified memory to be returned or freed must have been allocated by a previous call to the function allocateMemory The function has one argument a pointer to the memory to be freed Notes The DYNAMIC_MEMORY resource needs to be requested before calling this function The allocation of memory and the allocated memory are non volatile Pointers to non vola
121. strings for your modem e phoneNumber is the phone number of the remote controller The characters ATD and the dialing method will be prepended to the command and a carriage returned appended to the command when it is sent to the modem MTCP_CONFIGURATION The Modbus TCP Settings structure defines settings for the Modbus TCP communication protocol typedef struct st _ModbusTcpSettings UINT16 portNumber UINT32 masterIdleTimeout UINT32 slaveRecvTimeout UINT32 maxServerConnections MTCP_CONFIGURATION e portNumber is the Modbus TCP protocol port number Valid port numbers are 0 to 65535 Selecting port number 65535 allows a server to listen for incoming connection requests on all the ports Default port number is 502 e masterldleTimeout is the length of time in seconds that a master connection will wait for the user to send the next command before ending the connection Set to 0 to disable timeout and let application close the connection Valid values are any 32 bit integer Default value is 10 seconds e slaveRecvTimeout is the length of time in seconds that a server connection will wait for a message before ending the connection Set to 0 to disable timeout and let remote client close connection Valid values are any 32 bit integer Default value is 10 seconds maxServerConnections is the maximum number of connections allowed by the server at once Default value is 20 Document Version 1 61 5 19 2011 619
122. structure Returns 0 Success 1 An error occurred getpeername can fail for any of the following reasons EBADF socketDescriptor is not a valid descriptor ENOTCONN The socket is not connected EINVAL One of the passed parameters is not valid Document Version 1 61 5 19 2011 256 Function Specifications getPortCharacteristics Get Serial Port Characteristics Syntax include lt ctools h gt BOOLEAN getPortCharacteristics FILE stream PORT CHARACTERISTICS pCharacteristics Description The getPortCharacteristics function gets information about features supported by the serial port pointed to by stream If stream does not point to a valid serial port the function has no effect and FALSE is returned otherwise TRUE is returned The getPortCharacteristics function copies the serial port characteristics into the structure pointed to by pCharacteristics Notes Refer to the Overview of Functions section for detailed information on serial ports Refer to the Structures and Types section for a Description of the fields in the PORT_CHARACTERISTICS structure See Also get_port Example include lt ctools h gt int main void PORT CHARACTERISTICS options getPortCharacteristics com3 amp options fprintf coml Dataflow options d r n options dataflow fprintf coml Protocol options d r n options protocol Document Version 1 61 5 19 2011 257 Function Specificat
123. succeeded The function returns FALSE if the log ID is invalid or if the data log does not exist Notes This function is useful in determining how much memory needs to be allocated for a call to datalogReadNext or datalogWrite See Also See example DataLog program in the Example Programs section datalogSettings Example See the example for datalogReadStart Document Version 1 61 5 19 2011 142 Function Specifications datalogSettings Data Log Settings Function Syntax include lt ctools h gt BOOLEAN datalogSettings UINT16 logID DATALOG CONFIGURATION pLogConfiguration Description This function reads the configuration of the specified data log The log needs to have been previously created with the datalogCreate function The function has two parameters og D specifies the data log The valid range is 0 to 15 pLogConfiguration points to a structure that will hold the data log configuration The function returns TRUE if the operation succeeded The function returns FALSE if the log ID is invalid or if the data log does not exist Notes The configuration of an existing data log cannot be changed The log needs to be deleted and recreated to change the configuration See Also See example DataLog program in the Example Programs section datalogRecordSize Example See example for datalogDelete Document Version 1 61 5 19 2011 143 Function Specifications datalogWrite Write Da
124. tes a E a ee ee eae echo Checking for unresolved externals with SCADAPack 350 CTools library lecho S lt S44S ss4 5855 358 S 5s 5 5 SSeS s se SSS a Sse so sacao ldarm e0 imImage o INCLUDE PATH SCADAPack 350 IEC 61131 1 Firmware Image o imLink SCADAPack350 0 imLink 4203 0 imImage o echo echo Hq 95s Sess SSeS SSS Ses Seas Se Sao SSS SSeS sas echo Checking for unresolved externals with 4203 library eCho sass essa RaT pS ss ae a Sa eae aS SSS hase SSS ldarm e0 imImage o INCLUDE PATH SCADASense 4203 IEC 61131 1 Firmware Image o imLink 4203 0 Document Version 1 61 5 19 2011 25 Getting Started Build the Application The next section lists the dependencies of the object files on header and source files Add additional header files and source files here The ctools h file is not added to the list of dependencies list all source file dependencies her appstart o appstart cpp nvMemory h main o main cpp nvMemory h The next section contains the rules for compiling files Generally no changes will ever be required in this section The compiler options affecting this that should be changed are defined in the CFLAGS setting above P ens el Sn ES Oe E E EOE EE a S E rules for making files r ENE E E EEEE E E ches seee Sosee 5 O S C ccarm CFLAGS c lt o 6 0 Se CPP ccarm CFLAGS c lt o The next section contains the rules for cleaning out output files from a folder
125. the Modbus RTU protocol emulation for the serial port Document Version 1 61 5 19 2011 576 Macro Definitions MODEM_CMD_MAX_LEN Maximum length of the modem initialization command string MODEM_MSG System event new modem message generated MT_4203DRInputs 4203 DR controller board inputs MT_Aout4_Checksum Four channel analog output module with checksum This module type can only be used with analog output modules with checksum support MT_Counter4 Four channel counter input module MT_CounterSP2 SCADAPack 350 controller board counter inputs MT_Din16 Sixteen channel digital input module MT_Din32 Thirty two channel digital input module MT_Din8 Eight channel digital input module MSG_POINTER Specifies the data field in an envelope contains a pointer MT_5604Inputs 5604 module analog and digital inputs MSG_DATA Specifies the data field in an envelope contains a data value Document Version 1 61 5 19 2011 577 Macro Definitions N serial port code for a Modbus Handler speed database section register section register section section O om Species od pariy O Specifies switch is in open position P Document Version 1 61 5 19 2011 578 Macro Definitions PC_FLOW_RX_RECEIVE_ST Receiver disabled after receipt of a OP message PC_FLOW_RX_XON_XOFF Receiver Xon Xoff flow control PC_FLOW_TX_IGNORE_CT Transmitter flow control ignores CTS PC_FLOW_TX_XON_XOFF Transmitter Xo
126. the Modbus register number associated with the point class is the reporting class for the object It may be set to CLASS _1 CLASS_2 or CLASS_3 threshold is the amount by which the counter input value needs to change before an event will be reported for the point Document Version 1 61 5 19 2011 604 Structures and Types dnpMasterPoll The dnpMasterPoll type describes an entry in the DNP Master Poll Table typedef struct dnpMasterPoll type UINT16 dnpRemoteStationAddress UINT16 classOPollRate UINT16 class1PollRate UINT16 class2PollRate UINT16 class3PollRate UINT16 timeSyncRate UINT16 unsolicitedResponseFlags dnpMasterPoll e dnpRemoteStationAddress is the remote DNP station address e classOPollRate is the Class 0 Polling rate e class1PollRate is the Class 1 Polling rate e class2PollRate is the Class 2 Polling rate e class3PollRate is the Class 3 Polling rate e timeSyncRate is the time synchronization rate e _unsolicitedResponseFlags are the DNP Master Unsolicited Response enable flags DNP Master Poll table Extended Entry The dnpMasterPollEx type describes an extended entry in the DNP Master Poll Table typedef struct dnpMasterPollTableEx type INT16 dnpRemoteStationAddress INT16 classOPollRate INT16 classlPollRate INT16 class2PollRate INT16 class3PollRate INT16 timeSyncRate UINT16 unsolicitedResponseFlags UINT16 classOPollOffset UINT16 class1Poll
127. the controller Controller Initialization The controller should be initialized when beginning a new programming project or when it is desired to start from default conditions It is not necessary to initialize the controller before every program load To completely initialize the controller perform a Cold Boot When the controller starts in the cold boot mode The default serial communication parameters are used The IEC 61131 1 application program is erased The C program is erased The controller is unlocked To perform a Cold Boot use the following procedure Remove power from the controller Hold down the LED POWER button Apply power to the controller Continue holding the LED POWER button for 25 seconds until the STAT LED begins to flash on and off continuously Release the LED POWER button If the LED POWER button is released before the STAT LED begins to flash the controller will start in service mode not the cold boot mode Document Version 1 61 5 19 2011 29 Getting Started Connect to Controller Before the project can be loaded to the controller a connection or link needs to be made between the PC and the controller The serial ports are set to their default parameters when a Cold Boot is done These settings are 9600 baud 8 data bits no parity 1 stop bit Modbus RTU protocol and station address 1 The IEC 61131 1 PC PLC Link parameters define how the communication link between the PC and
128. the device to be read a pointer to the PV current variable and a pointer to the PV percent variable The pvCurrent and pvPercent variables are updated when the response is received by the 5904 interface The pvCurrent and pvPercent variables must be static modular or global variables A pvCurrent and pvPercent variable should be declared for each HART I O module in use A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid Notes The HART_DEVICE structure needs to be initialized using hartCommandO or hartCommand11 The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command The code field of both HART_VARIABLE structures is not changed The response from the HART device to command 2 does not include variable codes The units field of the pvCurrent variable is set to 39 units mA The units field of the pvPercent variable is set to 57 units percent The response from the HART device to command 2 does not include units See Also hartCommand1 hartStatus hartSetConf
129. the media used by the configured data log For non auto transfer enabled data logs the states can be either typedef enum dlogMediaStatus_ type DLOGS MEDIA PRESENT DLOGS MEDIA NOT PRESENT DLOGS MEDIA EXT FULL DLOGS MEDIA INT FULL DLOGS MEDIA ALL FULL dlogMediaStatus dlogRecordElement Type media is present no external media present external media is full internal media is full ext and int media full This structure defines a data log record It provides on how an element in a record can be packed into a log file typedef struct dlogRecord UCHAR type UINTI UINT 32 size 32 offset Element typ Document Version 1 61 5 19 2011 589 Structures and Types dlogRecordElement e type is the type of field Valid values are bios une starsat 4 32 bit signed integer en a Dy E a a point DLOG_FIRST_USER_TYPE custom types type specific to DLOG_LAST_USER_TYPE e size is the size in bytes of the element The sizeof function can be used to determine this value e offset is the offset in bytes of the first byte of the element from the start of the record passed to the dlogWrite function Example This is an example on how a record can be defined It contains information on how the structure can be packed into log files User type definition array of 10 UINT16 variable
130. the module is processed The f array unction has two parameters the module address and a reference to an of two INT16 variables Data are read from the array and written to the I O table The valid range for moduleAddress is 0 to 15 The f unction returns TRUE if the data was written The function returns FALSE if the module address is invalid Document Version 1 61 5 19 2011 389 Function Specifications ioWriteAout4 Write Data to 4 Point Analog Output Module Syntax include lt ctools h gt BOOLEAN ioWriteAout4 UINT16 moduleAddress INT16 amp data 4 Description This function writes data to the I O tables for the 4 point analog output module at the specified module address Data are written to the module when an I O request for the module is processed The function has two parameters the module address and a reference to an array of four INT16 variables Data are read from the array and written to the I O table The valid range for moduleAddress is 0 to 15 The function returns TRUE if the data was written The function returns FALSE if the module address is invalid Notes This function writes to the output table only Use the ioRequest function to write the data to the module e Call ioRequest with the module type MT_Aout4 for analog output modules without checksum support All modules can use this module type e Call ioRequest with the module type MT_Aout4_Checksum for analog output mod
131. the short form address of the HART device 0 to 15 and a pointer to a HART_DEVICE structure The information read by command 0 is written into the HART_DEVICE structure when the response is received by the 5904 interface The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid or if the device address is invalid Notes The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command A program needs to initialize the link before executing any other commands See Also hartCommand11 hartStatus hartSetConfiguration Document Version 1 61 5 19 2011 285 Function Specifications hartCommand1 Read Primary Variable Syntax include lt ctools h gt BOOLEAN hartCommandl UINT16 module HART DEVICE const device HART VARIABLE primaryVariable Description This function reads the primary variable of a HART device using command 1 The function has three parameters the module number of the 5904 module 0 to 3 the device to be read and a pointer to the primary variable The variable pointed to by primaryVariable is updated when the response is received by the 5904 interface The primaryVariable must be a static modular or
132. the target controller functions These parameters are set to match the serial port parameters To open the PC_PLC link parameters dialog e Select Link Setup from the Debug menu When selected the PC PLC Link Parameters dialog is displayed Target Slave Number 0 Communication port TeleBUS Driver z Cancel Control Setup Time out seconds 1 fT Retries The Target Slave Number entry is ignored when the TeleBUS Driver is selected The TeleBUS Driver sets the target slave number Ignore the value in this field e From the Communication port dropdown list box select TeleBUS Driver If the TeleBUS Driver is not selectable from the Communication port drop down menu then the Control Microsystems Extensions have not been installed Refer to the installation CD jacket for installation information The Time out Seconds edit box sets the length of time in seconds to wait for a response to a command It is an integer in the range 1 to 255 seconds The default value is 3 The Retries edit box sets the number of communication attempts before a message is aborted It is an integer in the range 1 to 20 The default value is 3 e Select the Setup button When selected the PC Communication Settings dialog is displayed e Click the Default button This will ensure the serial parameters for the PC are the same as the parameters on each of the serial ports e Inthe Port dropdown selection select the serial port you
133. these C Tools functions These functions provide user access to third party C compatible devices Without these functions access is limited to Control Microsystems I O modules only Function ioBusStart ioBusStop ioBusReadByte ioBusReadLastByte ioBusWriteByte ioBusSelectForRead ioBusSelectForWrite ioBusReadMessage ioBusWriteMessage Timers The following C Tools Timer functions are not supported Use the functions readStopwatch or startTimedEvent instead Function interval read_timer_info Document Version 1 61 5 19 2011 691 Porting Existing C Tools Applications Document Version 1 61 5 19 2011 692
134. timing functions this should not be a problem If you ve used delay loops then these will execute slower You should replace them with standard timing functions Partially Supported C Tools Functions The following sections describe functions that are supported by the SCADAPack 32 C Tools but are only partially supported by the SCADAPack C Tools The following features are similar to existing SCADAPack 32 C Tools features but require some source code modification Refer to these sections when porting existing SCADAPack 32 C Tools Applications to the SCADAPack 350 4203 controllers Event Numbers for SCADAPack C Applications The SCADAPack 350 4203 support up to 32 separate user loaded C Applications Event numbers 0 to 31 were made available to the SCADAPack 32 C application This same event number range need to be shared on the SCADAPack 350 4203 among the user loaded C Applications The Realflo C Application uses events 20 21 or 22 These events may not be used by other C Applications when the Realflo C Application is loaded in the SCADAPack 350 4203 Stack used by fprintf Function Tasks that call the function fprintf require at least 5 stack blocks This function required only 4 stack blocks when used in SCADAPack 32 C applications As a general rule add 1 stack block to the amount used in a SCADAPack 32 C application Document Version 1 61 5 19 2011 674 Porting Existing C Tools Applications
135. to be requested before calling this function See Also setClockAlarm Document Version 1 61 5 19 2011 102 Function Specifications allocate_envelope Obtain an Envelope from the RTOS Syntax include lt ctools h gt envelope allocate_envelope void Description The allocate_envelope function obtains an envelope from the operating system If no envelope is available the task is blocked until one becomes available The allocate_envelope function returns a pointer to the envelope Notes Envelopes are used to send messages between tasks The RTOS allocates envelopes from a pool of free envelopes It returns envelopes to the pool when they are de allocated An application program needs to check that unneeded envelopes are de allocated Envelopes may be reused See Also deallocate_envelope Example include lt ctools h gt extern UINT32 other task id void taskl void nvelope letter send a message to another task assume it will deallocate th nvelop letter allocate envelope letter gt destination other task id letter gt type MSG DATA letter gt data 5 send message letter receive a message from any other task letter receive message process the data here deallocate_ envelope letter the rest of the task 7 X7 Document Version 1 61 5 19 2011 103 Function Specifications allocate
136. up task exit handler to stop signalling of events when this task ends Document Version 1 61 5 19 2011 670 Example Programs getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR myshutdown KY _TO_ PRINT 100 start timed even startTimedEvent TIM Fl ct while TRUE wait event TIME TO PRINT request resource IO SYSTEM getclock amp now release resource IO SYSTEM fprintf coml Time 02u 02u 02u r n now hour now minute now second Document Version 1 61 5 19 2011 671 Porting Existing C Tools Applications Porting Existing C Tools Applications Porting SCADAPack 32 C Applications to the SCADAPack 350 and 4203 Compiler Differences between Hitachi and GNU The Hitachi compiler used with the SCADAPack 32 has the following difference with GNU compiler used with the SCADAPack 350 and 4203 The order of bit fields is reversed Bit field ordering is not specified by the C standard It is left to the compiler maker Existing programs using bit fields need to be modified if the order of the bit fields affects the operation of the program If the bit fields are being used only for space efficiency the program does not need rewriting Porting Existing C Tools Applications Existing SCADAPack 32 C applications are highly compatible with the SCADAPack 350 and 4203 C Tools However changes are necessary The following
137. variable named Delay include lt ctools h gt int main void BOOLEAN status request_resource IO SYSTEM status writeTimerVariable Delay 10000 release resource IO SYSTEM Document Version 1 61 5 19 2011 568 Function Specifications xcopy Copy a folder and all sub folders Syntax include lt ctools h gt STATUS xcopy const char source const char destination Description The xcopy function copies all files in the specified source folder and sub folders to the location specified by destination If the xcopy operation failed then ERROR is returned OK is returned if the xcopy operation completed successfully The xcopy function used a significant amount of stack space 2 extra stack blocks are required for each layer of sub directories that are to be copied Example When copying myFolder at least 6 stack blocks will be needed due to the 3 levels of folder structure myFolder ProjectA ltem 1 myFolder ProjectB ltem2 myFolder ProjectC ltem1 myFolder ProjectD ltem1 See Also copy xdelete Document Version 1 61 5 19 2011 569 Function Specifications xdelete Delete a folder and all sub folder Syntax include lt ctools h gt UINT16 xdelete const char source Description The xdelete function deletes all files and folders in the specified source folder If the xdelete operation fails then ERROR is returned OK is returned if the xdelete
138. write data over the freed variable space The variableCode array specifies which variables are to be read from the transmitter Consult the documentation for the transmitter for valid values The variables array is updated when the response is received by the 5904 interface as follows Variables 0 transmitter variable code and units specified by variableCode 0 Variables 1 transmitter variable code and units specified by variableCode 1 Variables 2 transmitter variable code and units specified by variableCode 2 Variables 3 transmitter variable code and units specified by variableCode 3 The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid Notes The HART_DEVICE structure needs to be initialized using hartCommandO or hartCommand11 The pointer variables needs to point to an array with at least four elements Document Version 1 61 5 19 2011 291 Function Specifications The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command The function requests four variables and expects four variables in the response See Also hartCommanda3 hartStatus hartSetConfiguration Document Version 1 61 5 19 2011 292
139. 1 61 5 19 2011 557 Function Specifications wait_event Wait for an Event Syntax include lt ctools h gt void wait event UINT32 event Description The wait_event function tests if an event has occurred If the event has occurred the event counter is decrements and the function returns If the event has not occurred the task is blocked until it does occur Notes Refer to the Real Time Operating System section for more information on events Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in primitiv h are not valid events for use in an application program Example See the Example for the signal_event function Document Version 1 61 5 19 2011 558 Function Specifications wd_auto Automatic Watchdog Timer Mode Syntax include lt ctools h gt void wd_auto void Description The wd_auto function gives control of the watchdog timer to the operating system The timer is automatically updated by the system Notes Refer to the Functions Overview section for more information Example See the Example for the wd_manual function Document Version 1 61 5 19 2011 559 Function Specifications wd_enabled Enable Watchdog Syntax include lt ctools h gt void wd_enabled BOOLEAN state Description The function wd_enabled enables or disables the controller watchdog This function should only be needed in the context of the startup function appstart where
140. 1 MTE A A A codvtisteedebetectes 561 WO a T AEE PEE EE E A P EAE P E V E E T 562 Writ eBoolVarable iiinn einernie ae e raare ioa raae E iSe 563 WritelntVariable iee srs ae erratea iesire ae a raaraa ar oaeen tanec oee raent 564 writeRealVarlable iiielccrcccccdeticies tebcevendelavecd cobeavcccetancecteceeedecelaxtulexteas eodvtastuetebetectes 565 writeMsg Variable gnito apa eira A Taa E SE EEA EAN SAE tee ES ERR 566 WwriterimerVarniable s rerni einser ae n earar axtulexteezcodvtasteetetetectes 568 MOO PY A E TT Maiaetetraviveshaniedevtuarace elatestearices 569 KOC A A lates bebeevgedehasieleetesret tas es tebeieoed sie EA 570 Macro DeTINIMIONS wiiiiccciccscccctccncnccdccucsccascuascusxcucncudecceccuducvdccnteckaxs 571 Pst ee tickets wate see fa tbe Aaa ate deeds Satae ioe lake 571 Bie tiandiedicitee diate dee bata Readies ten itaniiiers askin Graded tetanic vetted teste 571 Gaee a eat e diene aad etki ee laine eet 572 D EEE EE Satine eats edd EA EE itd ved eeted 573 Ee Satna lini aii ete tile invite ata avail inet ain evel 574 Fics cede na Mel Saws ht sera EIE AAEE TIAN AEE I cect evaded inesta 575 Gre cosa bash EANA E asennad nates hon ea esa A Neat EA E E LEA EEEE 575 E E A E A A EEA A E A he E EEA AE A EAT 575 EE E A A Sota E EIA E A E oh E A A Nha aie once tae 575 EEEE E A E A A A A r A E A E A E A AR 575 E EA EE A A E A A AE A AA TEA AT 576 EEEE E T r AA e A E AET A E A T 578 OE E E E EA E E A A AE AA AE AT 578 AE AA T acne dade nee E A A E
141. 11 HART Communicat Msni aaa ea ada a i a i e 84 Fil Management AP horcrisorni unenian i eee 86 Function Specifications sssssnnnnennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnne 87 Functions Supported by Telepace OMly cccsceeeeeeeeeeeeeeneeseeeeeseeeeenaeeeeeeesaees 87 Functions Supported by IEC 61131 1 Only 0 cece eeeececeeeeeeeeeeeeeeeeeeeeeaeeeeeeeeeaees 87 ACCE pinana ees eet erred als eee eae teat a E ate aoe ella teens 89 AAAREGASSIGNMEM ce eeeeeeeeeceeeneeeeeeeeeeeeeeaeeeeeeaaeeeeeseaeeeeeeeeeeeeeseeeeeeeseneaeeeeeeeaees 91 addRegAssignmentEXx 0 0 se eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeseaeeeeeeeaeeeeeseeeeeeseneeeeeseneaeeneeeeaees 96 AlarMIN orean delineated ead ade delineated 102 allocate_envelope 0 eee ceeeenceceeeeeeeeeeaneeeeesaeeeeeesanaeseesaeeeseenaneeseesenseseeseneeeeenenes 103 allocate Memory anenun a aa N AN 104 DING ei ee Wipe aap a ede Nid eee 105 CHECK OrrOr y2 s tssc2d che elise ee ae ae edo 106 CHECKSUM sorrentina dane Ai de iglesia id nolan 107 CheckSFTranslation Table cccccccceeeceeeeeeeeeeeeeeeceeeeesaeeesaaeseeeeeseaeeessaeeseeessaees 108 ClearAllForcing anani a iraa inane 109 ClearBreakConditiOn nisi si a aeran aaraa inaia tenteeaiiebed eetdestibeetenteatds 110 clear error ae a e a a e a eee tine nace aie is 111 Clear Protocol statusi riia herean iaa eaten a a aaa aaraa a aaa tet caved ate aa aa 112 ClearLoginCredentials mtis tarii iaaa Aata ea aaa EAE Aa a a aaia 113 clea
142. 11 397 Function Specifications ipGetConnectionSummary Get Summary of Active TCP IP Connections Syntax include lt ctools h gt void ipGetConnectionSummary IP CONNECTION SUMMARY pSummary Description The ipGetConnectionSummary function returns a Summary of the number of active IP connections The IP connections include Modbus TCP Modbus RTU over UDP Modbus ASCII over UDP DNP over TCP and DNP over UDP The information is copied to the structure pointed to be pSummary The structure IP_CONNECTION_SUMMARY is described in the Structures and Types section The information in the structure summarizes the number of connections as master slave or unused Note that if a connection is allocated to master messaging but is currently disconnected it will still be listed in the number of master connections Also additional connections for store and forward translations will be included in the summary For Example a master connection will be listed if a serial to Ethernet store and forward translation is currently active Document Version 1 61 5 19 2011 398 Function Specifications ipGetinterfaceType Get Interface Type from IP Address Syntax include lt ctools h gt BOOLEAN ipGetInterfaceType IP_ADDRESS localIP COM INTERFACE x pIfType Description The function ipGetlnterfaceType determines the interface that is configured to the specified local IP address ocallP If no inter
143. 11 403 Function Specifications ipWriteFriendlyIPListEntry Write one entry in the friendly IP list Syntax BOOLEAN ipWriteFriendlyIPListEntry UINT16 index IP_ADDRESS ipAddressStart IP_ADDRESS ipAddressEnd i Description This function writes an entry in the Friendly IP List index specifies the location in the list and needs to be less than or equal to the Friendly IP List size ipAddressStart and ipAddressEnd specify a range of IP addresses or a single IP address if they are the same to be added to the list Valid values are any IP address the start IP address needs to be lower than or equal to the end IP address The function returns TRUE if successful and FALSE if the index or address is invalid Notes lpWriteFriendlylPListSize needs to be called before calling this function See Also ipReadFriendlylPListEntry Document Version 1 61 5 19 2011 404 Function Specifications ipWriteFriendlyIPListSi ze Write the size of the Friendly IP List Syntax BOOLI EAN ipWriteFriendlyIPListSize UINT16 size Description This function sets the size of the Friendly IP List This needs to be written before any entries are written to the list size specifies the number of active entries in the list Valid values are 0 to 32 The f unction returns TRUE if successful FALSE otherwise See Also ipReadFriendlylPListSize Document Version 1 61 5 19 2011 405 Function Specifi
144. 16 struct myDatabase pMyDatabase EAN dbaseHandler L6 address Modbus register address value pointer to value at address pointer to custom database pMyDatabase struct myDatabase pNvMemory gt pAllocatedMem if pMyDatabase NULL database could not be allocated return FALSE if address gt 1000 amp amp address lt 1000 SAMPLE SIZE value pMyDatabase gt coilDbase address 1001 return TRUE else if address gt 11000 amp amp address lt 11000 SAMPLE SIZE value pMyDatabase gt statusDbase address 11001 return TRUE else if address gt 31000 amp amp address lt 31000 SAMPLE SIZE value pMyDatabase gt inputDbase address 31001 return TRUE else if address gt 41000 amp amp address lt 41000 SAMPLE SIZE value pMyDatabase gt holdingDbase address 41001 return TRUE else all other addresses are not handled return FALSE PR terete SS te eee ee SS a ee ee This is the setdbase handler on tan BT tN Sasa Se SA Nk eS pind AN static BOOLEAN setdbaseHandler UINT16 address Modbus register address INT16 value value to write at address Document Version 1 61 5 19 2011 654 Example Programs struct myDatabase pMyDatabase pointer to custom database pMyDatabase str
145. 16 logID UINT32 sequenceNumber UINT32 pSequenceNumber UINT32 pNextSequenceNumber UINT16 pData Description This function reads the next record from the data log starting at the specified sequence number The function returns the record with the specified sequence number if it is present in the log If the record no longer exists it returns the next record in the log The function has five parameters og D specifies the data log The valid range is 0 to 15 sequenceNumber is sequence number of the record to be read pSequenceNumber is a pointer to a variable to hold the sequence number of the record read pNextSequenceNumber is a pointer to a variable to hold the sequence number of the next record in the log This is normally used for the next call to this function pData is a pointer to memory to hold the data read from the log The function returns TRUE if a record is read from the log The function returns FALSE if the log ID is not valid if the log has not been created or if there are no more records in the log Notes Use the datalogReadStart function to obtain the sequence number of the oldest record in the data log The pData parameter needs to point to memory of sufficient size to hold all the data in a record It is normally necessary to call this function until it returns FALSE in order to read all the data from the log This accommodates cases where data is added to the log while it is being read If
146. 2011 610 Structures and Types HART_SETTINGS HART_VARIABLE e HR_NoResponse returns no response after all attempts e HR_WaitTransmit returns modem is not ready to transmit The HART_SETTINGS type is a structure containing the configuration for the HART modem module The useAutoPreamble field indicates if the number of preambles is set by the value in the HART_SETTINGS structure FALSE or the value in the HART_DEVICE structure TRUE The deviceType field determines if the 5904 modem is a HART primary master or secondary master device primary master is the recommended setting typedef struct hartSettings t UINT16 attempts UINT16 preambles BOOLEA useAutoPreamble UINT16 deviceType HART SETTINGS attempts is the number of command attempts 1 to 4 e preambles is the number of preambles to send 2 to 15 e useAutoPreamble is a flag to use the requested preambles e deviceType is the type of HART master 1 primary 0 secondary The HART_VARIABLE type is a structure containing a variable read from a HART device The structure contains three fields that are used by various commands Not all fields will be used by all commands Refer to the command specific documentation typedef struct hartVariable t float value UINT16 units UINT16 variableCode HART VARIABLE e value is the value of the variable e units are the units of measurement e variableCode is the transmitter spe
147. 2011 80 Overview of Programming Functions Modbus I O Database The Modbus database is a user defined database that allows data to be shared between Telepace or IEC 61131 1 programs C programs and communication protocols Telepace and IEC 61131 1 firmware support different ranges of Modbus Database registers The following table shows the register ranges for these firmware types Telepace IEC 61131 1 Data Type Modbus Modbus Addresses Addresses 00001 to 00001 to Coil Register 04096 09999 1 returned if variable is non zero 0 returned if variable is 0 10001 to 10001 to Status Register 14096 19999 1 returned if variable is non zero 0 returned if variable is 0 30001 to 30001 to Input Register 39999 39999 word 16 bits 40001 to 40001 to Holding Register 49999 49999 word 16 bits Modbus I O Database Register Types The I O database is divided into four types of I O registers Each of these types is initially configured as general purpose registers by the controller Coil Registers Coil or digital output database registers may be assigned to 5000 digital output modules or SCADAPack I O modules through the Register Assignment Coil registers may also be assigned to controller on board digital outputs and to system configuration modules Status Registers Status or digital input database registers may be assigned to 5000 digital input modules or SCADAPack I O modules through the Register Assignment Status r
148. 210 Document Version 1 61 5 19 2011 dnpSaveBOConlig ais cine ail eee eel i aiai 211 AnpSaveClt6Conhig vs ccc aa nde ache teenie anaes 212 dnpSaveGl32Conlig was ccc ae ibe ec eine staan eevee een 213 dnpSaveConfiguration ccccccceeeceeeeeceeeeeeeaeeeeeeeceeeeesaeeesaaeseeeeeceaeeesaeeseneeenaees 214 AnpSaveContiguration Ey cccccesceeeeeececeeeeeaeeeeaeeceeeeeseaeeesaaeeeeeeeseaeeeseaeeseaeeenaees 216 AnpSaveUnsolicitedBackoffT ime cecccecceceeececeeeeeceeeeseaeeeeeeeceaeeessaeeneneeeeaees 217 AnpSendUnsolicitedResponse ccceccceeeeeeeeneeceeeeeseaeeeeaaeeeeeeeseaeeesaeeseaeeesaees 218 AnpSearchRouting Table cccccececececeeeceeeeeeeeeeceeeeesaeeeeaaeseeeeeseaeeeseaeeseneeenaees 219 dnpStation Statusi seisena aaan iioi iaa i aian eae ne 220 dnpWriteAddressMappingTableEntry eecceeeeesseeeeeenneeeeeeeeeeeeeaeeeeeeaeeeeseaas 221 dnpWriteMasterApplicationLayerConfig esseessessseeseesnesesnnennrennnernnsrnnennnes 222 dnpWriteMasterPollTableEntry usireirriietnnei tenien ei a 223 dnpWriteMasterPollTableEntryEX sssseessssesssrnesssrnesrnnnesrnnnesrnnnesnnnnnnnnnnsnnnnnnnnnne 224 dnpWriteRoutingTableEntry_DialString c ccceccceseeeeeeeeeeeeeeeseeeeeseaeeeeeeeeaees 225 AnpWriteRouting Table Entry sesini etree EE a ETA ER E ER 226 dnpWrieRouting Table Entry E K anairt enirn E ENa E REEE E EEEE 227 end APPIICATON a staceus seveshedevtaelustebescehevbantel vebeanatevban
149. 31 lOReadS5 06 Inputs oien a a NE a Ea E E AA EE 333 iORead55060utp tS iiaa aaraa aae apia i a a aaa 335 i ReadS5S606INPUS oieri a a NE Aaa EA E EE 337 ORead5606QUtP tS iieii aniei eiaa read a aiaia eoii iaai aaa daian 339 Document Version 1 61 5 19 2011 iORead5607 Inputs 2 00 ced ae ieee ce areca en cect 341 ioReadS60 Outputs i seers ale oe el aden iain eee 343 IORGACAING a ieee keete t rete eed he EEA UAE 345 IORGACAING argiei Aa iieii sree tie eee Aik EAEE AATE 346 IORGACA OUT cso Aa tente E re eens eevee aunedele ec via 347 IORGACAOUIA ar Aa irii hve eee ai Eie V e ven avi vee ve ees 348 IORGadAOUtS303 eieiaeo irunia riino eee ceive cnvivee dene cee ATAKAA EENAA ETEEN 349 iORGAadGounter vrei cere ed Gels cere eo eee ein ranean Gene 350 iOREadGouUnterSP2 ice ye ae eee aia eiia aiii aai taeda 351 IGROAUD IN Ory cick ececs cette a a EEE AEE RAE E E SEEE EREA S SERA E ES 352 IORCAUD ING Z aaae e E a A T EE ETEA AT S E EER A R 353 IORCAUDING a E O CI E I E A E E O E O E 355 ORGAGDOUTG srera a rea E Ta ESE EA eer SAE EER S RRS 356 IORCAUDOUS 2 aere n EERE A EERE ESE ETEA SARENET R 357 ORGAGDONB a ree ter Pret errr rer ert A Raa ESE EEA SAR SAE EER E ERRES 358 IORECadSP2INPUIS i rena peranane antrana aaae aaraa aaan eatea eaka aa Saanaa 359 IORCadSPZOU DUS eeen ana atanan an e oa trene aaen a Era a an a Saien aE a ARNa 361 ela ae EPEE EA EPEN O CI E I E EE E A E O TE 363 iOSetQonfiguratiO Miisan asa atanan e atre a a aera a
150. 394 TOATA IS ADD i o i EEE TTT EAT 395 IPFindFriendlylPACCress cccceeeeeeceeeeeeeeeeeeeeeeeeeeeaeeeeeeeaeeeeesaeeeeeseeeaeeeeeneaees 397 IPGetConnectiONSUMMAaLy ee cece eeee eens cree eene terete eeeeeseeeeeeeeseeetaeetneeenaeeaee 398 IpPGetlnterface T yPe cecececeecesececeeeeeceeeeeeeaeseeeeeceaeeesaaeeseaaesgeeeeseaeeesaaeseeaeeseeeeess 399 ipReadFriendlyListControl 0 0 cece eee esee eens ceeeceneeeeeeeeeeeeeeseeeseeesaeesneeenaeenaee 400 ijpReadFriendlylPListEntry ssori sers A E A 401 ipReadFriendlylPListSize eeccceccceceeeceeeeeeeeeeeceeeeesaeeeeaaeseeeeeseaeeesaeeseeeeeeeeess 402 ipWriteFriendlyListControl eseseeeeeseeeiesreeiesrreresrnerisristrntinrntinsrnetnsinntnnrnnnnennet 403 IpWriteFriendlyIPListEntry 0 00 0 eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeseeeeeeeseeeaeeeeeeeaees 404 ipWriteFriendlylPListSiZe o oo eee eee cee cee eee eee eeeeeeeeeeeeeseeeseaeetaeeseeeaeeaees 405 ledGetDefaultens jue ene el Chie ae 406 lOUPOWGR ieis ceviiac diese n tec cies ated need ds de dled ate 407 ledPowerSwitChisi cics o i Ai ed a ad ieee Se 408 Document Version 1 61 5 19 2011 l dSetDefa lt irinenn ee i eS ee A A 409 NSCOR vi sie Rie ah chee res Ae T a ena dal area 410 master messaga aiiai une dee Gsich deca a a a dovetecbuedei E 411 memoryPool sagen ciuine ee ee ea i E e AN TE 413 memory PoolSizE aiiin iiai ea a aiai iii aii 414 modbusExceptionStatus 0 2 cece cece ceee eect eeeeee cee ee
151. 5534 in extended Modbus 65535 entry cleared This station address must be different from the station address assigned to the forwardinterface forwardiPAddress is the IP address of the remote slave device to forward a Modbus IP command message to Set to zero if not applicable timeout is the maximum time the forwarding task waits for a valid response from the forward station in tenths of seconds Valid values are 0 to 65535 The SFTranslationStatus structure contains information about a Store and Forward Translation table entry It is used to report information about specific table entries struct SFTranslationStatus TASKINFO UINT16 index UINT16 code e index is the location in the store and forward table to which the status code applies code is the status code It is one of SF_VALID SF_INDEX_OUT_OF_RANGE SF_NO_ TRANSLATION SF_PORT_OUT_OF_RANGE SF_STATION_OUT_OF_RANGE SF_ALREADY_DEFINED or SF_INVALID FORWARDING _IP macros The TASKINFO type is a structure containing information about a task Task Information Structure typedef struct taskInformation tag UINT16 taskID UINT16 priority UINT16 status UINT16 requirement UINT16 error UINT16 type TASKINFO taskID is the identifier of the task priority is the execution priority of the task status is the current execution status of the task This may be one of TS_READY TS_EXECUTING TS_WAIT_ENVELOPE TS_WAIT_EVENT TS_WAIT_MES
152. 94 Function Specifications runTarget Start the Run Time Engine Syntax include lt ctools h gt void runTarget BOOLEAN state Description The runTarget function is used to start or stop the run time engine task For Telepace firmware this is the Ladder Logic run time engine For IEC 61131 1 firmware this is the IEC 61131 1 IEC 1131 run time engine Calling the function with the argument state set to FALSE stops the run time engine task Calling the function with state set to TRUE starts the task This function should only be needed in the context of the startup function appstart Document Version 1 61 5 19 2011 495 Function Specifications select Syntax include lt ctools h gt int select int numberSockets fd_set readSocketsPtr fd_set writeSocketsPtr fd_set exceptionSocketsPtr struct timeval timeOutPtr Description select examines the socket descriptor sets whose addresses are passed in readSocketsPtr writeSocketsPtr and exceptionSocketsPtr to see if any of their socket descriptors are ready for reading are ready for writing or have an exceptional condition pending respectively Out of band data is the only exceptional condition The numberSockets argument specifies the number of socket descriptors to be tested Its value is the maximum socket descriptor to be tested plus one The socket descriptors from 0 to numberSockets 1 in the socket descriptor sets are exa
153. 999 Application Identifier The application identifier is formatted as follows Company ID see below Application number 0 to 65535 Document Version 1 61 5 19 2011 122 Function Specifications Application version major 100 minor Company Identifier Control Microsystems will maintain a list of company identifiers to keep the company IDs is unique Contact the technical support department Company ID 0 indicates an identifier is unused See Also configurationRegisterMapping Notes Application IDs for C programs are not automatically removed A task exit handler can be used to remove the ID when the C application is ended Application IDs are cleared when the controller is reset Document Version 1 61 5 19 2011 123 Function Specifications connect Syntax include lt ctools h gt int connect int socketDescriptor const struct sockaddr addressPtr int addressLength Description The parameter socketDescriptor is a socket If it is of type SOCK_DGRAM connect specifies the peer with which the socket is to be associated this address is the address to which datagrams are to be sent if a receiver is not explicitly designated it is the only address from which datagrams are to be received If the socket socketDescriptor is of type SOCK_STREAM connect attempts to make a connection to another socket either local or remote The other socket is specified by addressPtr addre
154. A A E A acts 578 a EEE T AE A E E fede ATE EAA T EA 579 E E A E AT E AAT A A E AET A A T 580 EEEE A E E E A AEE EA nate T A 581 A ATE ae EAE A A A E AEA E A 582 AY E A T EEEE E A E E T eee 582 Str t res and TYPOS i ciuisicatasianneaacecantcnsianncaensiannteiccanonidavias 584 ADDRESS MODE 2a 2h Fier viesoe seas vs ee a os ea cee hats aos 584 AZAR MS Bali RIN Gara r2 22 cde E EE E E E E E E EEEO 584 SOENNIETEN EEE 584 COMM ENDPOINT cccccccccccecsesssseceseeeceeseseeaeseceeeceeseaaeaeceseesseeseaeseeeeseeenes 585 CONNECTION TYPE sata KAE Ea AREA ET ARAR a RERE E 585 Document Version 1 61 5 19 2011 10 DATALOG_CONFIGURATION o eee ee ee eee cere eeeeeeeeesaeesaeesaaesaeseaeeeaeeeeennees 585 DATALOG STATUSw taiieis she tl in a ear ae 586 DATALOG VARIABLE wick ae ei eels eel ein ania 586 DIE MOliavevcccvii adele Sviie oe Giie cue eal ie oie ire oie id 586 DialState 24 ice so ehst arene Sh ei ei eel oni ree 587 dlogConfiguration Type ccecccecececeeeeeceneeeeeaeeeeeeeceeeeecaaeeesaaeseeeeeseaeeesaeeneneeenaees 588 CIOQGMITiMe Typa ssrsri iisisti ikidi aiiai 589 dlogMediaStatus Type ccccccecesecsecceceeeeeesaeeeeneeceeeesaaeeseaaesseeeeseaeeesaeeneneeesaees 589 dlogRecordElement Type ccsccccecsseccceeeeeceeeeeseceeeeseeaeeeenseeeeesneeeeeesseeaeeeenaes 589 dlogStat s Type eoar e a aaae aa a aaa a a a a aaaea rae an paa Wheerees 591 dlogTransferStatus Type eccccccccecescecsse
155. AE E NEE AA a N AN EA 463 readinput Voltage eee eeeeeeeceeeeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeceaeeeseeaaeeeeeeaeeeseeseneeeeeeeneees 464 readintVarlable s 2 iss ccl eee eine sanded eee telecine indeed oie 465 reaAdMsgV arable n aeina iea aii oeae CEA a E A E NEE 467 readRealVariable oaii a i eaea E aa ia 469 readStopwateh sepiii aiino e aaa ead ieee Se 471 Document Version 1 61 5 19 2011 r adhimer Variables iaeiiai iaeiiai et alee renee 473 rete MESSAGE sie keeriiriii ritar Eaa EKUE AEAEE AEAN EEA 475 OCV sat a ai i a a a a a aad a i a A 476 FECVIFOM isiin ia dean leet ieaie aiita ia e a iaaa aA ataia e iiiad iaai 478 registerBulkDevOperation cceccceceeeeeeeeeeeeeeeceeeeeeaaeeeeaaeseneeeseaeeesaeeseaeeseeeeess 480 release PrOCOSSOl cies scviee eee eee ienai ri aari vaek aN uHe eKA EEN a aaa Kad KENEAN aN 482 FElIEASE reS0UlC Eiin voce dock eect vas e i aa i auc a ae a a a 483 removeModbusHandler eeeeeeeeeeeeeceeeeeeeeeeeeeeeeeeeeeaeeeeeeeaeeeeeseeeeeeseeeaeeeeeeeaees 484 FEDO EIOP arisin irn aaa a ar aaan Enar aa aaa ana ara edanari aaa aaea 485 req eSt TOSOUICO cies sete scccextsctectetesvccentseeedcxtven aces spaccedetinudvenspeded evtuanavestaeeeeeetaanines 486 FESCIAIIABSIAVES sic cesses ccdedindin EER AE EARE EAE EE EEEE RAREN ERAAN ESENTA 487 FESCICIOCKALANIM stated eere a ar a ARa E E DEAR AR EEEE ASE ATAS 488 FOULG A E T A A E T E TEA 489 r nBackgro ndlO is enen asa utanna a atraen ia aet aE
156. AISF point e AISF_reportingMethod is the event reporting method Change Of State or Log All Events e AISF_bufferSize is the short float Analog Input Event Buffer Size e AISF_wordOrder is the word order of AISF points O LSW first 1 MSW first e AQ16_number is the number of 16 bit analog output points Valid values are 0 to 9999 e AQ16_startAddress is the DNP address of the first AO16 point e AOQ832_number is the number of 32 bit analog output points Valid values are 0 to 9999 e AQ32_startAddress is the DNP address of the first AO32 point e AQ32_wordOrder is the Word Order of AO32 points O LSW first 1 MSW first e AOSF_number is the number of short float Analog Outputs e AOSF_startAddress is the DNP address of first AOSF point e AOSF_wordOrder is the Word Order of AOSF points O LSW first 1 _MSW first e autoUnsolicitedClass1 enables or disables automatic Unsolicited reporting of Class 1 events e holdTimeClass1 is the maximum period to hold Class 1 events before reporting e holdCountClass1 is the maximum number of Class 1 events to hold before reporting e autoUnsolicitedClass2 enables or disables automatic Unsolicited reporting of Class 2 events e holdTimeClass2 is the maximum period to hold Class 2 events before reporting e holdCountClass2 is the maximum number of Class 2 events to hold before reporting e autoUnsolicitedClass3 enables or disables automatic Unsolicited reporting of Class 3 events
157. CI32 reportingMethod REPORT ALL EVENTS configuration CI32 bufferSize 0 configuration CI32 wordOrder MSW_FIRST configuration AI16 number 751 configuration AI16 startAddress 0 configuration AI16 reportingMethod REPORT ALL EVENTS configuration AI16 bufferSize 1000 configuration AI32 number 0 configuration AI32 startAddress 100 configuration AI32 reportingMethod REPORT ALL EVENTS configuration AIl32 bufferSize 0 configuration AI32 wordOrder MSW_FIRST configuration AISF number 0 configuration AISF startAddress 200 configuration AISF_ reportingMethod REPORT CHANGE EVENTS configuration AISF bufferSize 0 configuration AISF wordOrder MSW_FIRST Document Version 1 61 5 19 2011 642 Example Programs configuration AO16 number 20 configuration AO1l6 startAddress 0 configuration AO32 number 12 configuration AO32 startAddress 100 configuration A032 wordOrder MSW_FIRST configuration AOSF_ number 0 configuration AOSF startAddress 200 configuration AOSF wordOrder MSW_FIRST configuration autoUnsolicitedClass1l TRUE configuration holdTimeClass1l 10 configuration holdCountClass1l 3 configuration autoUnsolicitedClass2 TRUE configuration holdTimeClass2 10 configuration holdCountClass2 3 configuration autoUnsolicitedClass3 7 configuration holdTimeClass3 10 configuration holdCountC
158. DAPack 350 counters v ioReadDin16 Read buffered data from 16 point digital input module v ioReadDin8 Read buffered data from 8 point digital input module v ioReadDout16 Read buffered data for 16 point digital output module v ioReadDout8 Read buffered data for 8 point digital output module y ioReadSP2lnputs Read buffered data from SCADAPack 350 inputs v ioReadSP2Ouiputs Read buffered data for SCADAPack 350 outputs ioWriteAout2 Write buffered data for 2 point Document Version 1 61 5 19 2011 684 Porting Existing C Tools Applications analog output module v ioWriteAout4 Write buffered data for 4 point analog output module ioWriteDout16 Write buffered data for 16 point digital output module ioWriteDout8 Write buffered data for 8 point digital output module ioWriteSP2Outputs Write buffered data for SCADAPack 350 outputs Controller I O Functions The following functions are no longer supported The replacement function is indicated for each readCounterinpa IEC 61131 1 I O Functions The I O System functions are used in place of the following IEC 61131 1 C Tools I O functions which are no longer supported Document Version 1 61 5 19 2011 685 Porting Existing C Tools Applications Replaced wit isaWrite8Dout ioWriteDout8 isaWrite16Dout ioWriteDout16 isaWrite5601 Outputs ioWriteSP2Outputs Backwards Compatibility I O Functions The following I O related functions were available
159. DEVICE structure when the response is received by the 5904 interface The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid Notes The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command A program needs to initialize the link before executing any other commands See Also hartCommand0 hartStatus hartSetConfiguration Document Version 1 61 5 19 2011 290 Function Specifications hartCommand33 Read Transmitter Variables Syntax include lt ctools h gt BOOLEAN hartCommand33 UINT16 module HART DEVICE const device UINT16 variableCode 4 HART VARIABLE variables Description This function reads selected variables from a HART device using command 33 The function has four parameters the module number of the 5904 module 0 to 3 the device to be read an array of codes and a pointer to an array of four HART_VARIABLE structures The variables array must be static modular or global variables An array of variables should be declared for each HART I O module in use A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will
160. DID WRONGPARAM BUFFERFULL NOTSTARTED COMPLETE strLogDescription Data Log to File Example strLogName AIN1 data log INT16 rtcPreviousSecond 0 dinlCurrentState 0 dinlPreviousState 0 UINT32 dlogIidNumber dlogStatus dlogStatusInfo dlogRecordElement recordFieldsDefinitions 3 TIME currentTime BOOLEAN logData TRUE Document Version 1 61 5 19 2011 637 Example Programs dlogRecord flashMemoryRecord dlogConfiguration usbMemLogConfig Add RTC and SP350 I Os in register assignment Ey request_resource IO SYSTEM clearRegAssignment addRegAssignment SCADAPack 210 0 1 10001 30001 40001 release resource IO SYSTEM Delete all existing logs 3y dlogStatusInfo dlogDeleteAll Data log configuration Config struct version should be always set to 1 usbMemLogConfig configVersion would exceed defined maximum number of files iy E to TRUI 1 The oldest log file will be deleted when a new fil when this parameter is set TRUI Tis B usbMemLogConfig fileRingBuffer r Interval in seconds after which server will flush buffer to file usbMem 10 LogConfig bufferFlushInterval Buffer size is number of records in the data log buffer usbMemLogConfig buff
161. DRESS_MODE enumerated type describes addressing modes for communication protocols typedef enum addressMode t AM standard 0 AM extended ADDR ESS MODE e e AM_standard returns standard Modbus addressing Standard addressing allows 255 stations and is compatible with standard Modbus devices e AM extended returns extended addressing Extended addressing allows 65534 stations ALARM_SETTING The ALARM_SETTING structure defines a real time clock alarm setting typedef struct alarmSetting tag UINT16 type UINT16 hour UINT16 minute UINT16 second A ARM SETTING e type specifies the type of alarm It may be the AT_NONE or AT_ABSOLUTE macro e hour specifies the hour at which the alarm will occur e minute specifies the minute at which the alarm will occur e second specifies the second at which the alarm will occur COM_INTERFACE The COM_INTERFACE enumerated type defines a communication interface type and may have one of the following values typedef enum interface t CIF Coml 1 CIF Com2 2 CIF _Com3 3 Document Version 1 61 5 19 2011 584 Structures and Types CIF _Ethernetl 100 COM_INTERFACE COMM_ENDPOINT The COMM_ENDPOINT structure defines a communication endpoint If ethernet based protocols are not used then the ipAddress and portNumber fields should be set to 0 struct COM_INTERFACE interface
162. E if the index is invalid See Also ipReadFriendlyIPListSize ipWriteFriendlyIPListEntry ipWriteFriendlyIPListSize Document Version 1 61 5 19 2011 401 Function Specifications ipReadFriendlylPListSize Read the size of the friendly IP list Syntax UINT16 ipReadFriendlyIPListSize void Description This function reads the total number of active entries in the Friendly IP List The function has no parameters The function returns the total number of active entries in the list or zero if the list is empty See Also ipReadFriendlyIPListEntry ipWriteFriendlylPListEntry ipWriteFriendlyIPListSize Document Version 1 61 5 19 2011 402 Function Specifications ipWriteFriendlyListControl Enable or disable the friendly IP list Syntax BOOLEAN ipWriteFriendlyListControl BOOLEAN state Description This function enables or disables the friendly IP list When the list is disabled the controller accepts messages from any IP address When the list is enabled only messages from the IP addresses on the list are accepted state specifies if the friendly IP list is enabled or disabled Valid values are TRUE enabled and FALSE disabled If the list is not valid then it can not be enabled The function returns TRUE if command was successful It returns FALSE if it was attempted to enable an empty list or a list with invalid entries See Also ipReadFriendlyListControl Document Version 1 61 5 19 20
163. EVENT event Description The dnpConnectionEvent function is used to report a change in connection status to DNP This function is only used if a custom DNP connection handler has been installed dnpAddress is the address of the remote DNP station event is current connection status The valid connection status settings are DNP_CONNECTED and DNP_DISCONNECTED See Also dnplnstallConnectionHandler Example See the dnpinstallConnectionHandler example Document Version 1 61 5 19 2011 162 Function Specifications dnpCreateAddressMappingTable Create DNP Address Mapping Table Syntax include lt ctools h gt BOOLEAN dnpCreateAddressMappingTable UINT16 size CHAR enableMapChangeEvents Description The dnpCreateAddressMappingT able function destroys any existing DNP address mapping table and allocates memory for a new address mapping table according to the size parameter Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns TRUE if successful FALSE otherwise Document Version 1 61 5 19 2011 163 Function Specifications dnpCreateMasterPollTable Create DNP Master Poll Table Syntax include lt ctools h gt BOOLEAN dnpCreateMasterPollTable UINT16 size Description This function destroys any existing DNP master poll table and allocates memory for a new table according to the size
164. Example This program turns on all 10 digital outputs and sets the analog outputs to full scale on the SCADAPack 350 include lt ctools h gt define MY EVENT 1 int main void UCHAR doutData 2 INT16 aoutData 2 IO_ STATUS io_status BOOLEAN status main loop while TRUE write data to output tables for next scan doutData 0 OxFF doutData 1 0x03 aoutData 0 32767 aoutData 1 32767 status ioWriteSP20utputs doutData aoutData Document Version 1 61 5 19 2011 395 Function Specifications add module scan to queue if ioRequest MT_SP2Outputs 0 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_EVENT check status of last scan if ioStatus MT SP2Outputs 0 amp io_ status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 396 Function Specifications ipFindFriendlylPAddress Checks if an address is in the Friendly IP List Syntax BOOLEAN ipFindFriendlyIPAddress UINT32 ipAddress Description This function checks if the IP address ipAddress is in the Friendly IP List The function returns TRUE if the supplied ipAddress is in the Friendly IP List Otherwise FALSE is returned Document Version 1 61 5 19 20
165. Group for this application Use this variable in calls to create_task by this application UINT32 applicationGroup 0 A C application should not require any further modifications to appstart cpp There are no longer function calls in appstart for starting various drivers as there were in the SCADAPack 32 version These drivers are already running when a C Application is executed It is still possible to call these functions to disable functionality For example runTarget FALSE may still be called from appstart or main to stop the logic application Replace main cpp Replace the sample file main cpp with the main cpp from your SCADAPack 32 C Application Edit your main cpp and make the following changes e In addition to the ctools h header you need to include the header file nvMemory h e The C Tools require main to have the prototype int main void Change the syntax of main so that it returns the data type int instead of void Note that the returned int value is not accessible to the user and so any value may be returned or none at all e Remove the function definition for abort This function is provided by the operating system e The call release_processor in the main loop can be deleted See section Operating System Scheduling for details Add Remaining C and CPP Files Copy any additional C CPP or H files from your application to the copied sample application directory Replace Partially S
166. HAR variable If the moduleAddress is valid digital input data are copied to the variable The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 358 Function Specifications ioReadSP2Inputs Read SCADAPack 350 Inputs Syntax include lt ctools h gt BOOLEAN ioReadSP2Inputs UCHAR amp dinData 2 INT16 amp ainData 8 Description This function reads buffered data from the digital and analog inputs of the SCADAPack 350 I O Buffered data are updated when an I O request for the module is processed dinData is a reference to an array of two UCHAR variables Digital data for the 12 inputs are written to this array One bit in the array represents each input point ainData is a reference to an array of eight INT16 variables Analog data are written to this array The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioReadSP2Ouiputs ioWriteSP2Outputs Example This program displays the values of the first 8 digital inputs and the 5th analog input read from the SCADAPack 350 I O include lt ctools h gt define MY EVENT 1 int main void UCHAR dinData 2 INT16 ainData 8 IO_ STATUS io_status BOOLEAN status BOOLEAN done BOOLEAN printNow main loop while TRUE add module scan to que
167. Handler function to install a write access handler for the same addresses handled by the dbase handler The C Tools functions dbase and setdbase are used by all protocols to access Modbus or Linear registers Notes Call this function with the NULL pointer to remove the dbase handler This needs to be done when the application program is ended with an exit handler Use the installExitHandler function to install the exit handler If the Dbase handler is not removed within an exit handler it will remain installed and continue to operate until the controller power is cycled Erasing the C Program from the Initialize dialog will not remove the Dbase handler If the handler is located in a RAM based application and left installed while a different C application is downloaded the original handler will be corrupted and the system will likely crash Document Version 1 61 5 19 2011 304 Function Specifications installSetdbaseHandler Install User Defined Setdbase Handler IEC 61131 1 firmware only Syntax include lt ctools h gt void installSetdbaseHandler BOOLEAN handler UINT16 address INT16 value Description The installSetdbaseHandler function allows an extension to be defined for the setdbase function If a handler is installed it is called by the setdbase function when one of the following conditions apply e There is no IEC 61131 1 application downloaded or e There is no IEC 61131 1 varia
168. I protocols only See the TeleBUS Protocols User Manual for details Refer to the TeleBUS Protocols User Manual section for detailed information on communication protocols See Also setProtocolSettings get_protocol Example This program displays the protocol configuration for com1 include lt ctools h gt int main void PROTOCOL SETTINGS settings if getProtocolSettings coml amp settings fprintf fprintf com1 Type d r n settings type com1 Station d r n settings station fprintf com1 Address Mode d r n settings mode fprintf coml SF Messaging d r n settings SFMessaging fprintf coml Priority d r n settings priority else Document Version 1 61 5 19 2011 262 Function Specifications fprintf coml Serial port is not valid r n Document Version 1 61 5 19 2011 263 Function Specifications getProtocolSettingsEx Reads extended protocol settings for a serial port Syntax include lt ctools h gt BOOLEAN getProtocolSettingsEx FILE stream PROTOCOL SETTINGS EX pSettings Description The setProtocolSettingsEx function sets protocol parameters for a serial port This function supports extended addressing and Enron Modbus parameters The function has two arguments e port specifies the serial port It is one of com1 com2 or com3 pSettings is a pointer to a PROTOCOL_SETTINGS_EX structure Refer to the
169. I O module Configuration data are written using the ioWrite5506Outputs function moduleAddress is the address of the 5506 module Valid values are 0 to 15 inputType is a reference to an array of eight UINT16 variables Analog input measurement types are written to this array Valid values are e O0 0to 5V e 1 1to5V e 2 0to20mA e 3 4to 20 mA inputFilter is a reference to a UINT16 variable The input filter selection is written to this variable e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency is a reference to a UINT16 variable The scan frequency selection is written to this variable e 0 60Hz e 1 50 Hz The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5506 Inputs ioWrite55060utputs Document Version 1 61 5 19 2011 335 Function Specifications Example This program reads configuration data for the 5506 I O module at address 5 include lt ctools h gt int main void UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency BOOLEAN status BOOLEAN done main loop while TRUE read output data from I O table status ioRead55060utputs 5 inputType inputFilter scanFrequency print data if done fprintf coml status u inputType 0 Sd inputFilter d scanFrequency d r n status inputType 0 inputFilter scanFrequency done TRUE release processor to o
170. ID enum DialError status enum DialState state struct pconfig portSettings Configure serial port 1 Document Version 1 61 5 19 2011 668 Example Programs portSettings baud BAUD1200 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATA8 portSettings stop bits STOP1 portSettings flow_rx RFC_MODBUS RTU portSettings flow tx TFC_NONE portSettings type RS232 MODEM portSettings timeout 600 request resource IO SYSTEM set_port coml amp portSettings release resource IO SYSTEM Initialize Hayes modem to answer incoming calls initSettings port strcpy initSettings modemCommand if com r F1QOV1X1 SO 1 modemInit amp initSettings amp portID DE NoError do Allow other tasks to execute release processor Wait for the initialization to complete modemInitStatus coml portID amp status amp state while state DS Calling Terminate the initialization modemInitEnd coml portID amp status Real Time Clock Program Example The following program illustrates how the date and time can be set and displayed All fields of the clock structure need to be set with valid values for the clock to operate properly include lt ctools h gt int main void Set to 12 01 now now now now now now now TIME now LO
171. M Document Version 1 61 5 19 2011 469 Function Specifications fprintf coml status u Flow Sf r n status value Document Version 1 61 5 19 2011 470 Function Specifications readStopwatch Read Stopwatch Timer Syntax include lt ctools h gt UINT32 readStopwatch void Description The readStopwatch function reads the stopwatch timer The stopwatch time is in ms and has a resolution of 10 ms The stopwatch time rolls over to 0 when it reaches the maximum value for an unsigned long integer 4 294 967 295 ms or about 49 7 days Example This program measures the execution time in ms of an operation include lt ctools h gt int main void UINT32 startTime endTime startTime readStopwatch operation to be timed endTime readStopwatch fprintf com1 Execution time lu ms r n endTime startTime Document Version 1 61 5 19 2011 471 Function Specifications readThermistor Read Controller Ambient Temperature Syntax include lt ctools h gt INT16 readThermistor UINT16 scale Description The readThermistor function returns the temperature measured at the main board in the specified temperature scale If the temperature scale is not recognized the temperature is returned in Celsius The scale may be T_CELSIUS T_FAHRENHEIT T_KELVIN or T_RANKINE The temperature is rounded to the nearest degree Example include lt cto
172. MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes If the specified register is currently forced dbase returns the forced value for the register The I O database is not modified when the controller is reset It is a permanent storage area which is maintained during power outages The IO_SYSTEM resource needs to be requested before calling this function See Also setdbase Example include lt ctools h gt int main void int az request resource IO SYSTEM Read Modbus status input point a dbase MODBUS 10001 Read 16 bit register a dbase LINEAR 3020 Read 16 bit register beginning at first status register Document Version 1 61 5 19 2011 145 Function Specifications a dbase LINEAR START STATUS Read 6th input register a dbase LINEAR START INPUT 5 release resource IO SYSTEM Document Version 1 61 5 19 2011 146 Function Specifications Dbase Handler Function User Defined Dbase Handler Function The dbase handler function is a user defined function that handles reading of Modbus addresses not assigned in the IEC 61131 1 Dictionary The function can have any name dbaseHandler is used in the description below Syntax include lt ctools h gt BOOLEAN dbaseHandler UINT16 address INT value Des
173. Memory Allocate Non Volatile Dynamic Memory Syntax include lt ctools h gt BOOLEAN allocateMemory void ppMemory UINT32 size Description The allocateMemory function allocates the requested memory from the system memory pool The pool is a separate area of memory from the system heap Memory in the system pool is preserved when the controller is reset The function has two arguments ppMemory a pointer to a pointer to the memory allocated and size the number of bytes of memory to be allocated The function returns TRUE if the memory was allocated and FALSE if the memory is not available Use the freeMemory function to free non volatile memory Notes The DYNAMIC_MEMORY resource needs to be requested before calling this function The allocation of memory and the allocated memory are non volatile Pointers to non volatile dynamic memory need to be statically allocated in a non volatile data section Otherwise they will be initialised at reset and the non volatile dynamic memory will be lost The example below demonstrates how to create a non volatile data section to save pointers to non volatile dynamic memory See Also freeMemory Example See the Memory Allocation Example in the Examples section Document Version 1 61 5 19 2011 104 Function Specifications bind Bind an address to an unnamed socket Syntax include lt ctools h gt int bind int socketDescriptor const struct sockaddr add
174. Messaging translation information This is used to define an address and port translation with a timeout typedef struct st_SFTranslationEx COM INTERFACE slavelInterface slave interface typ UINT16 slaveStation slave station address COM_INTERFACE forwardInterface forwarding interface type UINT16 forwardStation forwarding station address IP_ADDRESS forwardIPAddress forwarding IP address UINT16 timeout time out SF TRANSLATION EX slavelnterface is the communication interface which receives the slave command message Valid interface types are 1 com1 2 com2 3 coms 100 Etherneti slaveStation is the station address used in the slave command message Valid address range is 0 to 255 in standard Modbus 0 to 65534 in extended Modbus 65535 entry cleared This station address must be different from the station address assigned to the slavelnterface forwardIinterface is the communication interface from which to forward the command message as master Valid interface types are 1 com1 2 com2 3 com3 100 Modbus TCP network 101 Modbus RTU over UDP network 102 Modbus ASCII over UDP network Document Version 1 61 5 19 2011 628 Structures and Types SFTranslationStatus forwardStation is the station address of the remote slave device to forward the command message to Valid address range is 0 to 255 in standard Modbus 0 to 6
175. Mode setlOErrorindication Sets the control flag for the I O module error indication setOutputsInStopMode Sets the control flags for state of Outputs in Ladders Stop Mode Register Assignment Enumeration Types The ctools h file defines one enumeration type The ioModules enumeration type defines a list of results of sending a command Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Document Version 1 61 5 19 2011 83 Overview of Programming Functions Register Assignment Structure The ctools h file defines the structure RegAssign Refer to the C Tools Structures and Types section for complete information on structures and enumeration types IEC 61131 1 Variable Access Functions Variables declared in an IEC 61131 1 application are accessed from a C application using the IEC 61131 1 variable access functions listed below Refer to the Function Specification section for details on each function listed readBoolVariable Returns the current value of the specified boolean variable readintVariable Returns the current value of the specified integer variable readRealVariable Returns the current value of the specified real variable readMsgVariable Returns the current value of the specified message variable readTimerVariable Returns the current value of the specified timer variable writeBoolVariable Writes to the specified boolean variable writelntVariable Writes to t
176. Mode Set Outputs In Stop Mode Telepace firmware only Syntax include lt ctools h gt void setOutputsInStopMode BOOLEAN holdDoutsOnStop BOOLEAN holdAoutsOnStop Description The setOutputsInStopMode function sets the holdDoutsOnStop and holdAoutsOnStop control flags to the specified state If holdDoutsOnStop is set to TRUE then digital outputs are held at their last state when the Ladder Logic program is stopped If holdDoutsOnStop is FALSE then digital outputs are turned OFF when the Ladder Logic program is stopped If holdAoutsOnStop is TRUE then analog outputs are held at their last value when the Ladder Logic program is stopped If ho dAoutsOnStop is FALSE then analog outputs go to zero when the Ladder Logic program is stopped To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ PERMANENT release resource FLASH MEMORY See Also getOutputsInStopMode Example This program changes the output conditions to hold analog outputs at their last value when the Ladder Logic program is stopped include lt ctools h gt int main void unsigned holdDoutsOnStop unsigned holdAoutsOnStop getOutputsiInStopMode amp holdDoutsOnStop amp holdAoutsOnStop holdAoutsOnStop TRUE setOutputsInStopMode holdDoutsOnSt
177. O E 00 on January 1 hour set the time minute second day month year dayofweek 2 1 a 0 T set the date ds 97 3 day is Wed Document Version 1 61 5 19 2011 669 Example Programs request resource IO SYSTEM setclock amp now getclock amp now read the clock Ry release resource IO SYSTEM Display current hour minute and second fprintf com1 2d 2d 2d now day now month now year fprintf com1l 2d 2d r n now hour now minute Start Timed Event Example This program prints the time every 10 seconds include lt string h gt include lt ctools h gt define TIME TO PRINT 15 The myshutdown function stops the signalling of TIME TO PRINT events Bee Soe ot E NN go ES O eS ete A ee oe void myshutdown void endTimedEvent TIME TO PRINT Ye Boe eee eee eee ee ees eek ee oe The main function sets up signalling of a timed event then waits for that event The time is printed each time the event occurs Poe eee eo See eee se So SSS int main void struct prot settings settings struct clock now TASKINFO taskStatus Disable the protocol on serial port 1 settings type NO PROTOCOL settings station 1 settings priority 250 settings SFMessaging FALSE request resource IO SYSTEM set_protocol coml amp settings release resource IO SYSTEM set
178. ONNECT_ID returns invalid connection ID e MM_BAD_PROTOCOL_TYPE returns invalid protocol type e MM _BAD_IP_ADDRESS returns invalid slave IP address e MM _BUSY returns last message is still being processed e MM_ENDED returns Master connection has been released This status is only reported by the IEC 61131 1 masterIP function block It is not available from the mTcpMasterStatus function e MM_CONNECT_ERROR returns error while connecting to slave IP address Document Version 1 61 5 19 2011 617 Structures and Types Modeminit ModemSetup MM_NO MORE_CONNECTIONS returns no more connections are available MM_BAD_CONNECTION_TYPE returns invalid connection type used in mTcpMasterMessage MM_EXCEPTION_FUNCTION Returns master message status Modbus slave returned a function exception MM_EXCEPTION_ADDRESS Returns master message status Modbus slave returned an address exception MM_EXCEPTION_VALUE Returns master message status Modbus slave returned a value exception MM_QUEUE_FULL Returns master message status Serial transmit queue is full MM_STATIONS_ARE_EQUAL Returns master message status Master and slave stations are equal They must be different The ModemInit structure specifies modem initialization parameters for the modemlnit function struct ModemInit e FILE port CHAR modemCommand MODEM CMD MAX LEN 2 port is the serial port where the modem is connected modemCommand is the i
179. Offset UINT16 class2Poll0Offset UINT16 class3PollOffset UINT16 timeSyncOffset INT16 classlMaxEvents INT16 class2MaxEvents INT16 class3MaxEvents UINT16 savelIINFlagsRegister dnpMasterPollTableEx Document Version 1 61 5 19 2011 605 Structures and Types dnpPointType dnpRemoteStationAddress is the remote DNP station address classOPollRate is the Class 0 Polling rate class1PollRate is the Class 1 Polling rate class2PollRate is the Class 2 Polling rate class3PollRate is the Class 3 Polling rate timeSyncRate is the time synchronization rate unsolicitedResponseFlags are the DNP Master Unsolicited Response enable flags TimeSyncRate is the time synchronisation rate unsolicitedResponseFlags are the flags for enabling Unsolicited Responses classOPollOffset is the offset for Class 0 Polling class1PollOffset is the offset for Class 1 Polling class2PollOffset is the offset for Class 2 Polling class3PollOffset is the offset for Class 3 Polling timeSyncOffset is the offset for time synchronization class1MaxEvents is the maximum limit of Class 1 events in poll response class2MaxE vents is the maximum limit of Class 2 events in poll response class3MaxEvents is the maximum limit of Class 3 events in poll response savellNFlagsRegister The enumerated type DNP_POINT_TYPE includes all allowed DNP data point types typedef enum dnpPointType DNP POINT TYPE BI_ POINT 0
180. Operating System This does not stop deadlocks that occur when each task requests a resource that the other has already obtained This deadly embrace is a design error in the application program Operating System Scheduling The operating system supports a round robin scheduling algorithm combined with pre emptive priority scheduling It shares the CPU fairly among ready tasks of the same priority Round robin scheduling uses time slicing to achieve fair allocation of the CPU to tasks with the same priority Each task in a group of tasks with the same priority executes for a defined interval or time slice Because the time slicing is performed by the kernel of the operating system it is not necessary anymore for the tasks to call explicitely release_processor to release CPU time to other tasks of the same priority In contrary it can harm When a task expects a fair share of the CPU calling release_processor before the end of the time slice puts it immediately at the end of round robin queue Therefore the CPU time share can be significantly reduced The function release_processor still makes sense if the calling task does not have anything to do for the moment A new function sleep_processor is introduced to release CPU for a certain time Task Management Functions There are five RTOS functions for task management Refer to the Function Specification section for details on each function listed create_task Create a task and ma
181. READY EBADF ECONNREFUSED EPERM EINVAL EISCONN EHOSTUNREACH EPROTOTYPE ETIMEDOUT another socket call to obtain a new descriptor before attempting another connect call The specified address is not available on the remote local machine Addresses in the specified address family cannot be used with this socket The socket is non blocking and the current connection attempt has not yet been completed The socket is non blocking and a previous connection attempt has not yet been completed socketDescriptor is not a valid descriptor The attempt to connect was forcefully rejected The calling program should close the socket descriptor and issue another socket call to obtain a new descriptor before attempting another connect call Cannot call connect after listen call One of the parameters is invalid The socket is already connected The calling program should close the socket descriptor and issue another socket call to obtain a new descriptor before attempting another connect call No route to the host we want to connect to The socket referred to by addressPtris a socket of a type other than type socketDescriptor for example socketDescriptor is a SOCK_DGRAM socket while addressPtr refers to a SOCK_STREAM socket Connection establishment timed out without establishing a connection The calling program should close the socket descriptor and issue another socket call to obtain a new descriptor before atte
182. S PATH C Program Files Control Microsystems CTools endif INCLUDE PATH CTOOLS PATH Controller IEC 61131 1 Document Version 1 61 5 19 2011 23 Getting Started The next section sets the default compiler flags You can add to or modify these flags Change the default options with care as many are required for correct operation The flags are described in the gnu C compiler manual BP ee a ee E ea a a compiler flags Ct Ea a a e aE CFLAGS 03 mapcs 32 mlittle endian march armv4 ansi fno builtin DARMEL I INCLUDE PATH DCPU ARMARCH4 DTOOL_ FAMILY gnu DTOOL gnu std c99 The next section lists the suffixes used in this make file Generally you will not have to modify this section Consult the gnu make documentation if you add files with new suffixes to your application SUFFIXES SUFFIXES cpp c o out The next section determines the targets that will be linked to check if symbols will be resolved in firmware determine intermediate link target s used to check if all symbols can be resolved in firmware stripTarget strip TARGET ifeq stripTarget SCADAPack350 4203 intermediate objects imLink SCADAPack350 0 imLink 4203 0 endif ifeq stripTarget SCADAPack350 intermediate objects imLink SCADAPack350 0 endif ifeq stripTarget 4203 intermediate objects imLink 4203 0 endif The next section describes how to make the
183. SAGE or TS_WAIT_RESOURCE macros requirement is used if the task is waiting for an event or resource If the status field is TS_WAIT_EVENT then requirement indicates on which event Document Version 1 61 5 19 2011 629 Structures and Types taskInfo_tag TIME Str ct cl it is waiting If the status field is TS_WAIT_RESOURCE then requirement indicates on which resource it is waiting error is the task error code This is the same value as returned by the check_error function type is the task type It will be either SYSTEM or applicationGroup The taskInfo_tag structure contains start up task information struct taskInfo tag void address UINT16 stack UINT16 identity address is the pointer to the start up routine stack is the required stack size for the routine identity is the type of routine found STARTUP_APPLICATION or STARTUP_SYSTEM The TIME structure contains time and date for reading or writing the real time clock o UI 6 year 6 month 16 day T16 dayofweek 6 hour 6 minute 6 second 6 hundredth HHHHHHH 6 E C C C Cc E year is the current year It is in the range 97 for the year 1997 to 96 for the year 2096 month is the current month It is in the range 1 to 12 day is the current day It is in the range 1 to 31 dayofweek is the current day of the week Itis in the range 1 to 7 The application program defines the meaning of this fi
184. SCADAPack 300 amp 4203 C Tools User and Reference Manual 5 19 2011 Schneider The information provided in this documentation contains general descriptions and or technical characteristics of the performance of the products contained herein This documentation is not intended as a substitute for and is not to be used for determining suitability or reliability of these products for specific user applications It is the duty of any such user or integrator to perform the appropriate and complete risk analysis evaluation and testing of the products with respect to the relevant specific application or use thereof Neither Schneider Electric nor any of its affiliates or subsidiaries shall be responsible or liable for misuse of the information contained herein If you have any suggestions for improvements or amendments or have found errors in this publication please notify us No part of this document may be reproduced in any form or by any means electronic or mechanical including photocopying without express written permission of Schneider Electric All pertinent state regional and local safety regulations must be observed when installing and using this product For reasons of safety and to help ensure compliance with documented system data only the manufacturer should perform repairs to components When devices are used for applications with technical safety requirements the relevant instructions must be followed Failure to use Schne
185. SE COMIC aeae aria iana asana a aaa aa aiana aaa pa ataata 170 AnpGetAO 1G CONIC Auriasta anaran aa aa aa aaiae diet adeneeces 171 AnpGetAOS2CoOntig Aege arta irana iasan a anaa aiaa aas pa adie 172 dnpPGetAOSFECONTG eiaeaen anaran aaa aa aaa aa aaen iaaa paa atrauta 173 dnPGetBICONTig iet irana anta aana ana an a a aeaa a a aeaa artes Aata 174 AnpGetBl Contig EX Srirama dde asaan dann anaa Pea edanean fas Aaaa 175 dApPGetBOCONTI Oisin araia ien ansora readen aapa levee ha stattazitevesh comsendd ice 176 AnpGetCl 1 SConbig sacscesesccseee cde Needed eseado aasian aidaa iada padal ia onkun aa ikid deers 177 dnpGetGlS2Conig sieraad ier dial deaddveet disse ni aerian aariad a Aiaia Aik 178 dnpGetConfiguration cccccccccccececeeceeceeeeeseaeeeeaeeceeeeseaeeesaaeseeeeeceaeeeseaeeseneeseaees 179 AnpGetContiguration EX ccccccccceceeececeeeeeaeeeeaeeceeeesaeeesaaeseeeeeseaeeesaeeseneesnaees 183 AnpGetRuntiMeStatus eee eecceceeececeeeceeeeeeeaeeeeeeeseeeeecaaeeeeaaeseeeeeseaeeesaeeseneeeeaees 184 AnpGetUnsolicitedBackorfTime ccccceecceceeeeeeeeceeeeeceaeeeeaaeeeeeeeseaeeesaeeseneeenaees 185 AnplnstallConnectionHandler c ccceecceceeeceeeeeceeeeeceaeeesaeeseeeeeceeeesaeeneneeesaees 186 AnpMasterClassPoll c ccccccceceeeceeeeeceeeeeeaeeeeaeeceeeeeseaeeeeaaeseeeeeseaeeesaeeseneeenaees 191 AnpMasterClockSync c ccccecceeeeeceeeee cece eeeeaeeeeneeseaeeeceaeeeeaaeseeeeeseaeeesaeeseneeenaees 192 OMPPOR StAtUs
186. SaveAO32Config function sets the configuration of a DNP 32 bit analog output point The function has two parameters the point number and a pointer to an analog output point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetAO32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 207 Function Specifications dnpSaveAOSFConfig Save Short Floating Point Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAOSFConfig UINT16 point dnpAnalogOutput pAnalogOutput Description The dnpSaveAOSFConfig function sets the configuration of a DNP short floating point analog output point The function has two parameters the point number and a pointer to a configuration structure The function returns TRUE if the configuration was successfully written or FALSE otherwise if the point number is not valid or the configuration is not valid or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP Document Version 1 61 5 19 2011 208 Function Specifications dnpSav
187. Status is the status of the last protocol command sent The dnpRoutingTableEx type describes an entry in the DNP Routing Table The DNP Routing Table is a list of routes which are maintained in ascending order of DNP addresses typedef struct RoutingTableEx type UINT16 address station address UINT16 comPort com port interface UINT16 retries number of retries UINT16 timeout timeout in milliseconds IP_ADDRESS ipAddress IP address dnpRoutingTableEx address is the DNP station address of the destination station comPort specifies the communications port interface Allowed values are 1 serial port com1 2 serial port com2 3 serial port com3 Document Version 1 61 5 19 2011 607 Structures and Types envelope 103 DNP over TCP using LAN port 104 DNP over UDP using LAN port retries is the number of times the data link layer will retry the message in the event of a failure timeout is the timeout in milliseconds ipAddress is the IP address of the destination station DNP_RUNTIME_STATUS The dnpRuntimeStatus type describes a structure for holding status information about DNP event log buffers ag xy ad DNP Runtime Status typedef struct dnp runtime status UINT16 eventCountBI number of binary input events UINT16 eventCountCI16 number of 16 bit counter events UINT16 eventCountC1I32 number of 32 bit counter events UINT16 eventCountAI16
188. TEM resource must be requested before calling this function See Also setForceFlag getForceFlag overrideDbase Document Version 1 61 5 19 2011 109 Function Specifications clearBreakCondition Clear a break condition on a serial port Syntax include lt ctools h gt void clearBreakCondition FILE stream Parameters stream is a pointer to a serial port valid serial ports are com1 com2 com3 and com4 Description The clearBreakCondition function clears a break condition on the communication port specified by stream The communication port will return to idle status Notes This function is only relevant for RS232 ports The function will have no effect on other port types See Also setBreakCondition Document Version 1 61 5 19 2011 110 Function Specifications clear_errors Clear Serial Port Error Counters Syntax include lt ctools h gt void clear errors UCHAR port Description The clear_errors function clears the serial port error counters for the serial port specified by port If port is not a valid serial port the function has no effect The IO_SYSTEM resource needs to be requested before calling this function Document Version 1 61 5 19 2011 111 Function Specifications clear_protocol_status Clear Protocol Counters Syntax include lt ctools h gt void clear protocol status FIL Description E stream The clear_protocol_status function cle
189. Telepace firmware only Syntax include lt ctools h gt BOOLEAN setForceFlag UINT16 type UINT16 address UINT16 value Description The setForceFlag function sets the force flag s for the specified database register s to value value is either 1 or 0 or a 16 bit mask for LINEAR digital addresses The valid range for address is determined by the database addressing type If the address or addressing type is not valid force flags are left unchanged and FALSE is returned otherwise TRUE is returned The table below shows the valid address types and ranges Type Address Ranges Register Size MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes When a register s force flag is set the value of the I O database at that register is forced to its current value This register s value can only be modified by using the overrideDbase function or the Edit Force Register dialog While forced this value cannot be modified by the setdbase function protocols or Ladder Logic programs Force Flags are not modified when the controller is reset Force Flags are ina permanent storage area which is maintained during power outages The IO_SYSTEM resource needs to be requested before calling this function See Also clearRegAssignment getForceFlag getOutputsInStopMode overrideDbase Document Version 1 61 5 19 2011 516 Funct
190. There was insufficient user memory available to complete the operation EHOSTUNREACH No route to destination host EMSGSIZE The socket requires that message be sent atomically and the message was too long EPROTOTYPE TCP protocol requires usage of send not sendto EWOULDBLOCK The socket is marked as non blocking and the send operation would block Document Version 1 61 5 19 2011 504 Function Specifications serialModbusMaster Send Modbus Command Syntax include lt ctools h gt BOOLEAN serialModbusMaster MASTER MESSAGE message MODBUS_SESSION session Description The serialModbusMaster function sends a command on a serial port using a Modbus protocol The Modbus protocol task waits for the response from the slave station The current task continues execution e message points to a MASTER_MESSAGE structure defining the message parameters and serial port to use MASTER_MESSAGE is described in the Structures and Types section e session points to a MODBUS_SESSION structure This structure is used by the Modbus protocol task Declare the MODBUS_ SESSION structure as a static modular or global variable A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space The serialModbusMaster function returns TRUE if a valid message has been queued for transmission The functi
191. Time Operating System Sample Copyright c 2006 Control Microsystems Inc This program creates several simple tasks for demonstration of the functionality of the real time operation system a include lt stdio h gt include lt ctools h gt E signalCharacter Document Version 1 61 5 19 2011 51 Real Time Operating System The signalCharacter function signals an event when a character is received This function must be called from an interrupt handler x7 void signalCharacter UINT16 character UINT16 error Tf there was no error signal that a character was received if error 0 interrupt signal event CHARACTER RECEIVED Prevent compiler unused variables warning generates no code character PR Saeed Sosie ses ste Sete E se eet teste sek eee see eee see se echoData The echoData function is a task that waits for a character to be received on coml and echoes the character back It installs a character handler for coml to generate events on the reception of characters void echoData void struct prot_settings protocolSettings struct pconfig portSettings int character Disable communication protocol get_protocol coml amp protocolSettings protocolSettings type NO PROTOCOL set_protocol coml amp protocolSettings Set serial communication parameters portSettings baud BAUD9600 portSe
192. U will request a time synchronization from the master e Set this to NO_TIME_SYNC to disable time synchronization requests e Set this to STARTUP_TIME_SYNC to request time synchronization at start up only e Set this to 1 to 32767 to set the time synchronization period in seconds e Bl_number is the number of binary input points Valid values are 0 to 9999 e Bl_startAddress is the DNP address of the first Binary Input point e _Bl_reportingMethod determines how binary inputs are reported either Change Of State or Log All Events e Bl_soebufferSize is the Binary Input Change Event Buffer Size Document Version 1 61 5 19 2011 601 Structures and Types e BO_number is the number of binary output points Valid values are O to 9999 e BO_startAddress is the DNP address of the first Binary Output point e Cl16_number is the number of 16 bit counter input points Valid values are 0 to 9999 e Cl16_startAddress is the DNP address of the first C116 point e Cl16_reportingMethod determines how C116 inputs are reported either Change Of State or Log All Events e Cl16_bufferSize is the number of events in the 16 bit counter change buffer Valid values are 0 to 9999 e CI32_number is the number of 32 bit counter input points Valid values are 0 to 9999 e ClI32_startAddress is the DNP address of the first C132 point e CI32_reportingMethod determines how C132 inputs are reported either Change Of State or Log All Events
193. UNINTENDED EQUIPMENT OPERATION e Verify that all installation and set up procedures have been completed e Before operational tests are performed remove all blocks or other temporary holding means used for shipment from all component devices e Remove tools meters and debris from equipment Failure to follow these instructions can result in death serious injury or equipment damage Follow all start up tests recommended in the equipment documentation Store all equipment documentation for future references Software testing must be done in both simulated and real environments Verify that the completed system is free from all short circuits and grounds except those grounds installed according to local regulations according to the National Electrical Code in the U S A for instance If high potential voltage testing is necessary follow recommendations in equipment documentation to prevent accidental equipment damage Document Version 1 61 5 19 2011 15 Before energizing equipment e Remove tools meters and debris from equipment e Close the equipment enclosure door e Remove ground from incoming power lines e Perform all start up tests recommended by the manufacturer OPERATION AND ADJUSTMENTS The following precautions are from the NEMA Standards Publication ICS 7 1 1995 English version prevails e Regardless of the care exercised in the design and manufacture of equipment or in the selection and rati
194. Za 22240 Zz TS ey z BA a 220 a a a a a a a a H J Fa dor Ov oO 3 d OO OD OO 5 d 0D eeo OOOO OOOO applicationTimeout timeSynchronization BI_number BI_startAddress BI_reportingMethod BI_soeBufferSize BO number BO_startAddress CI16 number C116 startAddress C116 reportingMethod C116 bufferSize C132 number C132 startAddress C132 reportingMethod C132 bufferSize C132 wordOrder AI16_ number AI16_ startAddress AI16_ reportingMethod AI16 bufferSize AI32_ number AI32_ startAddress AI32_reportingMethod AI32_ bufferSize AI32_wordOrder AISF_ number AISF_startAddress AISF_reportingMethod AISF_ bufferSize AISF_wordOrder AO16 number AO16 startAddress AO32_ number AO32_startAddress AO32_wordOrder AOSF_ number AOSF_startAddress AOSF_wordOrder autoUnsolicitedClass1 holdTimeClass1 holdCountClass1 holdTimeClass2 holdCountClass2 holdTimeClass3 holdCountClass3 enableUnsolicitedOnStartup sendUnsolicitedOnStartup level2Compliance masterAddressCount masterAddress 8 maxEventsInResponse dialAttempts dialTimeout autoUnsolicitedClass2 autoUnsolicitedClass3 Document Version 1 61 5 19 2011 600 Structures and Types UINT16 pauseTime UINT16 onlineInactivity UINT16 dialType Char modemInitString 64 dnpConfigurationEx e rtuAddress is the address of the RTU The mas
195. _5415Inputs 0 status FALSE wait for scan to complete ioNotification MY EVENT Document Version 1 61 5 19 2011 325 Function Specifications wait event MY_ EVENT read input data from last scan status ioRead5415Inputs 0 dinData check status of last scan if io0Status MT_5415Inputs 0 amp io status status FALSE else if io status commStatus status FALSE print data fprintf coml status u Dins 0 to 7 X r n status dinData 0 release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 326 Function Specifications ioRead5415O0utputs Read 5415 module outputs Syntax include lt ctools h gt BOOLEAN i0oRead54150utputs UINT16 moduleAddress UCHAR amp doutData 2 Description This function reads buffered data from I O table for the 12 output points of a 5415 relay output module Buffered data are written using the ioWrite54150Outputs function moduleAddress is the address of the 5415 module Valid values are 0 to 15 doutData is a reference to an array of two UCHAR variables Digital data for the 12 outputs are written to this array One bit in the array represents each output point See Also ioWrite5415Outputs ioRead5415Inputs Document Version 1 61 5 19 2011 327 Function Specifications ioRead5505Inputs Read 5505 Inpu
196. a problem in either the hardware or system firmware A user program can take control of the watchdog timer so it will detect abnormal execution of the program A watchdog timer is a retriggerable time delay timer It begins a timing sequence every time it receives a reset pulse The time delay is adjusted so that regular reset pulses stops the timer from expiring If the reset pulses cease the watchdog timer expires and turns on its output signifying a malfunction The timer output in the controller resets the CPU and turns off outputs at the I O system The watchdog timer is normally reset by the operating system This is transparent to the application program Operating in such a fashion the watchdog timer detects any hardware or firmware problems Document Version 1 61 5 19 2011 68 Overview of Programming Functions The watchdog timer can detect failure of an application program The program takes control of the timer and resets it regularly If unexpected operation of the program occurs the reset pulses cease and the watchdog timer resets the CPU The program restarts from the beginning There are three library functions related to the watchdog timer Refer to the Function Specification section for details on each function listed wd_auto Gives control of the watchdog timer to the operating system default wd_manual Gives control of the watchdog timer to an application program wd_pulse Generates a watchdog reset pu
197. aa a eT a EEEE O A tedeazeesd 491 TUNIOSYSLOM ES E A TAE EE 492 AUTA E TO AA T A T TA E R 493 r nNMasterlpStartTaS kreesen nanu antrenarea aaraa a a Taaa aa Naa a Aaaa 494 EARE E EE EE O C AAE T E T EET trerr retreat 495 A a EA E A A A E EE 496 SO EA A EA E L T ERE 498 eea e Cs E A E E E EE E 501 SOMO EPEAT EES 503 s nalModb sMastel ce eeeeeececeenneeeeeenaeeeeeeaaeeeeeeaaeeeceeaaeeeeeeaaeeeseeaaeeeeeeaeeeeeeaas 505 Set DF1 Protocol Configuration ccccceesceeeeceeceeeeeeeaeeeeeeeseeeeeseaeeesaeeeeeeeenaees 507 SEtBreak COMAIOM s faze ceed fiezesctdacechicsavses adaedsaddaviesai Sadestdaathen AAAS FEAE EEAO RRRS 508 SCICIOCK feecedecnsacin T T Sache denon Ruicedragdeenadtadigucs te isenon aa E TT 509 SELCIOGKA ANI EE PE TEE P EAEE EEEE EALE A E E T 510 TEAL o C1 EE ATTEST T A A ET 511 Setdbase Handler Function ccccccccceeeeeseceeeeeeeeeeeeaeeeeeeeseeeeseaeeesaeeseneeenaees 513 SOU H a TEE ET A A T 514 setFtpServerState eeecccccecceeceeeeeceeeeeceeeeeaaeseeneeceaeeesaaeseeaaesseeeeseaeeeeaesseneeenaees 515 Setr OCORA o A EA N 516 selOErrorindicaliOn eee 518 setOutputsInStopMode ee eeeececeeeceeeee cece eeeeaeeeeeeeseeeeeseaeeesaaeseeeeeseaeeesaeeseneeeeaees 519 SOL DOME EE E E 520 setLoginCredentials 20 2 ecececeeceeceeeeeecee cee eeeeaeeeeeeeceeeeeseaeeeeaaeeeeeeeseeeseaeseeneeesaees 522 SOtTPOWErMOdG EPE E ATE T T E A 523 SCIPFOGAM Status tees area a eat ee aS 524 SOU Protocole cscstecst
198. adCounter Input no replacement function Document Version 1 61 5 19 2011 675 Porting Existing C Tools Applications ioReadDin5232 no replacement function ioReadCounter5232 ioReadCounterSP2 ioRead5601 Inputs ioReadSP2inputs ioRead5601 Outputs ioReadSP2Outputs ioWrite5601 Outputs ioWriteSP2Outputs Exit Handler Function The argument used to specify the exit handler function in existing calls to installExitHandler must be cast to the type FUNCPTR Please see the documentation for installExitHandler in the Function Specifications section for more details Program Status Functions The functions getProgramStatus and setProgramStatus have changed syntax To support multiple C applications these functions now have an argument to specify the application The new syntax for these functions is documented in the Function Specifications section Freeing Dynamic Memory When a C Application is ended e g by using the STOP button from the C C Program Loader memory allocated by using the malloc function is not freed automatically An exit handler must be installed to free allocated memory Please see the documentation for installExitHandler in the Function Specifications section for more details Non Volatile Data Sections Socket Functions The SCADAPack 350 and 4203 have a different method for declaring static non volatile memory There is still 8 KB of memory available but it needs to now be shared with all user lo
199. address and a reference to an INT16 variable If the moduleAddress is valid digital input data are copied to the variable The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 352 Function Specifications ioReadDin32 Read 32 Digital Inputs Syntax include lt ctools h gt BOOLEAN ioReadDin32 UINT16 moduleAddress UINT32 amp data Description This function reads buffered data from the 32 point digital input module at the specified module address Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the digital output module The valid range is 0 to 15 data is a reference to a variable to receive the input data The function returns TRUE if data was written The function returns FALSE if the module address is invalid See Also ioReadDin8 ioReadDin16 Example This program displays the values of the 32 digital inputs read from a 32 point Digital Input Module at module address 0 include lt ctools h gt define IO NOTIFICATION 0 int main void UINT16 point UINT32 dinData request read from digital input module ioRequest MT Din32 0 wait for the read to complete ioNotification IO NOTIFICATION wait _ event IO NOTIFICATION get the data read ioReadDin32 0 dinData Print module data
200. address of the point A change event is generated for the specified point with the current time and current value and stored in the DNP event buffer The format of the event will depend on the Event Reporting Method and Class of Event Object that have been configured for the point The function returns TRUE if the event was generated It returns FALSE if the DNP point is invalid or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 166 Function Specifications dnpGenerateEventLog Generates a change event for the DNP point Syntax include lt ctools h gt BOOLEAN dnpGenerateEventlLog UINT16 pointType UINT16 pointAddress Description The dnpGenerateEventLog function generates a change event for the DNP point Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 167 Function Specifications dnpGetAl16Config Get DNP 16 bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAI16Config UINT16 point dnpAnalogInput pAnalogInput Description The dnpGetAl16Config function reads the configuration of a DNP 16 bit analog input point The function has two parameters the point number and a pointer to an analog input point configuration structure The function returns TRUE if th
201. addressing The Protocol Settings structure defines settings for a communication protocol This structure differs from the extended settings in that it allows fewer settings to be specified struct prot _ settings UCHAR type UCHAR station UCHAR priority UINT16 SFMessaging type is the protocol type It may be one of NO PROTOCOL MODBUS_RTU MODBUS_ASCIl AB_FULL_BCC AB_HALF_BCC AB_FULL_CRC AB_HALF_CRC DNP macros To set the remaining settings use the function mTcpSetinterfaceEx station is the station address of the controller Each serial port may have a different address The valid values are determined by the communication protocol This field is not used if the protocol type is NO_PROTOCOL priority is the task priority of the protocol task This field is not used if the protocol type is NO_PROTOCOL SFMessaging is the enable Store and Forward messaging control flag The prot_status structure contains protocol status information struct prot status UINT16 command_errors UINT16 format_errors UINT16 checksum_errors UINT16 cmd received UINT16 cmd sent UINT16 rsp received UINT16 rsp sent Document Version 1 61 5 19 2011 624 Structures and Types UINT16 command INT16 task id UINT16 stored messages UINT16 forwarded messages e command_errors is the number of messages received with invalid command codes e format_errors is the number of messages received with bad message
202. aded C applications Non volatile variable declarations and their pragma statements need to be removed from each source file and declared globally in the one file nvMemory h Include nvMemory h in each source file that uses non volatile variables Please see the section Non Volatile Memory for more details on editing nvMemory h and on using these variables in your source files The following functions are no longer supported The replacement function is indicated for each Replaced wih Close HGetSocketEror Modbus Handler Functions Document Version 1 61 5 19 2011 676 Porting Existing C Tools Applications The installModbusHandler is used to add user defined extensions to the standard Modbus protocol To uninstall a Modbus handler in a SCADAPack 32 C application the same function is called with the NULL pointer SCADAPack C applications support the installation of multiple Modbus handlers In order to remove a specific Modbus handler the new function removeModbusHardler is used Calling installModbusHandler with the NULL pointer has no effect Unsupported C Tools Functions The following sections describe functions that are supported by the SCADAPack 32 C Tools but are not supported by the SCADAPack C Tools Refer to these sections when porting existing C Tools Applications to the SCADAPack 350 and 4203 Timers The following C Tools Timer functions are not supported Use the functions readStopwatc
203. aeecstevegs feyasths shims ceyiitadba NA 525 Set roto Set Sess cscs epete cath si perk castes tasnepep estes aitt sath cher a aenetens etl Sais 526 SetProtocolSettingSEy ccccccceesceeeeeeececeeeeaeseeneeceeeeseaeeseaaeegeeeeceaeessaeseeneessaees 528 SELSE Translation ists c ctievaeh S dsateastsietesduepiahesasttinsedenns 530 SCISF Translation EX aoran iaeaea a TEE a AAEE deeded aasteg 533 SetsOCkOpls 2 sai inde A Ad die i NE A E A ER 536 SCISalUSBibes Miche iia hie eine hin neni ee ta Ae nee 540 StS atUSMOde cigs tesa sade iti iadad nie iad aes eee heii 541 SetWakeSOurce naa a a a a ne 542 SHUTHOWMN i aaa tie aie dae eee eae 543 Signal events arnie ia a ee a a a A 544 Document Version 1 61 5 19 2011 SleGCpMOde ect eave aise Aileen eee te tie te eee 547 SOCKET 22 2 0 h cee een en ae eee rea nein ee eee 548 Start Protocol wie iied eee viee Agee eae eve eine ieee es 550 Startup E E ease T T E Ghee din 551 Start NimedE vents natier ee rene tn a lee A 552 SySSerialSetRxTime Out ccccccececcecceceneceeaeeeeneeceeeeeseaeseeaaesseeeseaeeseaesseneeesaees 553 unregisterBulkDevOperation ceccceceeeeeeeeeceeeeeceeeeeceaeeeeeeeseeeeeseaeeesaeeseeeseeeeees 556 Walt OVEN snein nietaes AT Wesel a e a ae Eai caverta deel ev E aat 558 WO QUILO PARE PE A A A Sebaexcodelansutestacn A a sveubeetain A 559 wd enabled ini ait estonet ara tetseventelaveeleotecn coeetineettecatecadel awteleetespeteytantet obraren 560 Anne M Ae a LETE
204. al time clock alarm occurs The IO_SYSTEM resource needs to be requested before calling this function Example See the Example for the installClockHandler function Document Version 1 61 5 19 2011 488 Function Specifications route Redirect Standard I O Streams Syntax include lt ctools h gt void route UCHAR logical UCHAR hardware Description The route function redirects the I O streams associated with stdout stdin and stderr These streams are routed to the com1 serial port by default logical specifies the stream to redirect hardware specifies the hardware device which will output the data It may be one of 0 com1 1 com2 or 2 coms Notes This function has a global effect so all tasks need to agree on the routing Output streams need to be redirected to a device that supports output Input streams need to be redirected to a device that supports input The use of this function is strongly discouraged since tasks beyond the control of the C Application may make use of the streams stdout stdin and stderr This may result in data being unexpectedly added or removed from these streams Example This program segment will redirect all input output and errors to the com2 serial port include lt ctools h gt route STD_ERR 1 _ send errors to com2 route STD_OUT 1 send output to com2 route STD_IN 1 get input from com2 rresvport Syntax include lt ctools h gt in
205. alid FALSE is returned otherwise TRUE is returned and the settings are set for the specified interface The valid value for iffype is CIF_Ethernet1 The enumeration type COM_INTERFACE and the structure MTCP_IF_SETTINGS are described in the Structures and Types section To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Document Version 1 61 5 19 2011 434 Function Specifications mTcpSetinterfaceEx Set Modbus IP Interface Extended Settings Syntax include lt ctools h gt BOOLEAN mTcpSetInterfaceEx COM_ INTERFACE ifType MTCP_IF SETTINGS EX pSettings Description This function sets the interface settings used for Modbus IP protocols including Enron Modbus settings The function has two parameters e ifType specifies the interface The valid value is CIF_Ethernet1 e pSettings is a pointer to a Modbus IP interface extended settings structure that contains the desired settings The function returns TRUE if the specified interface and settings are valid and FALSE otherwise To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN releas
206. alid events for use in an application program Example See the Examples for startTimedEvent See Also startTimedEvent Document Version 1 61 5 19 2011 231 Function Specifications enronInstallCommandHandler Installs handler for Enron Modbus commands Syntax include lt ctools h gt void enronInstallCommandHandler UINT16 function UINT16 length UCHAR pCommand UINT16 responseSize UINT16 pResponseLength UCHAR pResponse Description This function installs a handler function for Enron Modbus commands The protocol driver calls this handler function each time a command is received for the Enron Modbus station function is a pointer to the handler function If function is NULL the handler is disabled The function has no return value Notes The application needs to disable the handler when the application ends This stops the protocol driver from calling the handler while the application is stopped Call the enronlinstallCommmandHandler with a NULL pointer The usual method is to create a task exit handler function to do this See the Example below for details The handler function has five parameters e length is the number of characters in the command message e pCommand is a pointer to the command message The first byte in the message is the function code followed by the Enron Modbus message See the Enron Modbus protocol specification for details on the message formats e r
207. alup h section for a complete Description of error codes Notes The serial port type needs to be set to RS232_ MODEM The modemDialStatus function returns the status of the connection attempt initiated by modemDial The modemDialEnd function terminates the connection to the remote controller A pause of a few seconds is required between terminating a connection and initiating a new call This pause allows the external modem time to hang up If a communication protocol is active on the serial port when a connection is initiated the protocol will be disabled until the connection is made then re enabled This allows the controller to communicate with the external modem on the port The protocol settings will also be restored when a connection is terminated with the modemDialEnd function If a modeminit function or an incoming call is active on the port the modemDial function cannot access the port and will return an error code of DE_NotInControl If communication stops for more than five minutes then outgoing call requests are allowed to end the incoming call This prevents the modem or the calling application from permanently disabling outgoing calls The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port Document Version 1 61 5 19 2011 420 Function Specifications To optimize performance minimize the length of messages on com3 Examples of
208. an a Saien aE a teased 365 FOSTERS ois EEE E E A A E RE 366 lOSYSTEMRES biel oien a eai a e anaa r a ae a aaa a aa Taa 368 OVES O a EAR IEEE E A AAEE EEA AAAS 369 joWrite4203DROutputs s eeeseeeseeese nee netnsstnstnsstnsstnsstnsstnssresstensrensrensnnnsnnnnnnnne 370 joWrite4203DSOutputs ee eeceee cece ee cece ee eeeeeeeeeeceeeeeseaeeeeaaeseeeeeseaeeesaeeteaeeeeeeeess 372 IOWrite521 OOUTDUS 2 0 2 cece eeeee cece cece eeeeaeeeeeee ceases aid aaoi midani uad idani aaar kae idas 374 joWrite54140utputs 0 cee eee ee eee cece ee ceee ee ee ae eeeeee sees ee caaeeeeaaeseeeeeseaeeesaeeeeaeeeeeeeess 376 joWrite54150utputs 0 cee eee ceeece cece ee ceeeeeeaaeeeeeee cae eeeaaeeeeaaeseeeeseaeeesaaesseneeeeeeeees 377 joWrite55050utputs 0 2 cece ee eee cece eect eeeeaeeeeeee ceases eaaeeeeaaeseeeeeseaeeesaeeseaeeeeeeeess 379 joWrite55060utputs eee eect ee ene ceeeeeceeeeeaaeeeeeeeceaeeecaaeeeeaaeseeeeeseaeeesaeeeeaeeseeeeess 381 joWrite56060utputs eee ee eeee cece ee ceeeeeeaeeeeeee ceases saaeeesaaeseeeeeseaeeesaeeseaeeeeeeeess 383 joWrite56070utputs cece cece eeeeee cece cece eeeeeeaeeeeeee ceases seaeeeeaaeseeeeeseaeeesaeeseaeeseeeeess 386 lOW rtGAOUt2 sei isin E PATEE PEE ATETA EEE EE E TTET A EE EE 389 IOWTITCAOUT4 ae E EE TA S A teh oleae sae leo ety 390 IOWTITEAOUTS SOS ia ETE A ERE EAE EE RAA 391 ION It DOU O r aa E E A R EEA TE T 392 IOW rIREDOUTS Z Sraa a EA A R E ET 393 IOW rO DOUG oe a R A A EEA EEES
209. and the forwarding interface to forward the command The response to the command is automatically returned to master through the same communication path in reverse Additional entries in the Store and Forward Table are not needed to describe the response path The IO_SYSTEM resource needs to be requested before calling this function To save the Store and Forward Table with the controller settings in flash memory so that it is loaded on controller reset call flashSettingsSave as shown below save Store amp Forward table with controller settings request _ resource FLASH MEMORY flashSettingsSave CS_ RUN release resource FLASH MEMORY Translations may involve any combination of interfaces The interfaces may be running a Serial Modbus or Modbus IP protocol Serial Modbus Interface Serial Modbus Interface Modbus IP Interface Serial Modbus Interface Serial Modbus Interface Modbus IP Network e g com1 com2 or com3 e g Modbus TCP Modbus RTU over UDP or Modbus ASCII over UDP Modbus IP Interface Modbus IP Network e g Ethernet e g Modbus TCP Modbus RTU over UDP or Modbus ASCII over UDP Modbus IP Network as Forwarding Interface When forwarding to a TCP or UDP network the protocol type is selected for the forwardinterface in the SF_TRANSLATION_ EX structure The IP Stack automatically determines the exact interface e g Ethernet1 to use when it searches the network for the forward PAd
210. any of the event numbers declared in ctools h as system events BACKGROUND This event triggers execution of the background I O routines An application program cannot use it COM1_RCVR This event is used by communication protocols to signal a character or message received on com1 It can be used in a custom character handler see install_handler COM2_RCVR This event is used by communication protocols to signal a character or message received on com2 It can be used in a custom character handler see install_handler COM3_RCVR This event is used by communication protocols to signal a character or message received on coma It can be used in a custom character handler see install_handler COM4_RCVR This event is used by communication protocols to signal a character or message received on com4 It can be used in a custom character handler see install_handler NEVER This event will never occur It can be used to disable a task by waiting for it to occur However to end a task it is better to use end_task This frees all resources and stack space allocated to the task Sharable O drivers to return error information to the calling task use the error reporting functions These functions provide that an error code generated by one task is not reported in another task The errno global variable used by some functions may be modified by another task before the current task can read it Document Version 1 61 5 19 2011 50 Real Tim
211. any value greater than 0 fileRecordSize is the number of records in the each data log file Valid values are any value greater than 0 numRecordElements is the number of elements in each record Valid values are any value greater than 0 Document Version 1 61 5 19 2011 588 Structures and Types e recordList is a pointer to a list of record element definitions See the dlogRecordElement type for details e _securityToken is a security token that must be present on an inserted mass storage device for these logs to be copied to that device Set this to 0 to disable the token e description is a string describing the log The description is included in the header of the log files The string has to be null terminated e logName is the name of the log The log name is used to name the log files The string has to be null terminated dlogCMITime Type This structure represents the time stamps for data log records Time is measured as the number of days since January 1 1997 and the number of centiseconds since the start of the current day The time in this format can be obtained using the getClockTime function typedef struct INT32 days INT32 centiseconds dlogCMITime e days is the number of days since January 1 1997 e centiseconds is the number of hundredths of a second since the start of the current dlogMediaStatus Type day The dlogMediaStatus enumerated type indicates the status of
212. application for SCADAPack 350 controller make TARGET 4203 makes application for 4203 controller make clean deletes all output files Document Version 1 61 5 19 2011 22 Getting Started The first section of the file sets the name of the output file The default name is myApp You should modify this for you application set the name of the output file here APPLICATION NAME myApp a The next section lists all the object files in the application There is one object file corresponding to each C or CPP source file The framework has two files You should add additional files here objects appstart o main o The next section sets the default list of controllers for which the application is made The targets in this list are used when make is typed on the command line without arguments The default list can be overridded by specifying targets on the command line The application is linked against symbol files for the firmware for these target controllers The C Tools and include paths are set in the next section The paths are taken from the environment variable you set during installation If the variable is not present they default to the standard paths You don t need to do anything to this section take the C Tools path from the environment or set default if it s not there default may not be correct for all installations ifeq strip CTOOLS PATH CTOOL
213. arameter pointer is null or port number to reserve is less than IPPORT_RESERVEDSTART 600 Document Version 1 61 5 19 2011 490 Function Specifications runBackgroundlO Run Background I O Task Syntax include lt ctools h gt void runBackgroundIO BOOLEAN state Description The runBackgroundlO function is used to start or stop the Background I O task This task provides dialup support and controls the LED Power pushbutton Calling the function with the argument state set to FALSE stops the Background I O task Calling the function with state set to TRUE starts the task This function should only be needed in the context of the startup function appstart Document Version 1 61 5 19 2011 491 Function Specifications runlOSystem Run I O System Syntax include lt ctools h gt void runIOSystem BOOLEAN state Description The runlOSystem function is used to start or stop the I O System tasks The I O System needs to be running to access I O modules through the functions in the ioRead and ioWrite group Calling the function with the argument state set to FALSE stops the I O System Calling the function with state set to TRUE starts the I O System This function should only be needed in the context of the startup function appstart Document Version 1 61 5 19 2011 492 Function Specifications runLed Control Run LED State Syntax include lt ctools h gt void runLed UINT16
214. ariable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the variable value is written to the floating point value pointed to by value If the variable is not found or if the IEC 61131 1 Symbols Status is invalid FALSE is returned and the current value is left unchanged The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the dbase function The lO_SYSTEM system resource needs to be requested before calling this function See Also readintVariable Example This program displays the contents of the real variable named Flow include lt ctools h gt int main void BOOLEAN status float value request resource IO SYSTEM status readRealVariable Flow amp value release resource IO SYSTE
215. arizes the number and type of active TCP IP connections typedef struct st_connectionSummary UINT32 slaveConnections UINT32 masterConnections UINT32 unusedConnections Document Version 1 61 5 19 2011 612 Structures and Types IP CONNECTION SUMMARY slaveConnections is the number of active slave TCP IP connections masterConnections is the number of active master TCP IP connections unusedConnections is the number of unused TCP IP connections available IP_CONFIG_MODE Enumeration The IP_CONFIG_MODE enumeration defines IP configuration options The PPP options are not supported on SCADAPack 350 or 4203 controllers typedef enum ipConfigMode t IP_CONFIG MODE IPConfig CtrilSettings IPConfig GatewayOnLAN IPConfig GatewayOnComl IPConfig GatewayOnCom2 IPConfig_ GatewayOnCom3 IPConfig GatewayOnCom4 tow wt we teu os NN NS BwWNHrR OO IPConfig_CtrlSettings configures IP settings from controller settings Default gateway is on LAN subnet IP_SETTINGS defines gateway address Same as IPConfig_GatewayOnLAN IPConfig_GatewayOnLAN configures IP settings from controller settings Default gateway is on LAN subnet IP_SETTINGS defines gateway address Same as IPConfig_CirlSettings IPConfig_GatewayOnCom1 configures IP settings from controller settings Default gateway is the com1 PPP connection IPConfig_GatewayOnCom2 configures IP settings from controller settings Default gateway is the
216. array One bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are written to this array The function returns TRUE See Also ioReadSP2Inputs ioWriteSP2Outputs Example This program reads output data from the I O table for the SCADAPack 350 digital outputs and analog outputs include lt ctools h gt int main void UCHAR doutData 2 INT16 aoutData 2 BOOLEAN status BOOLEAN done BOOLEAN printNow main loop while TRUE read output data from I O table status ioReadSP2O0utputs doutData aoutData print data when coil register 100 is selected request_resource IO SYSTEM printNow dbase MODBUS 100 Document Version 1 61 5 19 2011 361 Function Specifications fprintf coml Douts 0 to 7 done TRUE release resource IO SYSTEM if printNow if done status Su X Aout 0 sd r n status doutData 0 else done FALSE aoutData 0 release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 362 Function Specifications ioRequest Add I O Module Scan Request to Request Queue Syntax include lt ctools h gt BOOLEAN ioRequest IO TYPE moduleType UINT16 moduleAddress Description This function adds to the I O Controller
217. ars the error and message counters for the serial port specified by port If port is effect not a valid serial port the function has no The IO_SYSTEM resource needs to be requested before calling this function Document Version 1 61 5 19 2011 112 Function Specifications clearLoginCredentials Clears all configured usernames and passwords for the specified service Syntax include lt ctools h gt BOOLEAN clearLoginCredentials UINT32 service Parameters service specifies the service for which the credentials are being cleared Description The clearLoginCredentials function removes all configured usernames and passwords from the specified service True is returned if the usernames and passwords were removed False is returned if the usernames and passwords could not be removed Notes Valid services are 0 FTP See Also setLoginCredentials getLoginCredentials Document Version 1 61 5 19 2011 113 Function Specifications clearRegAssignment Clear Register Assignment Telepace firmware only Syntax include lt ctools h gt void clearRegAssignment void Description The clearRegAssignment function erases the current Register Assignment Call this function first before using the addRegAssignment function to create a new Register Assignment To save the Register Assignment with the controller settings in flash memory so that it is loaded on controller reset call flashSetting
218. ask modem connections or initializations must be aborted in the exit handler Otherwise the reservation ID for the port remains valid No other task or Ladder Logic program may use modem functions on the port Not calling modemAbort or modemAbortAll in the task exit handler may result in the port being unavailable to any programs until the controller is reset The modem connection or initialization is automatically terminated when IEC 61131 1 stops the C application and when the controller is rebooted This function will terminate all open dial up connections or modem initializations started by the C application even those started by other tasks The exit handler can call this function instead of multiple calls to modemAbort if all the connections or initializations were started from the same task Reservation IDs returned by the modemDial and modemInit functions are invalid after calling modemAbort or modemAbortAll See Also Example This program installs an exit handler for the main task that terminates any dial up connections made by the task This handler is not strictly necessary if IEC 61131 1 ends the main task However it demonstrates how to use the modemAbortAll function and an exit handler for another task in a more complex program include lt ctools h gt Document Version 1 61 5 19 2011 418 Function Specifications The shutdown function aborts any active modem connections when the task is ended void shut
219. ask and the Ladder Logic and I O scanning task have a priority of 100 If the created task is continuously running processing code create the task with a priority of 100 The scheduling algorithm of the operating system will give each task of the same priority time slices to share the CPU For tasks such as a protocol handler that wait for an event using the wait_event or receive_message function a priority higher than 100 e g 75 may be selected without blocking other lower priority tasks The number of stack blocks required depends on the functions called within the task and the size of local variables created Tasks usually require 2 stack blocks Document Version 1 61 5 19 2011 128 Function Specifications If the fprintf function is used then at least 5 stack blocks are required Add local variable usage to these limits if large local arrays or structures are created Large structures and arrays are usually handled as static global variables within the task source file The variables are global to all functions in the task but cannot be seen by functions in other files Additional stack space may be made available by disabling unused protocol tasks See the section Program Development or the set_protocol function for more information See Also end_task Example See the Create Task Example in the Examples section Document Version 1 61 5 19 2011 129 Function Specifications databaseRead Read Value fro
220. askGroup Description The end_group function terminates all tasks of the specified type This function should only be used with taskGroups of APPLICATION_GROUP_0 APPLICATION _GROUP_9 Stack space and resources used by the tasks are freed Notes This function is used normally by communication protocols to stop an executing application program See Also end_application end_task Document Version 1 61 5 19 2011 229 Function Specifications end_task Terminate a Task Syntax include lt ctools h gt void end_task UINT16 task ID Description The end_task function terminates the task specified by task_ D Stack space and resources used by the task are freed The end_task function terminates any type task See Also end_application end_group Document Version 1 61 5 19 2011 230 Function Specifications endTimedEvent Terminate Signaling of a Regular Event Syntax include lt ctools h gt UINT16 endTimedEvent UINT16 event Description This endTimedEvent function cancels signaling of a timed event initialized by the startTimedEvent function The function returns TRUE if the event signaling was canceled The function returns FALSE if the event number is not valid or if the event was not previously initiated with the startTimedEvent function The function has no effect in these cases Notes Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in ctools h are not v
221. ata for the 10 outputs are read from this array One bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are read from this array inputType is a reference to an array of eight UINT16 variables selecting the input range for the corresponding analog input Valid values are e 0 0to 5V e 1 0t010V e 2 0to20mA e 3 4to 20 mA inputFilter selects input filter selection is written to this variable e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency selects the scan frequency setting Valid values are e 0 60 Hz e 1 50 Hz Document Version 1 61 5 19 2011 386 Function Specifications outputType selects the analog output type setting Valid values are e 0 0to20mA e 1 4to20 mA The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5607Outputs ioRead5607Inputs Example This program turns on all 10 digital outputs and sets the analog outputs to full scale on the 5607 module at address 5 include lt ctools h gt define MY EVENT 1 void main void UCHAR doutData 2 INT16 aoutData 2 UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType IO_ STATUS io_status BOOLEAN status main loop while TRUE write data to output tables for next scan doutData 0 OxFF doutData 1 OxFF aoutData 0
222. ata sent If none of the message data fits then 1 is returned with socket error being set to EWOULDBLOCK Non blocking datagram socket send if the socket does not have enough buffer space available to hold the message being sent no data is being sent and 1 is returned with socket error being set to EWOULDBLOCK The select call may be used to determine when it is possible to send more data Sending Out of Band Data For Example if you have remote login application and you want to interrupt with a C keystroke at the socket level you want to be able to send the C flagged as special data also called out of band data You also want the TCP protocol to let the peer or remote TCP know as soon as possible that a special character is coming and you want the peer or remote TCP to notify the peer or remote application as soon as possible At the TCP level this mechanism is called TCP urgent data At the socket level the mechanism is called out of band data Out of band data generated by the socket layer is implemented at the TCP layer with the urgent data mechanism The user application can send one or several out of band data bytes With TCP you cannot send the out of band data ahead of the data that has already been buffered in the TCP send buffer but you can let the other side know with the urgent flag i e the term urgent data that out of band Document Version 1 61 5 19 2011 498 Function Specifications data is com
223. ation SF_PORT_OUT_OF_RANGE Result code serial port is not valid SF_STATION_OUT_OF_RAN Result code station number is not valid GE SF_TABLE_SIZE Number of entries in the store and forward table l 1 SIGNAL_RING Not supported forced low 0 SIGNAL_VOICE I O line bit mask voice data switch signal Document Version 1 61 5 19 2011 580 Macro Definitions START_COIL Start of the coils section in the linear database START_HOLDING Start of the holding register section in the linear database linear database database STARTUP_ Specifies the application start up task STARTUP_SYSTEM Specifies the system start up task STOP1 Specifies 1 stop bit SYSTEM Specifies a system type task System tasks are not terminated by the end_application function T_CELSIUS Specifies temperatures in degrees Celsius T_FAHRENHEIT Specifies temperatures in degrees Fahrenheit TFC_IGNORE_CTS Flow control type may be used in place of ENABLE TFC_NONE Flow control type may be used in place of DISABLE TS_READY Task status indicating task is ready to execute TS_WAIT_ Task status indicating task is blocked RESOURCE waiting for a resource 581 Document Version 1 61 5 19 2011 Macro Definitions TS_WAIT_ENVELOPE Task status indicating task is blocked waiting for an envelope TS_WAIT_EVENT Task status indicating task is blocked waiting for an event TS_WAIT_MESSAGE Task status indicating task is block
224. ation_ type INT16 masterAddress INT16 rtuAddress HAR datalinkConfirm HAR datalinkRetries INT16 datalinkTimeout INT16 operateTimeout CHAR applicationConfirm INT16 maximumResponse CHAR applicationRetries INT16 applicationTimeout NT16 timeSynchronization I oe aeaaeea2ea aG E T16 BI number UINT16 BI startAddress UINT UINT HAR BI_reportingMethod INT16 BI _soebufferSize INT16 BO number 16 BO_startAddress UINT16 CIl6_number 16 CI16_startAddress CHAR CI16 reportingMethod UINT16 CI16 bufferSize UINT16 CI32 number UINT16 CI32 startAddress CHAR C132 reportingMethod UINT16 C132 bufferSize CHAR CI32 wordOrder UINT16 AI16_ number Document Version 1 61 5 19 2011 595 Structures and Types UINT16 AI16 startAddress CHAR AI16 reportingMethod UINT16 AI16 bufferSize UINT16 AI32 number UINT16 AI32 startAddress CHA AI32_ reportingMethod UINT16 AI32 bufferSize CHAR AI32 wordOrder 16 AISF number UINT16 AISF startAddress CHAR AISF_reportingMethod 16 AISF bufferSize CHAR AISF wordOrder 16 AO16 number UINT16 AO16 startAddress UINT16 AO32 CHAR AO32 wordOrder UINT16 AOS 16 AO32_ number startAddress 16 AOSF_ number startAddress F CHAR AOSF wordOrder 16 autoUnsolicitedClass1 UINT16 holdTimeClass1 holdCountClass1 autoUnsolicitedClass2 holdTimeClass2 holdCountClass2 autoUns
225. ave device Document Version 1 61 5 19 2011 85 Overview of Programming Functions File Management API File management library functions are provided by the GNU libraries that are installed with C Tools Documentation of these functions is included in the installed document GNU Documentation The functions listed below are recommended for file access clearerr closedir fclose feof fflush fgetc fgets fopen fprintf fputc fputs fread fseek ftell fwrite getc gets mkdir opendir putc puts readdir remove rmdir Document Version 1 61 5 19 2011 86 Function Specifications Function Specifications This section of the user manual contains specifications for using each of the available functions The functions in the sections that follow are available for use in C programs These functions are available for use with both Telepace and IEC 61131 1 firmware unless otherwise noted Functions Supported by Telepace Only The following functions are only supported by C Tools running on Telepace firmware addRegAssignment clearRegAssignment getForceFlag getOutputsInStopMode overrideDbase setForceFlag setOutputsInStopMode Functions Supported by IEC 61131 1 Only The following functions are only supported by C Tools running on IEC 61131 1 firmware Dbase Handler Function installDbaseHandler installSetdbase Handler readBoolVariable readintVariable readMsg Variable readRealVariab
226. ber of Class 2 events to hold before reporting autoUnsolicitedClass3 enables or disables automatic Unsolicited reporting of Class 3 events holdTimeClass3 is the maximum period to hold Class 3 events before reporting holdCountClass2 is the maximum number of Class 3 events to hold before reporting enableUnsolicitedOnStartup controls whether unsolicited reporting is initially enabled or disabled in the controller sendUnsolicitedOnStartup controls whether a null unsolicited message is sent from the controller on startup level2Compliance controls which DNP point types are sent in a Class 0 Poll If level2Compliance is TRUE floating point types and 32 bit Analog Outputs are not sent because they are not level 2 compliant DNP types they are converted to 32 bit Analog Inputs and 16 bit Analog Outputs If level2Compliance is FALSE all points are reported as their true point type The dnpConfigurationEx type includes extra parameters in the DNP Configuration typedef struct dnpConfigurationEx type T16 rtuAddress HAR datalinkConfirm HAR datalinkRetries T16 datalinkTimeout operateTimeout HAR applicationConfirm T16 maximumResponse HAR applicationRetries Ce ey ey ey Gy eae QAHAHHAAH bh Oo Document Version 1 61 5 19 2011 599 Structures and Types H Z HHHHHHHHHHHHHHHHHOHHKHOQOHHHHOAOHQOHHAHQAHHHOHHAHQAQAHQOAHHHOHHHHHOHHZH Zz Za Z22240 Zz T2a4a4240 Zz
227. ber of records remaining in the data log buffer for the log This determines how many records the data log server can be written to the log without data loss Document Version 1 61 5 19 2011 158 Function Specifications dlogSuspend Suspend writing to the data log file from the data log buffer Syntax include lt ctools h gt dlogStatus dlogSuspend UINT32 dlogID Parameters The function has these parameters e dlogID is the ID of the data log The function returns e DLOGS_SUCCESS if logging was suspended e DLOGS_BADID if the data log ID is invalid e Description This function suspends the writing to data log files and closes any open files After successful suspension removal or exchange of an external drive is safe as is moving files to another device Nevertheless further calls to dlogWrite are still allowed and will succeed as long as records fit in the buffer dlogSuspend calls dlogFlush to move data log buffer records as possible to file before the output is suspended A repeated call to dlogSuspend has no effect See Also dlogResume Document Version 1 61 5 19 2011 159 Function Specifications dlogWrite Write to a data log Syntax include lt ctools h gt dlogStatus dlogWrite UINT32 dlogID UCHAR pRecord Parameters The function has these parameters e dlogID is the ID of the data log e pRecord is a pointer to a data record to write to the log The function returns
228. bit Notes When writing to LINEAR digital addresses value is a bit mask which writes data to 16 1 bit registers at once The I O database is not modified when the controller is reset It is a permanent storage area which is maintained during power outages Refer to the Functions Overview chapter for more information The IO_SYSTEM resource needs to be requested before calling this function See Also Example include lt ctools h gt int main void request resource IO SYSTEM overrideDbase MODBUS 40001 102 overrideDbase LINEAR 302 330 Document Version 1 61 5 19 2011 447 Function Specifications release resource IO SYSTEM Document Version 1 61 5 19 2011 448 Function Specifications pidExecute Execute PID control algorithm Syntax include lt ctools h gt BOOLEAN pidExecute PID DATA pData Description This function executes the PID algorithm The function may be called as often as desired but needs to be called at least once per the value in the period field for proper operation The function has one parameter pData is a pointer to a structure containing the PID block data and outputs The function returns TRUE if the PID block executed The function returns FALSE if it was not time for execution Notes To properly initialize the PID algorithm do one of the following e Call the pidlnitialize function once before calling this f
229. ble assigned to the specified Modbus address The function installSetdbaseHandler has one parameter a pointer to a function to handle the setdbase extensions See the section Setdbase Handler Function for a full Description of the handler function and it s parameters If the pointer is NULL no handler is installed The installed handler is called with a Modbus address Linear addresses are converted to Modbus addresses before calling the handler Use the installDbaseHandler function to install a read access handler for the same addresses handled by the setdbase handler The C Tools functions dbase and setdbase are used by all protocols to access Modbus or Linear registers Notes Call this function with the NULL pointer to remove the setdbase handler This needs to be done when the application program is ended with an exit handler Use the installExitHandler function to install the exit handler If the Setdbase handler is not removed within an exit handler it will remain installed and continue to operate until the controller power is cycled Erasing the C Program from the Initialize dialog will not remove the Setdbase handler If the handler is located in a RAM based application and left installed while a different C application is downloaded the original handler will be corrupted and the system will likely crash Document Version 1 61 5 19 2011 305 Function Specifications See Also setdbase installDbaseHandler Examp
230. calling mTcpMasterClose to disconnect and end the mastering task If this is not done mTcpMasterClose returns FALSE and the connectiD is not released Example See Example for Master Message Example Using mTcpMasterMessage Document Version 1 61 5 19 2011 437 Function Specifications mTcpMasterDisconnect Disconnect Modbus IP Master Connection Syntax include lt ctools h gt BOOLEAN mTcpMasterDisconnect UINT32 connectID Description The mTcpMasterDisconnect function signals the mastering task to tell it to disconnect from the remote slave and end the task FALSE is returned if the specified connectiD is invalid otherwise a TRUE is returned FALSE is also returned if the master task has not completed the last command In this case the mTcpMasterDisconnect function needs to be called repeatedly until TRUE is returned After calling the mTcpMasterDisconnect function the function mTcpMasterStatus may be used to determine the progress of the disconnect These functions may not be called after calling the function mTcpMasterClose with the same connectID The results of such a call are unpredictable as the connectiID may have been re used already for a new connection After calling mTcpMasterDisconnect successfully call mTcpMasterClose to return the connection ID to the pool of available connections Example See the Example in the Example Programs chapter under the section Master IP Message Example Docu
231. calling this function in order to create the DNP configuration The function returns the total number of entries in the DNP master poll table Document Version 1 61 5 19 2011 198 Function Specifications dnpReadRoutingTableEntry_DialStrings Read DNP Routing Table Entry Dial Strings Syntax BOOLEAN dnpReadRoutingTableEntry DialStrings UINT16 index UINT16 maxPrimaryDialStringLength CHAR primaryDialString UINT16 maxSecondaryDialStringLength CHAR secondaryDialString Description This function reads a primary and secondary dial string from an entry in the DNP routing table index specifies the index of an entry in the DNP routing table maxPrimaryDialStringLength specifies the maximum length of primaryDialString excluding the null terminator character The function uses this to limit the size of the returned string to keeps from overflowing the storage passed to the function primaryDialString returns the primary dial string of the target station It needs to point to an array of size maxPrimaryDialStringLength maxSecondaryDialStringLength specifies the maximum length of secondaryDialString excluding the null terminator character The function uses this to limit the size of the returned string to keep from overflowing the storage passed to the function secondaryDialString returns the secondary dial string of the target station It needs to point to an array of size maxSecondaryDialStringLength
232. cation Document Version 1 61 5 19 2011 253 Function Specifications getOutputsInStopMode Get Outputs In Stop Mode Telepace firmware only Syntax include lt ctools h gt void getOutputsInStopMode BOOLEAN holdDoutsOnStop BOOLEAN holdAoutsOnStop 3 Description The getOutputsInStopMode function copies the values of the output control flags into the integers pointed to by doutsinStopMode and aoutsinStopMode If the value pointed to by holdDoutsOnStop is TRUE then digital outputs are held at their last state when the Ladder Logic program is stopped If the value pointed to by holdDoutsOnStop is FALSE then digital outputs are turned OFF when the Ladder Logic program is stopped If the value pointed to by holdAoutsOnStop is TRUE then analog outputs are held at their last value when the Ladder Logic program is stopped If the value pointed to by holdAoutsOnStop is FALSE then analog outputs go to zero when the Ladder Logic program is stopped See Also setOutputsInStopMode Example See the Example for setOutputsInStopMode function Document Version 1 61 5 19 2011 254 Function Specifications getLoginCredentials Gets login credentials for a service Syntax include lt ctools h gt BOOLEAN getLoginCredentials UINT32 service UINT32 index UCHAR username UINT32 maxUsernameLength Parameters service specifies the service for which the credentials are being retri
233. cations ledGetDefault Read LED Power Control Parameters Syntax include lt ctools h gt struct ledControl tag ledGetDefault void Description The ledGetDefault routine returns the default LED power control parameters The controller controls LED power to 5000 I O modules To conserve power the LEDs can be disabled The user can change the LED power setting with the LED POWER switch on the controller The LED power returns to its default state after a user specified time period Example See the Example for the ledSetDefault function Document Version 1 61 5 19 2011 406 Function Specifications ledPower Set LED Power State Syntax include lt ctools h gt UINT16 ledPower UINT16 state Description The ledPower function sets the LED power state The LED power will remain in the state until the default time out period expires state needs to be LED_ON or LED_OFF The function returns TRUE if state is valid and FALSE if it is not Notes The LED POWER switch also controls the LED power A user may override the setting made by this function The ledSetDefault function sets the default state of the LED power This state overrides the value set by this function See Also ledPowerSwitch ledPowerSwitch Document Version 1 61 5 19 2011 407 Function Specifications ledPowerSwitch Read State of the LED Power Switch Syntax include lt ctools h gt UINT16 ledPowerSwitch void Des
234. cations setPowerMode Set Current Power Mode Syntax include lt ctools h gt BOOLEAN setPowerMode UCHAR cpuPower UCHAR lan UCHAR usbHost Description The setPowerMode function returns TRUE if the new settings were successfully applied The setPowerMode function allows for power savings to be realised by controlling the power to the LAN port changing the clock speed and individually controlling the host and peripheral USB power The following table of macros summarizes the choices available PM_CPU_FULL The CPU is set to run at full speed PM_CPU_REDUCED The CPU is set to run at a reduced speed PM_CPU_SLEEP The CPU is set to sleep mode TRUE is returned if the requested change was made otherwise FALSE is returned The application program may view the current power mode with the getPowerMode function See Also getPowerMode setWakeSource getWakeSource Document Version 1 61 5 19 2011 523 Function Specifications setProgramStatus Set Program Status Flag Syntax include lt ctools h gt void setProgramStatus FUNCPTR entryPoint UINT16 status Description The setProgramStatus function sets the application program status flag The status flag is set to NEW_PROGRAM when a cold boot of the controller is performed or a program is downloaded to the controller from the program loader The parameter entryPoint should always be set to the function main Notes There are three pre defined values for
235. ceeseeeeeeeeenseeeesaeeeeeaeseseeesaeseeaaeseeeaeenaees 591 DNP ADDRESS MAP TABLE coionnan baaa a iiaae iaaa pia Sataua 592 OnpAnalog MpPUt aa iir e ea eR EA E RAA AT EEEE E ESS 592 DnpAnaloglnputS hon Float i s atandan aaien iiaae iaaa pia EET 593 AnpANAalogOuUtpUt sisean raa aeta a aa aa aiaa aas pa atana 593 gneBinaryInpuUE sE ETAR AAEE EA RR AT EEE G ER 593 OnpBiniary NpUtE X eretet arg Ern A EER EA RRA ATE ETEA E ETE 593 dnpBiNaryOUtPUt Aetoli eaa dined ar a aa a a aa aa aa ea diet niente 594 dnpConnectionEventType sasiada aaaea aiaiai as ia aiaia 594 dnpConfiguratiO Mise krs ran errana a eean aeara ea an aain 595 ANPCONTIGUIATIONEX scree eset aviv narran a aaa tele aea anaa a a AET 599 dnpCounterlNp t m iridoider enrian danaa aaan enara eudi a anaratas 604 dipMasterR ai srra ie aeqiegiieieatiatesead eeeieadVateids EREE AN FUARA OEE EAA ARKKIA ANKE 605 DNP Master Poll table Extended Entry ssseeeeeeesseeessrreserrssrrrssrrnssrrrnssrnns 605 EAE a e ATEEN ET EE EEEE ATE ade 606 dnpProtocolStatus s aa maeaea ea aaa raana aaaea aaa Aaaa Aaaa a Aiaia naa EREE aiik 607 dnpRouting T ADIGE Kaodan enina ARE ATAT CTARA aids ied dea 607 DNP RUNTIME STATUS a eiit en aadorin erda dvausra davani daanna nada oaaao niitan aa nikaiai 608 AAE E 0 EEEE TE T ARE A TE EE A TEE E E 608 HART COMMA N D aa aaa a reaa aaa a na eaa A da ndatevieteevirsaaieextece 609 aa nana D AO EEA E A E A TEE 609 HART RESPON SE a raa ara a a Rates Act aaea pear Eae LAPSENA att 610
236. cessful It returns FALSE if the DNP configuration has not been created Document Version 1 61 5 19 2011 217 Function Specifications dnpSendUnsolicitedResponse Send DNP Unsolicited Response Syntax BOOLEAN dnpSendUnsolicitedResponse UINT16 classFlags Description The dnpSendUnsolicitedResponse function sends an Unsolicited Response message in DNP with data from the specified classes classFlags specifies the class or classes of event data to include in the message It can contain any combination of the following values if multiple values are used they should be ORed together CLASSO_FLAG enables Class 0 Unsolicited Responses CLASS1_FLAG enables Class 1 Unsolicited Responses CLASS2_FLAG enables Class 2 Unsolicited Responses CLASS3_FLAG enables Class 3 Unsolicited Responses The function returns TRUE if the DNP unsolicited response message was successfully triggered It returns FALSE if any of the configured master addresses has not been configured in the DNP Routing Table or the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration If no events are pending an empty unsolicited message will be sent Example See the example program DNP Configuration Document Version 1 61 5 19 2011 218 Function Specifications dnpSearchRoutingTable Search Routing Table Syntax include lt ctools h gt BOOLEAN d
237. cific variable ID 1O0_CONFIG Structure The lO_CONFIG structure contains I O System configuration data typedef struct UINT16 slaveAddress UINT16 dataRate Document Version 1 61 5 19 2011 611 Structures and Types UINT16 numberOfAttempts UINT16 ledPower 1O_ CONFIG e slaveAddress returns the I C address 0 slave mode disabled e dataRate returns the I O bus data rate 0 100 kHz 1 150 kHz 2 200 kHz 3 250 kHz 4 300 kHz 5 350 kHz 6 400 kHz default 7 450 kHz e numberOfAttempts returns the number of attempts 1 to 4 default 1 e ledPower returns the led power state 0 off 1 on default 10 STATUS Structure IP_ADDRESS The IO_STATUS structure contains status information from the last scan of a specific I O module typedef struct UINT16 commStatus UINT32 scanTime IO_ STATUS The lO_STATUS structure contains the following data fields e commStatus returns the communication status O failed 1 success e scanTime returns time of last scan in milliseconds according to the stop watch clock The IP Address structure defines an IPv4 address This is the standard IPv4 address structure used by sockets APIs and is also used by Modbus TCP C Tools functions struct in_addr u_long s_addr bi typedef struct in_addr IP_ADDRESS e s_addris a 32bit netis hostid address in network byte order IP_CONNECTION_SUMMARY The IP Connection Summary structure summ
238. cinData 2 Description This function reads buffered data from the digital and analog inputs of the 4203 DS I O Buffered data are updated when an I O request for the module is processed dinData is a reference to a UCHAR variable Digital data for the input is written to this array One bit in the array represents each input point ainData is a reference to an array of three INT16 variables Analog data are written to this array cinData is a reference to two UINT32 variables Counter data is written to this array The function returns FALSE if the data was read from the internal table otherwise TRUE is returned See Also ioWrite4203DSOutputs Example This program displays the values of the digital input and the 3rd analog input read from the 4203 DS I O include lt ctools h gt define MY EVENT 1 int main void UCHAR dinData INT16 ainData 5 UINT32 cinData 2 IO_ STATUS io_status BOOLEAN status main loop while TRUE add module scan to queue if ioRequest MT_4203DSInputs 0 Document Version 1 61 5 19 2011 318 Function Specifications status FALSE else wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioRead4203DSInputs dinData ainData cinData check status of last scan if status FALSE insert code t
239. conds The C Tools function setjiffy is not supported Elapsed time from a particular point can be measured by saving the time at the start of the interval rather than setting the clock to zero Document Version 1 61 5 19 2011 686 Porting Existing C Tools Applications Real Time Clock Functions The getclock function has a new syntax A clock structure is no longer returned by the function Instead a pointer to a clock structure is passed as an argument The getclock function is documented in the Function Specifications section Get Task Information Function The getTaskInfo function has a new syntax A TASKINFO structure is no longer returned by the function Instead a pointer to a TASKINFO structure is passed as an argument and a status flag is returned The getTaskInfo function is documented in the Function Specifications section EEPROM Flash Memory Functions SCADAPack 350 and 4203 controllers use flash memory instead of EEPROM to store controller settings The following functions are no longer supported The replacement function is indicated for each Replaced wih Ta T as iStings oa flashSettingsSave Controller Status Function The controller status functions setStatusBit and getStatusBit are fully supported The setStatus function is no longer supported Use setStatusBit in place of setStatus Store and Forward Functions The syntax for the following two functions has been changed Instead of passing or re
240. configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveCl16Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 177 Function Specifications dnpGetCli32Config Get DNP 32 bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetCI32Config UINT32 point dnpCounterInput pCounterInput Description The dnpGetCl32Config function reads the configuration of a DNP 32 bit counter input point The function has two parameters the point number and a pointer to a counter input point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveCl32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 178 Function Specifications dnpGetConfiguration Get DNP Configuration Syntax include lt ctools h gt BOOLEAN dnpGetConfiguration dnpConfiguration pConfiguration Description The dnpGetConfigura
241. connectID can be used to re connect to multiple IP addresses Valid values for protocolType are IPP_ModbusTcp IPP_ModbusRtuOverUdp or IPP_ModbusAsciiOverUdp The remaining arguments are used in the same way as they are used in master_message to send a serial Modbus command e function specifies the Modbus function code Refer to the communication protocol manual for supported function codes e _slaveStation specifies the network address of the slave station This is also known as the slave station number e slaveRegister specifies a Modbus register in the slave station Depending on the protocol function code data may be read or written at this location e masterRegister specifies a Modbus register in the master this controller Depending on the protocol function code data may be read or written at this location e length specifies the number of registers Document Version 1 61 5 19 2011 439 Function Specifications The timeout in tenths of seconds tells the mastering task how long to wait for a response from the slave For TCP protocols the same timeout is also used by the mastering task as the time to wait for a connection to be re established if this is required To disable the timeout and have the mastering task wait forever for a response or a connection to be established set the timeout to 0 This timeout replaces the initial timeout specified in mTcpMasterOpen This allows mTcpMasterMessage to specify differen
242. connection is attempted by the created master task To disable the timeout and wait forever for a connection to be established set the timeout to 0 Each time this function is called a new connection ID is allocated from the connection pool If the number of currently allocated connections is less than 20 a task is created to service the allocated connection and the function returns TRUE If there are no connections available or if there is an error in one of the arguments FALSE is returned and an error code is copied to the value pointed by cmdSiatus The new mastering task establishes the initial connection and sends Modbus IP master messages each time mTcpMasterMessage is called Use the function mTcpMasterStatus to determine the status of the connection or master message in progress The connection ID for this master connection is copied to the value pointed to by connectID This ID needs to be used when calling the remaining master messaging API functions for this connection mTcpMasterMessage mTcpMasterStatus mTcpMasterDisconnect and mTcpMasterClose The enumeration types and structures used for the function arguments are described in the Structures and Types section Document Version 1 61 5 19 2011 441 Function Specifications Notes The functions mTcpMasterDisconnect and mTcpMasterClose needs to be called to disconnect and return this connection ID to the pool of available connections Even if the connection to the r
243. cription The ledPowerSwitch function returns the status of the led power switch The function returns FALSE if the switch is released and TRUE if the switch is pressed Notes This switch may be used by the program for user input However pressing the switch will have the side effect of changing the LED power state See Also ledPower ledSetDefault Document Version 1 61 5 19 2011 408 Function Specifications ledSetDefault Set Default Parameters for LED Power Control Syntax include lt ctools h gt UINT16 ledSetDefault struct ledControl_tag ledControl Description The ledSetDefault routine sets default parameters for LED power control The controller controls LED power to 5000 I O modules To conserve power the LEDs can be disabled The LED power setting can be changed by the user with the LED POWER switch on the controller The LED power returns to its default state after a user specified time period The ledContro structure contains the default values Refer to the Structures and Types section for a Description of the fields in the edControl_tag structure Valid values for the state field are LED_ON and LED_OFF Valid values for the time field are 1 to 65535 minutes The function returns TRUE if the parameters are valid and false if they are not If either parameter is not valid the default values are not changed The IO_SYSTEM resource needs to be requested before calling this function To save these
244. cription This function is called by the dbase function when one of the following conditions apply e There is no IEC 61131 1 application downloaded or e There is no IEC 61131 1 variable assigned to the specified Modbus address The function has two parameters e The address parameter is the Modbus address to be read e The value parameter is a pointer to an integer containing the current value at address If the address is to be handled the handler function needs to return TRUE and the value pointed to by value needs to be set to the current value for the specified Modbus address If the address is not to be handled the function needs to return FALSE and the value pointed to by va ue needs to be left unchanged Notes The lO_SYSTEM resource must be requested before calling dbase which calls this handler Requesting the O_SYSTEM resource allows that only one task may call the handler at a time Therefore the function does not have to be re entrant An array may be defined to store the current values for all Modbus addresses handled by this function See the section Data Storage if a non initialized data array is required See Also installDbaseHandler Document Version 1 61 5 19 2011 147 Function Specifications deallocate_envelope Return Envelope to the RTOS Syntax include lt ctools h gt void deallocate_ envelope envelope penv Description The deallocate_envelope function returns the envelope po
245. ction code data may be read or written at this location length specifies the number of registers timeout specifies how long in tenths of seconds to wait for a response eventRequest requests an event to be signaled on completion If set to TRUE the eventNo will be signaled when the response is received or a timeout has occurred Set to FALSE to disable this feature eventNo specifies the event to signal on completion This field is only used if eventRequest is set to TRUE MODBUS_CMD_STATUS The master command status codes have been changed from macros to the enumeration type MODBUS_CMD_STATUS The previously supported status codes have the same value as they did as a macro typedef enum modbusCmdStatus_ t SENT 0 RECEIVED NO MESSAGE BAD_FUNCTION 2 BAD SLAVE BAD ADDRESS BAD LENGTH PROTOCOL NOT SUPPORTED 7 Au FPF WNE additional master command status codes used for Modbus TCP master messaging only MM CONNECTING 8 CONNECTED 9 CONNECT TIMEOUT 10 SEND ERROR i RSP_TIMEOUT S02 RSP_ERROR siS DISCONNECTING 14 DISCONNECTED 15 BAD CONNECT _ID 16 BAD PROTOCOL TYPE 17 BAD IP_ADDRESS 18 BUSY 19 ENDED 20 CONNECT ERROR 2T NO MORE CONNECTIONS 22 BAD CONNECTION TYPE 23
246. ction has one parameter a pointer to a DNP configuration structure The function returns TRUE if the configuration was updated and FALSE if an error occurred No changes are made to any parameters if an error occurs Notes This function needs to be called before enabling DNP This function does not write the configuration for the Unsolicited Back Off Time Use the function dnpSaveUnsolicitedBackoffTime to save the Unsolicited Back Off Time configuration The following parameters cannot be changed if DNP is enabled The function will not make any changes and will return FALSE if this is attempted The protocol needs to be disabled in order to make a change involving these parameters e Bl number e BI _cosBufferSize e BI soeBufferSize e BO_number e Cl16_ number e Cl16_bufferSize e Cl32_ number e Cl32_bufferSize e Al16 number e Al16_reportingMethod e Al16_bufferSize e Al32_number e Al32_reportingMethod e Al32_bufferSize Document Version 1 61 5 19 2011 214 Function Specifications e AQO16_number e AQ32_number The following parameters can be changed when DNP is enabled e masterAddress e rtuAddress e datalinkConfirm e datalinkRetries e datalinkTimeout e operateTimeout e applicationConfirm e maximumResponse e applicationRetries e applicationTimeout e timeSynchronization e unsolicited e holdTime e holdCount See Also dnpGetConfiguration Example See example in the dnoGetConfigura
247. ctions System Functions Area Flag Loaded on Reset Controller Settings in this Area Register assignment Outputs on stop settings a settings loaded Serial port settings Serial on Run Boot protocol settings Modbus TCP Default settings settings HART I O settings loaded on Service LED power settings Store and Boot forward table Replaced with default settings on Cold Boot There are two library functions related to the configuration data flash memory Refer to the Function Specification section for details on each function listed flashSettingsLoad This function stores the controller settings in the indicated area or areas to flash memory flashSettingsSave This function loads the controller settings in the indicated area or areas from flash memory The ctools h file defines the following functions for system initialization and for retrieving system information Some of these functions are primarily used in the appstart c routine having limited use in an application program Refer to the Function Specification section for details on each function listed ioClear Clears I O points ioDatabaseReset Resets the controller to default settings ioRefresh Refresh outputs with internal data ioReset Reset I O modules Controller I O Hardware This section of the manual provides an overview of the C Tools functions relating to controller signal input and output I O Analog Input Functions The controller supports in
248. ctions to detect the event The function returns TRUE if the event can be signaled If interval is 0 or if the event number is not valid the function returns FALSE and no change is made to the event signaling a previously enabled event will not be changed Notes Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in primitiv h are not valid events for use in an application program The application program should stop the signaling of timed events when the task which waits for the events is ended If the event signaling is not stopped events will continue to build up in the queue until a function waits for them The Start Timed Event Example shows a simple method using the installExitHandler function See Also endTimedEvent Document Version 1 61 5 19 2011 552 Function Specifications sysSerialSetRxTimeout Set Serial Idle Timeout Before Received Characters Signaled Syntax include lt ctools h gt void sysSerialSetRxTimeout UCHAR port UCHAR timeout Description The sysSerialSetRxTimeout function causes the operating system to report the arrival of characters on the specified port after the specified number of 4 bit timeout intervals A port value of 0 specifies com1 1 specifies com2 and 2 specifies com3 The timeout specifies the number of 4 bit time intervals that the serial receive line needs to be idle for before reporting character arrival Care needs to be exercised as the charac
249. ctools h gt define ALARM EVENT 20 This function signals an event when the alarm occurs Document Version 1 61 5 19 2011 651 Example Programs void alarmHandler void interrupt _signal_event ALARM EVENT This task processes alarms signaled by the clock handler void processAlarms void while TRUE wait event ALARM EVENT Reset the alarm for the next day request resource IO SYSTEM resetClockAlarm release resource IO SYSTEM fprintf coml It s quitting time r n int main void struct prot settings settings ALARM SETTING alarm Disable the protocol on serial port 1 settings type NO PROTOCOL settings station 1 settings priority 250 settings SFMessaging FALSE request resource IO SYSTEM set_protocol coml amp settings release resource IO SYSTEM Install clock handler function installClockHandler alarmHandler Create task for processing alarm events create task processAlarms 75 applicationGroup 4 Set real time clock alarm alarm type AT ABSOLUTE alarm hour 16 alarm minute 0 alarm second 0 request resource IO SYSTEM setClockAlarm alarm release resource IO SYSTEM while TRUE Document Version 1 61 5 19 2011 652 Example Programs body of main task loop
250. cv call without the MSG_OOB flag SO_SNDBUF and SO_RCVBUF are options that adjust the normal buffer sizes allocated for output and input buffers respectively The buffer size may be increased for high volume connections or may be decreased to limit the possible backlog of incoming data The Internet protocols place an absolute limit of 64 Kbytes on these values for UDP and TCP sockets in the default mode of operation The following options are recognized at the IP level IP_PROTOIP protocolLevel options IP_MULTICAST_IF Get the configured IP address that uniquely identifies the outgoing interface for multicast datagrams sent on this socket A zero IP address parameter indicates that we want to reset a previously set outgoing interface for multicast packets sent on that socket IP_MULTICAST_TTL Get the default IP TTL for outgoing multicast datagrams IP_TOS IP type of service Default 0 IP_TTL IP Time To Live in seconds Default 64 The following options are recognized at the TCP level IP_PROTOTCP protocolLevel options Document Version 1 61 5 19 2011 271 Function Specifications TCP_MAXSEG TCP_NODELAY Get the maximum TCP segment size sent on the network The TCP_MAXSEG value is the maximum amount of data including TCP options but not the TCP header that can be sent per segment to the peer i e the amount of user data sent per segment is the value given by the TCP_MAXSEG option minus any enabled TCP option for exampl
251. d Forward entry The SF_TRANSLATION_EX structure supports a timeout and is described in the Structures and Types section The function returns a SFTranslationStatus structure It is described in the Structures and Types section The code field of the structure is set to one of the following If there is an error the index field is set to the location of the translation that is not valid SF_VALID All translations are valid SF_NO_TRANSLATION The entry defines re transmission of the same message on the same port SF_PORT_OUT_OF_RANG One or both of the interfaces is not valid E SF_ALREADY_DEFINED The translation already exists in the table SF_INDEX_OUT_OF_RAN The entry referenced by index does not exist in GE the table SF_INVALID_FORWARDIN The forwarding IP address is invalid G_IP Notes SF_STATION_OUT_OF_R One or both of the stations is not valid ANGE The TeleBUS Protocols User Manual describes store and forward messaging mode Document Version 1 61 5 19 2011 533 Function Specifications Writing a translation with both stations set to station 65535 can clear a translation in the table Station 65535 is not a valid station The Modbus protocol type and communication parameters may differ between serial ports The store and forward messaging will translate the protocol messages Translations describe the communication path of the master command e g the slave interface which receives the command
252. d can have similar impact on user applications In the new architecture I O requests are added to a queue Requests are read from the queue and processed by separate I O controller hardware Data are stored in I O arrays that can be read and written by the application program The Document Version 1 61 5 19 2011 683 Porting Existing C Tools Applications application program can also synchronize with the I O controller to determine when a set of I O requests is complete Existing application programs need to be rewritten to use the new I O system functions Most I O System functions are C functions In order to call C functions from a source file the source file must be a CPP file If an existing C file must be renamed to a CPP file The following is a list of the I O System functions Each function is documented in the Function Specifications section Description ioNotficafon Request notiica on T oSystemReset Request reset of all 7O modules L T oRegues Request TO module scan C oses Read 0 mle status v ioReadAin4 Read buffered data from 4 point analog input module y ioReadAin8 Read buffered data from 8 point analog input module v ioReadAout2 Read buffered data for 2 point analog output module v ioReadAout4 Read buffered data for 4 point analog output module v ioReadCounter4 Read buffered data from 4 point counter input module v ioReadCounterSP2 Read buffered data from SCA
253. d in the AF_INET address family support out of band data MSG_DONTROUTE The SO_DONTROUTE option is turned on for the duration of the operation Only diagnostic or routing programs use it Returns gt 0 Number of bytes actually sent on the socket 1 An error occurred send will fail if EBADF The socket descriptor is invalid ENOBUFS There was insufficient user memory available to complete the operation EHOSTUNREACH Non TCP socket only No route to destination host EMSGSIZE The socket requires that message to be sent atomically and the message was too long Document Version 1 61 5 19 2011 499 Function Specifications EWOULDBLOCK ENOTCONN ESHUTDOWN The socket is marked as non blocking and the send operation would block Socket is not connected User has issued a write shutdown TCP socket only Document Version 1 61 5 19 2011 500 Function Specifications send_message Send a Message to a Task Syntax include lt ctools h gt void send message envelope penv Description The send_message function sends a message to a task The envelope specified by penv contains the message destination type and data The envelope is placed in the destination task s message queue If the destination task is waiting for a message it is made ready to execute The current task is not blocked by the send_message function Notes Envelopes are obtained from the operating system with the all
254. data field from the message The function returns TRUE if the 5904 interface responded and FALSE if it did not or if the module number is not valid or there is an error in the command Notes The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command A program needs to initialize the link before executing any other commands The function determines if long or short addressing is to be used by the command number Long addressing is used for all commands except commands O and 11 The functions hartCommandO hartCommand1 etc are used to send commands provided by the Network Layer Document Version 1 61 5 19 2011 283 Function Specifications See Also hartStatus hartSetConfiguration hartCommandO hartCommand1 Document Version 1 61 5 19 2011 284 Function Specifications hartCommand0O Read Unique Identifier Syntax include lt ctools h gt BOOLEAN hartCommand0 UINT16 module UINT16 address HART DEVICE const device Description This function reads the unique identifier of a HART device using command 0 with a short form address This is a link initialization function The function has three parameters the module number of the 5904 module 0 to 3
255. de The function always returns TRUE The application program may set the current power mode with the setPowerMode function See Also setPowerMode setWakeSource getWakeSource Document Version 1 61 5 19 2011 259 Function Specifications getProgramStatus Get Program Status Flag Syntax include lt ctools h gt UINT16 getProgramStatus FUNCPTR entryPoint Description The getProgramStatus function returns the application program status flag of the program specified by entryPoint The passed parameter should always be in the function main The status flag is set to NEW_PROGRAM when the C program downloaded to the controller from the program loader The status flag is set to PROGRAM_NOT_LOADED when the C program is erased The application program may modify the status flag with the setProgramStatus function See Also setProgramStatus Example See the Get Program Status Example in the Examples section Document Version 1 61 5 19 2011 260 Function Specifications get_protocol Get Protocol Configuration Syntax include lt ctools h gt struct prot settings get_ protocol FILE stream struct prot_settings settings Description The get_protocol function gets the communication protocol configuration for the port If port does not point to a valid serial port the function has no effect settings must point to a protocol configuration structure prot_settings The get_protocol function co
256. de MIP WAIT FOR RESPONSE break default remaining status codes are message not sen mode MIP DISCONN break oct CT break case MIP WAIT FOR_RESPONSE check master command status status mTcpMasterStatus connectID if status switch cmdStatus case MM SENT still waiting for break case MM RECEIVED Document Version 1 61 5 19 2011 667 Example Programs response received successfully send next messag mode MIP SEND MESSAGE break default remaining status codes are error codes mode MIP DISCONNECT break break case MIP DISCONNECT if mTcpMasterDisconnect connectID disconnect is successfully started mode MIP CLOSE break case MIP CLOSE if mTcpMasterClose connectID connection has been successfully released open new connection and start again mode MIP OPEN CONNECTION break release processor to other priority 254 tasks release processor Modem Initialization Example The following code shows how to initialize a modem Typically the modem initialization is used to prepare a modem to answer calls The example sets up a Hayes modem to answer incoming calls include lt ctools h gt include lt string h gt int main void struct ModemInit initSettings reserve id port
257. done after reading the log The sequence number used is that of the last record read from the log This removes the records that have been read and leaves any records added since the records were read If the sequence number specifies a record that is not in the log no records are removed See Also See example DataLog program in the Example Programs section datalogReadStart datalogReadNext datalogWrite Example include lt ctools h gt int main void UINT16 lLogID UINT32 sequenceNumber BOOLEAN purgeAll Document Version 1 61 5 19 2011 136 Function Specifications select data log to be purged logID 10 set flag to purge only part of data log purgeAll FALSE purge the oldest 150 records sequenceNumber 150 if datalogPurge logID purgeAll sequenceNumber Successful at purging the first 150 records of log Start writing records again To purge the entire data log set flag to TRUE purgeAll TRUE call function with same parameters if datalogPurge logID purgeAll sequenceNumber Successful at purging the entire data log Start writing records again Document Version 1 61 5 19 2011 137 Function Specifications datalogReadNext Read Data Log Next Function This function returns the next record in the data log Syntax include lt ctools h gt BOOLEAN datalogReadNext UINT
258. down void modemAbortAll int main void TASKINFO taskStatus set up exit handler for this task getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR shutdown while TRUE vest of main task here Allow other tasks to execute release processor Document Version 1 61 5 19 2011 419 Function Specifications modemDial Connect to a Remote Dial up Controller Syntax include lt ctools h gt enum DialError modemDial struct ModemSetup configuration reserve id id Description The modemDial function connects a controller to a remote controller using an external dial up modem One modemDial function may be active on each serial port The modemDial function handles port sharing and multiple dialing attempts The ModemSetup structure specified by configuration defines the serial port dialing parameters modem initialization string and the phone number to dial Refer to the Structures and Types section for a Description of the fields in the ModemSetup structure id points to a reservation identifier for the serial port The identifier provides that no other modem control function can access the serial port This parameter needs to be supplied to the modemDialEnd and modemDialStatus functions The function returns an error code DE_NoError indicates that the connect operation has begun Any other code indicates an error Refer to the di
259. dress Also when forwarding on a TCP or UDP network the forwarding destination IP address needs to be entered as the forward iPAddress The forward PAddress is entered as an IP address string of the format 255 255 255 255 The forwardlPAddress is needed to know where to connect so that the command can be forwarded to its final destination Document Version 1 61 5 19 2011 534 Function Specifications Modbus IP Network as Slave Interface There is no field for a slave IP address This information is irrelevant because we don t care about the IP address of the remote master We care only that the remote master connects to the specified slave nterface and sends a command to be forwarded The protocol type is not specified for slavelnterface All messages in any Modbus IP protocol received on s avelnterface for slaveStation will be forwarded Serial Modbus Interface as Forwarding Interface The forward PAddress field in the SF_TRANSLATION_EX structure should be set to zero when the forwardinterface field is a Serial Modbus interface Set forward lPAddress to zero as follows SF TRANSLATION EX sfTranslation sfTranslation forwardIPAddress s addr 0 See Also getSFTranslationEx checkSFTranslation clearSFTranslation Document Version 1 61 5 19 2011 535 Function Specifications setsockopt Syntax include lt ctools h gt int setsockopt int socketDescriptor int protocollLevel int optionName c
260. dule Read the digital and analog inputs from a 5606 O Module Read the digital and analog outputs from a 5606 O Module Read the digital and analog inputs from a 5607 I O Module Read the digital and analog outputs from a 5607 I O Module Read the inputs from a 4203 DR controller Read the inputs from a 4203 DS controller The controller supports external analog output modules Refer to the SCADAPack 350 System Hardware Manual or the SCADAPack 4203 Hardware Manual for further information on these modules There are three library functions related to analog output modules Refer to the Function Specification section for details on each function listed ioReadAout2 ioReadAout4 ioReadAout5303 ioRead5606Ouitputs Read buffered data for 2 point analog output module Read buffered data for 4 point analog output module Read buffered data for 5303 analog output module Read the digital and analog outputs from a 5606 I O Module Document Version 1 61 5 19 2011 62 Overview of Programming Functions ioRead56070utputs ioWriteAout2 ioWriteAout4 ioWriteAout5303 ioWrite4203DRinputs iowrite4203DSInputs ioWrite5606Outputs ioWrite56070utputs Digital Input Functions Read the digital and analog outputs from a 5607 I O Module Write buffered data for 2 point analog output module Write buffered data for 4 point analog output module Write buffered data for 5303 analog output module Write to the outputs of a 4203 DR
261. dware Information srs isiiiuerr nir inn ERA A EEE EATE 252 getlOErrorlndication ccececeeceeeeeeceeeeeceeeeeeaeeeeeeeseeeeesaaeeesaaeseeeeeseaeessiaeeseaeeeeaees 253 getOutputsINStopMode ceeeceeeeeceeeee cece eeeaeeeeeeeceeeeeseaeeesaaeseeeeeseaeeesaeeseneeeeaees 254 QetLoginCredentials cccecccceseeceeeeeceneeeeaeeeeaeeceeeeesaeeeeaaeseeeeeseaeeessaeeseeeessaees 255 QEIPCOIMN AM e iesiscscccssiescuecaseineceainvasesssnieecedindacevapainestainiasedasaiaccsiabaiesapaiasseaininuedeas 256 QetPortCharacteristiCs ccccceceeeceeeeeceneeeeeaeeeeeeeceeeeecaeessaaeseeeeeseaeessaeeseeeeeaees 257 Ot POM o f sseus pede ices inbssleuavainiaesiaiavesavadeecsadedaveuapainesaiaisucdazaiacsiajaisuduagaiaiauainineesaeas 258 getPowerMode ss aiceccit ni eideiedieeen aiiec hie ETAN EEEE ENa A EUERE ET ANTEE 259 QetProgramMStatus wives adi eel Gnd da ia ia atd a eai 260 get mrotOCo la aE a eae 261 QetProtocolSettings naiaiaee dee hel escheat cnnedactacnusdeeedsvidendates 262 GetProtocolSettingSEX ccccceccceescecsenceceeeeeeaeeeeaeeceeeesaaeeeeaaesseeeeseaeeseaeseeneeesaees 264 get protocol Status ohe anieri a heen ied dinetiai EEEN 266 QetSF Translations wish cinta haa ea 267 Document Version 1 61 5 19 2011 getak Transla oni koian allie dnt ia he ns 268 QelSOCkNalN Ge eeri iiia Aileen ti eee se dine hen ee 269 QelsockOpt nia T E E lie a dite itiee dain nese T Gian eee nei 270 QetsSlalws sce Were ad Mt ek eee
262. e This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the dbase function The lO_SYSTEM system resource needs to be requested before calling this function See Also readintVariable readRealVariable Example This program displays the contents of the timer variable named Time1 include lt ctools h gt int main void BOOLEAN status UINT32 value request resource IO SYSTEM status readTimerVariable Timel amp value Document Version 1 61 5 19 2011 473 Function Specifications release resource IO SYSTEM fprintf coml status u Timel lu r n status value Document Version 1 61 5 19 2011 474 Function Specifications receive_message Receive a Message Syntax include lt ctools h gt nvelope receive message void Description The receive_message function reads the next available envelope from the message queue for the current task If the queue is empty the task is blocked until a message is sent to it The receive_message function returns a pointer to an envelope structure Notes Refer to the Real Time Operating System section for more information on messag
263. e lt ctools h gt BOOLEAN dnpWriteRoutingTableEntryEx UINT16 index UINT16 address UINT16 comPort UINT16 retries UINT16 timeout IP_ADDRESS ipaddress Description dnpWriteRoutingTableEntryEx writes an entry in the DNP routing table This function is used to write entries with IP addresses To create an entry without an IP address use the dnpWriteRouting TableEntry function Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Use the dnpCreateRoutingTable function to create the routing table and specify its size The function returns TRUE if successful FALSE otherwise Example See the Example in the dnpGetConfiguration section Document Version 1 61 5 19 2011 227 Function Specifications end_application Terminates all Application Tasks Syntax include lt ctools h gt void end_application void Description The end_application function terminates all APPLICATION type tasks created with the create_task function Stack space and resources used by the tasks are freed Notes This function is used normally by communication protocols to stop an executing application program prior to loading a new program into memory See Also end_group end_task Document Version 1 61 5 19 2011 228 Function Specifications end_group Terminates all Tasks in a Task Group Syntax include lt ctools h gt void end_group UINT16 t
264. e the Event 10 queue and the executing task These are the only queues relevant to the example This point occurs just before the main task begins The main task has not been created by the RTOS The null task has been created but is not running No task is executing Document Version 1 61 5 19 2011 54 Real Time Operating System Event 10 Queue Running Task none Figure 1 Queue Status before Execution of main Task Execution Point 2 This point occurs just after the creation of the main task It is the running task On the next instruction it will create the echoData task Ready Queue Event 10 Queue Running Task main 25 50 75 foo He Figure 2 Queue Status at Start of main Task Execution Point 3 This point occurs just after the echoData task is created The echoData task is higher priority than the main task so it is made the running task The main task is placed into the ready queue It will execute when it becomes the highest priority task The echoData task initializes the serial port and installs the serial port handler function signalCharacter It will then wait for an event This will suspend the task until the event occurs The signalCharacter function will generate an event each time a character is received without an error Ready Queue Event 10 Queue Running Task echoData main null
265. e 12 bytes for a TCP time stamp option Default is IP MTU minus 40 bytes If this option value is non zero the Nagle algorithm that buffers the sent data inside the TCP is disabled Useful to allow client s TCP to send small packets as soon as possible like mouse clicks Default 0 Parameters socketDescriptor The socket descriptor to get the option from protocolLevel The protocol to get the option from See below optionName The option to get See above and below optionValuePtr The pointer to a user variable into which the option value is returned User variable is of data type described below optionLengthPtr Pointer to the size of the user variable which is the size of the option data type described below It is a value result parameter and the user should set the size prior to the call SOL_SOCKET Socket level protocol IP_PROTOIP IP level protocol IP_PROTOTCP TCP level protocol Protocol Level Option Name Option data Option value type SOL_SOCKET SO_ACCEPTCONN int 0 or 1 SO_DONTROUTE int Oor1 SO_KEEPALIVE int Oor1 SO_LINGER struct linger SO_OOBINLINE int 0 or 1 SO_RCVBUF unsigned long SO_RCVLOWAT unsigned long SO_REUSEADDR int 0 or 1 SO_SNDBUF unsigned long SO_SNDLOWAT unsigned long IP_PROTOIP IP_MULTICAST_IF struct in_addr IP_MULTICAST_TTL unsigned char IP_TOS unsigned char Document Version 1 61 5 19 2011 272 Function Specifications Protocol Level IP_PROTOTCP Returns Value 0 1 getsockopt will
266. e Operating System Error Reporting Functions There are two RTOS functions for error reporting Refer to the Function Specification section for details on each function listed check_error Check the error code for the current task report_error Set the error code for the current task RTOS Example Application Program The following program is used in the explanation of the RTOS functions It creates several simple tasks that demonstrate how tasks execute A task is a C language function that has as its body an infinite loop so it continues to execute forever The main task creates two tasks The echoData task is higher priority than main The auxiliary task is the same priority as main The main task then executes round robin with other tasks of the same priority The auxiliary task is a simple task that executes round robin with the other tasks of its priority Only the code necessary for task switching is shown to simplify the example The echoData task waits for a character to be received on a serial port then echoes it back out the port It waits for the event of the character being received to allow lower priority tasks to execute It installs a character handler function signalCharacter that signals an event each time a character is received This function is hooked into the receiver interrupt handler for the serial port The execution of this program is explained in the Explanation of Task Execution section Real
267. e The controller is unlocked To perform a Cold Boot use the following procedure e Remove power from the controller e Hold down the LED POWER button e Apply power to the controller e Continue holding the LED POWER button for 25 seconds until the STAT LED begins to flash on and off continuously e Release the LED POWER button If the LED POWER button is released before the STAT LED begins to flash the controller will start in service mode not the cold boot mode To connect to a controller using Telepace firmware e Connect the cable to a serial port on the PC e Connect the cable to the com3 serial port on the controller e Open the Telepace program To configure the PC serial port select PC Communication Settings from the Telepace Communications menu The PC Communications Settings dialog will appear The default settings shown in this dialog are the same as the default serial port settings for the controller Document Version 1 61 5 19 2011 27 Getting Started Modbus RTU Configuration General Advanced Information Communication Component Modbus RTU Control Microsystems Inc Modbus Communication Settings Addressing Standard Station fi Timeout Booo seconds Attempts 3 Serial Port Settings Port com o Baud eo Parity None x Stop Bits hi o Connection Type Direct Connection x Use the drop down selector for the Port box to select the PC serial port being u
268. e a new data log file Syntax include lt ctools h gt dlogStatus dlogNewFile UINT32 dlogID Parameters The function has these parameters e dlogID is the ID of the data log The function returns e DLOGS_SUCCESS if the new data log was created e DLOGS_BADID if the data log ID is invalid Description This function creates a new data log file which becomes the active data log output file The former active file is closed and won t be used for any further output This function is useful to give the data log client the opportunity to create a new data file by its own definition not just when the defined log file size is exceeded A data log client could create daily files for example Notes The new file is not created immediately but when the first data log record is written from the data log buffer by the data log server task Records that remain in the data log buffer when this function is called are not flushed automatically To start the new file with a specific record call dlogFlush before calling this function The oldest file will be deleted if fileRingBuffer mode is enabled and the maximum number of files is reached If fileRingBuffer mode is disabled no new file will be created until older log files are deleted manually This may cause logging to stop although the space in the log buffer may still be available See Also dlogFlush dlogWrite Document Version 1 61 5 19 2011 156 Function Specifications
269. e configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 168 Function Specifications dnpGetAl32Config Get DNP 32 bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAI32Config UINT32 point dnpAnalogInput pAnalogInput Description The dnpGetAl32Config function reads the configuration of a DNP 32 bit analog input point The function has two parameters the point number and a pointer to an analog input point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAl32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 169 Function Specifications dnpGetAlISFConfig Get Short Floating Point Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAISFConfig UINT16 point dnpAnalogInput pAnalogInput Description The dnpGetAlSFCo
270. e oe Stop any protocol currently active on com port 3 fSSSe a Sie Rat StS AR Sa SSS Ree Ste ea Ra Sea SS SSSR ae get_protocol com3 amp protocolSettings protocolSettings type NO PROTOCOL set_protocol com3 amp protocolSettings 1 a a aa a a a aaa a a a alle Load DNP Configuration Parameters S eo a Ss a Se eo ee oe configuration masterAddress 100 configuration rtuAddress 1 configuration datalinkConfirm FALSE configuration datalinkRetries DEFAULT DLINK_RETRIES configuration datalinkTimeout DEFAULT DLINK_ TIMEOUT configuration operateTimeout DEFAULT OPERATE TIMEOUT configuration applicationConfirm FALSE configuration maximumResponse DEFAULT MAX RESP LENGTH configuration applicationRetries DEFAULT APPL RETRIES configuration applicationTimeout DEFAULT APPL TIMEOUT configuration timeSynchronization NO TIME SYNC configuration BI number 1701 configuration BI startAddress 07 configuration BI reportingMethod REPORT ALL EVENTS configuration BI soeBufferSiz 1000 configuration BO number 1051 configuration BO startAddress mae configuration CI16 number 1 00 configuration CI16 startAddress 0 configuration CI16 reportingMethod REPORT ALL EVENTS configuration CI16 bufferSize 0 configuration CI32 number 0 configuration CI32 startAddress 100 configuration
271. e of the first change event measured e Set this to CURRENT_VALUE to report the value of the latest change event measured e Al32_bufferSize is the number of events in the 32 bit analog input change buffer Valid values are 0 to 9999 e Al32_wordOrder is the Word Order of AI32 points O LSW first 1 MSW first e AQ16_number is the number of 16 bit analog output points Valid values are 0 to 9999 e AQ16_startAddress is the DNP address of the first AO16 point e AQO832_number is the number of 32 bit analog output points Valid values are 0 to 9999 e AQ32_startAddress is the DNP address of the first AO32 point e AQ32_wordOrder is the Word Order of AO32 points O LSW first 1 MSW first e AOSF_number is the number of short float Analog Outputs e AOSF_startAddress is the DNP address of first AOSF point Document Version 1 61 5 19 2011 598 Structures and Types dnpConfigurationEx AOSF_wordOrder is the Word Order of AOSF points O LSW first 1 MSW first autoUnsolicitedClass1 enables or disables automatic Unsolicited reporting of Class 1 events holdTimeClass1 is the maximum period to hold Class 1 events before reporting holdCountClass1 is the maximum number of Class 1 events to hold before reporting autoUnsolicitedClass2 enables or disables automatic Unsolicited reporting of Class 2 events holdTimeClass2 is the maximum period to hold Class 2 events before reporting holdCountClass2 is the maximum num
272. e same connect D The results of such a call are unpredictable as the connectlD may have been re used already for a new connection Expected values returned for the command status are described for the enumeration type MODBUS_CMD_STATUS in the Structures and Types section Example See Example for Master Message Example Using mTcpMasterMessage Document Version 1 61 5 19 2011 443 Function Specifications mTcpRunServer Run Modbus IP Servers Syntax include lt ctools h gt void mTcpRunServer BOOLEAN state Description The mTcpRunServer function is used to start the servers for each IP protocol The IP protocols include Modbus TCP Modbus RTU over UDP Modbus ASCII over UDP DNP over TCP and DNP over UDP Calling this function with TRUE starts the servers according to the IP protocol settings If the server enabled setting for the protocol is TRUE then the server is started If the server enabled setting for the protocol is FALSE then the server is stopped Calling this function with FALSE stops each IP protocol server and updates IP protocol settings accordingly Use the function mTcpSetProtocol to enable or disable a server for a specific IP protocol This function should only be needed in the context of the startup function appstart Document Version 1 61 5 19 2011 444 Function Specifications ntohl Syntax include lt ctools h gt unsigned long ntohl unsigned long longValue i D
273. eBlConfig Save DNP Binary Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveBIConfig UINT16 point dnpBinarylInput pBinaryInput i Description The dnpSaveBlConfig function sets the configuration of a DNP binary input point The function has two parameters the point number and a pointer to a binary input point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetBlConfig Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 209 Function Specifications dnpSaveBlConfigEx Write DNP Binary Input Extended Point Syntax BOOLEAN dnpSaveBIConfigEx UINT16 point dnpBinarylInputEx pBinarylInput Description This function writes the configuration of an extended DNP Binary Input point The function has two parameters the point number and a pointer to an extended binary input point configuration structure The function returns TRUE if the configuration was successfully written It returns FALSE if the point number is not valid if the configuration is not valid or if the DNP configuration has not been created This function supersedes dnpSaveBlConf
274. eSource WS_ALL Enable wake up on real time clock only setWakeSource WS _RTC_ALARM Document Version 1 61 5 19 2011 542 Function Specifications shutdown Syntax include lt ctools h gt int shutdown int socketDescriptor int howToShutdown Description Shutdown a socket in read write or both directions determined by the parameter howToShutdown Parameters socketDescriptor The socket to shutdown howToShutdown Direction 0 Read 1 Write 2 Both Returns 0 Success 1 An error occurred shutdown will fail if EBADF The socket descriptor is invalid EINVAL One of the parameters is invalid ENOPROTOOPT The option is unknown at the level indicated Document Version 1 61 5 19 2011 543 Function Specifications signal_event Signal Occurrence of Event Syntax include lt ctools h gt void signal event UINT32 event number Description The signal_event function signals that the event_number event has occurred If there are tasks waiting for the event the highest priority task is made ready to execute Otherwise the event flag is incremented Up to 32767 occurrences of an event will be recorded The current task is blocked if there is a higher priority task waiting for the event Notes Refer to the Real Time Operating System section for more information on events Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in ctools h are not valid events fo
275. e_resource FLASH_MEMORY Notes The IO_SYSTEM resource needs to be requested before calling this function with Telepace firmware The settings take effect for all new connections made thereafter on the specified interface Existing connections are not affected Document Version 1 61 5 19 2011 435 Function Specifications mTcpSetProtocol Set Modbus IP Protocol Settings Syntax include lt ctools h gt BOOLEAN mTcpSetProtocol IP PROTOCOL TYPE type IP PROTOCOL SETTINGS pSettings Description The mTcpSetProtocol function is used to configure settings for a specific Modbus IP protocol The protocol type argument may be set to any of the following IPP_ModbusTcp IPP_ModbusRtuOverUdp IPP_ModbusAsciiOverUdp IPP_DnpOverTcp or IPP_DnpOverUdp If this function is used to change the port number then the server task for the selected protocol is ended and re started with the new settings Port number changes will only affect new connections made after calling this function Other changes take effect on existing as well as new connections This function may be used to change the server enable status The serverEnabled setting selects whether the server is enabled for the selected protocol If this flag is set to TRUE the controller supports incoming slave messages that use the selected protocol Setting this flag to FALSE prevents the controller from processing slave messages for this protocol Master messaging is
276. ease _ processor PR Dertte b einion ie e eE E master2 This task sends commands to a Modbus slave using the same serial port as main Use a Document Version 1 61 5 19 2011 663 Example Programs different MODBUS SESSION structure when sharing a serial port with another master This task uses th vent request option The task waits for the completion event to free up the processor for other tasks Sete toe See ee et See Les static void master2 void MASTER MESSAGE message BOOLEAN status UINT16 good bad define master message to copy slave digital inputs to master outputs message stream com2 message function 2 message slaveStation 2 message slaveRegister 10001 message masterRegister 1 message length 8 message timeout 30 message eventRequest TRUE message eventNo 1 main communication loop while TRUE send a new command request resource IO SYSTEM status serialModbusMaster amp amp message masterSession2 release resource IO SYSTEM if status wait for completion event when response or timeout has occurred wait_event 1 if masterSession2 masterCmdStatus good badt t allow other tasks to execute release processor Document Version 1 61 5 19 2011 664 Example Programs Master Message E
277. ease the appropriate resources for proper operation Document Version 1 61 5 19 2011 280 Function Specifications The station address is not included in the message or response string It will be added to the response string before sending the reply The checksum is not included in the message or the response string It will be added to the response string before sending the reply The maximum size of the response string is 253 bytes If a longer response length is returned the Modbus protocol will report an ILLEGAL_DATA_VALUE exception The response will not be returned See Also installModbusHandler Document Version 1 61 5 19 2011 281 Function Specifications hartlO Read and Write 5904 HART Interface Module Syntax include lt ctools h gt BOOLEAN hartIO UINT16 module Description This function reads the specified 5904 interface module It checks if a response has been received and if a corresponding command has been sent If so the response to the command is processed This function writes the specified 5904 interface module It checks if there is a new command to send If so this command is written to the 5904 interface The function has one parameter the module number of the 5904 interface 0 to 3 The I O read and write operations are added to the I O System queue The function returns TRUE if the 5904 interface responded to the previous I O request and FALSE if it did not or if the
278. econd The sequence then repeats The sequence may be read as the Controller Status Code Refer to the SCADAPack 350 System Hardware Manual or the SCADAPack 4203 Hardware Manual for further information on the status LED and digital output There are three library functions related to the status LED and digital output Refer to the Function Specification section for details on each function listed clearStatusBit Clears bits in controller status code getStatusBit Gets the bits in controller status code setStatusBit Sets the bits in controller status code I O Forcing Functions There are six library functions related to I O forcing Refer to the Function Specification section for details on each function listed These functions are supported by Telepace firmware only setOutputsInStopMode Sets the doutsinStopMode and aoutsInStopMode control flags to the specified state getOutputsInStopMode Copies the values of the output control flags into the integers pointed to by doutsinStopMode and aouts InStopMode clearAllForcing Removes forcing conditions from I O database registers setForceFlag Sets the force flag s for the specified database register s getForceFlag Copies the value of the force flag for the specified database register overrideDbase Writes a value to the I O database even if the database register is currently forced Document Version 1 61 5 19 2011 65 Overview of Programming Functions Status LED and Ou
279. ed waiting for a message V VI_DATE_SIZE Number of characters in version information date field WwW WRITESTATUS enum WriteStatus WS_NONE Bit mask to disable all wake sources WS_REAL_TIME_CLOCK Bit mask to enable real time clock as a wake up source WS_INTERUPT_INPUT Bit mask to enable interrupt input as wake up source WS_LED POWER_SWITCH Bit mask to enable LED power switch as wake up source WS_COUNTER_1_OVERFLO Bit mask to enable counter 1 overflow as a W wake up source WS_COUNTER_2_OVERFLO Bit mask to enable counter 2 overflow as a W wake up source WS_COUNTER_3_OVERFLO Bit mask to enable counter 3 overflow as a W wake up source WS_LED_POWER_SWITCH Bit mask to enable LED power switch as a wake up source WS_DIN_1_CHANGE Bit mask to enable DIN 1 change of state as a wake up source WS_COM3_VISION Bit mask to enable the SCADAPack Vision on COM 3 as a wake up source WS_COM3_DCD Bit mask to enable CDC signal on COM3 as wake up source WS_DINO_CHANGE Bit mask to enable digital input 0 as wake up source WS_410_ENABLE_SWITCH Bit mask to enable the SOLARPack 410 enable switch as wake up source WS_ONE_SECOND_ALARM Bit mask to enable one second alarm as Document Version 1 61 5 19 2011 582 Macro Definitions Macro Definition wake up source WS_ALL Bit mask to enable all wake up sources Document Version 1 61 5 19 2011 583 Structures and Types Structures and Types ADDRESS_MODE The AD
280. ed Configuration Syntax BOOLEAN dnpGetConfigurationEx dnpConfigurationEx pDnpConfigurationEx Description This function reads the extended DNP configuration parameters The function has one parameter a pointer to the DNP extended configuration structure The function returns TRUE if the configuration was successfully read or FALSE otherwise if the pointer is NULL or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration This function supersedes the dnpGetConfiguration function This function does not return the configuration for the Unsolicited Back Off Time Use the function dnpGetUnsolicitedBackoffTime to get the Unsolicited Back Off Time configuration Document Version 1 61 5 19 2011 183 Function Specifications dnpGetRuntimeStatus Get DNP Runtime Status Syntax include lt ctools h gt BOOLEAN dnpGetRuntimeStatus DNP_ RUNTIME STATUS status Description The dnpGetRuntimeStatus function reads the current status of all DNP change event buffers and returns information in the status structure DNP needs to be enabled before calling this function in order to create the DNP configuration Example See the example in the dnoGetConfiguration section Document Version 1 61 5 19 2011 184 Function Specifications dnpGetUnsolicitedBackoffTime Read the DNP unsolicited r
281. ed data from any 8 point Digital input module Document Version 1 61 5 19 2011 63 Overview of Programming Functions Digital Output Functions The controller supports external digital output modules Refer to the SCADAPack 350 System Hardware Manual for further information on controller digital output modules There are several library functions related to digital output modules Refer to the Function Specification section for details on each function listed ioRead5606Inputs ioReadDout16 ioReadDout32 ioRead5415Inputs ioRead5415O0utputs ioRead5601 Outputs ioRead5604Outputs ioReadDout8 ioWriteDout16 ioWriteDout32 ioWrite54150utputs ioWrite5601 Outputs ioWrite56040utputs ioWrite5606Outputs ioWrite56070utputs ioWriteDout8 Counter Input Functions Read the digital and analog outputs from a 5606 I O Module Read buffered data from any 16 point Digital output module Read buffered data from any 32 point Digital output module Read buffered data from the 5415 digital output module Read buffered data from the 5415 digital output module Read buffered data from any 5601 I O Module Read buffered data from any 5604 I O Module Read buffered data from any 8 point Digital output module Write data to the I O tables for any 16 point Digital output module Write data to the I O tables for any 32 point Digital output module Write data to the I O table for the digital outputs of a 5415
282. ee ee ae oe Constants Af define CONNECTION REQUIRED 10001 register for signaling connection required define MESSAGE COMPLETE 10002 register for signaling unsolicited message is complete define MESSAGE FAILED 10003 register for signaling unsolicited message failed define CONNECTION STATUS 1 connection status register Jo eee Petes sos Se st Ste Sat US Bes He 8 Se a eat US Se Private Functions BY TN a ES eR ee sampleDNPHandler This function is the user defined DNP connection handler It will be called by internal DNP routines when a connection is required when confirmation of a message is received and when a communication timeout occurs Document Version 1 61 5 19 2011 187 Function Specifications nput This inpu DNP CONNECTION R EQU TIRED DNP_MESSAGE_COMPLE1 E T An haas e DNP MESSAGE TIMEOUT he function does no n tatic void sampleDN return any values he function takes a variable of type DNP CONN instructs the handler as to what func s required The valid choices are connection required message confirmation received and timeout occurred EVENT as an ECTION_ tionality PHandler DNP_CONN ECTION_ EV ENT event Determine what connection event is required or just occurred switch event case DNP_CONNECTION_R oth
283. eeaeeeeaaeseeeeeseaeeesaeeseaeeseeeeess 415 m dbusSlavelD iis ceciese cueee ee eee Seve be cde iiaiiaaaeaiue ianiai aE 416 MOCEMAD Ot fee ieee ee avira eden eb avi ee ee 417 MOCeMADOMAM Niii iniaa ive eed ener 418 modemak riesa gertn a EE E RAE E E SEEE ERA ede svbectaiy E Ea 420 modem ENG eunero u eeraa A Ra EE ETA A EER r e ERa 422 modemDialStat S siiri neran ans atrauen ae aaraa aaan agaia a Kaan a Aaaa OAR 423 Modemni srar eeo a a E Ta ert O TAAR EER r RS 424 MOCSM NMEN Gs ceteh eter ec eiedis tebeecendsd amie eteoveecetand vs teteeereestenteleetenyecteindis teladvetel 426 MOGEMINIMStatus si ornan asa atanan an e ontran ia aen aE aa a eT A AEE A A REE 427 MOCSMNOICALION sesering serna EERE ESE ETa KAR EAEE RAA AEAT 428 M TepGetC ON iG eain asa aiaa an e ontrennbar a e A AERES AAE E tbeazeel 429 mTepGetlInterfaCe ariin eieae entane ea eana Ea aE na ENa 430 mT CpGetlntetace Ex ir ar eiar eiae a a e a aE ache aa 431 mM TepGetProtoCO hinien naran anaa on tra aa baaa aa EEEa ao ATARE KAD a SNEEN 432 MTEPSEtCON IG isc cetececces aae eaae aoaea aa a Eaa E A Taa a a Taa 433 IMT CPSetlnterhAace oridi apaadi aapa paad dnain 434 MI CpSetinterAace Ex cciscvss cieeescedseseecbducdvee enact td den arapi raddiena yna rari iaaio 435 MI CpPSetProtoCOl epetan op araea e aa ead aa aa E LARA ireen 436 mrepMasterC lose naa aa aea r aO aati Ao ea EELA E orice 437 ML CpMasterDiISCONNGCh rscisecccasdeisccsseadtiessnedsvaevee eaeeddausbitwadsbevandsccnretadanceetdaced
284. eeeeeeeeeceeeeeeaeeeeaaeseeeeeseaeeesiaeeseeeseeeeess 305 InstallEXitHANler ecececcceceeeeeeeeeceee cece ee eeeeeaaeeeceeeeeseeaaeaeeeeeeeeeseeaeaeeeeeeseeeeenaees 307 INStalIMOGDUSHANAIEN ee eeeeeeeeeeeeeeceeeeeeeeeeeeaeeeeeeeaeeeeeeaeeeeeseeeeeeeseeeaeeeeeeeaees 308 INStAlIRT CHANAIEL ce ceeccccesseececeeseececeeeeeeeeeceneeeeeseneeeeeseneeeeeseneeeeeseeeaeenseneaees 309 RT CHandler Function 0 cccccccccecsecceceesneeececsneeeeesneeeeessaeeeeessaeeeeesseeeeesneeeenss 310 FO GIS AM cis chtaceecudusdetsihiasesapasacbeeshadcecshar oohishtactenanzicabaahiaceeesasaestsintaubenmauaabnsthuncnsents 311 loDatabasGReset 2 5sceesazicees shes E EEEIEE TEENA TE 312 joGetConfiguration sseesseeeseseenernesrnsrnssrnsstnsstnsstnnstnsstnsstnastensteasnnnsnnnnnnnnn ennt 314 FONOTINGC ATION EAEE TE S E A A E 315 ioRead42 03 UR MPUS iarra a E RA EAR EE RAT 316 joRead4203DSlnputs cece ceenceceeeeeceeeeeeeaeeeeeeeceeeeesaaeseeaaeseeneeseaeeesaaeseeaeeeseeeees 318 lORSadS2 1 OIMPUTS sara hus cecenyascheshtaalshpagacehs chbickeepaghectishtaslanpaggceneshuiceaeaiy 320 lORGAaAdS21 OOULPUTS a seas ecg dans a a a aapa Ta aa a a aa Aa NASSP ERKAN iS 322 lORCaAd54 1 4 MOUIE soina E T 323 lORCAdS4 1 SIMPUTS scria E 325 joRead54150utputs 0 eee eee cece cece ee ceeeeeeeaeeeeeeeceaeeeeaaeeeeaaeegeeeeseaeeesaaesseneeeseneess 327 lORead5505 Inputs onien ceeded cine E NE aAA a N AN AN E 328 ioRead55050utp tS i iaaa eee She ee 3
285. egisters may also be assigned to controller on board digital inputs and to system diagnostic modules Input Registers Input or analog input database registers may be assigned to 5000 analog input modules or SCADAPack I O modules through the Register Assignment Input registers may also be assigned to controller internal analog inputs and to system diagnostic modules Holding Registers Document Version 1 61 5 19 2011 81 Overview of Programming Functions Holding or analog output database registers may be assigned to 5000 analog output modules or SCADAPack analog output modules through the Register Assignment Holding registers may also be assigned to system diagnostic and configuration modules Modbus I O Database Functions There are several library functions related to the Modbus database Refer to the Function Specification section for details on each function listed dbase installDbaseHandler installSetdbaseHandler Dbase Handler Function setdbase Reads a value from the database Allows an extension to be defined for the dbase function Allows an extension to be defined for the setdbase function User defined function that handles reading of Modbus addresses not assigned in the IEC 61131 1 Dictionary Writes a value to the database Setdbase Handler Function User defined function that handles writing to Modbus I O Database Macros Modbus addresses not assigned in the IEC 61131 1 Dictionary
286. eld hour is the current hour It is in the range 00 to 23 minute is the current minute It is in the range 00 to 59 second is the current second It is in the range 00 to 59 hundredth is the current hundredth of a second It is in the range 00 to 99 Document Version 1 61 5 19 2011 630 Structures and Types timer_info timeval VERSION WRITESTATUS The timer_info structure contains information about a timer struct timer info UINT16 time UINT16 interval UINT16 interval remaining e e time is the time remaining in the timer in ticks e interval is the length of a timer tick in 10ths of a second e interval_remaining is the time remaining in the interval count down register in 10ths of a second struct timeval long tv_sec Number of Seconds long tv_usec Number of micro seconds The Firmware Version Information Structure holds information about the firmware typedef struct versionInfo tag UINT16 version UINT16 build UINT16 controller CHAR date VI_DATE_SIZE 1 CHAR copyright VI_STRING_SIZE 1 VERSION e version is the firmware version number e controller is target controller for the firmware e date is a string containing the date the firmware was created e copyright is a string containing Control Microsystems copyright information The WRITESTATUS enumerated type indicates the status of an I C bus message read and may have one o
287. elow If there are additional headers included copy these include statements to the main cpp file next ftir aoe E E oe BIS Sh SB ee ee alos ee ee See SCADAPack 350 and 4203 C Application Main Program Copyright 2006 Control Microsystems Inc eek see st See Se ee ee ek Sa Se include lt ctools h gt include nvMemory h JRoewe Sea sae et es Se ees ee ee ee E ee eee C Function Prototypes EAS Sates Bes oN ene ae he E EEE ee ee A add prototypes here a a a a E E E E ee C Function Prototypes eee ee ee ae ee a ee REEN E extern C add prototypes here Document Version 1 61 5 19 2011 680 Porting Existing C Tools Applications Paste your code here e Delete the additional stub function main at the end of the file main cpp The C Tools require main to have the prototype int main void Change the syntax of main so that it returns the data type int instead of void The returned int value is not accessible to the user and so any value may be returned or none at all Replace Older C Tools Headers with ctools h If the ported application used SCADAPack C Tools version 2 12 or older the program C files will likely have include statements with C Tools header files such as protocol h primitiv h etc Replace all these C Tools include statements in all program C files with just one include statement include lt ctools h gt Replace Partially Supported and Unsupported Functions Build the A
288. emNotification when writing a custom protocol See Also get_protocol Example This code fragment changes the station number of the com2 protocol to 4 include lt ctools h gt struct prot settings settings get_protocol com2 amp settings settings station 4 request resource IO SYSTEM set protocol com2 amp settings release resource IO SYSTEM Document Version 1 61 5 19 2011 525 Function Specifications setProtocolSettings Set Protocol Extended Addressing Configuration Syntax include lt ctools h gt BOOLEAN setProtocolSettings FILE stream PROTOCOL SETTINGS settings Description The setProtocolSettings function sets protocol parameters for a serial port This function supports extended addressing The function has two arguments portis one of com1 com2 or com3 and settings a pointer to a PROTOCOL_SETTINGS structure Refer to the Description of the structure for an explanation of the parameters The function returns TRUE if the settings were changed It returns FALSE if the stream is not valid or if the protocol does not start The IO_SYSTEM resource must be requested before calling this function To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Notes
289. ement amp REQ MQUEUE fprintf coml Waiting to receive a message r n if taskStatus requirement amp REQ RESOURCE fprintf coml Waiting for resource sd r n taskStatus requirement amp REQ MASK Document Version 1 61 5 19 2011 646 Example Programs if taskStatus requirement amp REQ EVENT fprintf coml Waiting on event number sd r n taskStatus requirement amp REQ MASK fprintf coml Error Sd r n taskStatus error while TRUE Allow other tasks to execute release processor Handler Function Example JR ee etecs ese he ee ee EE handler c This is a sample program for the InstallModbusHandler function This sample program uses function code 71 to demonstrate a simple method for using the installModbusHandler function When the handler is installed Modbus ASCII messages using function code 71 that are received on com2 of the controller will be processed as shown in the program text To turn on digital output 00001 From a terminal send the ASCII command 014701B7 Where 01 is the station address 47 is the function code in hex 01 is the command for the function code B7 is the message checksum To turn off digital output OOOOL From a terminal send the ASCII command 014700B8 Where 01 is the station address 47 is the function code in hex 00 is the command for the function code
290. emote IP is disconnected manually or automatically after an idle timeout the connection ID remains allocated until mTcpMasterDisconnect is called to disconnect and end the mastering task and mTcpMasterClose is called to return the connection ID There are only 20 connections available for all Modbus IP master and slave connections Use the function ipGetConnectionSummary obtain the number of master and slave connections that are currently active If the initial connection started by this function fails the connection will be attempted again if necessary each time mTcpMasterMessage is called See the function mTcpMasterMessage for a discussion of whether to allocate one or several connections when polling multiple remote IP addresses Example See Example for Master Message Example Using mTcpMasterMessage Document Version 1 61 5 19 2011 442 Function Specifications mTcpMasterStatus Modbus IP Master Command Status Syntax include lt ctools h gt BOOLEAN mTcpMasterStatus UINT32 connectID MODBUS CMD STATUS cmdStatus Description The mTcpMasterStatus function obtains the Modbus command status for the connection specified by connectID This function copies the master command status to the value pointed to by cmdStatus FALSE is returned if the specified connectiD is invalid otherwise TRUE is returned and the status is copied This function may not be called after calling the function mTcpMasterClose with th
291. ength of secondaryDialString excluding the null terminator character secondaryDialString specifies the dial string to be used when dialing the target station It is used for the next attempt if the first attempt fails The function returns TRUE if the configuration was written and FALSE if an error occurred Notes This function needs to be used in conjunction with the dnpWriteRoutingTableEntry function to write a complete entry in the DNP routing table Document Version 1 61 5 19 2011 225 Function Specifications dnpWriteRoutingTableEntry Write Routing Table Entry Syntax include lt ctools h gt BOOLEAN dnpWriteRoutingTableEntry UINT16 index UINT16 address UINT16 comPort UINT16 retries UINT16 timeout Description This function writes an entry in the DNP routing table This function is used to write entries without IP addresses To create an entry with an IP address use the dnpWriteRoutingTableEntryEx function Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Use the dnpCreateRoutingTable function to create the routing table and specify its size The function returns TRUE if successful FALSE otherwise Example See the example in the dnpGetConfiguration section Document Version 1 61 5 19 2011 226 Function Specifications dnpWriteRoutingTableEntryEx Write Routing Table Entry with Extended Information Syntax includ
292. eported either Change Of State or Log All Events e Cl16_bufferSize is the number of events in the 16 bit counter change buffer Valid values are 0 to 9999 e CI32_number is the number of 32 bit counter input points Valid values are 0 to 9999 e Cl32_startAddress is the DNP address of the first C132 point Document Version 1 61 5 19 2011 597 Structures and Types e CI32_reportingMethod determines how C132 inputs are reported either Change Of State or Log All Events e CI32_bufferSize is the number of events in the 32 bit counter change buffer Valid values are 0 to 9999 e CI32_wordOrder is the Word Order of CI32 points O LSW first 1 MSW first e Al16_number is the number of 16 bit analog input points Valid values are 0 to 9999 e Al16_startAddress is the DNP address of the first Al16 point e Al16_reportingMethod determines how 16 bit analog changes are reported e Set this to FIRST _VALUE to report the value of the first change event measured e Set this to CURRENT_VALUE to report the value of the latest change event measured e Al16_bufferSize is the number of events in the 16 bit analog input change buffer Valid values are 0 to 9999 e AI32_number is the number of 32 bit analog input points Valid values are 0 to 9999 e AI32_startAddress is the DNP address of the first Al32 point e AI32_reportingMethod determines how 32 bit analog changes are reported e Set this to FIRST _VALUE to report the valu
293. er bits case DNP_M EQUIR ED indicate connection is needed and clear request resource IO SYSTEM setdbase MODBUS CONNECTION REQUIRED 1 setdbase MODBUS MESSAGE COMPLETE 0 setdbase MODBUS MESSAGE FAILED 0 release resource IO SYSTEM break ESSAGE COMPLETE indicate messag e sent and clear other bits R request_resource IO SYSTEM setdbase MODBUS CONNECTION REQUIRED 0 setdbase MODBUS MESSAGE COMPLETE 1 setdbase MODBUS MESSAGE FAILED 0 release resource IO SYSTEM break case DNP_ MESSAGE TIMEOUT indicate message failed and clear other bits request resource IO SYSTEM setdbase MODBUS CONNECTION REQUIRED 0 setdbase MODBUS MESSAGE COMPLETE 0 setdbase MODBUS MESSAGE FAILED 1 release resource IO SYSTEM break default ignore invalid requests break YRo See ere tate eS el kt et ee ee Pf Document Version 1 61 5 19 2011 188 Function Specifications This function is the main task of a user application It monitors a register from the ladder logic application When the register value changes the function signals DNP events The function has no parameters The function does not return Z int main void
294. erRecordSize 1000 External drive selected when set to 3 usbMemLogConfig fileMode 3 Maximum number of log files usbMemLogConfig numFiles 50 File size in number of records usbMemLogConfig fileRecordSize 1000 Number of usbMemLogConfig numRecord lements fields in each record Elements 3 1st field Date and Time recordFieldsDefinitions 0 type DLOG_CMITIME recordFieldsDefinitions 0 size sizeof dlogCMITime recordFieldsDefinitions 0 offset offsetof dlogRecord valuel 2nd field 16 bit AIN raw value recordFieldsDefinitions 1 type DLOG_INT16 Document Version 1 61 5 19 2011 638 Example Programs recordFieldsDefinitions 1 size sizeof INT16 recordFieldsDefinitions 1 offset offsetof dlogRecord value2 3rd field 32 bit floating point scaled value recordFieldsDefinitions 2 type DLOG_ FLOAT recordFieldsDefinitions 2 size sizeof float recordFieldsDefinitions 2 offset offsetof dlogRecord value3 Pointer to array of record element definitions usbMemLogConfig recordList recordFieldsDefinitions Security token disabled when set to 0 usbMemLogConfig securityToken 0 Text description of log Maximum 255 characters memcpy usbMemLogConfig description strLogDescription strlen strLogDescription 1 The log name Maximum 255 characters memcpy usbMemLogConfig
295. erface Modbus IP Interface Serial Modbus Interface Serial Modbus Interface Modbus IP Network e g com1 com2 or com3 e g Modbus TCP Modbus RTU over UDP or Modbus ASCII over UDP Modbus IP Interface Modbus IP Network e g Ethernet e g Modbus TCP Modbus RTU over UDP or Modbus ASCII over UDP Modbus IP Network as Forwarding Interface When forwarding to a TCP or UDP network the protocol type is selected for the forwardinterface in the SF_TRANSLATION structure The IP Stack automatically determines the exact interface e g Ethernet1 to use when it searches the network for the forward PAddress Also when forwarding on a TCP or UDP network the forwarding destination IP address needs to be entered as the forward PAddress The forward PAddress is entered as an IP address string of the format 255 255 255 255 The forwardlPAddress is needed to know where to connect so that the command can be forwarded to its final destination Document Version 1 61 5 19 2011 531 Function Specifications Modbus IP Network as Slave Interface Note that there is no field for a slave IP address This information is irrelevant because we don t care about the IP address of the remote master We care only that the remote master connects to the specified s ave nterface and sends a command to be forwarded The protocol type is not specified for slavelnterface All messages in any Modbus IP protocol received on s avelnterface for slaveS
296. erial port the function has no effect function specifies the handler function which takes two arguments The first argument is the port number The second argument is the received character If function is NULL the default handler for the port is installed The default handler does nothing Notes The install_ handler function can be used to write custom communication protocols The handler is called at the completion of the receiver interrupt handler RTOS calls see functions listed in the section Real Time Operating System Functions at the start of this chapter may not be made within the interrupt handler with one exception The interrupt_signal_event RTOS call can be used to signal events To optimize performance minimize the length of messages on com3 Examples of recommended uses for com3 are for local operator display terminals and for programming and diagnostics using the IEC 61131 1 program Example See the Install Serial Port Handler Example in the Examples section Document Version 1 61 5 19 2011 302 Function Specifications installClockHandler Install Handler for Real Time Clock Syntax include lt ctools h gt void installClockHandler void function void Description The installClockHandler function installs a real time clock alarm handler function The real time clock alarm function calls this function each time a real time clock alarm occurs function specifies the handler function If fu
297. ersion 1 61 5 19 2011 529 Function Specifications setSFTranslation Write Store and Forward Translation Syntax include lt ctools h gt struct SFTranslationStatus setSFTranslation UINT16 index SF_TRANSLATION pTranslation Description Instead of using the setSFTranslation function use the setSFTranslationEx function which supports translations with a timeout and with authentication Otherwise a default timeout of 10 seconds is set for all forwarded commands The setSFTranslation function copies the structure pointed to by pTranslation into the store and forward translation table at the location specified by index Valid values for index are 0 to 127 The function checks for invalid translations The translation is stored even if invalid The SF_TRANSLATION structure is described in the Structures and Types section The function returns a SFTranslationStatus structure It is described in the Structures and Types section The code field of the structure is set to one of the following If there is an error the index field is set to the location of the translation that is not valid SF_VALID ss VALID All All translations are valid All translations are valid valid message on the same spart E valid ANGE SF_ALREADY DEFINED The translation already exists in the table SF_INDEX_OUT_OF_RAN The entry referenced by index does not exist in GE the table SF_INVALID_FORWARDIN The forwarding IP address is inval
298. es 5414 I O Module parameter 0 defines the input type Valid values are 5414 I O Module parameter 1 defines the scan frequency for AC inputs Valid e 0 DC e 1 AC values are e 0 60 Hz e 1 50Hz Document Version 1 61 5 19 2011 97 Function Specifications 5505 I O Module parameters 0 to 3 define the analog input type for the corresponding input Valid values are e 0 RTD in deg Celsius e 1 RTD in deg Fahrenheit e 2 RTD in deg Kelvin e 3 resistance measurement in ohms 5505 I O Module parameters 4 defines the analog input filter Valid values are e 0 0 5s e q1 i1s e 2 2S e 3 4s 5506 I O Module parameters 0 to 7 define the analog input type for the corresponding input Valid values are e 0 0to5 V input e 1 1 to 5 V input e 2 0 to 20 mA input e 3 4to 20 mA input 5506 I O Module parameters 8 defines the analog input filter Valid values are e O lt 3 Hz maximum filter e 1 6Hz e 2 11 Hz e 3 30 Hz minimum filter 5506 I O Module parameters 9 defines the scan frequency Valid values are e 0 60Hz e 1 50 Hz 5606 I O Module parameters 0 to 7 define the analog input type for the corresponding input Valid values are e 0 0to5 V input e 1 1to5 V input e 2 0 to 20 mA input e 3 4to 20 mA input 5606 I O Module parameters 8 defines the analog input filter Valid values are e O lt 3 Hz maximum filter Document Version 1 61 5 19 2011 98 Function Spec
299. es See Also send_message Example This task waits for messages then prints their contents The envelopes received are returned to the operating system include lt ctools h gt void show_message void envelope msg while TRUE msg receive message fprintf coml Message data ld r n msg gt data deallocate_ envelope msg Document Version 1 61 5 19 2011 475 Function Specifications recv Syntax include lt ctools h gt int recv int socketDescriptor char bufferPtr int bufferLength int flags Ne Description recv is used to receive messages from another socket recv may be used only on a connected socket see connect accept socketDescriptor is a socket created with socket or accept The length of the message is returned If a message is too long to fit in the supplied buffer excess bytes may be discarded depending on the type of socket the message is received from see socket The length of the message returned could also be smaller than bufferLength this is not an error If no messages are available at the socket the receive call waits for a message to arrive unless the socket is non blocking or the MSG_DONTWAIT flag is set in the flags parameter in which case 1 is returned with socket error being set to EWOULDBLOCK Out of band data not in the stream urgent data when the SO_OOBINLINE option is not set default TCP protocol only A single out of band
300. es ee 624 0 RA 0 eee ee ee 624 PORT_CHARACTERISTICS irriteniet aini iia eiia eiiiai 625 PstatU Saia E E E A N A 626 READSTIAT US aai a ae aa aa aa baa a a raa a a aariaa aa aa SE Eana 626 e tila enkla DAET EE AEI ETA AE T E rere E A 627 SF TRANSLATION eraren kiogu neanta aranana a aa araa aa aaa a na a E Saa Taai 627 SF TFRANSLAT ON E X sinh ict ararasan e aipa aga ana aaa aranana a a iaai 628 SPT ranslatioNStatus eieiaeo ar raaa a Aa aa aa aana aa aa aaa iaaii 629 TASKIN O aaea raa an a a hae ceca aaa era aar aaraa aan pan atrata 629 taskmfo tagiria oana a EA AERA EE Ra SETAE TAE SEISA 630 1A eter rome a aaraa an a a aa aane aaa eera aa aaraa aa an atatt 630 iiaae AMO sehen E E E A A E 631 imeval i ea ee E e An EE E TAER E EEAS 631 VERSION AE E E easter tn A E tendon 631 WRITESTATU S rta a naa a aa anara aa death ta aaa aaan aa eaves 631 Example Program aisiiicdiictiicdiicdiicciistiacanisanandnacaiaedniaananavanaiananins 633 Connecting with a Remote Controller Example ccscceeecesseeeesseeeeeeeeesees 633 Greate Task Exam pleri naene ate Ad taint ein ad aaa 634 Patalog Examples ceini E a ian hein ean ete 636 Get Program Status Example cc cccceceeeseeceeeeeceeeeesaeeeeeeeseeeesaeeesaeeseneeesaees 645 Get Task Status Exampleei iicctesde atie aaa eaaa a ee aa aea aa feast 646 Handler Function Example ececceceecceeeeeeeeeeeeeeeeeeeeeeeeeeeneeeeeseeeeeeeseneaeeeeeeeaees 647 Install Serial Port Handler Example
301. es selecting the input range for the corresponding analog input Valid values are e 0 0to 5V e 1 0t010V e 2 0t020mA e 3 41to 20 mA inputFilter selects input filter selection is written to this variable e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency selects the scan frequency setting Valid values are e 0 60 Hz e 1 50 Hz Document Version 1 61 5 19 2011 383 Function Specifications outputType selects the analog output type setting Valid values are e 0 0to20mA e 1 4to20 mA The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5606Inputs ioRead5606Outputs Example This program turns on all 16 digital outputs and sets the analog outputs to full scale on the 5606 module at address 5 include lt ctools h gt define MY EVENT 1 int main void UCHAR doutData 2 INT16 aoutData 2 UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType IO_ STATUS io_status BOOLEAN status main loop while TRUE write data to output tables for next scan doutData 0 OxFF doutData 1 OxFF aoutData 0 32767 aoutData 1 32767 set analog input types to 4 20 mA inputType 0 3 inputType 1 3 inputType 2 35 inputType 3 3 inputType 4 3 inputType 5 3 inputType 6 3 inputType 7 3 set filter and frequency inputFilter 3 mi
302. escription This function converts a long value from network byte order to host byte order Parameters longValue The value to convert Returns The converted value Document Version 1 61 5 19 2011 445 Function Specifications ntohs Syntax include lt ctools h gt unsigned short ntohs unsigned short shortValue i Description This function converts a short value from network byte order to host byte order Parameters shortValue The value to convert Returns The converted value Document Version 1 61 5 19 2011 446 Function Specifications overrideDbase Overwrite Value in Forced I O Database Telepace firmware only Syntax include lt ctools h gt BOOLEAN overrideDbase UINT16 type UINT16 address INT16 value Description The overrideDbase function writes value to the I O database even if the database register is currently forced type specifies the method of addressing the database address specifies the location in the database If the register is currently forced the register remains forced but forced to the new value If the address or addressing type is not valid the I O database is left unchanged and FALSE is returned otherwise TRUE is returned The table below shows the valid address types and ranges Type Address Ranges Register Size MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16
303. escription This function returns the configuration settings of a 5904 module The function has two parameters the module number of the 5904 module 0 to 3 and a pointer to the settings structure The function returns TRUE if the settings were read The function returns FALSE if the module number is invalid See Also hartSetConfiguration Document Version 1 61 5 19 2011 295 Function Specifications hartSetConfiguration Write HART Module Settings Syntax include lt ctools h gt BOOLEAN hartSetConfiguration UINT16 module HART SETTINGS settings Description This function writes configuration settings to a 5904 module The function has two parameters the module number of the 5904 module 0 to 3 and a settings structure The function returns TRUE if the settings were written The function returns FALSE if the module number or the settings are invalid Notes The configuration settings are stored in flash The user defined settings are used when the controller is reset in the RUN mode Default settings are used when the controller is reset in the SERVICE or COLD BOOT modes To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY See Also hartGetConfiguration Document Version 1 61 5 19 2011 296 Function Speci
304. esend time Syntax UINT16 dnpGetUnsolicitedBackoffTime Description The dnpGetUnsolicitedBackoffTime function reads the unsolicited resend time from the controller The time is in seconds and the allowed range is 0 65535 seconds A value of zero indicates that the unsolicited resend timer is disabled Document Version 1 61 5 19 2011 185 Function Specifications dnpinstallConnectionHandler Configures the connection handler for DNP Syntax include lt ctools h gt void dnpInstallConnectionHandler void handler UINT16 dnpAddress DNP_CONNECTION EVENT event Description This function installs a handler that will permit user defined actions to occur when DNP requires a connection message confirmation is received or a timeout occurs handler is a pointer to the handler function If function is NULL the handler is disabled The function has no return value Notes The handler function needs to process the event and return immediately If the required action involves waiting this needs to be done outside of the handler function See the example below for one possible implementation The application needs to disable the handler when the application ends This prevents the protocol driver from calling the handler while the application is stopped Call the dnplinstallConnectionHandler with a NULL pointer The usual method is to create a task exit handler function to do this See the example below for
305. esponseSize is the size of the response buffer in characters e pResponseLength is a pointer to a variable that will hold the number of characters in the response If the handler returns TRUE it needs to set this variable e pResponse is a pointer to a buffer that will hold the response message The buffer size is responseSize characters The handler must not write beyond the end of the buffer If the handler returns TRUE it needs to set this variable The data needs to start with the function code and end with the last Document Version 1 61 5 19 2011 232 Function Specifications data byte The protocol driver will add the station address checksum and message framing to the response The handler function returns the following values NORMAL Indicates protocol handler should send a normal response message Data are returned using pResponse and pResponseLength ILLEGAL_FUNCTION Indicates protocol handler should send an Illegal Function exception response message This response should be used when the function code in the command is not recognized ILLEGAL_DATA_ADDRESS Indicates protocol handler should send an Illegal Data Address exception response message This response should be used when the data address in the command is not recognized ILLEGAL_DATA_VALUE Indicates protocol handler should send an Illegal Data Value exception response message This response should be used when invalid data is found in the command
306. ess of the 5607 module Valid values are 0 to 7 doutData is a reference to an array of two UCHAR variables Digital data for the 10 outputs are written to this array One bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are written to this array inputType is a reference to an array of eight UINT16 variables Analog input measurement types are written to this array Valid values are e 0 0to 5V e 1 0t010V e 2 0to20mA e 3 41to 20 mA inputFilter is a reference to a UINT16 variable The input filter selection is written to this variable e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency is a reference to a UINT16 variable The scan frequency selection is written to this variable e 0 60Hz Document Version 1 61 5 19 2011 343 Function Specifications e 1 50 Hz outputType is a reference to a UINT16 variable The analog output type is written to this variable e 0 0to20mA e 1 4to 20 mA The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5607 Inputs ioWrite5607Outputs Example This program reads output data from the I O table for the 5607 digital outputs and analog outputs at address 5 include lt ctools h gt void main void UCHAR doutData 2 INT16 aoutData 2 UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType
307. essaging is the enable Store and Forward messaging control flag Enable store and forward when set to TRUE Disable store and forward when set to FALSE Default value is FALSE e enronEnabled determines if the Enron Modbus station is enabled It may be TRUE or FALSE Document Version 1 61 5 19 2011 620 Structures and Types e enronStation is the station address for the Enron Modbus protocol It is used if enronEnabled is set to TRUE Valid values are 1 to 255 for standard addressing and 1 to 65534 for extended addressing pconfig The pconfig structure contains serial port settings struct pconfig UINT16 baud UINT16 duplex UINT16 parity UINT16 data_bits UINT16 stop bits UINT16 flow rx UINT16 flow tx UINT16 type UINT16 timeout E e baud is the communication speed It is one of the BAUD macros e duplex is either the FULL or HALF macro e parity is one of NONE EVEN or ODD macros e data_bits is the word length It is either the DATA7 or DATA8 macro e stop_bits in the number of stop bits transmitted The only supported selection is the STOP1 macro e flow_rx specifies flow control on the receiver It is either the RFC_MODBUS_RTU ENABLE or RFC_NONE DISABLE If the Modbus RTU protocol is used set flow_rx to RFC_MODBUS_RTU For the Modbus ASCII protocol or any other protocol set flow_rx to RFC_NONE e flow_tx specifies flow control on the transmitter It is either the TFC_IGNORE_CTS
308. et forwardinterface field portB 1 1 com1 2 com2 3 coms 100 Ethernet1 stationA field slaveStation field stationB field forwardStation field Instead of entering a translation in any order for the communication interfaces as done with the old structure the translation data is entered specifying the receiving slave interface slavelnterface and slaveStation and the forwarding master interface forwardinterface forwardStation and forward PAddress if applicable Translations describe the communication path of the master command e g the slave interface which receives the command and the forwarding interface to forward the command The response to the command is automatically returned to the master through the same communication path in reverse The getSFTranslation and setSFTranslation functions are documented in the Function Specifications section Document Version 1 61 5 19 2011 688 Porting Existing C Tools Applications Serial Port Configuration Functions portConfiguration The C Tools function portConfiguration returned a pointer to the port configuration table for com1 and com2 only These functions are no longer supported Use the functions get_port and set_port in place of portConfiguration Default Settings for Com1 and Com2 Rx Flow Control The default settings for Com1 and Com2 have changed All serial ports of the SCADAPack 350 and 4203 have the same default settings and the same range
309. et only One of the parameters is invalid or the MSG_OOB flag is set and either the SO_OOBINLINE option is set or there is no out of band data to read or coming from the peer Socket is not connected Document Version 1 61 5 19 2011 477 Function Specifications recvfrom Syntax include lt ctools h gt int recvfrom int socketDescriptor char bufferPtr int bufferLength int flags struct sockaddr fromPtr int fromLengthPtr Description recvfrom is used to receive messages from another socket recvfrom may be used to receive data on a socket whether it is in a connected state or not but not ona TCP socket socketDescriptor is a socket created with socket If fromPtr is not a NULL pointer the source address of the message is filled in fromLengthPtr is a value result parameter initialized to the size of the buffer associated with fromPtr and modified on return to indicate the actual size of the address stored there The length of the message is returned If a message is too long to fit in the supplied buffer excess bytes may be discarded depending on the type of socket the message is received from see socket If no messages are available at the socket the receive call waits for a message to arrive unless the socket is non blocking or the MSG_DONTWAIT flag is set in the flags parameter in which case 1 is returned with socket error being set to EWOULDBLOCK select may be used to determine w
310. et to RS232_MODEM The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port The modemDialStatus function will return a DE_NotInControl error code if another dial function or incoming call is now in control of the port Do not call this function in a task exit handler Document Version 1 61 5 19 2011 423 Function Specifications modemlnit Initialize Dial up Modem Syntax include lt ctools h gt enum DialError modemInit struct ModemInit configuration reserve id id Description The modemlnit function sends an initialization string to an external dial up modem It is typically used to set up a modem to answer incoming calls One modemlnit function may be active on each serial port The modemInit function handles port sharing and multiple dialing attempts The ModemInit structure pointed to by configuration defines the serial port and modem initialization string Refer to the Structures and Types section for a Description of the fields in the Modeminit structure The id variable is set to a reservation identifier for the serial port The identifier provides that no other modem control function can access the serial port This parameter needs to be supplied to the modemInitEnd and modemInitStatus functions The function returns an error code DE_NoError indicates that the initialize operation has begun Any other code indicates an err
311. eturn value is TRUE if pMasterPoll was successfully written or FALSE otherwise Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns the total number of entries in the DNP routing table Document Version 1 61 5 19 2011 196 Function Specifications dnpReadMasterPollTableEntryEx Read DNP Master Poll Table Extended Entry Syntax BOOLEAN dnpReadMasterPollTableEntryEx UINT16 index DnpMasterPollEx type pMasterPoll Description This function is only available on the SCADAPack 32 SCADAPack 350 and 4203 This function reads an extended entry from the DNP master poll table pMasterPoll is a pointer to an extended table entry it is written by this function The return value is TRUE if pMasterPoll was successfully written or FALSE otherwise Notes This function is only available on the SCADAPack 32 SCADAPack 350 and 4203 DNP needs to be enabled before calling this function in order to create the DNP configuration This function supersedes the dnpReadMasterPollTableEntry function Document Version 1 61 5 19 2011 197 Function Specifications dnpReadMasterPollTableSize Read DNP Master Poll Table size Syntax include lt ctools h gt UINT16 dnpReadPMasterPollTableSize void Description This function reads the total number of entries in the DNP master poll table Notes DNP needs to be enabled before
312. eved index specifies the index for the credentials Indices are service specific username specifies the username to grant access to maxUsernameLength specifies the maximum length username that can be returned Description The getLoginCredentials function retrieves the username at the specified index for the specified service Valid services are 0 FTP Maximum username and password length is 16 bytes Only index 0 is supported The valid values of index are service specific The username returned will be NULL terminated and placed in the buffer pointed to by username True is returned if the credentials were retrieved False is returned if the service rejected the request if the service was unrecognized or if the username could not fit in the specified sized buffer See Also setLoginCredentials clearLoginCredentials Document Version 1 61 5 19 2011 255 Function Specifications getpeername Syntax include lt ctools h gt int getpeername int socketDescriptor Struct sockaddr fromAddressPtr int addressLengthPtr Description This function returns to the caller the IP address Port number of the remote system that the socket is connected to Parameter Description socketDescriptor The socket descriptor that we wish to obtain this information about fromAddressPtr A pointer to the address structure that we wish to store this information into addressLengthPtr The length of the address
313. everal library functions related to DNP communication protocol Refer to the Function Specification section for details on each function listed dnpClearEventLogs Deletes change events from the DNP change event buffers dnpConnectionEvent Report a DNP connection event dnpCreateAddressMappingTable Allocates memory for a new address mapping table according to the size parameter dnpCreateMasterPollTable Allocates memory for a new table according to the size parameter dnpCreateRoutingTable Allocates memory for a new routing table according to the size parameter dnpGenerateChangeEvent Generates a change event for the DNP point dnpGenerateEventLog Generates a change event for the DNP point dnpGetAl16Config Reads the configuration of a DNP 16 bit analog input point dnpGetAl32Config Reads the configuration of a DNP 32 bit analog input point dnpGetAlSFConfig Reads the configuration of a DNP 32 bit short floating analog input point dnpGetAO16Config Reads the configuration of a DNP 16 bit analog output point dnpGetAO32Config Reads the configuration of a DNP 32 bit analog output point dnpGetAOSFConfig Sets the configuration of a DNP 32 bit short floating analog output point dnpGetCl16Config Reads the configuration of a DNP 16 bit counter input point dnpGetCl32Config Reads the configuration of a DNP 32 bit counter input point Document Version 1 61 5 19 2011 75 Overview of Programming Functions
314. f the following values enum WriteStatus WS_ success WS_selectFailed WS_noAcknowledge Document Version 1 61 5 19 2011 631 Structures and Types typedef enum WriteStatus WRITESTATUS e WS success returns write was successful e WS selectFailed returns slave could not be selected e WS_noAcknowledge returns slave failed to acknowledge data Document Version 1 61 5 19 2011 632 Example Programs Example Programs Connecting with a Remote Controller Example The following code shows how to connect to a remote controller using a modem The example uses a US Robotics modem It also demonstrates the use of the modemAbort function in an exit handler include lt ctools h gt include lt string h gt The myshutdown function aborts any active modem connections when the task is ended void myshutdown void modemAbort com1 int main void struct ModemSetup dialSettings reserve id portID enum DialError status enum DialState state struct pconfig portSettings TASKINFO taskStatus Configure serial port 1 portSettings baud BAUD19200 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATA8 portSettings stop bits STOP1 portSettings flow_rx RFC_MODBUS RTU portSettings flow tx TFC_NONE portSettings type RS232 MODEM portSettings timeout 600 request resource IO SYSTEM set_port coml amp portSetti
315. face is configured to the specified IP address FALSE is returned otherwise TRUE is returned and the interface type if copied to the value pointed to by ifType iplnitializeFriendlylP Settings Reset the friendly IP list Syntax void iplnitializeFriendlylPSettings void Description This function deletes all Friendly IP List entries and disables the Friendly IP List The function has no parameters The function has no return value Document Version 1 61 5 19 2011 399 Function Specifications ipReadFriendlyListControl Get the status of the friendly IP list Syntax UCHAR ipReadFriendlyListControl void Description This function returns the status of friendly IP list control The function has no parameters The function returns TRUE if friendly IP list is enabled and FALSE otherwise See Also ipWriteFriendlyListControl Document Version 1 61 5 19 2011 400 Function Specifications ipReadFriendlylPListEntry Read one entry in the friendly IP list Syntax BOOLEAN ipReadFriendlyIPListEntry UINT16 index IP_ADDRESS pIpAddressStart IP_ADDRESS pIpAddressEnd i Description This function reads an entry from the Friendly IP List index specifies the location in the list and needs to be less than or equal to the Friendly IP List size plpAddressStart and plpAddressStart are pointers to IP addresses they are written by this function The function returns TRUE if successful and FALS
316. fail if EBADF EINVAL ENOPROTOOPT Option Name Option data Option value type IP_TTL unsigned char TCP_MAXSEG int TCP_NODELAY int Oor1 Meaning Successful set of option An error occurred The socket descriptor is invalid One of the parameters is invalid The option is unknown at the level indicated Document Version 1 61 5 19 2011 273 Function Specifications get_status Get Serial Port Status Syntax include lt ctools h gt struct pstatus get_status FILE stream struct pstatus status Description The get_status function returns serial port error counters I O lines status and I O driver buffer information for stream If port is not a valid serial port the function has no effect status must point to a valid serial port status structure pstatus The get_status function copies the serial port status into the structure pointed to by status and returns a pointer to the structure settings Refer to the Overview of Functions section for detailed information on serial ports See Also clear_errors Example This program displays the framing and parity errors for com1 include lt ctools h gt int main void STLUCL pstatuyus status get_status coml amp status fprintf coml Framing d r n status framing fprintf com1 Parity d r n status parity Document Version 1 61 5 19 2011 274 Function Specifications getStatusBit Read Bits in Controller Status Code
317. fications hartPackString Convert String to HART Packed String Syntax include lt ctools h gt void hartPackString CHAR pPackedString const CHAR pString UINT16 sizePackedString Description This function stores an ASCII string into a HART packed ASCII string The function has three parameters a pointer to a packed array a pointer to an unpacked array and the size of the packed array The packed array needs to be a multiple of three in size The unpacked array needs to be a multiple of four in size It should be padded with spaces at the end if the string is not long enough The function has no return value See Also hartUnpackString Document Version 1 61 5 19 2011 297 Function Specifications hartUnpackString Convert HART Packed String to String Syntax include lt ctools h gt void hartUnpackString CHAR pString const CHAR pPackedString UINT16 sizePackedString Description This function unpacks a HART packed ASCII string into a normal ASCII string The function has three parameters a pointer to an unpacked array a pointer to a packed array and the size of the packed array The packed array needs to be a multiple of three in size The unpacked array needs to be a multiple of four in size The function has no return value See Also hartPackString Document Version 1 61 5 19 2011 298 Function Specifications htonl Syntax include lt ctools h gt unsigned long ht
318. fig fields 5 dLogConfig typesOfFields 0 DLV_UINT16 dLogConfig typesOfFields 1 DLV_INT32 dLogConfig typesOfFields 2 DLV_DOUBLE Document Version 1 61 5 19 2011 134 Function Specifications dLogConfig typesOfFields 3 DLV_FLOAT dLogConfig typesOfFields 4 DLV_FLOAT datalogCreate logID amp dLogConfig else could not delete log else Could not read settings Document Version 1 61 5 19 2011 135 Function Specifications datalogPurge Purge Data Log Function Syntax include lt ctools h gt BOOLEAN datalogPurge UINT16 ogID BOOLEAN purgeAll UINT32 sequenceNumber Description This function removes records from a data log The function can remove all the records or a group of records starting with the oldest in the log The function has three parameters og D specifies the data log The valid range is O to 15 If purgeAll is TRUE all records are removed otherwise the oldest records are removed sequenceNumber specifies the sequence number of the most recent record to remove All records up to and including this record are removed This parameter is ignored if purgeAll is TRUE The function returns TRUE if the operation succeeds The function returns FALSE if the log ID is invalid if the log has not been created or if the sequence number cannot be found in the log Notes Purging the oldest records in the log is usually
319. following functions that use stdout do not work printf putc getc Use the replacement functions listed below Replaced with iprint Task Creation Function The task priorities have changed with the SCADAPack 350 and 4203 There are now 255 priority levels and the highest priority task has a priority of 0 Existing calls to create_task will need to be modified to account for a lower number being a higher priority The table below contains the recommended priority values to use when porting Priority Description Equivalent Priority Priority Value for Value for SCADAPack SCADAPack 350 and 4203 Higher Prioriy _ J eo e cc Lower Priory Document Version 1 61 5 19 2011 682 Porting Existing C Tools Applications Exit Handler Function The argument used for application type in existing calls to create_task needs to be replaced with the global variable applicationGroup The operating system assigns a unique value to applicationGroup when it is defined in appStart cpp Please see the documentation for create_task in the Function Specifications section for more details The argument used to specify the exit handler function in existing calls to installExitHandler must be cast to the type FUNCPTR Please see the documentation for installExitHandler in the Function Specifications section for more details Program Status Functions The functions getProgramStatus and setProgramStatus have changed synta
320. function when creating a new Register Assignment Duplicate or overlapping register assignments are not checked for by this function Overlapping register assignments may result in unpredictable I O activity To obtain error checking that avoids invalid register assignments such as these use the Telepace Register Assignment dialog to build the Register Assignment Then save the Register Assignment in a Ladder Logic file e g filename lad and download it with the C program or transfer the Register Assignment to the C program using the clearRegAssignment and addRegAssignmentEx functions To save the Register Assignment with the controller settings in flash memory so that it is loaded on controller reset call flasnSettingsSave as shown in the example below The IO_SYSTEM resource needs to be requested before calling this function See Also addRegAssignment clearRegAssignment Example include lt ctools h gt int main void UINT16 parameters 16 request resource IO SYSTEM Create the Register Assignment clearRegAssignment add a 5606 module parameters 0 0 0 to 5 V parameters 1 0 0 to 5 V parameters 2 0 0 to 5 V parameters 3 0 0 to5 V parameters 4 3 4 to 20 mA parameters 5 3 4 to 20 mA parameters 6 3 4 to 20 mA parameters 7 3 4 to 20 mA parameters 8 0 3 Hz input filter parameters 9 0 60 Hz scan frequency parameter
321. g The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified floating point va ue is written to the variable If the variable is not found or if the IEC 61131 1 Symbols Status is invalid nothing is done and FALSE is returned The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the setdbase function The lO_SYSTEM system resource needs to be requested before calling this function Example This program writes the value 25 607 to the real variable named Flowrate include lt ctools h gt int main void BOOLEAN status request_resource IO SYSTEM status writeRealVariable Flowrate 25 607 release resource IO SYSTEM Document Version 1 61 5 19 2011 565 Function Specifications writeMsgVariable Write to IEC 61131 1 Messa
322. ge Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN writeMsgVariable UCHAR varName UCHAR msg Description This function writes to the specified message variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified string is written to the message variable If the variable is not found or if the IEC 61131 1 Symbols Status is invalid nothing is done and FALSE is returned The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum The pointer msg must point to a character string large enough to hold the maximum length declared for the specified message variable plus two length bytes and a null termination byte i e max declared length 3 When writing to the message variable all bytes are copied except the first byte max length byte and the last byte null termination byte IEC 61131 1 message variables have the following format Byte Description Location aa length as declared in IEC 61131 1 a ey 1 to 255 Current Length location of first null byte 0 to maximum length First message data byte a byte in message buffer max 2 Null termination byte Terminates a message having the maximum length
323. ger Default value is 250 seconds TCP protocols only Not used by UDP protocols e _serverEnabled is the enable server control flag IP_PROTOCOL_TYPE IP_SETTINGS The IP_PROTOCOL_TYPE enumerated type defines TCP IP protocols supported by the SCADAPack 350 typedef enum ipProtocol t PP_None 0 IPP_ModbustTcp IPP_ModbusRtuOverUdp IPP ModbusAsciiOverUdp IPP _DnpOverTcp IPP_DnpOverUdp IP_PROTOCOL TYPE e The IP Settings structure defines IP settings for a communication interface installed on the TCP IP stack typedef struct st_IPSettings IP CONFIG MODE ipConfigMode UINT32 ipAddress 4 UINT32 gateway 4 UINT32 netMask UCHAR ipVersion IP SETTINGS Document Version 1 61 5 19 2011 614 Structures and Types ledControl_tag e ipConfigMode are the IP configuration options See the IP_CONFIG_MODE enumeration for values supported e ipAddress is the IP address Only the first 32 bit value in this array is supported and contains IP address in form of 32 bit unsigned integer For example IP address 172 016 017 018 will be represented with following 32 bit unsigned number 172 16x256 17x256x256 18x256x256x256 303108268 e gateway is the network gateway Only the first 32 bits are supported e netMask is the subnet mask e ipVersion is the IP version Only the value 4 is supported for IP version 4 The ledControl_tag structure defines LED power control parameters str
324. global variable A primaryVariable should be declared for each HART I O module in use A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid Notes The HART_DEVICE structure needs to be initialized using hartCommandO or hartCommand11 The function returns immediately after the command is sent The calling program needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command The code field of the HART_VARIABLE structure not changed Command 1 does not return a variable code See Also hartCommana2 hartStatus hartSetConfiguration Document Version 1 61 5 19 2011 286 Function Specifications hartCommand2 Read Primary Variable Current and Percent of Range Syntax include lt ctools h gt BOOLEAN hartCommand2 UINT16 module HART DEVICE const device HART VARIABLE pvCurrent HART VARIABLE pvPercent Description This function reads the primary variable PV as current and percent of range of a HART device using command 2 The function has four parameters the module number of the 5904 module 0 to 3
325. gt struct SFTranslationStatus checkSFTranslationT able void Description The checkSFTranslationT able function checks all entries in the address translation table for validity It detects the following errors The function returns a SFTranslationStatus structure Refer to the Structures and Types section for a description of the fields in the SFTrans ationStatus structure The code field of the structure is set to one of the following If there is an error the index field is set to the location of the translation that is not valid SF_VALID All translations are valid SF_NO_TRANSLATION The entry defines re transmission of the same message on the same port SF_PORT_OUT_OF_RANG One or both of the interfaces is not valid E SF_STATION_OUT_OF_R One or both of the stations is not valid ANGE SF_ALREADY_DEFINED The translation already exists in the table SF_INVALID_FORWARDIN The forwarding IP address is invalid G_IP Notes The TeleBUS Protocols User Manual describes store and forward messaging mode See Also clearSFTranslationT able Example See the example for the setSFTranslationEx function Document Version 1 61 5 19 2011 108 Function Specifications clearAllForcing Clear All Forcing Telepace firmware only Syntax include lt ctools h gt void clearAllForcing void Description The clearAllForcing function removes all forcing conditions from all I O database registers The IO_SYS
326. gt include nvMemory h define CHAR RECEIVED 11 void signal serial INT32 port INT32 character int main void INT32 character struct prot settings protocolSettings disable protocol get_protocol com2 amp protocolSettings protocolSettings type NO PROTOCOL request resource IO SYSTEM set_protocol com2 amp protocolSettings release resource IO SYSTEM Enable character handler install handler com2 BOOLEAN INT32 INT32 signal serial while TRUE if poll event CHAR RECEIVED character fgetc com2 Document Version 1 61 5 19 2011 453 Function Specifications m if character EOF clear overflow error flag to re enable com1 clearerr coml fputs character com2 fputc character com2 fputs r n com2 Allow other tasks to execute release processor void signal serial INT32 port INT32 character interrupt signal event CHAR RECEIVED Document Version 1 61 5 19 2011 454 Function Specifications poll_ message Test for Received Message Syntax include lt ctools h gt envelope poll message void Description The poll_message function tests if a message has been received by the current task The poll_message function returns a pointer to an envelope if a message has been received It returns NULL if no me
327. gt variablel pNvMemory gt arrayl 0 pNvMemory gt table 0 index file2 cpp include ctools h include nvMemory h void functionl void Document Version 1 61 5 19 2011 41 C Program Development pNvMemory gt variable2 t nvMemory h nvMemory h Global definitions for user variables that need to be non volatile Copyright 2006 Control Microsystems Inc x7 Prevent multiple inclusions ifndef NVMEMORY H define NVMEMORY H ifdef cplusplus extern C endif if BRR OR SASS RAS Shae Se aa Se Saat Se Sea CR ee See ease Sea e ee Include files J1 cake a aa ae lnc e ca laa aaa oleae include ctools h Add fields to this global structure for variables used in your application file s that need to be non volatile Include nvMemory h in all files that use the variable pNvMemory to access NV memory typedef struct s_nvMemory UCHAR dummyVariable Add fields here for variables used in your application file s that need to be non volatile Non volatile variables required by main cpp UINT32 variablel UCHAR arrayl 20 struct sample table 10 Non volatile variables required by file2 cpp float variable2 NV_MEMORY Pointer to static non volatile data Document Version 1 61 5 19 2011 42 C Program Development extern NV_ MEMORY pNvMemory ifdef cplusplus endif endif NVMEMORY H
328. guide describes the steps in porting an application Copy SCADAPack C Application Framework Begin by making a copy of the SCADAPack C application framework using the IEC 61131 1 sample application or the Telepace sample application By default the samples are installed at C Program Files Control Microsystems CTools Controller Framework Applications Make a copy of one of the following directories e C Program Files Control Microsystems CTools Controller Framework Applications Telepace e C Program Files Control Microsystems CTools Controller Framework Applications IEC 61131 1 Changes to appstart cpp Instead of appSettings src used in SCADAPack 32 C applications the new appstart cpp assigns the stack size as well as the main task priority Task priorities are discussed under changes to the function create_task The heap size is no longer configurable The C application has access to the entire system heap Open the sample appstart cpp to review these application settings Priority of the task main Priority 100 is recommended for a continuously running task UINT32 mainPriority 100 Document Version 1 61 5 19 2011 672 Porting Existing C Tools Applications Stack space allocated to the task main Note that at least 5 stack blocks are needed to call fprintf UINT32 mainStack 5 Application group assigned to the task main A unique value is assigned by the system to the application
329. guration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetCl1 6Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 212 Function Specifications dnpSaveCl32Config Save DNP 32 Bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveCI32Config UINT32 point dnpCounterInput pCounterInput Description The dnpSaveCl32Config function sets the configuration of a DNP 32 bit counter input point The function has two parameters the point number and a pointer to a counter input point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetCl32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 213 Function Specifications dnpSaveConfiguration Save DNP Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveConfiguration dnpConfiguration pConfiguration Description The dnpSaveConfiguration function sets the DNP configuration The fun
330. h 1 return value and with ETIMEDOUT as the specific socket error The TCP protocols optionally keep sockets warm by forcing transmissions roughly every two hours in the absence of other activity An error is then indicated if no response can be elicited on an otherwise idle connection for an extended period for instance 5 minutes SOCK_DGRAM or SOCK_RAW sockets allow datagrams to be sent to correspondents named in sendto calls Datagrams are generally received with recvfrom which returns the next datagram with its return address The operation of sockets is controlled by socket level options These options are defined in the file lt ctools h gt setsockopt and getsockopt are used to set and get options respectively Parameters family The protocol family to use for this socket currently only PF_INET is used type The type of socket protocol The layer 4 protocol to use for this socket Family Type Protocol Actual protocol PF_INET SOCK_DGRAM IPPROTO_UDP UDP PF_INET SOCK_STREAM IPPROTO_TCP TCP PF_INET SOCK_RAW IPPROTO_ICMP ICMP PF_INET SOCK_RAW IPRPTOTO_IGMP IGMP Returns New Socket Descriptor or 1 on error If an error occurred the socket error can be retrieved by calling getErrorCode socketDescriptor socket will fail if EMFILE No more sockets are available ENOBUFS There was insufficient user memory available to complete the operation EPROTONOSUPPORT The protocol type or the specified protocol is not supported w
331. h or startTimedEvent instead Function interval read_timer_info runTimers settimer timer Option Switch Function The following C Tools function is not supported optionSwitch IP Functions The following C Tools functions are not supported Document Version 1 61 5 19 2011 677 Porting Existing C Tools Applications Function tfGetOobDataOftset tfGetPppDnslpAddress tfGetPppPeerlpAddress tfGetSendCompltBytes tfiGetWaitingBytes tfGetZeroCopyBuffer tflnetToAscii tfloctl tfPingClose tfPingGetStatistics tfPingOpenStart tfPppSetOption tfRead tfRegisterSocketCB tfRegisterSocketCBParam tfResetConnection tfSendTolnterface tfSetPppPeerlpAddress tfSetTreckOptions tfSocketArrayWalk tfUseDialer tfWrite tfZeroCopyRecv tfZeroCopyRecvFrom tfZeroCopySend tfZeroCopySendTo writev PPP Functions The following C Tools PPP functions are not supported Function pppGetlnterfaceHandle pppReadSettings pppReadUserTableEntry pppReadUserTableSize pppWriteSettings pppWriteUserTableEntry pppWriteUserTableSize Document Version 1 61 5 19 2011 678 Porting Existing C Tools Applications Porting SCADAPack C Applications to the SCADAPack 350 and 4203 Porting Existing C Tools Applications Existing SCADAPack C applications are highly compatible with the SCADAPack C Tools However changes are necessary The following guide describes the steps in porting an application Copy SCADAPack C Ap
332. h the Microtec C compiler report errors using the global variable errno The error code in this variable may be written over by another task before it can be used Document Version 1 61 5 19 2011 485 Function Specifications request_resource Obtain Control of a Resource Syntax include lt ctools h gt void request _resource UINT32 resource Description The request_resource function obtains control of the resource specified by resource lf the resource is in use the task is blocked until it is available Notes Use the request_resource function to control access to non sharable resources Refer to the Real Time Operating System section for more information on resources See Also release_resource Example This code fragment obtains the dynamic memory resource allocates some memory and releases the resource include lt ctools h gt void task void unsigned ptr code here request resource DYNAMIC MEMORY ptr unsigned malloc size _t 100 release resource DYNAMIC MEMORY more code here Document Version 1 61 5 19 2011 486 Function Specifications resetAllIABSlaves Erase All DF1 Slave Responses Syntax include lt ctools h gt UINT16 resetAllABSlaves FILE stream Description The resetAllABSlaves function is used to send a protocol message to all slaves communicating on the specified port to erase all responses not yet polled s
333. haracter x extern C add prototypes here This program displays all characters received om coml using an installed handler to signal the reception of a character int main void INT32 port 1 INT32 character struct prot settings protocolSettings disable Protocol get_protocol com2 amp protocolSettings protocolSettings type NO PROTOCOL Document Version 1 61 5 19 2011 650 Example Programs request resource IO SYSTEM set_protocol com2 amp protocolSettings release resource IO SYSTEM Enable character handler install handler com2 BOOLEAN INT32 INT32 signal serial Print each character as it is received while TRUE wait event CHAR RECEIVED character fgetc com2 if character EOF clear overflow error flag to re enable coml clearerr coml fputs character com2 fputc character com2 fputs r n com2 release processor to other priority 1 tasks release _ processor Rosas e ae eS Le a ee eee ee eee signal serial This routine signals an event when a character is received If there is an error the character is ignored Af void signal serial INT32 port INT32 character interrupt signal event CHAR RECEIVED Install Clock Handler Example This program demonstrates how to call a function at a specific time of day include lt
334. he function returns e DLOGS_SUCCESS if all data logs were deleted e DLOGS FAILURE if all data logs could not be deleted Description This function deletes all data logs The memory for the logs is freed The data log IDs are marked as invalid The data log server will not collect further records Directory files are deleted if they are accessible This might be not the case if data log files were written to removable media The data log names are removed from the master log files Data Log files are not deleted If a log was created with a path the created directory still exists after the log is deleted Document Version 1 61 5 19 2011 152 Function Specifications dlogFlush Flush data log buffer contents to log file Syntax include lt ctools h gt dlogStatus dlogFlush UINT32 dlogID Parameters The function has these parameters e dlogID is the ID of the data log The function returns e DLOGS_SUCCESS if the data log was flushed This indicates that as much data was flushed as was possible to be flushed under current conditions e DLOGS_BADID if the data log ID is invalid e DLOGS FAILURE if existing data cannot be flushed Description A dlogWrite call writes a data log record to a data log buffer This buffer is written regularly to the log file by the data log server The dlogFlush function explicitly flushes data log buffer contents to the log file The function flushes all or part of the buffer to the fi
335. he port Not calling modemAbort or modemAbortAll in the task exit handler may result in the port being unavailable to any programs until the controller is reset The modem connection or initialization is automatically terminated when IEC 61131 1 stops the C application and when the controller is rebooted Reservation IDs returned by the modemDial and modemInit functions on this port are invalid after calling modemAbort See Also modemAbortAll modemDial Example Refer to the Examples in the Functions Overview section Document Version 1 61 5 19 2011 417 Function Specifications modemAbortAll Unconditionally Terminate All Dial up Connections Syntax include lt ctools h gt void modemAbortAll void Description The modemAbortAll function unconditionally terminates all dial up connections connections in progress or modem initializations started by the C application The connections or initializations are terminated only if they were started from a C application Connections made from a Ladder Logic application and answered calls are not terminated This function can be used in a task exit handler Notes A pause of a few seconds is required between terminating a connection and initiating a new call This pause allows the external modem time to hang up Use this function in a task exit handler to clean up any open dial up connections or modem initializations If executing end_task from another task ends a t
336. he specified integer variable writeRealVariable Writes to the specified real variable writeMsgVariable Writes to the specified message variable writeTimerVariable Writes to the specified timer variable HART Communication The HART protocol is a field bus protocol for communication with smart transmitters The HART protocol driver provides communication between SCADAPack controllers and HART devices The protocol driver uses the model 5904 HART modem for communication Four HART modem modules are supported per controller The driver allows HART transmitters to be used with C application programs and with Realflo The driver can read data from HART devices HART Command Functions The ctools h file defines the following HART command related functions Refer to the Function Specification section for details on each function listed hartlO Reads data from the 5904 interface module processes HART responses processes HART commands and writes commands and configuration data to the 5904 interface module Document Version 1 61 5 19 2011 84 Overview of Programming Functions hartCommand hartCommand0O hartCommand1 hartCommand2 hartCommand3 hartCommand11 hartCommand33 hartStatus hartGetConfiguration hartSetConfiguration hartPackString hartUnpackString HART Command Macros send a HART command string and specify a function to handle the response read unique identifier using short address algorithm read primar
337. he structure for an explanation of the parameters The function returns TRUE if the settings were changed It returns FALSE if the stream is not valid or if the protocol does not start To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Notes The IO_SYSTEM resource needs to be requested before calling this function Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it Add a call to modemNotification when writing a custom protocol Extended addressing and the Enron Modbus station are available on the Modbus RTU and Modbus ASCII protocols only See the TeleBUS Protocols User Manual for details Example This code fragment sets protocol parameters for the com2 serial port include lt ctools h gt PROTOCOL SETTINGS EX settings settings type MODBUS_RTU Document Version 1 61 5 19 2011 528 Function Specifications settings station settings priority settings SFMessaging settings mode settings enronEnabled settings enronStation request _resourc IO_SYS7 a 1 250 FALSE AM standard TRUE 4 EM setProtocolSettingsEx com2 amp settings release resourc I0_SYS1 p EM Document V
338. he task sending the message This field is specified automatically by the send_message function The receiving task may read this field to determine the source of the message e destination is the task ID of the task to receive the message It must be specified before calling the send_message function e type specifies the type of data in the data field It may be MSG_DATA MSG_POINTER or any other value defined by the application program This field is not required e data is the message data The field may contain a datum or pointer The application program determines the use of this field The HART_COMMAND type is a structure containing a command to be sent to a HART slave device The command field contains the HART command number The length field contains the length of the data string to be transmitted the byte count in HART documentation The data field contains the data to be sent to the slave typedef struct hartCommand_t UINT16 command UINT16 length CHAR data DATA SIZE b HART COMMAND e command is the HART command number e length is the number of characters in the data string e data DATA_SIZE is the data field for the command The HART_DEVICE type is a structure containing information about the HART device The information is read from the device using command 0 or command 11 The fields are identical to those read by the commands Refer to the command documentation for more information typedef
339. hen an I O request for the module is processed The function has two parameters the module address and the data to be written Data are read from the 16 bit data value and written to the I O table The valid range for moduleAddress is 0 to 15 The function returns TRUE if the data was written The function returns FALSE if the module address is invalid Document Version 1 61 5 19 2011 392 Function Specifications ioWriteDout32 Write to 32 Digital Outputs Syntax include lt ctools h gt BOOLEAN ioWriteDout32 UINT16 moduleAddress UINT32 data Description This function writes data to the I O tables for the 32 point digital output module at the specified module address Data are written to the module when an I O request for the module is processed moduleAddress is the address of the digital output module The valid range is 0 to 15 data is the output data to be written Data are written to the I O table The function returns TRUE if the data was written The function returns FALSE if the module address is invalid See Also Example This program turns ON all 32 digital outputs of a 32 point Digital Output Module at module address 0 include lt ctools h gt int main void Write data to digital output module ioWriteDout32 0 OxFFFFFFFF ioRequest MT Dout32 0 Document Version 1 61 5 19 2011 393 Function Specifications ioWriteDout8 Write Data to 8 Point Digital Ou
340. hen more data arrives or and when out ofband data arrives Parameters socketDescriptor The socket descriptor to receive data from bufferPtr The buffer to put the received data into bufferLength The length of the buffer area that bufferPtr points to flags See Below fromPtr The socket the data is or to be received from fromLengthPtr The length of the data area the fromPtr points to then upon return the actual length of the from data The flags parameter is formed by ORing one or more of the following MSG_DONTWAIT Don t wait for data but rather return immediately MSG_PEEK Peek at the data present on the socket the data is returned but not consumed so that a subsequent receive operation will see the same data Document Version 1 61 5 19 2011 478 Function Specifications Returns gt 0 0 1 recvfrom will fail if EBADF EINVAL EMSGSIZE EPROTOTYPE ENOBUFS EWOULDBLOCK Number of bytes actually received from the socket EOF An error occurred The socket descriptor is invalid One of the parameters is invalid The socket requires that message be received atomically and bufferLength was too small TCP protocol requires usage of recv not recvfrom There was insufficient user memory available to comp lete the operation The socket is marked as non blocking and no data is available to be read Document Version 1 61 5 19 2011 479 Function Specifications registerBulkDe
341. hods This is not an application specific program and it is presented as a programming example only Control Microsystems assumes no liability for the use or application of this example program or any portion thereof SCADAPack 350 C Application Main Program Copyright c 2009 Control Microsystems Inc DESCRIPTION The following program demonstrates how to configure data log for data logging into the external FLUSH memory This program is doing the following adding register assignment for SCADAPack 350 configure data for logging thr values per record date time AIN1 raw value and AIN1 scaled value 0 to 100 and then creates the log use DIN1 to suspend DIN1 OFF or resume DIN1 ON data loging toggling FORCE LED every second as indication that data logging is active loging data every 5 seconds Date 01 APR 09 Name Goran Babic Descr File Example created FE KK include ctools h include nvMemory h extern C Document Version 1 61 5 19 2011 636 Example Programs add prototypes here typedef struct dataRecord dlogCMITime valuel INT16 value2 float value3 dlogRecord R KKK KK KK KK OK main This routine is the main application loop FE KK I int main void SUCCESS char statusString FATLURE INPROGRESS EXISTS DIFFERENT INVALID NOMEMORY BA
342. icates the function code in the message was understood but that the command referenced an address that is not valid The Modbus protocol will return an Illegal Data Address exception response e ILLEGAL_DATA_VALUE indicates the function code in the message was understood but that the command included data that is not valid The Modbus protocol will return an Illegal Data Address exception response e FUNCTION _NOT_HANDLED must be returned by the function handler if the function was not handled If no installed handler can process the function then an ILLEGAL_FUNCTION exception response will be sent Function Codes Used The following function codes are currently used by the TeleBUS Modbus compatible protocol All other function codes are available for use For maximum compatibility with other Modbus and Modbus compatible devices it is recommended that codes in the user defined function code range be used first 6 Modbus standard Write a single holding register 86 TeleBUS extension Used by Telepace 68 TeleBUS extension Used by Telepace 85 TeleBUS extension Used by Telepace Notes One handler function is used for all serial ports Only one port will be active at any time Therefore the function does not have to be re entrant The handler function is called from the Modbus protocol task This task may pre empt the execution of another task If there are shared resources the handler function must request and rel
343. ice could not be selected Document Version 1 61 5 19 2011 626 Structures and Types routingTable The routingTable structure type describes an entry in the DNP Routing Table This structure can be used with IP routing table entries but it cannot set the IP address Use the dnpRoutingTableEx structure instead The DNP Routing Table is a list of routes which are maintained in ascending order of DNP addresses typedef struct RoutingTable type SF_TRANSLATION UINT16 address station address UINT16 comPort com port interface UINT16 retries number of retries UINT16 timeout timeout in milliseconds routingTable address is the DNP station address of the destination station comPort specifies the communications port interface Allowed values are 1 serial port com1 2 serial port com2 3 serial port com3 4 serial port com4 103 DNP over TCP using LAN port 104 DNP over UDP using LAN port retries is the number of times the data link layer will retry the message in the event of a failure timeout is the timeout in milliseconds The SF_TRANSLATION structure contains Store and Forward Messaging translation information This is used to define an address and port translation typedef struct st_SFTranslationMTcp type COM_INTERFACE slaveInterface slave interface typ UINT16 slaveStation slave station address COM_INTERFACE forwardInterface forwarding interface
344. id G_IP Notes The TeleBUS Protocols User Manual describes the store and forward messaging mode Writing a translation with both stations set to station 65535 can clear a translation in the table Station 65535 is not a valid station Document Version 1 61 5 19 2011 530 Function Specifications The Modbus protocol type and communication parameters may differ between serial ports The store and forward messaging will translate the protocol messages Translations describe the communication path of the master command e g the slave interface which receives the command and the forwarding interface to forward the command The response to the command is automatically returned to master through the same communication path in reverse Additional entries in the Store and Forward Table are not needed to describe the response path The IO_SYSTEM resource needs to be requested before calling this function To save the Store and Forward Table with the controller settings in flash memory so that it is loaded on controller reset call flashSettingsSave as shown below save Store amp Forward table with controller settings request _resource FLASH MEMORY flashSettingsSave CS_ RUN release resource FLASH MEMORY Translations may involve any combination of interfaces The interfaces may be running a Serial Modbus or Modbus IP protocol Slave Interface Serial Modbus Interface Serial Modbus Int
345. ider Electric software or approved software with our hardware products may result in injury harm or improper operating results Failure to observe this information can result in injury or equipment damage 2010 Schneider Electric All rights reserved Document Version 1 61 5 19 2011 Table of Contents Safety IMPONMAUOM sisscccsieccccvcsccicccsiccivescriccticveccvecvedccticveccvercvecede 14 Abo t The BOOK sicracsais aces barsidacbateticebaiedesbateidncoannidentaneatanausGieesaine 17 7 ts WG bs 19 o PRE EA OP RR PRES A TEETE ORE PEERS WEEE Re SORTED TOP OPE PEELS OO 17 OV OIVICW viscid ccvascuseccucedincvincvands iccusecedadsisdvastvesuni ceveadvesave sevexeveeanacass 18 Getting Started eseon eeto aa aa ea 19 SCADAPack C Tools Installation 0 0 cccccccccceccscesceeeeeeeceseseseaeaeeeeeeeeeeseeananeees 19 Program Development Tutorial ccceccccceceeeeeeeeeeneceeeeeeeseeeaeeeeeeeeesensnaeeeeess 20 C Program Development cccccccccsseseseeeeeeeeeeeeeeeeeseeeeeeeeeees 32 ProgramArchit cture a tcc c a ae a aaa aaa aaa aai a medi acto aaa a iaaa 32 GNU Compiler OponS sanra reei EAEE E E EAEE a EE 43 Application Development cccccceeceeeeeeceeceeeeeeeeeeeanaeceeeeeeesenaaeaeseeeeeeeeennaaeeeeees 44 Real Time Operating System ssssseeeeeeeeeeeeeeeeeseeeeeeeeeeeeeeneees 45 TaskiManagem ent reirs En AN AENEA tive titrivetatasiv nteivite EE 45 Resource Management istrie eraann ui t
346. ieeteatieeetidetventasidetaaere liste Manet 46 Inter task COMMUNICATION a cece eee eee aa E a aa a aia 49 SKINN iieri o a Ea E E EE E EEA 49 Emor Reporting Hr eaer na An EA EEE AEE E AE TEE 50 RTOS Example Application Program ccccccesceceeeeesseeeeeneeceeeeeseeeeseaeeeeeeeeaees 51 Overview of Programming FUNCTIONS cccccceeeeeseseeeeeeeeeees 59 Controller Operation r seie awaits ata ea ate eine A alae 59 Controller O Hardware i a e a a a reai a A aiee 61 Serial Communications niaren ieee ae e e aa a a a a 70 Serial Communication Protocols cccccccccccceeeeececcseeeeeaeeeeceseeeesueaueeseeeseeeeeaneaeess 72 DNP Communication Protocol 0 ccccccceccccceesceeeececceeeeseaueeseeeeeueeauaeeeeeeeeenaeas 74 DF1 Communication Protocol ccccccccececceeeeseeeeececeeeeseeaueeeeseeeeeseaeaaeeseeeeseeaeas 78 TCP IP Communications cccccccc cece ccccceeeeeeecececeeeseaueeeeseeeeusuaueueeseeeeeeuaeaneeeeeeness 78 Vee 1013 mall ma 0 01010 78 Data Log to File aici aaa a AA E ie eet ee eaeenee 79 SoCKeIS AP e AE E ee ddan tan ciev ted bedadbadevestact beavedacwext beta bodewtac stich ase feduviaa owes 80 Modbus I O Database o ceccce cece ececce cece eececeseesceaueeseeeeeseuauaueuseeseseuseaueaseseeeesenaeas 81 Register ASSIQNIMON nerea aae ea a aaa a a a ara 83 IEC 61131 1 Variable Access Functions eceseeeeeesessneeererrserreresrrrrrerrseesrrnnns 84 Document Version 1 61 5 19 20
347. ifications e 1 6Hz e 2 11 Hz e 3 30 Hz minimum filter 5606 I O Module parameters 9 defines the scan frequency Valid values are e 0 60 Hz e 1 50Hz 5606 I O Module parameters 10 defines the analog output type Valid values are e 0 0 to 20 mA output e 1 4to 20 mA output 5607 I O Module parameters 0 to 7 define the analog input type for the corresponding input The remaining parameters are not used Valid values are e 0 0to5 V input e 1 0to 10 V input e 2 0 to 20 mA input e 3 4to 20 mA input 5607 I O Module parameters 8 defines the analog input filter Valid values are e O lt 3 Hz maximum filter e 1 6Hz e 2 11 Hz e 3 30 Hz minimum filter 5607 I O Module parameters 9 defines the scan frequency Valid values are e 0 60Hz e 1 50Hz 5607 I O Module parameters 10 defines the analog output type Valid values are e 0 0 to 20 mA output e 1 4to 20 mA output Notes Up to 150 modules may be added to the Register Assignment If the Register Assignment is full or if an incorrect value is specified for any argument this function returns FALSE otherwise TRUE is returned Document Version 1 61 5 19 2011 99 Function Specifications Output registers specified for certain CNFG type modules are initialized with the current parameter values when the module is added to the Register Assignment e g CNFG_realTimeClock Call clearRegAssignment first before using the addRegAssignmentEx
348. ified port stream specifies the serial port The function returns FALSE if the slave number is invalid or if the protocol currently installed on the specified serial port is not an DF1 Half Duplex protocol Otherwise it returns TRUE and the protocol command status is set to MM_SENT Notes See the Example in the Example Programs chapter under the section Master Message Example Using DF1 Protocol The pollABSlave function is used in the sample polling function poll_for_response shown in this example See Also resetAllABSlaves Example This program segment polls slave station 9 for a response communicating on the com2 serial port include lt ctools h gt pollABSlave com2 9 Document Version 1 61 5 19 2011 452 Function Specifications poll_ event Test for Event Occurrence Syntax include lt ctools h gt BOOLEAN poll event UINT32 event Description The poll_event function tests if an event has occurred The poll_event function returns TRUE and the event counter is decrements if the event has occurred Otherwise it returns FALSE The current task always continues to execute Notes Refer to the Real Time Operating System section for more information on events Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in primitiv h are not valid events for use in an application program Example This program is based on the Install Serial Port Handler Example include lt ctools h
349. ig Document Version 1 61 5 19 2011 210 Function Specifications dnpSaveBOConfig Save DNP Binary Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveBOConfig UINT16 point dnpBinaryOutput pBinaryOutput Description The dnpSaveBOConfig function sets the configuration of a DNP binary output point The function has two parameters the point number and a pointer to a binary output point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetBOConfig Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 211 Function Specifications dnpSaveCl16Config Save DNP 16 Bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveC1I16Config UINT16 point dnpCounterInput pCounterInput Description The dnpSaveCl16Config function sets the configuration of a DNP 16 bit counter input point The function has two parameters the point number and a pointer to a counter input point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the confi
350. iguration Document Version 1 61 5 19 2011 287 Function Specifications hartCommand3 Read Primary Variable Current and Dynamic Variables Syntax include lt ctools h gt BOOLEAN hartCommand3 UINT16 module HART DEVICE const device HART VARIABLE variables Description This function reads dynamic variables and primary variable current from a HART device using command 3 The function has three parameters the module number of the 5904 module 0 to 3 the device to be read and a pointer to an array of five HART_VARIABLE structures The variables array must be static modular or global variables An array of variables should be declared for each HART I O module in use A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space The variables array is updated when the response is received by the 5904 interface as follows Variables O primary variable current Variables 1 primary variable Variables 2 secondary variable Variables 3 tertiary variable Variables 4 fourth variable The function returns TRUE if the command was sent The function returns FALSE if the module number is invalid Notes The HART_DEVICE structure needs to be initialized using hartCommandO or hartCommand11 The function returns immediately after the command is sent The calling pr
351. ing and you can let the peer TCP know the offset of the current data to the last byte of out of band data So with TCP the out of band data byte s are not sent ahead of the data stream but the TCP protocol can notify the remote TCP ahead of time that some out of band data byte s exist What TCP does is mark the byte stream where urgent data ends and set the Urgent flag bit in the TCP header flag field as long as it is sending data before or up to the last byte of out of band data In your application you can send out of band data by calling the send function with the MSG_OOB flag All the bytes of data sent that way using send with the MSG_OOB flag are out of band data bytes If you call send several times with out of band data TCP will always keep track of where the last out of band byte of data is in the byte data stream and flag this byte as the last byte of urgent data To receive out of band data please see the recv section of this manual Parameters socketDescriptor The socket descriptor to use to send data bufferPtr The buffer to send bufferLength The length of the buffer to send flags See below The flags parameter is formed by ORing one or more of the following MSG_DONTWAIT Don t wait for data send to complete but rather return immediately MSG_OOB Send out of band data on sockets that support this notion The underlying protocol needs to also support out of band data Only SOCK_STREAM sockets create
352. ing the size of the buffer pointed to by option ValuePtr and modified on return to indicate the actual size of the value returned optionName and any specified options are passed un interpreted to the appropriate protocol module for interpretation The include file lt ctools h gt contains definitions for the options described below Options vary in format and name Most socket level options take an int for option ValuePtr SO_LINGER uses a struct linger parameter that specifies the desired state of the option and the linger interval see below struct linger is defined in lt ctools h gt struct linger contains the following members onoff on 1 off 0 _linger linger time in seconds The following options are recognized at the socket level SOL_SOCKET protocolLevel options SO_ACCEPTCONN Enable disable listening for connections listen turns on this option SO_DONTROUTE Enable disable routing bypass for outgoing messages Default 0 SO_KEEPALIVE Enable disable keep connections alive Default 0 disable SO_OOBINLINE Enable disable reception of out of band data in band Default is 0 Document Version 1 61 5 19 2011 270 Function Specifications SO_REUSEADDR Enable disable local address reuse Default 0 disable SO_RCVLOWAT The low water mark for receiving SO_SNDLOWAT The low water mark for sending SO_RCVBUF The buffer size for input Default is 8192 bytes SO_SNDBUF The buffer size for output Default is 8192 bytes
353. input module at the specified moduleAddress Buffered data are updated when an I O request for the module is processed The function has two parameters the module address and a reference to an array of eight INT16 variables If the moduleAddress is valid analog input data are copied to the array The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 346 Function Specifications ioReadAout2 Read Data From 2 point Analog Output Module Syntax include lt ctools h gt BOOLEAN ioReadAout2 UINT16 moduleAddress INT16 amp data 2 Description This function reads buffered data used for the 2 point analog output module at the specified module address Buffered data are written using the ioWriteAout2 function The function has two parameters the module address and a reference to an array of two INT16 variables If the moduleAddress is valid data are copied to the array The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 347 Function Specifications ioReadAout4 Read Data From 4 point Analog Output Module Syntax include lt ctools h gt BOOLEAN ioReadAout4 UINT16 moduleAddress INT16 amp data 4 Description This function reads buffered data used for the 4 poin
354. inputFilter BOOLEAN status BOOLEAN done main loop while TRUE read output data from I O table status ioRead55050utputs 5 inputType inputFilter print data if done fprintf coml status u inputType 0 Sd inputFilter d r n status inputType 0 inputFilter done TRUE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 332 Function Specifications ioRead5506Inputs Read 5506 Inputs Syntax include lt ctools h gt BOOLEAN ioRead5506Inputs UINT16 moduleAddress UCHAR amp dinData INT1L6 amp ainData 8 Description This function reads buffered data from the digital and analog inputs of a 5506 I O module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5506 module Valid values are 0 to 15 dinData is a reference to a UCHAR variable Digital data for the 8 internal inputs are written to this variable One bit in the variable represents each input point The 8 internal inputs indicate if the corresponding analog input value is over range ainData is a reference to an array of eight INT16 variables Analog data are written to this array The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5506Outputs ioWrite5506Outputs Example This program displays the
355. inputType inputFilter scanFrequency outputType print data if done fprintf coml status u Douts 0 to 7 X Aout 0 d r n status doutData 0 aoutData 0 done TRUE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 340 Function Specifications ioRead5607Inputs Read 5607 Inputs Syntax include lt ctools h gt BOOLEAN i0Read5607Inputs UINT16 moduleAddress UCHAR amp dinData 3 INT16 amp ainData 8 Description This function reads buffered data from the digital and analog inputs of a 5607 I O module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5607 module Valid values are 0 to 7 dinData is a reference to an array of three UCHAR variables Digital data for the 16 external and 8 internal inputs are written to this array One bit in the array represents each input point The 8 internal inputs indicate if the corresponding analog input value is over range ainData is a reference to an array of eight INT16 variables Analog data are written to this array The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5607 Outputs ioWrite5607Outputs Example This program displays the values of the first 8 digital inputs and the 5th analog input read from 5607 I O at address 5 include lt ctools
356. inputType selects the input type of AC or DC Valid values are e 0 DC e 1 AC scanFrequency selects the scan frequency setting Valid values are e 0 60Hz e 1 50 Hz See Also ioRead5414lnputs Document Version 1 61 5 19 2011 376 Function Specifications ioWrite5415Outputs Write 5415 module outputs Syntax include lt ctools h gt BOOLEAN ioWrite54150utputs UINT16 moduleAddress UCHAR amp doutData 2 Description This function writes to the I O table for the 12 output points of a 5415 relay output module Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5415 module Valid values are 0 to 15 doutData is a reference to an array of two UCHAR variables Digital data for the 12 outputs are read from this array One bit in the array represents each output point See Also ioRead54150utputs ioRead5415Inputs Example This Example turns on all the digital outputs on the 5415 I O module include lt ctools h gt include nvMemory h define MY EVENT 1 void main void UCHAR doutData 2 IO_ STATUS io_status BOOLEAN status main loop while TRUE write data to output tables for next scan doutData 0 OxFF doutData 1 Ox0F status ioWrite54150utputs 0 doutData add module scan to queue if ioRequest MT_54150utputs 0 Document Version 1 61 5 19 2011 377 Func
357. inted to by penv to the pool of free envelopes maintained by the operating system See Also allocate_envelope Example See the example for the allocate_envelope function Document Version 1 61 5 19 2011 148 Function Specifications dlogCreate Create a data log using the specified configuration Syntax include lt ctools h gt dlogStatus dlogCreate dlogConfiguration pConfiguration UINT32 dlogID Parameters The function has these parameters e pConfiguration is a pointer to a data log configuration structure containing the data log configuration See the description of the configuration structure for details on the parameters that can be configured in the data log e dlogID is a pointer to a variable where the data log ID will be written if the function is successful If the pointer is NULL the creation of the data log will fail and the function will return DLOGS_FAILURE The function returns e DLOGS_SUCCESS if the log could be created Valid dlogID returned as output parameter e DLOGS EXISTS if a log exists with same configuration parameters Valid dlogID returned as output parameter e DLOGS_DIFFERENT if a log with the same name exists with different parameters The dlogID is not valid e DLOGS_NOMEMORY if the log could not be created due to lack of memory The dlogID is not valid e DLOGS_INVALID if the configuration data is not valid The dlogID is not valid e DLOGS_FAILURE if an er
358. ion 1 61 5 19 2011 462 Function Specifications readBattery Read Lithium Battery Voltage Syntax include lt ctools h gt INT16 readBattery void Description The readBattery function returns the RAM backup battery voltage in millivolts The range is 0 to 5000 mV A normal reading is about 3600 mV Example include lt ctools h gt if readBattery lt 2500 fprintf coml Battery Voltage is low r n Document Version 1 61 5 19 2011 463 Function Specifications readinputVoltage Read Input Voltage Syntax include lt ctools h gt INT16 readInputVoltage void Description The readInputVoltage function returns the input supply voltage in millivolts The typical range is 9000 to 30000 mV Example include lt ctools h gt if readInputVoltage lt 9000 fprintf coml The input supply voltage is low r n Document Version 1 61 5 19 2011 464 Function Specifications readintVariable Read IEC 61131 1 Integer Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN readIntVariable UCHAR varName INT32 value Description This function returns the current value of the specified integer variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the variable
359. ion Specifications Example This program clears the force flag for register 40001 and sets the force flags for the 16 registers at linear address 302 i e registers 10737 to 10752 include lt ctools h gt int main void request resource IO SYSTEM setForceFlag MODBUS 40001 0 setForceFlag LINEAR 302 255 release resource IO SYSTEM Document Version 1 61 5 19 2011 517 Function Specifications setlOErroriIndication Set I O Module Error Indication Syntax include lt ctools h gt void setIOErrorIndication BOOLEAN state Description The setlOErrorindication function sets the I O module error indication to the specified state If set to TRUE the I O module communication status is reported in the controller status register and Status LED If set to FALSE the I O module communication status is not reported To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ PERMANENT release resource FLASH MEMORY Notes Refer to the 5203 4 System Manual SCADAPack 32 System Manual or SCADAPack 350 System Manual for further information on the Status LED and Status Output See Also getlOErrorIndication Document Version 1 61 5 19 2011 518 Function Specifications setOutputsInStop
360. ion requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the dbase function Document Version 1 61 5 19 2011 467 Function Specifications The lO_SYSTEM system resource needs to be requested before calling this function See Also readintVariable readRealVariable Example This program displays the contents of the message variable named msgData of maximum length 20 include lt ctools h gt int main void BOOLEAN status UCHAR msg 23 request resource IO SYSTEM status readMsgVariable msgData msg release resource IO SYSTEM fprintf coml status u max length d current length message s r n status msg 0 msg 1 msg 2 Document Version 1 61 5 19 2011 468 Function Specifications readRealVariable Read IEC 61131 1 Real Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN readRealVariable UCHAR varName float value Description This function returns the current value of the specified real i e floating point variable The v
361. ions get_port Get Serial Port Configuration Syntax include lt ctools h gt struct pconfig get_port FILE stream struct pconfig settings Description The get_port function gets the serial port configuration for the port If port is nota valid serial port the function has no effect The get_port function copies the serial port settings into the structure pointed to by settings and returns a pointer to the structure Notes Refer to the Overview of Functions section for detailed information on serial ports Refer to the Structure and Types section for a Description of the fields in the pconfig structure See Also set_port Example include lt ctools h gt int main void struct pconfig settings get_port coml amp settings fprintf coml Baud rate Sd r n settings baud fprintf coml Duplex sd r n settings duplex Document Version 1 61 5 19 2011 258 Function Specifications getPowerMode Get Current Power Mode Syntax include lt ctools h gt BOOLEAN getPowerMode UCHAR cpuPower UCHAR lan UCHAR usbHost Description The getPowerMode function places the current state of the CPU LAN USB peripheral port and USB host port in the passed parameters The following table lists the possible return values and their meaning PM_CPU_FULL The CPU is set to run at full speed PM_CPU_REDUCED The CPU is set to run at a reduced speed PM_CPU_SLEEP The CPU is set to sleep mo
362. ions ioNotification Add I O Notification Request Syntax include lt ctools h gt BOOLEAN ioNotification UINT16 eventNumber Description This function adds a Notification Request to the I O Controller request queue The specified event number is signaled when the notification request is processed The function has one argument an event number Valid events are numbered 0 to 31 The function returns TRUE if the request was added The function returns FALSE if there is no room in the request queue or if the event number is invalid Document Version 1 61 5 19 2011 315 Function Specifications ioRead4203DRinputs Read 4203 DR Inputs Syntax include lt ctools h gt BOOLEAN ioRead4203DRInputs UCHAR amp dinData INT16 amp ainData UINT32 amp cinData 2 Description This function reads buffered data from the digital and analog input of the 4203 DR I O Buffered data are updated when an I O request for the module is processed dinData is a reference to a UCHAR variable Digital data for the input is written to this array One bit in the array represents each input point ainData is a reference to a INT16 variables Analog data are written to this array cinData is a reference to two UINT32 variables Counter data is written to this array The function returns FALSE if the data was read from the internal table otherwise TRUE is returned See Also ioWrite4203DROutputs Example
363. ions such as malloc and alloc Document Version 1 61 5 19 2011 574 Macro Definitions EXTENDED_DIN_END Number of last extended digital input channel EXTENDED_DIN_START Number of first extended digital input channel EXTENDED _DOUT_END Number of last extended digital output channel EXTENDED _DOUT_START Number of first extended digital output channel Defntion GASFLOW Gas Flow calculation firmware option Defnion lIO_SYSTEM System resource for all I O hardware functions LAN ENABLED Enables LAN communication power consumption Document Version 1 61 5 19 2011 575 Macro Definitions LINEAR Specifies linear database addressing LOAD MULTIPLE REGISTER Modbus function code S LOAD_SINGLE_REGISTER Modbus function code LOW_POWER_MODE Reduces the operating speed of the controller reducing power consumption MAX_NUMBER_OF_FIELDS The maximum number of fields in a data log record MAX_NUMBER_OF_LOGS The maximum number of data logs MAX_PRIORITY The maximum task priority address code length address returned an address exception returned a function exception returned a value exception sent ORTED not supported received MM_SENT Master message status message was sent MODBUS Specifies Modbus database addressing MODBUS_ASCIl Specifies the Modbus ASCII protocol emulation for the serial port MODBUS_PARSER System resource Modbus protocol message parser MODBUS_RTU Specifies
364. irect standard I O streams setDTR Control RS232 port DTR signal set_port Set serial port communication parameters Serial Communication Structures The ctools h file defines the structures Serial Port Configuration Serial Port Status and Serial Port Characteristics for serial port configuration and information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Dial Up Modem Functions These library functions provide control of dial up modems They are used with external modems connected to a serial port An external modem normally connects to the RS 232 port with a DTE to DCE cable Consult the System Hardware Manual for your controller for details Refer to the Function Specification section for details on each function listed The dial up modem functions apply to the SCADAPack 350 controllers RS 232 ports modenlnit send initialization string to dial up modem modemlnitStatus read status of modem initialization operation modemlnitEnd terminate modem initialization operation Document Version 1 61 5 19 2011 71 Overview of Programming Functions modemDial connect with an external device using a dial up modem modemDialStatus read status of connection with external device using a dial up modem modemDialEnd terminate connection with external device using a dial up modem modemAbort unconditionally terminate connection with external device or modem initiali
365. it is called only when a debug build is made of the application By default a Release build of the application enables the watchdog and a Debug build of the application disables the watchdog The watchdog needs to be disabled in order to debug an application using the source level debugging e g stepping setting breakpoints tools provided by the Hitachi HDI and Emulator Calling the function with state set to TRUE enables the watchdog Calling the function with state set to FALSE disables the watchdog Document Version 1 61 5 19 2011 560 Function Specifications wd_manual Manual Watchdog Timer Mode Syntax include lt ctools h gt void wd_manual void Description The wd_manual function takes control of the watchdog timer Notes The application program needs to retrigger the watchdog timer at least every 0 5 seconds using the wd_pulse function to avoid a controller reset Refer to the Functions Overview section for more information See Also wd_enabled Example This program takes control of the watchdog timer for a critical section of code then returns it to the control of the operating system include lt ctools h gt int main void wd_manual wd_pulse code executing in less than 0 5 s wd _pulse code executing in less than 0 5 s wd_auto as much code as you wish Document Version 1 61 5 19 2011 561 Function Specifications wd_
366. ithin this family Document Version 1 61 5 19 2011 549 Function Specifications start_protocol Start Serial Protocol Syntax include lt ctools h gt INT16 start protocol FILE stream Description The start_protocol function enables a protocol on the specified serial port It returns TRUE if the protocol was enabled and FALSE if it was not The protocol settings of the specified serial port determine the protocol type enabled by this function This function should only be needed in the context of the startup function appstart See Also set_port get_port Document Version 1 61 5 19 2011 550 Function Specifications startup_task Identify Start Up Task Syntax include lt ctools h gt struct taskInfo_ tag startup task void Description The startup_task function returns the address of the system or application start up task Notes This function is used by the reset routine It is normally not used in an application program Document Version 1 61 5 19 2011 551 Function Specifications startTimedEvent Enable Signaling of a Regular Event Syntax include lt ctools h gt UINT16 startTimedEvent UINT16 event UINT16 interval Description The startTimedEvent function causes the specified event to be signaled at the specified interval interval is measured in multiples of 0 1 seconds The task that is to receive the events should use the wait_event or poll_event fun
367. ization of Dial up Modem Syntax include lt ctools h gt void modemInitEnd FILE port reserve id id enum DialError error Description The modemInitEnd function terminates a modem initialization in progress port specifies the serial port where the modem is installed id is the port reservation identifier returned by the modemInit function The function sets the variable pointed to by error If no error occurred DE_NoError is returned Any other value indicates an error Refer to the dialup h section for a complete Description of error codes Notes The serial port type must be set to RS232_MODEM Normally this function should be called once the modemiInitStatus function indicates the initialization is complete The reservation identifier is valid until the initialization is complete or terminated and another modem function or an incoming call takes control of the port The modemInitEnd function returns a DE_NotInControl error code if another modem function or incoming call is in control of the port Do not call this function in a task exit handler Use modemAbort instead Document Version 1 61 5 19 2011 426 Function Specifications modemInitStatus Return Status of Dial up Modem Initialization Syntax include lt ctools h gt void modemInitStatus FILE port reserve id id enum DialError error enum DialState state Description The modemIinitStatus function returns the statu
368. ke it ready to execute end_task Terminate a task and free the resources and envelopes allocated to it end_application Terminate application program type tasks This function is used by communication protocols to stop the application program prior to loading new code installExitHandler Specify a function that is called when a task is ended with the end_task or end_application functions getTaskinfo Return information about a task Task Management Structures The ctools h file defines the structure Task Information Structure for task management information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Resource Management The resource management functions arbitrate access to non sharable resources These resources include physical devices such as serial ports and software that is not re entrant Document Version 1 61 5 19 2011 46 Real Time Operating System The RTOS defines nine system resources which are used by components of the I O drivers memory allocation functions and communication protocols An application program may define other resources as required Take care not to duplicate any of the resource numbers declared in ctools h as system resources Resource Management Functions There are three RTOS functions for resource management Refer to the Function Specification section for details on each function listed request_resource Request acce
369. ks are waiting the resource is made available and the current task continues to run Notes Refer to the Real Time Operating System section for more information on resources See Also request_resource Example See the Example for the request_resource function Document Version 1 61 5 19 2011 483 Function Specifications removeModbusHandler Removes a User Defined Modbus Handler Syntax include lt ctools h gt BOOLEAN removeModbusHandler UINT16 handler UCHAR UINT16 UCHAR UINT16 Description The removeModbusHandler function allows user defined extensions to standard Modbus protocol to be removed This function specifies the previously installed function that is to be removed This function returns TRUE if the specified handler was removed and FALSE if the specified handler is not present Notes This function is used to remove a user defined extension to the standard Modbus protocol See Also installModbusHandler Document Version 1 61 5 19 2011 484 Function Specifications report_error Set Task Error Code Syntax include lt ctools h gt void report _error UINT32 error Description The report_error functions sets the error code for the current task to error An error code is maintained for each executing task Notes This function is used in sharable I O routines to return error codes to the task using the routine Some functions supplied wit
370. l otherwise an error code of EMSGSIZE is returned protocol specifies a particular protocol to be used with the socket Normally only a single protocol exists to support a particular socket type within a given protocol family However multiple protocols may exist in which case a particular protocol needs to be specified in this manner The protocol number to use is particular to the communication domain in which communication is to take place If the caller specifies a protocol then it will be packaged into a socket level option request and sent to the underlying protocol layers Sockets of type SOCK_STREAM are full duplex byte streams A stream socket needs to be in a connected state before any data may be sent or received on it A connection to another socket is created with connect on the client side On the server side the server needs to call listen and then accept Once connected data may be transferred using recv and send calls or some variant of the send and recv calls When a session has been completed a close of the socket should be performed The communications protocols used to implement a Document Version 1 61 5 19 2011 548 Function Specifications SOCK_STREAM ensure that data is not lost or duplicated If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time then the connection is considered broken and calls will indicate an error wit
371. lass3 3 configuration enableUnsolicitedOnStartup TRUE configuration sendUnsolicitedOnStartup FALSE configuration level2Compliance FALSE e ll 5 G Ea get_protocol com3 amp protocolSettings protocolSettings type DNP set_protocol com3 amp protocolSettings I a aaa al aka a aac am Configure Binary Output Points pane eS Seas Sea a ee eo a Sass for index 0 index lt configuration BO number index binaryOutput modbusAddressl 1 index binaryOutput modbusAddress2 1 index binaryOutput controlType NOT PAIRED dnpSaveBOConfig configuration BO startAddress index amp binaryOutput hips SaeSe Ree SSeS sae SSS aS Se Sage oa Se eee a ee eee Configure Binary Input Points 1 aia a a a a aa aaa AA for index 0 index lt configuration BI number index t binaryInput modbusAddress 10001 index binaryInput eventClass CLASS 1 dnpSaveBIConfig configuration BI startAddress index amp binaryInput Fanne i a a mE A Configure 16 Bit Analog Input Points pte aa Se Sa ea See Gaara ee eee ar RSR for index 0 index lt configuration AI16 number index Document Version 1 61 5 19 2011 643 Example Programs analogInput modbusAddress 30001 index analogInput eventClass CLASS 2 analogInput deadband 1 dnpSaveAI16Config configuration AI16 startAddress index amp analogInput if Pat see area
372. le See Example for Setdbase Handler Function Document Version 1 61 5 19 2011 306 Function Specifications installExitHandler Install Handler Called when Task Ends Syntax include lt ctools h gt BOOLEAN installExitHandler UINT32 taskID FUNCPTR function Description The installExitHandler function defines a function that is called when the task specified by task D is ended function specifies the handler function If function is NULL the handler is disabled Notes The exit handler function will be called when e the task is ended by the end_task or end_group function e the end_application function is executed and the function is an APPLICATION type function e the program is stopped from the IEC 61131 1 or Telepace program and the task is an APPLICATION type function e the program is erased by the IEC 61131 1 or Telepace program The exit handler function is not called if power to the controller is removed In this case all execution stops when power is removed The application program starts from the beginning when power is reapplied Do not call any RTOS functions from the exit handler Example See the Example for startTimedEvent Document Version 1 61 5 19 2011 307 Function Specifications installModbusHandler Install User Defined Modbus Handler Syntax include lt ctools h gt void installModbusHandler UINT16 handler UCHAR UINT16 UCHAR UINT16 Desc
373. le depending on the current file conditions and buffer contents If files are full logging is suspended or external media is removed the flush might not remove any records from the buffer If this is the case the function returns DLOGS_ FAILURE The file remains open after flushing To close a file in preparation for moving it or removing external media use the dlogSuspend function See Also dlogSuspend Document Version 1 61 5 19 2011 153 Function Specifications dlogGetStatus Return the auto transfer and media status information of a data log Syntax include lt ctools h gt dlogStatus dlogGetStatus UINT32 dlogID dlogTransferStatus transferStatus dlogMediaStatus mediaStatus BOOLEAN extMedialInUse Parameters The function has these parameters e dlogID is the ID of the data log e transferStatus is a pointer to memory where the transfer status is written to e mediaStatus is a pointer to memory where the media status is written to e extMedialnUse is a pointer to memory where it is written if the external media is in use or not The function returns e DLOGS_SUCCESS if status information was retrieved e DLOGS_BADID if the data log ID is invalid Description This function returns the transfer status media status and external media in use information of a particular data log The transfer status indicates the result or the progress of a recent triggered auto transfer to a removable
374. le readTimerVariable read_timer_info Setdbase Handler Function writeBoolVariable writelntVariable Document Version 1 61 5 19 2011 87 Function Specifications e writeMsgVariable e writeRealVariable e writeTimerVariable Document Version 1 61 5 19 2011 88 Function Specifications accept Syntax include lt ctools h gt int accept int socketDescriptor struct sockaddr addressPtr int addressLengthPtr Description The argument socketDescriptor is a socket that has been created with socket bound to an address with bind and that is listening for connections after a call to listen accept extracts the first connection on the queue of pending connections creates a new socket with the properties of socketDescriptor and allocates a new socket descriptor for the socket If no pending connections are present on the queue and the socket is not marked as non blocking accept blocks the caller until a connection is present If the socket is marked as non blocking and no pending connections are present on the queue accept returns an error as described below The accepted socket is used to send and recv data to and from the socket that it is connected to It is not used to accept more connections The original socket remains open for accepting further connections accept is used with connection based socket types currently with SOCK_STREAM Using select prior to calling accept It is possible
375. le Using Modbus Protocol This program sends a master message on com2 using the Modbus protocol then waits for a response from the slave The number of good and failed messages is printed to com1 poll c Polling program for Modbus slave wait _for response The wait for response function waits for a response to be received to a master message on the serial port specified by stream It returns when a response is received or when the period specified by time in tenths of a second expires Document Version 1 61 5 19 2011 659 Example Programs void wait for response UCHAR port unsigned time UINT32 startTime struct prot status status static unsigned long good bad startTime readStopwatch do Allow other tasks to execute release processor status get_protocol status port while readStopwatch startTime lt 100 time amp amp status command MM SENT if status command MM RECEIVED goodt else bad t fprintf coml Good 8lu Bad 8lu r good bad JR eeteeeceteasatseacse este se soe Veneers eee main The main function sets up serial ports then sends commands to a Modbus slave int main void struct prot_settings settings struct pconfig portset request resource IO SYSTEM disable protocol on serial port 1 settings type NO PROTOCOL settings station 1 settings priority 250 settings SFMessagi
376. le Using serialModbusMaster setABConfiguration Document Version 1 61 5 19 2011 506 Function Specifications Set DF1 Protocol Configuration Syntax include lt ctools h gt UINT16 setABConfiguration FILE stream struct ABConfiguration ABConfig Description The setABConfiguration function sets DF1 protocol configuration parameters stream specifies the serial port ABConfig references a DF1protocol configuration structure Refer to the Description of the ABConfiguration structure for an explanation of the fields The setABConfiguration function returns TRUE if the settings were changed It returns FALSE if stream does not point to a valid serial port See Also getABConfiguration Example This code fragment changes the maximum protected address to 7000 This is the maximum address accessible by protected DF1 commands received on com2 include lt ctools h gt struct ABConfiguration ABConfig getABConfiguration com2 amp ABConfig ABConfig max protected address 7000 setABConfiguration com2 amp ABConfig Document Version 1 61 5 19 2011 507 Function Specifications setBreakCondition Set a break condition on a serial port Syntax include lt ctools h gt void setBreakCondition FILE stream Parameters stream is a pointer to a serial port valid serial ports are com1 com2 com3 and com4 Description The setBreakCondition function activates the break condition
377. lizeDatabase void TASKINFO taskStatus BOOLEAN status if getProgramStatus FUNCPTR main NEW PROGRAM Application has just been downloaded Any memory previously allocated has been freed automatically Allocate non volatile dynamic memory request_resource DYNAMIC MEMORY status allocateMemory void amp pNvMemory gt pAllocatedMem MEM SIZE release resource DYNAMIC MEMORY if status TRUE set program status so memory is not re allocated until next program download setProgramStatus FUNCPTR main PROGRAM EXECUTED zero fill new custom database memset pNvMemory gt pAllocatedMem 0 MEM SIZE else memory could not be allocated pNvMemory gt pAllocatedMem NULL install exit handler to remove the custom database if the application is stopped or erased getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR myshutdown Document Version 1 61 5 19 2011 656 Example Programs install database handlers installDbaseHandler dbaseHandler installSetdbaseHandler setdbaseHandler This routine is the main program The custom i o database is initialized The database is then updated continuously with I O data in the main 1 int main void UINT16 dinData INT16 ainData 8 oop UINT16 doutData 0 UINT16 index
378. lse A watchdog reset pulse needs to be generated at least every 500 ms The CPU resets and program execution starts from the beginning of the program if the watchdog timer is not reset Watchdog Timer Program Example The following program segment shows how the watchdog timer could be used to detect the failure of a section of a program wd_manual take control of watchdog timer do program code wd pulse reset the watchdog timer while condition wd_auto return control to OS Pass control of the watchdog timer back to the operating system before stopping a program or switching to another task that expects the operating system to reset the timer Checksum Functions To simplify the implementation of self checking communication algorithms the C Tools provide four types of checksums additive CRC 16 CRC CCITT and byte wise exclusive OR The CRC algorithms are particularly reliable employing various polynomial methods to detect communication errors Additional types of checksums are easily implemented using library functions There are two library functions related to checksums Refer to the Function Specification section for details on each function listed checksum Calculates additive CRC 16 CRC CCITT and exclusive OR type checksums crc_reverse Calculates custom CRC type checksum using reverse CRC algorithm Document Version 1 61 5 19 2011 69 Overview of Programming Functi
379. lt ctools h gt BOOLEAN dnpReadAddressMappingTableEntry UINT16 index dnpAddressMap_type pAddressMap Description The dnpReadAddressMappingTableEntry function reads an entry from the DNP address mapping table pRoute is a pointer to a table entry it is written by this function The return value is TRUE if pAddressMap was successfully written or FALSE otherwise Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 194 Function Specifications dnpReadAddressMappingTableSize Read DNP Address Mapping Table size Syntax include lt ctools h gt UINT16 dnpReadAddressMappingTableSize void Description The dnpReadAddressMappingTableSize function reads the total number of entries in the DNP address mapping table The function returns the total number of entries in the DNP address mapping table Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 195 Function Specifications dnpReadMasterPollTableEntry Read DNP Master Poll Table entry Syntax include lt ctools h gt BOOLEAN dnpReadMasterPollTableEntry UINT16 index dnpMasterPoll type pMasterPoll Description This function reads an entry from the DNP master poll table pMasterPoll is a pointer to a table entry it is written by this function The r
380. m It will return a value suitable for an array index in increasing order of external serial port numbers if no error occurs If the stream is not recognized SERIAL_PORTS is returned to indicate an error See Also portStream Document Version 1 61 5 19 2011 457 Function Specifications portStream Get Serial Port Corresponding to Index Syntax include lt ctools h gt FILE portStream UINT16 index Description The portStream function returns the file pointer corresponding to index This function is the inverse of the portIndex function If the index is not valid the NULL pointer is returned See Also portlIndex Document Version 1 61 5 19 2011 458 Function Specifications queryStack Query Stack Space for Known Tasks Syntax include lt ctools h gt void queryStack UCHAR filename Description The queryStack function generates a csv file with the supplied filename The csv file contains the current stack condition of all Known tasks The file that is created can be extracted through FTP or Telepace Studio s File Management tool Notes This function should be used infrequently as a debugging aid Itis also recommended to be used during C application development to confirm that the tasks created by the C application have sufficient stack space Exercising all code paths is recommended before calling this function to obtain the most useful results Example include lt c
381. m I O Database Syntax include lt ctools h gt BOOLEAN databaseRead UINT16 addrMode UINT16 address INT16 value Description The databaseRead function reads a value from the database addrMode specifies the method of addressing the database address specifies the location in the database The table below shows the valid address modes and ranges Type Address Ranges Register Size MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes The function databaseRead returns TRUE if the requested database value was read FALSE is returned if the requested database entry could not be read If the specified register is currently forced databaseRead reads the forced register value into the memory pointed to by value The I O database is not modified when the controller is reset It is a permanent storage area which is maintained during power outages The IO_SYSTEM resource needs to be requested before calling this function See Also databaseWrite Document Version 1 61 5 19 2011 130 Function Specifications databaseWrite Write Value to I O Database Syntax include lt ctools h gt BOOLEAN databaseWrite UINT16 addrMode UINT16 address INT16 value Description The databaseWrite function writes a value to the database addrMode specifies the method of addressing the database address specifies the locati
382. mass storage device The media status indicates the presence of log media and if it provides space for dlog operations The external media in use Boolean value shows TRUE if the external media is in use FALSE otherwise Please refer to the chapters dlogTransferStatus Type and dlogMediaStatus Type for the status values DLOGS_SUCCESS is returned if the status information could be retrieved The only reason not be able to do this is because the input parameter dlogID is wrong which would result in the return value DLOGS_BADID Document Version 1 61 5 19 2011 154 Function Specifications dlogID Return the ID of an existing data log Syntax include lt ctools h gt dlogStatus dlogID UCHAR dlogName UINT32 dlogID Parameters The function has these parameters e dlogName is a null terminated string containing the name of the data log e dlogID is a pointer to a variable where the data log ID will be written if the function is successful The function returns e DLOGS_SUCCESS if the data log ID was retrieved e DLOGS FAILURE if an error during data log ID retrieval occurred e DLOGS_WRONGPARANM if an error due to wrong parameter Description This function maps a data log name to an ID which is used for further operations to the data log To obtain the data log ID the data log under the specified name has to exist Document Version 1 61 5 19 2011 155 Function Specifications dlogNewFile Creat
383. me INT32 pDays INT32 pHundredths Description The getClockTime function reads the real time clock and returns the value as the number of whole days since 01 01 1997 and the number of hundredths of a second since the start of the current day The function works for years from 01 01 1997 to 12 31 2099 then rolls over The function has two parameters a pointer to the variable to hold the days and a pointer to a variable to hold the hundredths of a second The function has no return value Notes The IO_SYSTEM resource needs to be requested before calling this function See Also getclock Document Version 1 61 5 19 2011 246 Function Specifications getControllerID Get Controller ID Syntax include lt ctools h gt void getControllerID CHAR pID Description This function writes the Controller ID to the string pointed to by p D The Controller ID is a unique ID for the controller set at the factory The pointer p D must point to a character string of length CONTROLLER_ID_LEN Example This program displays the Controller ID include lt ctools h gt int main void char ctlrID CONTROLLER ID LEN UINT16 index getControllerID ctlrID fprintf coml r nController ID for index 0 index lt CONTROLLER_ ID LEN index fputc ctlriID index coml Document Version 1 61 5 19 2011 247 Function Specifications getForceFlag Get Force Flag S
384. me clock getClockAlarm Reads the real time clock alarm settings getClockTime Read the real time clock installClockHandler Installs a handler for real time clock alarms resetClockAlarm Resets the real time clock alarm so it will recur at the same time next day setclock Set the real time clock setClockAlarm Sets real time clock alarm Real Time Clock Structures The ctools h file defines the structures Real Time Clock Structure and Alarm Settings Structure for real time clock information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Stopwatch Timer Functions The stopwatch is a counter that increments every 10 ms The stopwatch is useful for measuring execution times or generating delays where a fine time base is required The stopwatch time rolls over to 0 when it reaches the maximum value for an unsigned long integer 4 294 967 295 ms or about 49 7 days There is one library function to access the stopwatch time Refer to the Function Specification section for details readStopwatch reads the stopwatch timer Watchdog Timer Functions A watchdog timer is a hardware device which enables rapid detection of computer hardware or software problems In the event of a major problem the CPU resets and the application program restarts The controller provides an integral watchdog timer to ensure reliable operation The watchdog timer resets the CPU if it detects
385. ment Version 1 61 5 19 2011 438 Function Specifications mTcpMasterMessage Send a Modbus IP Master Message Syntax include lt ctools h gt MODBUS_CMD STATUS mTcpMasterMessage UINT32 connectID IP_ADDRESS remoteIP IP PROTOCOL TYPE protocolType UINT16 function UINT16 slaveStation UINT16 slaveRegister UINT16 masterRegister UINT16 length UINT16 timeout Description The mTcpMasterMessage function builds a Modbus command message using the specified Modbus IP protocol and signals the mastering task to tell it to send the command The connectID specifies the connection ID returned by the function mTcpMasterOpen which was called to create a mastering task to service this connection The remotelP specifies the IP address of the remote slave The value of remotelP may be the same or different from the IP address used in mTcpMasterOpen or in a previous call to mTcpMasterMessage This is possible because the connect D represents the allocation of a connection from the connection pool and may be used to connect to any IP address When the IP address is changed between function calls the current connection is closed and a connection to the new IP address is automatically established It is more efficient to allocate one connectID and its associated master task for each remotelP because the connection remains connected to one IP address However if there are fewer connections available than there are remote slaves the same
386. ment Version 1 61 5 19 2011 555 Function Specifications unregisterBulkDevOperation Un register bulk device operation Syntax include lt ctools h gt BOOLEAN unregisterBulkDevOperation char extDriveName Description The unregisterBulkDevOperation function un registers an operation on a bulk memory device It is used in conjunction with the registerBulkDevOperation to ensure that internal resources used for the bulk device are correctly released if the device is un mounted in the middle of an operation Parameters extDriveName The mounted bulk device drive name typically bd0 Returns TRUE The un register was successful FALSE The drive name was invalid Notes The registerBulkDevOperation and unregisterBulkDevOperation should only be used with a dynamically mounted bulk device such as a USB memory stick The unregisterBulkDevOperation needs to be called with the same device drive name as the registerBulkDevOperation See Also registerBulkDevOperation Example include lt ctools h gt int main void if registerBulkDevOperation bd0 FALSE printf registerBulkDevOperation bd0 failed r n Copy d0 logs log1 bd0 logs 1log1 if unregisterBulkDevOperation bd0 FALSE printf unregisterBulkDevOperation bd0 failed r n Document Version 1 61 5 19 2011 556 Function Specifications Document Version
387. mined On return select replaces the given socket descriptor sets with subsets consisting of those socket descriptors that are ready for the requested operation The return value from the call to select is the number of ready socket descriptors The socket descriptor sets are stored as bit fields in arrays of integers The following macros are provided for manipulating such file descriptor sets FD_ZERO amp fdset Initializes a socket descriptor set fdset to the null set FD_SET fd amp fdset Includes a particular socket descriptor fd in fdset FD_CLR fd amp fdset Removes fd from fdset FD_ISSET fd amp fdset Is non zero if fd is a member of fdset zero otherwise The term fd is used for BSD compatibility since select is used on both file systems and sockets under BSD Unix Parameters numberSockets Biggest socket descriptor to be tested plus one readSocketsPtr The pointer to a mask of sockets to check for a read condition writeSocketsPitr The pointer to a mask of sockets to check for a write condition exceptionSocketsPir The pointer to a mask of sockets to check for an exception condition Out of Band data timeOutPtr The pointer to a structure containing the length of time to wait for an event before exiting Document Version 1 61 5 19 2011 496 Function Specifications Returns gt 0 Number of sockets that are ready 0 Time limit exceeded 1 An error occurred If an error occurred the socket
388. module number is not valid Notification of the completion of I O requests made by this function may be obtained using the ioNotification function See Also hartSetConfiguration hartGetConfiguration hartCommand ioNotification Document Version 1 61 5 19 2011 282 Function Specifications hartCommand Send Command using HART Interface Module Syntax include lt ctools h gt BOOLEAN hartCommand UINT16 module HART DEVICE const device HART COMMAND const command void processResponse UINT16 HART RESPONSE Description This function sends a command to a HART slave device using a HART interface module This function can be used to implement HART commands not provided by the Network Layer API The function has four parameters The first is the module number of the 5904 interface 0 to 3 The second is the device to which the command is to be sent The third parameter is a structure describing the command to send This contains the command number and the data field of the HART message See the HART protocol documentation for your device for details The fourth parameter is a pointer to a function that will process the response This function is called when a response to the command is received by the HART interface The function is defined as follows void function_name HART RESPONSE response The single parameter is a structure containing the response code and the
389. module to the current Register Assignment of type moduleType The following symbolic constants are valid values for moduleType AIN_520xTemperature AIN_520xRAMBattery AIN_5501 AIN_5502 AIN_5503 AIN_5504 AIN_5505 AIN_5506 AIN_5521 AIN_generic8 AOUT_5301 AOUT_5302 AOUT_5304 AOUT _generic2 AOUT _generic4 CNFG_5904Modem CNFG_clearPortCounters CNFG_clearProtocolCounters CNFG_IPSettings CNFG_LEDPower CNFG_modbuslpProtocol CNFG_MTCPIfSettings CNFG_MTCPSettings CNFG_PIDBlock CNTR_5410 DIAG_commStatus DIAG_controllerStatus DIAG_forceLED DIAG_IPConnections DIAG_ModbusStatus DIAG_protocolStatus DIN 5401 DIN 5402 DIN 5403 DIN 5404 DIN 5405 DIN 5414 DIN 5421 DIN_generic16 DIN_generic8 DOUT_5401 DOUT_5402 DOUT_5406 DOUT_5407 DOUT_5408 DOUT_5409 DOUT_5411 DOUT_5415 Document Version 1 61 5 19 2011 96 Function Specifications CNFG_portSettings CNFG_protocolExtended CNFG_protocolExtendedEx CNFG_protocolSettings CNFG_realTimeClock CNFG_saveTOEEPROM CNFG_setSerialPortDTR CNFG_storeAndForward SCADASENSE_4203_DR CNTR_520xCounter Inputs SCADAPack_5607I10 SCADAPack_350I10 DOUT_generic16 DOUT_generic8 SCADAPack_AOUT SCADAPack_lowerlO SCADAPack_upperlO SCADAPack_LPIO SCADAPack_2I0 SCADAPack_100IO SCADAPack_560610 SCADASENSE_4203_DS SCADAPack_33xlO moduleAddress specifies a unique address for the module For the valid range for moduleAddress refer to the list of modules in the chapter
390. mory h define MY EVENT 1 void main void UCHAR dinData UINT32 counterData 3 IO_STATUS io_ status BOOLEAN status main loop while TRUE add module scan to queue if ioRequest MT_5210Inputs 0 status FALSE Document Version 1 61 5 19 2011 320 Function Specifications wait for scan to complete ioNotification MY EVENT wait event MY_EVENT read input data from last scan status ioRead5210Inputs counterData dinData check status of last scan if io0Status MT_5210Inputs 0 amp io status status FALSE else if io status commStatus status FALSE print data fprintf coml status u Dins 0 to 7 X Counter 1 d r n status dinData counterData 0 release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 321 Function Specifications ioRead52100utputs Read SCADAPack 330 controller board outputs Syntax include lt ctools h gt BOOLEAN i0oRead52100utputs UCHAR amp doutData 3 Description This function reads buffered data from the digital outputs of a SCADAPack 330 controller board Buffered data are written with the ioWrite5210Outputs function doutData is a reference to a variable to receive the digital output values e Bit 0 of this variable is written with the USB LED control e Bit 1
391. mple This Example turns on the USB STAT LED include lt ctools h gt include nvMemory h define MY EVENT 1 void main void UCHAR doutData 1 IO_ STATUS io_status BOOLEAN status main loop while TRUE write data to output tables for next scan doutData 0 0x01 status ioWrite52100utputs doutData 0 add module scan to queue Document Version 1 61 5 19 2011 374 Function Specifications if ioRequest MT_52100utputs 0 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan check status of last scan if ioStatus MT _52100utputs 0 amp io status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 375 Function Specifications ioWrite54140utputs Write 5414 module configuration parameter outputs Syntax include lt ctools h gt BOOLEAN ioWrite54140utputs UINT16 moduleAddress UINT16 inputType UINT16 scanFrequency Description This function writes to the I O table for the output configuration of a 5414 module Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5414 module Valid values are 0 to 15
392. mpting another connect call Document Version 1 61 5 19 2011 125 Function Specifications copy Copy a File Syntax include lt ctools h gt STATUS copy const char source const char destination Description The copy function copies the file source to the path qualified file name destination If the copy operation failed then ERROR is returned OK is returned if the copy operation completed successfully See Also xcopy xdelete Document Version 1 61 5 19 2011 126 Function Specifications cre_reverse Calculate a CRC Checksum Syntax include lt ctools h gt UINT16 crc reverse UCHAR start UCHAR end UINT16 poly UINT16 initial Description The crc_reverse function calculates a CRC type checksum on memory using the reverse algorithm The memory starts at the byte pointed to by start and ends with the byte pointed to by end The generator polynomial is specified by poly poly may be any value but needs to be carefully chosen to ensure good error detection The checksum accumulator is set to initial before the calculation is started Notes The reverse algorithm is named for the direction bits are shifted In the reverse algorithm bits are shifted towards the least significant bit This produces different checksums than the classical or forward algorithm using the same polynomials See Also checksum Document Version 1 61 5 19 2011 127 Function Specifications crea
393. n 1 61 5 19 2011 223 Function Specifications dnpWriteMasterPollTableEntryEx Write DNP Master Poll Table Extended Entry Syntax BOOLEAN dnpWriteMasterPollTableEntryEx UINT16 index DnpMasterPollEx type pMasterPoll Description This function writes an extended entry in the DNP master poll table The function returns TRUE if successful FALSE otherwise Notes This function is only available on the SCADAPack 32 SCADAPack 350 and 4203 DNP needs to be enabled before calling this function in order to create the DNP configuration This function supersedes the dnpWriteMasterPollTableEntry function Document Version 1 61 5 19 2011 224 Function Specifications dnpWriteRoutingTableEntry_DialString Write DNP Routing Table Entry Dial Strings Syntax BOOLEAN dnpWriteRoutingTableEntry DialStrings UINT16 index UINT16 primaryDialStringLength CHAR primaryDialString UINT16 secondaryDialStringLength CHAR secondaryDialString Description This function writes a primary and secondary dial string into an entry in the DNP routing table index specifies the index of an entry in the DNP routing table primaryDialStringLength specifies the length of primaryDialString excluding the null terminator character primaryDialString specifies the dial string used when dialing the target station This string is used on the first attempt secondaryDialStringLength specifies the l
394. n 1 61 5 19 2011 248 Function Specifications getForceFlag MODBUS getForceFlag getForceFlag INI EAR IN EAR 40001 amp flag 302 1540 amp bitmask amp flag Document Version 1 61 5 19 2011 249 Function Specifications getForceLed Get status of Force LED Syntax include lt ctools h gt UINT16 getForceLed void Description The getForceLed function returns the status of the Force LED It returns TRUE if the LED is ON and FALSE if the LED is OFF See Also forceLed Document Version 1 61 5 19 2011 250 Function Specifications getFtpServerState Gets the state of the FTP server Syntax include lt ctools h gt BOOLEAN getFtpServerState UINT32 state Parameters state specifies the parameter that the current operational state of the FTP server will be placed in The following values for state are defined e 0 FTP server disabled e 1 FTP server enabled anonymous login permitted e 2 FTP server enabled username and password required Description The getFtpServerState function gets the state of the FTP server TRUE is returned if the current state was placed in the parameter state FALSE is returned if the current state was not placed in the parameter state Notes This function is only relevant for Ethernet enabled controllers See Also setFtpServerState Document Version 1 61 5 19 2011 251 Function S
395. n Xoff flow control al CTS PC_PROTOCOL_RTU_FRAMI Modbus RTU framing NG PHONE_NUM_MAX_LEN Maximum length of the phone number string PM_CPU_FULL_ CLOCK The CPU is set to run at full speed PM_CPU_REDUCED_ CLOCK The CPU is set to run at a reduced speed PM_CPU_SLEEP The CPU is set to sleep mode PM_LAN_ ENABLED The LAN is enabled PM_LAN_DISABLED The LAN is disabled PM_USB_PERIPHERAL_ENA The USB peripheral port is enabled BLED PM_USB_PERIPHERAL_DISA The USB peripheral port is disabled BLED The USB host port is enabled PROGRAM_NOT_LOADED The requested application program is not loaded RFC_MODBUS_RTU Flow control type may be used in place of ENABLE RFC_NONE Flow control type may be used in place of DISABLE RS232 Specifies serial port is an RS 232 port RS232_MODEM Specifies serial port is an RS 232 dial up Document Version 1 61 5 19 2011 579 Macro Definitions Bece a O RS232_COLLISION_AVOIDAN CE for collision avoidance RTOS_TASKS Number of RTOS tasks Run Service switch is in RUN position S MODULE FAILURE Status LED code for I O module communication failure S_ NORMAL Status LED code for normal status SERIAL_PORTS Number of serial ports SERVICE Run Service switch is in SERVICE position SF_ALREADY_DEFINED Result code translation is already defined in the table SF_INDEX_OUT_OF_RANGE Result code invalid translation table index SF_NO_TRANSLATION Result code entry does not define a transl
396. n listed ledGetDefault Get default LED power state ledPower Set LED power state ledPowerSwitch Read LED power switch ledSetDefault Set default LED power state LED Power Control Structure The ctools h file defines the structure LED Power Control Structure for LED power control information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Document Version 1 61 5 19 2011 66 Overview of Programming Functions Software Timer Functions The controller provides 32 powerful software timers which greatly simplify the task of programming time related functions Uses include e generation of time delays e timing of process events such as tank fill times e generation of time based interrupts to schedule regular activities e control of digital outputs by time periods The 32 timers are individually programmable for tick rates from ten per second to once every 25 5 seconds Time periods from 0 1 second to greater than nineteen days can be measured and controlled Timer functions require an initialization step before they are used This initialization step creates the timer support task The function runTimers starts the timer task and needs to be called first in order to provide timer functionality There are four library functions related to timers Refer to the Function Specification section for details on each function listed interval Set timer tick interval in te
397. n on backlog The maximum number of outstanding connections allowed on the socket Returns 0 Success 1 An error occurred listen can fail for the following reason EADDRINUSE The address is currently used by another socket EBADF The socket descriptor is invalid EOPNOTSUPP The socket is not of a type that supports the operation listen Document Version 1 61 5 19 2011 410 Function Specifications master_message Send Protocol Command Syntax include lt ctools h gt UINT16 master message FILE stream UINT16 function UINT16 slave station UINT16 slave address UINT16 master address UINT16 length Description The master_message function sends a command using a communication protocol The communication protocol task waits for the response from the slave station The current task continues execution e port specifies the serial port e function specifies the protocol function code Refer to the communication protocol manual for supported function codes e slave specifies the network address of the slave station This is also known as the slave station number e address specifies the location of data in the slave station Depending on the protocol function code data may be read or written at this location e master_address specifies the location of data in the master this controller Depending on the protocol function code data may be read or written at this location e length specifies the n
398. n8 0 ain Test input against alarm limits request resource IO SYSTEM if ain 0 gt dbase MODBUS HI ALARM setdbase MODBUS ALARM OUTPUT 1 else setdbase MODBUS ALARM OUTPUT 0 Document Version 1 61 5 19 2011 645 Example Programs release resource IO SYSTEM Allow other tasks to execute release processor Get Task Status Example The following program displays information about all valid tasks include lt string h gt include lt ctools h gt int main void struct prot_settings settings TASKINFO taskStatus Disable the protocol on serial port 1 settings type NO PROTOCOL settings station 1 settings priority 250 settings SFMessaging FALSE request resource IO SYSTEM set_protocol coml amp settings release resource IO SYSTEM display information about current task if getTaskInfo 0 amp taskStatus show information for valid task fprintf coml r n r nInformation about task Sd r n task fprintf coml Task ID Ox x r n taskStatus taskID fprintf coml Current Priority d r n taskStatus cPriority fprintf coml Normal Priority d r n taskStatus priority fprintf coml Task Group d r n taskStatus taskGroup if taskStatus requirement REQ NO WAIT fprintf coml Ready to run r n if taskStatus requir
399. nction is NULL the handler is disabled Notes RTOS calls see functions listed in the section Real Time Operating System Functions at the start of this chapter may not be made within the interrupt handler with one exception The interrupt_signal_event RTOS call can be used to signal events See Also setClockAlarm Example See the Install Clock Handler Example in the Examples section Document Version 1 61 5 19 2011 303 Function Specifications installDbaseHandler Install User Defined Dbase Handler IEC 61131 1 firmware only Syntax include lt ctools h gt void installDbaseHandler BOOLEAN handler UINT16 address INT16 value Description The installDbaseHandler function allows an extension to be defined for the dbase function If a handler is installed it is called by the dbase function when one of the following conditions apply e There is no IEC 61131 1 application downloaded or e There is no IEC 61131 1 variable assigned to the specified Modbus address The function installDbaseHandler has one parameter a pointer to a function to handle the dbase extensions See the section Dbase Handler Function for a full Description of the handler function and it s parameters If the pointer is NULL no handler is installed The installed handler is always called with a Modbus address Linear addresses are converted to Modbus addresses before calling the handler Use the installSetdbase
400. nctions The installModbusHandler is used to add user defined extensions to the standard Modbus protocol To uninstall a Modbus handler in a SCADAPack C application the same function is called with the NULL pointer SCADAPack 350 and 4203 C applications support the installation of multiple Modbus handlers In order to remove a specific Modbus handler the new function removeModbusHandler is used Calling installModbusHandler with the NULL pointer has no effect Unsupported C Tools Functions The following sections describe functions that are supported by the Telepace C Tools and IEC 61131 1 C Tools but are not supported by the SCADAPack C Tools Refer to these sections when porting existing SCADAPack C Tools Applications Document Version 1 61 5 19 2011 690 Porting Existing C Tools Applications Application Checksum Function A checksum is no longer used for the C application The C Tools function applicationChecksum is not supported Backwards Compatibility Functions These functions were supported in previous C Tools for backwards compatibility however they were stubs The following C Tools functions are not supported Function setSFMapping getSFMapping Boot Type Functions These functions are not useful to C Applications The following C Tools functions are not supported Function setBootType getBootType I O Bus Communication Functions The SCADAPack 350 and 4203 I O System does not support
401. ncy add module scan to queue if ioRequest MT _5506Outputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_EVENT check status of last scan if ioStatus MT 5506Outputs 5 amp io_ status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 382 Function Specifications ioWrite5606Outputs Write 5606 Outputs Syntax include lt ctools h gt BOOLEAN ioWrite56060utputs UINT16 moduleAddress UCHAR amp doutData 2 INT16 amp aoutData 2 UINT16 amp inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType Description This function writes data to the I O table for the 16 digital outputs and 2 analog outputs of a 5606 I O module Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5606 module Valid values are 0 to 7 doutData is a reference to an array of two UCHAR variables Digital data for the 16 outputs are read from this array One bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are read from this array inputType is a reference to an array of eight UINT16 variabl
402. nds on the character handler installed com2 Points to a file object for the com2 serial port COM2_RCVR System event indicates activity on com2 receiver The meaning depends on the character handler installed com3 Points to a file object for the com3 serial port COM3_RCVR System event indicates activity on com3 receiver The meaning depends on the character handler installed COUNTER_CHANNELS Specifies number of 5000 counter input channels Document Version 1 61 5 19 2011 572 Macro Definitions COUNTER_END Number of last counter input channel COUNTER_START Number of first counter input channel supported Frequency of the system clock in cycles per second Variable name control register CRC_16 CRC 16 type CRC checksum reverse algorithm CRC_CCITT CCITT type CRC checksum reverse algorithm DATA_SIZE Maximum length of the HART command or response field D Variable name deadbard DB_BADTYPE Error code bad database addressing type specified DB_OK DCA_ADD Add the ID to the configuration registers DCA_REMOVE Remove the ID from the configuration registers DCAT_C Device configuration application type is a C application DCAT_LOGIC1 Device configuration application type is the first logic application DCAT_LOGIC2 Device configuration application type is the second logic application DE_BadConfig The modem configuration structure contains an error DE_BusyLine The phone number called was b
403. ne bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are written to this array inputType is a reference to an array of eight UINT16 variables Analog input measurement types are written to this array Valid values are e 0 0to 5V e 1 0t010V e 2 0to20mA e 3 41to 20 mA inputFilter is a reference to a UINT16 variable The input filter selection is written to this variable e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency is a reference to a UINT16 variable The scan frequency selection is written to this variable e 0 60Hz Document Version 1 61 5 19 2011 339 Function Specifications e 1 50 Hz outputType is a reference to a UINT16 variable The analog output type is written to this variable e 0 0to20mA e 1 4to 20 mA The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5606 Inputs ioWrite5606Outputs Example This program reads output data from the I O table for the 5606 digital outputs and analog outputs at address 5 include lt ctools h gt int main void UCHAR doutData 2 INT16 aoutData 2 UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType BOOLEAN status BOOLEAN done main loop while TRUE read output data from I O table status ioRead56060utputs 5 doutData aoutData
404. ne of the parameters is invalid ENOPROTOOPT The option is unknown at the level indicated EPERM Option cannot be set after the connection has been established ENETDOWN Specified interface not configured yet EADDRINUSE Multicast host group already added to the interface ENOBUF ENOENT Attempted to delete a non existent multicast entry on the specified interface Not enough memory to add new multicast entry Document Version 1 61 5 19 2011 539 Function Specifications setStatusBit Set Bits in Controller Status Code Syntax include lt ctools h gt UINT16 setStatusBit UINT16 bitMask Description The setStatusBit function sets the bits indicated by bitMask in the controller status code When the status code is non zero the STAT LED blinks a binary sequence corresponding to the code If code is zero the STAT LED turns off The function returns the value of the status register Notes The status output opens if code is non zero Refer to the System Hardware Manual for more information The binary sequence consists of short and long flashes of the error LED A short flash of 1 10th of a second indicates a binary zero A binary one is indicated by a longer flash of approximately 1 2 of a second The least significant digit is output first As few bits as possible are displayed all leading zeros are ignored There is a two second delay between repetitions The STAT LED is located on the top left hand corner of the
405. nected to the transmit data input of the DCE device The receive data input of the DTE device is connected to the receive data output of the DCE device Modems are usually DCE devices This cable is described in the System Hardware Manual for your controller Many RS 232 devices require specific signal levels on certain pins Communication is not possible unless the required signals are present In the Document Version 1 61 5 19 2011 70 Overview of Programming Functions controller the CTS line needs to be at the proper level The controller will not transmit if CTS is OFF If the CTS line is not connected the controller will force it to the proper value If an external device controls this line it needs to turn it ON for the controller to transmit Serial Communication Functions The ctools h file defines the following serial communication related functions Refer to the Function Specification section for details on each function listed clear_errors Clear serial port error counters clear_tx Clear serial port transmit buffer get_port Read serial port communication parameters getPortCharacteristics Read information about features supported by a serial port get_status Read serial port status and error counters install_handler Install serial port character received handler portindex Get array index for serial port portStream Get serial port corresponding to index queue_mode Set serial port transmitter mode route Red
406. nfig function reads the configuration of a DNP short floating point analog input point The function has two parameters the point number and a pointer to a configuration structure The function returns TRUE if the configuration was successfully read or FALSE otherwise if the point number is not valid or pointer is NULL or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 170 Function Specifications dnpGetAO16Config Get DNP 16 bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAO16Config UINT16 point dnpAnalogOutput pAnalogOutput Description The dnpGetAO16Config function reads the configuration of a DNP 16 bit analog output point The function has two parameters the point number and a pointer to an analog output point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAO16Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 171 Function Specifications dnpGetAO32Config Get DNP 32 bit Analog Output C
407. ng FALSE set_protocol coml amp settings Set communication parameters for port 1 portset baud BAUD9600 portset duplex FULL portset parity NONE portset data_bits DATA8 portset stop bits STOP1 portset flow rx RFC_NONE portset flow tx TFC_NONE portset typ RS232 portset timeout 600 set_port coml amp portset enable Modbus protocol on serial port 2 Document Version 1 61 5 19 2011 660 Example Programs settings type MODBUS_ ASCII settings station 2 settings priority 250 settings SFMessaging FALSE set_protocol com2 amp settings Set communication parameters for port 2 portset baud BAUD9600 portset duplex HALF portset parity NONE portset data_bits DATA8 portset stop bits STOP1 portset flow_rx RFC_NONE portset flow_tx TFC_NONE portset typ RS485 4WIRE portset timeout 600 set_port com2 amp portset release resource IO SYSTEM enable timers used in wait for response runTimers TRUE Main communication loop while TRUE my E Xs Transfer slave inputs to outputs request resource IO SYSTEM master message com2 2 1 10001 17 8 release resource IO SYSTEM wait for response com2 10 ve outputs 1 Transfer inputs to sl request_resource IO SYST master message com2
408. ng Started Edit the main cpp text and add the text shown in bold in the following section int main void add program initialization here Print the message fprintf com2 hello world r n main loop while TRUE add remainder of program here Compiling the C Application Review makefile Once the editing of the project is completed the application needs to be compiled and linked This produces an executable file that can be loaded into the SCADAPack 350 or 4203 controller The C tools use the gnu make utility to build applications Application builds are managed by a make file For the simplest applications no modifications of the makefile are needed This section may be skimmed the first time through but contains information that will be usefull for building more sophisticated applications The makefile is designed to build a application for both the SCADAPack 350 and 4203 controllers Command line options allow the application to be targeted for a specific controller if the application code contains functions that are specific to the controller Open the file makefile in the application folder The file shown below is from the IEC 61131 1 application framework makefile Make file for SCADAPack 350 4203 C Tools application for TEC 61131 1 firmware Copyright 2007 Control Microsystems Inc usage make makes application for all controllers make TARGET SCADAPack350 makes
409. ngs release resource IO SYSTEM Configure US Robotics modem dialSettings port coml dialSettings dialAttempts 3 dialSettings detectTime 60 dialSettings pauseTime 30 dialSettings dialmethod 0 strcpy dialSettings modemCommand amp F1 amp A0 amp KO amp MO amp B1 strcpy dialSettings phoneNumber 555 1212 Document Version 1 61 5 19 2011 633 Example Programs set up exit handler for this task getTaskInfo 0 amp taskStatus installExitHandler taskStatus taskID FUNCPTR myshutdown Connect to the remote controller if modemDial amp dialSettings amp portID DE NoError do Allow other tasks to execute release processor Wait for initialization to complete modemDialStatus coml portID amp status amp state while state DS Calling If the remote controller connected if state DS Connected Talk to remote controller here Terminate the connection modemDialEnd coml portID amp status A pause of a few seconds is required between terminating a connection and initiating a new call This pause allows the external modem time to hang up Create Task Example include lt ctools h gt define TIME TO PRINT 20 void task1 void int a b while TRUE body of task 1 loop processing I O request resource IO SYSTEM a dbase MODBUS 30001
410. ngs of components there are hazards that can be encountered if such equipment is improperly operated e Itis sometimes possible to misadjust the equipment and thus produce unsatisfactory or unsafe operation Always use the manufacturer s instructions as a guide for functional adjustments Personnel who have access to these adjustments should be familiar with the equipment manufacturer s instructions and the machinery used with the electrical equipment e Only those operational adjustments actually required by the operator should be accessible to the operator Access to other controls should be restricted to prevent unauthorized changes in operating characteristics Document Version 1 61 5 19 2011 16 About The Book About The Book At a Glance Document Scope This manual describes C Tools for SCADAPack 300 and 4203 controllers Validity Notes This document is valid for all SCADAPack 300 and 4203 firmware versions Product Related Information AWARNING UNINTENDED EQUIPMENT OPERATION The application of this product requires expertise in the design and programming of control systems Only persons with such expertise should be allowed to program install alter and apply this product Follow all local and national safety codes and standards Failure to follow these instructions can result in death serious injury or equipment damage User Comments We welcome your comments about this document Y
411. nimum filter scanFrequency 0 60 Hz set analog output type to 4 20 mA outputType 1 Document Version 1 61 5 19 2011 384 Function Specifications inputType status ioWrite56060utputs 5 doutData aoutData inputFilter scanFrequency outputType add module scan to queue if ioRequest MT _5606Outputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT check status of last scan if io0Status MT 5606O0utputs 5 amp io status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 385 Function Specifications ioWrite56070utputs Write 5607 Outputs Syntax include lt ctools h gt BOOLEAN ioWrite56070utputs UINT16 moduleAddress UCHAR amp doutData 2 INT16 amp aoutData 2 UINT16 amp inputType 8 UINT16 inputFilter UINT16 scanFrequency UINT16 outputType Description This function writes data to the I O table for the 10 digital outputs and 2 analog outputs of a 5607 I O module Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5607 module Valid values are 0 to 7 doutData is a reference to an array of two UCHAR variables Digital d
412. nitialization string for the modem The characters AT will be prefixed to the command and a carriage returned suffixed to the command when it is sent to the modem Refer to the section Modem Commands for suggested command strings for your modem The ModemSetup structure specifies modem initialization and dialing control parameters for the modemDial function struct ModemSetup FILE port UINT16 dialAttempts UINT16 detectTime UINT16 pauseTime UINT16 dialmethod CHAR modemCommand MODEM CMD MAX LEN 2 CHAR phoneNumber PHONE NUM MAX LEN 2 Document Version 1 61 5 19 2011 618 Structures and Types e portis the serial port where the modem is connected e dialAttempts is the number of times the controller will attempt to dial the remote controller before giving up and reporting an error e detectTime is the length of time in seconds that the controller will wait for carrier to be detected It is measured from the start of the dialing attempt e pauseTime is the length of time in seconds that the controller will wait between dialing attempts e dialmethod selects pulse or tone dialing Set dialmethod to O for tone dialing or 1 for pulse dialing e modemCommand is the initialization string for the modem The characters AT will be prepended to the command and a carriage returned appended to the command when it is sent to the modem Refer to the section Modem Commands for suggested command
413. nloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the setdbase function The lO_SYSTEM system resource needs to be requested before calling this function Example This program writes a TRUE state to the boolean variable named Switch1 include lt ctools h gt int main void BOOLEAN status request_resource IO SYSTEM status writeBoolVariable Switch1 TRUE release resource IO SYSTEM x Document Version 1 61 5 19 2011 563 Function Specifications writelntVariable Write to IEC 61131 1 Integer Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN writeIntVariable UCHAR varName INT32 long value Description This function writes to the specified integer variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified signed long value is written to the variable If the variable is not found or if the IEC 61131 1 Symbols Status is invalid
414. notifications from being generated until the next level has looked at the data dataToProcess arg TRUE We handled the character so return FALSE retval TRUE break default We didn t handle the character so return TRUE retval TRUE break return retval int main void UINT32 UCHAR characterSize timeoutInterval install the serial character handler install _ handler com1 informOfCharacterArrival Calculate the character size ff ES tart bit 8 data bits no 1s charac parity bits top bit terSize 1 8 1 Delay for 5 seconds sleep processor 5000 Document Version 1 61 5 19 2011 554 Function Specifications Determine the number of timeout intervals needed The multiplication by 8 is due to 8 character times to delay The division by 4 is because every value specifies 4 bit times timeoutInterval characterSize 8 4 Set COM1 to signal character arrival after 8 character times of silence sysSerialSetRxTimeout COM1 INDEX timeoutInterval while TRUE Wait for the serial callback handler to report a message has been received wait event COM1 RCVR Reset the data to process flag so that we ll be notified when the next message arrives dataToProcess COM1 INDEX FALSE Read out data and process message her See Also install_ handler Docu
415. npSearchRoutingTable UINT16 Address routingTable pRoute Description This function searches the routing table for a specific DNP address pRoute is a pointer to a table entry it is written by this function The return value is TRUE if pRoute was successfully written or FALSE otherwise Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 219 Function Specifications dnpStationStatus Get communication status for a remote DNP station Syntax include lt ctools h gt DNP_PROTOCOL STATUS dnpStationStatus UINT16 dnpAddress BOOLEAN clear Description The dnpStationStatus function returns the DNP message statistics for a remote DNP station dnpAddress is the address of the remote DNP station Valid values are any DNP station number in the range 1 to 65532 If clear is TRUE the DNP message counters are reset to zero after they are read Document Version 1 61 5 19 2011 220 Function Specifications dnpWriteAddressMappingTableEntry Write DNP Address Mapping Table Entry Syntax include lt ctools h gt BOOLEAN dnpWriteAddressMappingTableEntry UINT16 index INT16 dnpRemoteStationAddress HAR dnpObjectType INT16 dnpRemoteObjectStart INT16 numberOfPoints INT16 dnpLocalModbusAddress r Sa eT OS Description The dnpWriteAddressMappingTableEntry function w
416. npStationStatus Returns the DNP message statistics for a remote DNP station dnpWriteAddressMappingTableEntry Writes an entry in the DNP address mapping table dnpWriteMasterApplicationLayerConfig Writes DNP Master application layer configuration dnpWriteMasterPollTableEntry Writes an entry in the DNP master poll table dnpWriteRoutingTableEntry Writes an entry in the DNP routing table dnpWriteRoutingTableEntryEx Writes an extended entry in the DNP routing table dnpWriteRoutingTableEniry_DialSitring Writes a primary and secondary dial string into an entry in the DNP routin Document Version 1 61 5 19 2011 77 Overview of Programming Functions DNP Communication Protocol Structures and Types The ctools h file defines the structures DNP Configuration Binary Input Point Binary Output Point Analog Input Point Analog Output Point and Counter Input Point Refer to the C Tools Structures and Types section for complete information on structures and enumeration types DF1 Communication Protocol The TeleBUS DF1 protocol supports the DF1 Basic Command Set in the Half Duplex and Full Duplex DF1 protocols DF1 Communication Protocol Functions There are several library functions related to DF1 communication protocol Refer to the Function Specification section for details on each function listed getABConfiguration Reads DF1 protocol configuration parameters pollABSlave Requests a response from a slave controller using the
417. ns readMsgVariable Read IEC 61131 1 Message Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN readMsgVariable UCHAR varName UCHAR msg Description This function returns the current value of the specified message variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the message is written to the string pointed to by msg If the variable is not found or if the IEC 61131 1 Symbols Status is invalid FALSE is returned and the buffer is left unchanged The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum The pointer msg needs to point to a character string large enough to hold the maximum length declared for the specified message variable plus two length bytes and a null termination byte i e max declared length 3 IEC 61131 1 message variables have the following format Byte Description Location Maximum length as declared in IEC 61131 1 Dictionary 1 to 255 1 Current Length number of bytes up to first null byte in message data 0 to maximum length First message data byte Last byte in message buffer max 2 Null termination byte Terminates a message having the maximum length Notes This funct
418. ns setDTR Control RS232 Port DTR Signal Syntax include lt ctools h gt void setDTR FILE stream UINT16 state Description The setDTR function sets the status of the DTR signal line for the communication port specified by port When state is SIGNAL_ON the DTR line is asserted When state is SIGNAL_OFF the DTR line is de asserted Notes The DTR line follows the normal RS232 voltage levels for asserted and de asserted states This function is only useful on RS232 ports The function has no effect if the serial port is not an RS232 port Document Version 1 61 5 19 2011 514 Function Specifications setFtpServerState Sets the state of the FTP server Syntax include lt ctools h gt BOOLEAN setFtpServerState UINT32 state Parameters state specifies the desired operational state of the FTP server The following values for state are defined e 0 FTP server disabled e 1 FTP server enabled anonymous login permitted e 2 FTP server enabled username and password required Description The setFtpServerState function sets the state of the FTP server TRUE is returned if the specified state was set FALSE is returned if the specified state could not be set Notes This function is only relevant for Ethernet enabled controllers See Also getFtpServerState Document Version 1 61 5 19 2011 515 Function Specifications setForceFlag Set Force Flag State for a Register
419. ns the modem configuration structure contains an error DE_NoModem returns the serial port is not configured as a modem port type must be RS232_MODEM Or no modem is connected to the controller serial port DE_InitError returns modem initialization failed the modem may be turned off DE_NoDialTone returns modem did not detect a dial tone or the S6 setting in the modem is too short DE_BusyLine returns the phone number called was busy DE_CallAborted returns a call in progress was aborted by the user DE_FailedToConnect returns the modem could not connect to the remote site DE_CarrierLost returns the connection to the remote site was lost modem reported NO CARRIER Carrier is lost for a time exceeding the S10 setting in the modem Phone lines with call waiting are very susceptible to this condition DE_NotInControl returns the serial port is in use by another modem function or has answered an incoming call DE_CallCut returns an incoming call was disconnected while attempting to dial out The DialState enumerated type defines the state of the modemDial operation and may have one of the following values enum DialState e DS_Inactive DS Calling DS_Connected DS_ Terminating DS_Inactive returns the serial port is not in use by a modem Document Version 1 61 5 19 2011 587 Structures and Types DS_Calling returns the controller is making a connection to a remote controller DS_ Connected returns the c
420. ntained after calling this function For this reason it is recommended that all connections using this protocol be closed before calling this function If this function is used to change the port number or maximum number of server connections then the Modbus TCP Server task is ended and re started with the new settings Port number changes will only affect new connections made after calling this function Other changes take effect on existing as well as new connections The function copies settings from the structure pointed to by pSettings to the Modbus TCP protocol configuration and returns TRUE The structure MTCP_CONFIGURATION is described in the Structures and Types section If there is an invalid setting FALSE is returned and the settings are not copied To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ RUN release resource FLASH MEMORY Document Version 1 61 5 19 2011 433 Function Specifications mTcpSetinterface Set Modbus IP Interface Settings Syntax include lt ctools h gt BOOLEAN mTcpSetInterface COM _ INTERFACE ifType MTCP_IF SETTINGS pSettings Description The mTcpSetinterface function is used to set the interface settings used by the Modbus IP protocols If the selected interface or the settings are inv
421. nths of seconds settimer Set a timer Timers count down from the set value to zero timer Read the time period remaining in a timer read_timer_info Read information about a software timer Timer Information Structure The ctools h file defines the structure Timer Information for timer information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Alternative Methods for Timing If the overhead of the timer task is undesired two alternative methods supported by the firmware exist for user timing See the functions timedEvents and readStopwatch Real Time Clock Functions The controller is provided with a hardware based real time clock that independently maintains the time and date for the operating system The time and date remain accurate during power off This allows the controller to be synchronized to time of day for such functions as shift production reports automatic instrument calibration energy logging etc The calendar can be used to automatically take the controller off line during weekends and holidays The calendar automatically handles leap years There are eight library functions which access the real time clock Refer to the Function Specification section for details on each function listed Document Version 1 61 5 19 2011 67 Overview of Programming Functions alarmin Returns absolute time of alarm given elapsed time getclock Read the real ti
422. o functions related to controller information Refer to the Function Specification section for details getConirollerID Get the controller ID code Firmware Version Information Functions There is one function related to the controller firmware version Refer to the Function Specification section for details getVersion Returns controller firmware version information Firmware Version Information Structure The ctools h file defines the structure Version Information Structure for controller firmware version information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Configuration Data Flash Memory Functions SCADAPack 350 and 4203 controllers use flash memory to store controller settings The flash memory functions have one parameter flags indicating which areas to store into flash A sum of more than one area may be selected Valid flags are listed below and defined in ctools h Area Flag Loaded on Reset Controller Settings in this Area CS_ETHERNET Ethernet MAC address CS_OPTIONS Controller factory options CS PERMANENT Saved settings loaded Controller type IP address on Service and Run Gateway Network mask IP Boot Configuration mode Lock state Replaced with default and password I O System settings on Cold Boot settings I O error indication setting Telepace Firmware only Document Version 1 61 5 19 2011 60 Overview of Programming Fun
423. o handle the failure here else if ioStatus MT_4203DSInputs 0 amp io status insert code to handle the failure here else if io _status commStatus insert code to handle the failure here else fprintf com2 status u Dins 0 X Ain 2 d r n status dinData ainData 2 done TRUE sleep processor for 100ms sleep processor 100 Document Version 1 61 5 19 2011 319 Function Specifications ioRead5210Inputs Read SCADAPack 330 controller board inputs Syntax include lt ctools h gt BOOLEAN i0Read5210Inputs UINT32 amp counterData 3 UCHAR amp dinData Description This function reads buffered data from the digital and counter inputs of a SCADAPack 330 controller board Buffered data are updated when an I O request for the module is processed counterData is a reference to an array to receive the counter input values Data from three counter inputs is written to this variable dinData is a reference to a variable to receive the digital input values e Bit 0 of this variable is written with the com3 HMI power status e Bits 1 to 7 are not used The function returns TRUE as no I O errors are possible See Also ioRead52100utputs Example This program displays the values of the 7 internal digital inputs and the single physical digital input The first counter input is displayed as well include lt ctools h gt include nvMe
424. o right order the standard system directories come after fdollars in identifiers Accept in identifiers Specifies the name of the output file Document Version 1 61 5 19 2011 43 C Program Development Application Development Please refer to the Program Development Tutorial for details on how to build load and execute a C Application Document Version 1 61 5 19 2011 44 Real Time Operating System Real Time Operating System The real time operating system RTOS provides the programmer with tools for building sophisticated applications The RTOS allows pre emptive scheduling of event driven tasks to provide quick response to real world events Tasks multi task cooperatively Inter task communication and event notification functions pass information between tasks Resource functions facilitate management of non sharable resources Task Management The task management functions provide for the creation and termination of tasks Tasks are independently executing routines The RTOS uses a cooperative multi tasking scheme with pre emptive scheduling of event driven tasks The initial task the main function may create additional tasks The maximum number of tasks is limited only by available memory There are 256 task priority levels to aid in scheduling of task execution Task Execution SCADAPack 350 and 4203 controllers can execute one task at a time The RTOS switches between the tasks to
425. ocate_envelope function See Also receive_message Example This program creates a task to display a message and sends a message to it include lt ctools h gt void showlIt void envelope msg while TRUE msg receive message fprintf coml Message data ld r n msg gt data deallocate_ envelope msg int main void envelope msg message pointer unsigned tid task ID tid create _task showIt 100 applicationGroup 4 msg allocate envelope msg gt destination tid msg gt type MSG_DATA msg gt data 1002 Document Version 1 61 5 19 2011 501 Function Specifications send message msg wait for ever so that main and other APPLICATION tasks won t end while TRUE Allow other tasks to execute release processor Document Version 1 61 5 19 2011 502 Function Specifications sendto Syntax include lt trsocket h gt int sendto int socketDescriptor char bufferPtr int bufferLength int flags const struct sockaddr toPtr int toLength Description sendto is used to transmit a message to another transport end point sendto may be used at any time either in a connected or unconnected state but not for a TCP socket socketDescriptor is a socket created with socket The address of the target is given by to with toLength specifying its size If the message is too long to pass atomically th
426. ocessor Memory Allocation Example This program allocates dynamic non volatile memory only when the C Application is run the first time after downloading Refer to the section Non Volatile Data Sections for instructions on declaring non volatile variables This program assumes that the pointer pAllocatedMem has been declared in nvMemory h include lt ctools h gt include nvMemory h struct myTable UINT32 data 100 define MEM SIZE sizeof struct myTable int main void BOOLEAN status struct myTable pTable status TRUE if getProgramStatus FUNCPTR main NEW_PROGRAM Application has just been downloaded request resource DYNAMIC MEMORY status allocateMemory void amp pNvMemory gt pAllocatedMem MEM SIZE release resource DYNAMIC MEMORY Document Version 1 61 5 19 2011 658 Example Programs if status TRUE set program status so memory is not re allocated until application is downloaded again setProgramStatus FUNCPTR main PROGRAM EXECUTED use non volatile memory for table structure pTable struct myTable pNvMemory gt pAllocatedMem while TRUE if status TRUE pTable is used in remainder of program print error message Allow other tasks to execute release processor Master Message Examp
427. ode Example The following code fragment displays the enabled wake up sources unsigned enabled nabled getWakeSource fputs Enabled wake up sources r n coml if enabled amp WS RTC_ALARM fputs Real Time Clock r n coml if enabled amp WS LED POWER SWITCH fputs LED Power Switch r n coml if enabled amp WS COUNTER_1 OVERFLOW fputs Counter 1 Overflow r n coml if enabled amp WS COUNTER_1 OVERFLOW fputs Counter 2 Overflow r n coml if enabled amp WS COUNTER_1 OVERFLOW fputs Counter 3 Overflow r n coml Document Version 1 61 5 19 2011 278 Function Specifications Handler Function User Specified Handler Function The handler function is a user specified function that handles processing of Modbus messages not recognized by the protocol The function can have any name handler is used in the Description below Syntax include lt ctools h gt UINT16 handler UCHAR message UINT16 messageLength UCHAR response UINT16 responseLength i Description This function handler is a user defined handler for processing Modbus messages The function is called for each Modbus message with a function code that is not recognized by the standard Modbus protocol The handler function should process the message string and create a response string If the message is not understood one of the error codes should
428. of available settings This change is most notable in the default setting for Rx Flow control as described below The documentation for the structure pconfig has been updated below to reflect these changes The C Tools required the Rx Flow Control for com1 and com2 to be set to DISABLE when the Modbus RTU protocol is used The ports com1 and com2 on the SCADAPack 350 and 4203 must have Rx Flow Control set to RFC_MODBUS_RTU or ENABLE when the Modbus RTU protocol is used Rx Flow Control must be set to RFC_NONE or DISABLE when the Modbus ASCII or any other protocol is used Rx and Tx Flow Control requirements are now the same for all serial ports of the SCADAPack 350 and 4203 New Flow Control MACROS To help clarify the type of Flow Control feature provided when ENABLE or DISABLE is specified four new macros have been defined RFC_MODBUS_RTU may be used in place of ENABLE Both have the value 1 RFC_NONE may be used in place of DISABLE Both have the value 0 TFC_IGNORE_CTS may be used in place of ENABLE Both have the value 1 TFC_NONE may be used in place of DISABLE Both have the value 0 Timeout Setting Not Supported Timed Events The timeout serial port setting is no longer supported for com1 and com2 The serial port timeout setting was never supported for com3 or com4 on the SCADAPack controller This setting is ignored and is fixed at 600ms for backwards compatibility Periodic timing may be desired when a continuous loop
429. ogram needs to wait for the response to be received Use the hartStatus command to read the status of the command The number of attempts and the number of preambles sent are set with the hartSetConfiguration command Document Version 1 61 5 19 2011 288 Function Specifications Not all devices return primary secondary tertiary and fourth variables If the device does not support a variable zero is written into the value and units code for that variable The code field of both HART_VARIABLE structures is not changed The response from the HART device to command 3 does not include variable codes The units field of variable 0 is set to 39 units mA The response from the HART device to command 3 does not include units See Also hartCommana33 hartStatus hartSetConfiguration Document Version 1 61 5 19 2011 289 Function Specifications hartCommand11 Read Unique Identifier Associated with Tag Syntax include lt ctools h gt BOOLEAN hartCommand11 UINT16 module char deviceTag HART DEVICE device Description This function reads the unique identifier of a HART device using command 11 This is a link initialization function The function has three parameters the module number of the 5904 module 0 to 3 a pointer to a null terminated string containing the tag of the HART device and a pointer to a HART_DEVICE structure The information read by command 11 is written into the HART _
430. ograms section datalogReadNext datalogPurge datalogWrite Example include lt ctools h gt include lt stdlib h gt int main void UINT16 logID recordSize pData UINT32 sequenceNumber seqNumRead nextSeqNum Select data log 10 logID 10 Find first record in data log 10 and store its sequence number in sequenceNumber xy if datalogReadStart logID amp sequenceNumber Get the size of this record Document Version 1 61 5 19 2011 140 Function Specifications if datalogRecordSize logID amp recordSize allocate memory of size recordSize pData UINT16 malloc recordSize read this record if datalogReadNext logID sequenceNumber amp seqNumRead amp nextSeqNum pData use pData to access record contents ay Document Version 1 61 5 19 2011 141 Function Specifications datalogRecordSize Data Log Record Size Function Syntax include lt ctools h gt BOOLEAN datalogRecordSize UINT16 logID UINT16 pRecordSize Description This function returns the size of a record for the specified data log The log needs to have been previously created with the datalogCreate function The function has two parameters og D specifies the data log The valid range is 0 to 15 pRecordSize points to a variable that will hold the size in bytes of each record in the log The function returns TRUE if the operation
431. ointer to an O_STATUS structure Refer to the table below for valid I O module types and address ranges The function returns TRUE if status information was copied to the structure pointed to by status The function returns FALSE if an argument is invalid is no room in the request queue or if an argument is invalid O70 15 Document Version 1 61 5 19 2011 366 Function Specifications Document Version 1 61 5 19 2011 367 Function Specifications ioSystemReset Add Reset Request to I O Controller Request Queue Syntax include lt ctools h gt BOOLEAN ioSystemReset void Description This function adds a reset request to the I O Controller request queue When the request is sent to the I O Controller all I O modules are reset The function has no arguments The function returns TRUE if the request was added The function returns FALSE if there is no room in the request queue Document Version 1 61 5 19 2011 368 Function Specifications ioVersion Get the I O Controller Firmware Version Syntax include lt ctools h gt BOOLI EAN ioVersion UINT16 amp pVersion Description This function returns the I O controller firmware version The version is read from the I O controller at initialization The f unction has one argument a reference to an UINT16 value to which the firmware version is copied if it is available The f unction returns TRUE if the firmware
432. ol_status function returns the protocol error and message counters for stream If stream does not point to a valid serial port the function has no effect Refer to the Overview of Functions section for detailed information on communication protocols See Also clear_protocol_status Example This program displays the checksum error counter for com2 include lt ctools h gt int main void struct prot_status status status get_protocol status com2 fprintf com1 Checksum d r n status checksum errors Document Version 1 61 5 19 2011 266 Function Specifications getSFTranslation Read Store and Forward Translation Syntax include lt ctools h gt void getSFTranslation UINT16 index SF TRANSLATION pfranslation Description Instead of using the getSFTranslation function use the getSFTranslationEx function which supports translations with a timeout and authentication The getSFTranslation function copies the entry from the store and forward translation table at index to the structure pointed to by pTransiation If index is invalid a disabled table entry is copied The disabled table entry has both station fields set to 65535 The SF_TRANSLATION structure is described in the Structures and Types section manual Notes The TeleBUS Protocols User Manual describes store and forward messaging mode See Also setSFTranslation clearSFTranslationTable checkSFTranslationTable Documen
433. olicitedClass3 holdTimeClass3 holdCountClass3 enableUnsolicitedOnStartup sendUnsolicitedOnStartup UINT16 lLevel2Compliance dnpConfiguration DOD DADA OD O C A J OD masterAddress is the address of the master station Unsolicited messages are sent to this station Solicited messages must come from this station Valid values are 0 to 65534 rtuAddress is the address of the RTU The master station must send messages to this address Valid values are 0 to 65534 datalinkConfirm enables requesting data link layer confirmations Valid values are TRUE and FALSE datalinkRetries is the number of times the data link layer will retry a failed message Valid values are 0 to 255 datalinkTimeout is the length of time the data link layer will wait for a response before trying again or aborting the transmission The value is measured in milliseconds Valid values are 100 to 60000 in multiples of 100 milliseconds Document Version 1 61 5 19 2011 596 Structures and Types e operateTimeout is the length of time an operate command is valid after receiving a select command The value is measured in seconds Valid values are 1 to 6500 e applicationConfirm enables requesting application layer confirmations Valid values are TRUE and FALSE e maximumResponse is the maximum length of an application layer response Valid values are 20 to 2048 The recommended value is 2048 unless the master cannot
434. ols h gt void checkTemperature void INT16 temperature temperature readThermistor T_FAHREHEIT if temperature lt 0 fprintf coml It s COLD r n lse if temperature gt 90 fprintf coml It s HOT r n Document Version 1 61 5 19 2011 472 Function Specifications readTimerVariable Read IEC 61131 1 Timer Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN readTimerVariable UCHAR varName UINT32 value Description This function returns the current value in milliseconds of the specified timer variable The maximum value returned is 86399999 ms or 24 hours The specified timer may be active or stopped The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the variable value is written to the unsigned long value pointed to by value If the variable is not found or if the IEC 61131 1 Symbols Status is invalid FALSE is returned and the current value is left unchanged The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC cod
435. on The IO_SYSTEM resource needs to be requested before calling this function Example See the Example in the Example Programs chapter under the section Master IP Message Example Document Version 1 61 5 19 2011 440 Function Specifications mTcpMasterOpen Open a Modbus IP Master Connection Syntax include lt ctools h gt BOOLEAN mTcpMasterOpen IP ADDRESS remoteIP IP PROTOCOL TYPE protocolType CONNECTION TYPE appType UINT16 timeout UINT32 connectID MODBUS CMD STATUS cmdStatus Description The mTcpMasterOpen function allocates the resources needed to make a Modbus IP master connection to a remote IP address These resources consist of a connection ID from the connection pool and the creation of a task to service the master IP connection When the task is created an initial connection to remotelP is attempted However the connection ID and master task are not restricted to just one remote P The currently connected IP address may be disconnected and connected to a different IP address any time mTcpMasterMessage is called with a different remotelP for this connection ID See mTcpMasterMessage for more details Valid values for protocolType are IPP_ModbusTcp IPP_ModbusRtuOverUdp or IPP_ModbusAsciiOverUdp There is only one valid value for appType CT_MasterCApp For TCP protocols the timeout specifies the time in tenths of seconds to wait for a connection to be established whenever a
436. on 1 61 5 19 2011 237 Function Specifications ethernetSetIP Set Ethernet Controller TCP IP Setting Syntax include lt ctools h gt BOOLEAN ethernetSetIP IP SETTINGS pIPSettings Description The ethernetSetIP function copies the settings pointed to by plPSettings to the Ethernet controller settings If the settings are different from the current settings the Ethernet interface is closed and re opened with the new settings When the Ethernet interface is closed all active connections through this interface are closed The structure IP_SETTINGS is described in the Structures and Types section If there is an invalid setting FALSE is returned and the settings are not saved otherwise TRUE is returned To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ PERMANENT release resource FLASH MEMORY Document Version 1 61 5 19 2011 238 Function Specifications flashSettingsLoad Load Controller Settings from Flash Syntax include lt ctools h gt BOOLEAN flashSettingsLoad UINT32 areaFlags Description This function loads the controller settings in the indicated area or areas from flash memory Settings in other areas are not affected The function has one parameter areaFlags indicating which areas to read
437. on in the database The table below shows the valid address modes and ranges Type Address Ranges Register Size MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes The function databaseWrite returns TRUE if the requested database value was written FALSE is returned if the requested database entry could not be written The I O database is not modified when the controller is reset It is a permanent storage area which is maintained during power outages The IO_SYSTEM resource needs to be requested before calling this function See Also databaseRead Document Version 1 61 5 19 2011 131 Function Specifications datalogCreate Create Data Log Function Syntax include lt ctools h gt DATALOG_STATUS datalogCreate UINT16 ogID DATALOG_CONFIGURATION pLogConfiguration Description This function creates a data log with the specified configuration The data log is created in the data log memory space The function has two parameters og D specifies the data log to be created The valid range is 0 to 15 pLogConfiguration points to a structure with the configuration for the data log The function returns the status of the operation Notes The configuration of an existing data log cannot be changed The log needs to be deleted and recreated to change the configuration All data logs are stored in memory f
438. on returns FALSE if the message definition is invalid or the transmission queue is full Refer to the session gt masterCmdStatus field for an error code Error codes are described in the Structures and Types section for the enum MODBUS_CMD_ STATUS The calling task monitors the status of the command sent using the session gt masterCmdStatus field The masterCmdStatus field is set to MM_SENT if a master message is sent It will be set to MM_RECEIVED when the response to the message is received The command status will be set to MM_RSP_TIMEOUT if the response is not received within the specified timeout The application needs to wait for a status of MM_RECEIVED or MM_RSP_TIMEOUT before sending the next master message This function may be used at the same time on the same serial port as a Telepace MSTR element or IEC 61131 1 master function block Notes Refer to the communication protocol manual for more information To optimize performance minimize the length of messages on com3 Examples of recommended uses for com3 are for local operator display terminals and for programming and diagnostics using the IEC 61131 1 program The IO_SYSTEM resource needs to be requested before calling this function Document Version 1 61 5 19 2011 505 Function Specifications See Also get_protocol_status clear_protocol_status master_message Example See the Example in the Example Programs chapter under the section Master Message Examp
439. on returns TRUE if the configuration was successfully written or FALSE otherwise if the point number is not valid or the configuration is not valid or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 205 Function Specifications dnpSaveAO16Config Save DNP 16 Bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAOl16Config UINT16 point dnpAnalogOutput pAnalogOutput 7 Description The dnpSaveAO1 6Config function sets the configuration of a DNP 16 bit analog output point The function has two parameters the point number and a pointer to an analog output point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpGetAO16Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 206 Function Specifications dnpSaveAO32Config Save DNP 32 Bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAO32Config UINT32 point dnpAnalogOutput pAnalogOutput 7 Description The dnp
440. on returns TRUE if the entry was added and FALSE if the index is not valid Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Use the dnpCreateRoutingT able function to create the routing table and specify its size See Also dnpCreateRoutingTable dnpWriteRoutingTableEntryEx Document Version 1 61 5 19 2011 201 Function Specifications dnpReadRoutingTableSize Read Routing Table size Syntax include lt ctools h gt UINT16 dnpReadRoutingTableSize void Description This function reads the total number of entries in the routing table Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 202 Function Specifications dnpSaveAl16Config Save DNP 16 Bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAI16Config UINT16 point dnpAnalogInput pAnalogInput 7 Description The dnpSaveAl1 6Config function sets the configuration of a DNP 16 bit analog input point The function has two parameters the point number and a pointer to an analog input point configuration structure The function returns TRUE if the configuration was written It returns FALSE if the point number is not valid if the configuration is not valid or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to
441. on the communication port specified by stream The break condition will persist until it is cleared by calling clearBreakCondition Notes If the serial port is transmitting characters when this function is called the transmission may not complete correctly No subsequent character transmissions will be possible until after clearBreakCondition has been called This function is only relevant for RS232 ports The function will have no effect on other port types See Also clearBreakCondition Document Version 1 61 5 19 2011 508 Function Specifications setclock Set Real Time Clock Syntax include lt ctools h gt void setclock TIME now Description The setclock function sets the real time clock now references a TIME structure containing the time and date to be set Refer to the Structures and Types section for a Description of the fields All fields of the clock structure needs to be set with valid values for the clock to operate properly Notes The IO_SYSTEM resource needs to be requested before calling this function See Also getclock Example This function switches the clock to daylight savings time include lt ctools h gt void daylight void TIME now request resource IO SYSTEM getclock amp now now hour now hour 1 24 setclock amp now request resource IO SYSTEM Document Version 1 61 5 19 2011 509 Function Specifications se
442. onfiguration Syntax include lt ctools h gt BOOLEAN dnpGetAO32Config UINT32 point dnpAnalogOutput pAnalogOutput Description The dnpGetAO32Config function reads the configuration of a DNP 32 bit analog output point The function has two parameters the point number and a pointer to an analog output point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAO32Config Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 172 Function Specifications dnpGetAOSFConfig Get Short Floating Point Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAOSFConfig UINT16 point dnpAnalogOutput pAnalogOutput Description The dnpGetAOSFConfig function reads the configuration of a DNP short floating point analog output point The function has two parameters the point number and a pointer to a configuration structure The function returns TRUE if the configuration was successfully read or FALSE otherwise if the point number is not valid or pointer is NULL or if the DNP configuration has not been created Notes DNP needs to be enabled before calling thi
443. onl unsigned long longValue i Description This function converts a long value from host byte order to network byte order Parameters longValue The value to convert Returns The converted value Document Version 1 61 5 19 2011 299 Function Specifications htons Syntax include lt ctools h gt unsigned short htons unsigned short shortValue i Description This function converts a short value from host byte order to network byte order Parameters shortValue The value to convert Returns The converted value Document Version 1 61 5 19 2011 300 Function Specifications inet_addr Syntax include lt ctools h gt unsigned long inet _addr char ipAddressDottedStringPtr e Function Description This function converts an IP address from the decimal dotted notation to an unsigned long Parameters ijpAddressDottedStringPtr The dotted string i e 208 229 201 4 Returns Value Meaning 1 Error Other The IP Address in Network Byte Order Document Version 1 61 5 19 2011 301 Function Specifications install_ handler Install Serial Port Handler Syntax include lt ctools h gt void install handler FILE stream BOOLEAN function INT32 INT32 Description The install_handler function installs a serial port character handler function The serial port driver calls this function each time it receives a character If stream does not point to a valid s
444. onnection and initiating a new call This pause allows the external modem time to hang up The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port The modemDialEnd function returns a DE_NotInControl error code if another modem function or incoming call is in control of the port Do not call this function in a task exit handler Use modemAbort instead Document Version 1 61 5 19 2011 422 Function Specifications modemDialStatus Return Status of Dial up Connection Syntax include lt ctools h gt void modemDialStatus FILE port reserve id id enum DialError error enum DialState state Description The modemDialStatus function returns the status of a remote connection initiated by the modemDial function port specifies the serial port where the modem is installed id is the port reservation identifier returned by the modemDial function The function sets the variable pointed to by error If no error occurred DE_NoError is returned Any other value indicates an error Refer to the Structures and Types section for a complete Description of error codes The function sets the variable pointed to by state to the current execution state of dialing operation The state value is not valid if the error code is DE_NotInControl Refer to the dialup h section for a complete Description of state codes Notes The serial port type must be s
445. ons Serial Communication SCADAPack 350 controllers offer three RS 232 serial ports 4203 controllers have two serial ports configurable for RS 232 or RS 485 The ports are configurable for baud rate data bits stop bits parity and communication protocol Default Serial Parameters Ports are configured at reset with default parameters when the controller is powered up in SERVICE mode The ports use stored parameters when the controller is reset in the RUN mode The default parameters are listed below 9600 Daas Je e e o Modbus RTU Debugging Serial Communication Serial communication can be difficult to debug This section describes common causes of communication failures To communicate the controller and an external device need to use the same communication parameters Check the parameters in both units If some but not all characters transmit properly you probably have a parity or stop bit mismatch between the devices The connection between two RS 232 Data Terminal Equipment DTE devices is made with a null modem cable This cable connects the transmit data output of one device to the receive data input of the other device and vice versa The controller is a DTE device This cable is described in the System Hardware Manual for your controller The connection between a DTE device and a Data Communication Equipment DCE device is made with a straight cable The transmit data output of the DTE device is con
446. onst char optionValue int optionLength i Description setsockopt is used manipulate options associated with a socket Options may exist at multiple protocol levels they are always present at the uppermost socket level When manipulating socket options the level at which the option resides and the name of the option must be specified To manipulate options at the socket level protoco Level is specified as SOL_SOCKET To manipulate options at any other level protocolLevel is the protocol number of the protocol that controls the option For Example to indicate that an option is to be interpreted by the TCP protocol protoco Level is set to the TCP protocol number The parameters optionValuePtr and optionlength are used to access option values for setsockopt optionName and any specified options are passed un interpreted to the appropriate protocol module for interpretation The include file lt ctools h gt contains definitions for the options described below Most socket level options take an int pointer for optionValuePtr For setsockopt the integer value pointed to by the optionValuePtr parameter should be non zero to enable a boolean option or zero if the option is to be disabled SO_LINGER uses a struct linger parameter that specifies the desired state of the option and the linger interval see below struct linger is defined in lt ctools h gt struct linger contains the following members _onoff on 1 off 0 _linge
447. ontroller is connected to a remote controller DS_Terminating returns the controller is ending a connection to a remote controller dlogConfiguration Type This structure defines the data log configuration It is used with the dlogCreate function typedef struct dlogConfiguration type UCHAR configVersion BOOLEAN fileRingBuffer UINT32 bufferFlushInterval UINT32 bufferRecordSize UINT32 fileMode UINT32 numFiles UINT32 fileRecordSize UINT32 numRecordElements dlogRecordElement recordList UINT32 securityToken UCHAR description 255 UCHAR logName 255 dlogConfiguration configVersion is the version of the configuration structure Always set this to 1 fileRingBuffer specifies if the oldest file is deleted when a new file would exceed the maximum number of files Set to TRUE to delete the oldest file Set to FALSE to stop writing to files and halt buffer flushing when the last file is full bufferFlushInterval is the interval in seconds at which the data log server will flush the buffer to file Valid values are any value greater than 0 bufferRecordSize is the number of records in the data log buffer fileMode selects where the data log files are stored Valid values are O internal flash drive 1 internal drive with auto copy to external drive 2 internal drive with auto move to external drive 3 external drive numFiles is the maximum number of log files Valid values are
448. op holdAoutsOnStop Document Version 1 61 5 19 2011 519 Function Specifications set_port Set Serial Port Configuration Syntax include lt ctools h gt void set _port FILE stream struct pconfig settings Description The set_port function sets serial port communication parameters port needs to specify one of com1 com2 or com3 settings references a serial port configuration structure Refer to the Description of the pconfig structure for an explanation of the fields Notes If the serial port settings are the same as the current settings this function has no effect The serial port is reset when settings are changed All data in the receive and transmit buffers are discarded The IO_SYSTEM resource needs to be requested before calling this function To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request resource FLASH MEMORY flashSettingsSave CS_ RUN release resource FLASH MEMORY See Also get_port Example This code fragment changes the baud rate on com2 to 19200 baud include lt ctools h gt struct pconfig settings get_port com2 amp settings settings baud BAUD19200 request resource IO SYSTEM set_port com2 amp settings release resource IO SYSTEM This code fragment sets com2 to the same settings as com1 include lt
449. operation completed successfully The xdelete function used a significant amount of stack space 2 extra stack blocks are required for each layer of sub directories that are to be deleted Example When deleting myFolder at least 6 stack blocks will be needed due to the 3 levels of folder structure myFolder ProjectA ltem 1 myFolder ProjectB ltem2 myFolder ProjectC ltem1 myFolder ProjectD ltem1 See Also copy xcopy Document Version 1 61 5 19 2011 570 Macro Definitions Macro Definitions AD_BATTERY Internal AD channel connected to lithium battery AlO_BADCHAN Error code bad analog input channel specified applicationGroup Specifies an application type task All application tasks are terminated by the end_application function AT_ABSOLUTE Specifies a fixed time of day alarm AT_NONE Disables alarms BACKGROUND System event background I O requested The background I O task uses this event It should not be used in an application program Document Version 1 61 5 19 2011 571 Macro Definitions Byte wise exclusive OR checksum Variable name cascade setpoint source data data data CLASS3_FLAG Specifies a flag for enabling DNP Class 3 data CLOSED Specifies switch is in closed position COLD_BOOT Cold boot switch depressed when CPU was reset com1 Points to a file object for the com1 serial port COM1_RCVR System event indicates activity on com1 receiver The meaning depe
450. or Refer to the Structures and Types section for a complete Description of error codes Notes The serial port type must be set to RS232_MODEM The modemInitStatus function returns the status of the connection attempt initiated by modemInit The modemInitEnd function terminates initialization of the modem If acommunication protocol is active on the serial port the protocol will be disabled until the initialization is complete then re enabled This allows the controller to communicate with the external modem on the port The protocol settings will also be restored when initialization is terminated with the modemInitEnd function If a modemDial function or an incoming call is active on the port the modemInit function cannot access the port and will return an error code of DE_NotInControl The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port To optimize performance minimize the length of messages on com3 Examples of recommended uses for com3 are for local operator display terminals and for programming and diagnostics using the IEC 61131 1 program Do not call this function in a task exit handler Document Version 1 61 5 19 2011 424 Function Specifications Example Refer to the Example in the Modem Initialization Example section Document Version 1 61 5 19 2011 425 Function Specifications modemlnitEnd Abort Initial
451. or Telepace folder for your application For example e Copy files from C program files Control Microsystems CTools Controller Framework Applications IEC 61131 1 e Copy files to C projects SP350 hello The appstart cpp file defines the basic settings for the application such as stack size and main task priority Applications typically can use the settings in this file without modification Open appstart cpp to review these application settings Priority of the task main Priority 100 is recommended for a continuously running task A task with priority gt 100 will never be given the CPU See manual for details UINT32 mainPriority 100 Stack space allocated to the task main Note that at least 10 stack blocks are needed when calling fprintf UINT32 mainStack 10 Application group assigned to the task main A unique value is assigned by the system to the applicationGroup for this application Use this variable in calls to create _task by this application See manual for details UINT32 applicationGroup 0 For this tutorial the C code to print hello world to serial port 2 will be added to the main task The hello world message will be output to the com2 serial port of the controller A terminal connected to the port will display the message The fprintf function prints the message to the com2 serial port Document Version 1 61 5 19 2011 21 Getti
452. ors occur A separate error code is maintained for each task Notes Some routines in the standard C library return errors in the global variable errno This variable is not unique to a task and may be modified by another task before it can be read Document Version 1 61 5 19 2011 106 Function Specifications checksum Calculate a Checksum Syntax include lt ctools h gt UINT16 checksum UCHAR start UCHAR end UINT16 algorithm Description The checksum function calculates a checksum on memory The memory starts at the byte pointed to by start and ends with the byte pointed to by end The algorithm may be one of ADDITIVE 16 bit byte wise sum CRC_16 CRC 16 polynomial checksum CRC_CCITT CRC CCITT polynomial checksum BYTE_EOR 8 bit byte wise exclusive OR The CRC checksums use the crc_reverse function Example This function displays two types of checksums include lt ctools h gt void checksumExample void char str This is a test UINT16 sum Display additive checksum sum checksum str str strlen str ADDITIVE fprintf coml Additive checksum u r n sum r r Display CRC 16 checksum sum checksum str str strlen str CRC_16 fprintf coml CRC 16 checksum u r n sum r r Document Version 1 61 5 19 2011 107 Function Specifications checkSFTranslationTable Test for Store and Forward Configuration Errors Syntax include lt ctools h
453. ou can reach us by e mail at technicalsupport controlmicrosystems com Document Version 1 61 5 19 2011 17 Overview Overview The SCADAPack C Tools are ideal for engineers and programmers who require advanced programming tools for SCADA applications and process control The SCADAPack controllers execute Telepace Ladder Logic or IEC 61131 1 and up to 32 C application programs simultaneously providing you with maximum flexibility in implementing your control strategy This manual provides documentation on SCADAPack C programming and the library of C language process control and SCADA functions We sincerely hope that the reliability and flexibility afforded by this fully programmable controller enable you and your company to solve your automation projects in a cost effective and efficient manner Technical Support Support related to any part of this documentation can be directed to one of the following support centers Technical Support The Americas Available Monday to Friday 8 00am 6 30pm Eastern Standard Time Toll free within North America 1 888 226 6876 Direct Worldwide 1 613 591 1943 Email TechnicalSupport controlmicrosystems com Technical Support Europe Africa Middle East Available Monday to Friday 8 30am 5 30pm Central European Standard Time Direct Worldwide 31 71 597 1655 Email euro support controlmicrosystems com Technical Support Asia Pacific Available Monday to Friday 8 30am
454. ou to potential personal injury hazards Obey all safety messages that follow this symbol to avoid possible injury or death Dancer injury DANGER indicates an imminently hazardous situation which if not avoided will result in death or serious Awarnine injury WARNING indicates a potentially hazardous situation which if not avoided can result in death or serious Document Version 1 61 5 19 2011 14 Acaution CAUTION indicates a potentially hazardous situation which if not avoided can result in minor or moderate CAUTION CAUTION used without the safety alert symbol indicates a potentially hazardous situation which if not avoided can result in equipment damage PLEASE NOTE Electrical equipment should be installed operated serviced and maintained only by qualified personnel No responsibility is assumed by Schneider Electric for any consequences arising out of the use of this material A qualified person is one who has skills and knowledge related to the construction and operation of electrical equipment and the installation and has received safety training to recognize and avoid the hazards involved BEFORE YOU BEGIN Do not use this product on machinery lacking effective point of operation guarding Lack of effective point of operation guarding on a machine can result in serious injury to the operator of that machine CAUTION
455. pecifications getHardwarelnformation Obtains the hardware type and version Syntax include lt ctools h gt BOOLEAN getHardwareInformation UCHAR majorVersion UCHAR minorVersion UCHAR hardwareType Description The getHardwarelnformation function will place the major version of the hardware into the memory pointed to by majorVersion the minor version of the hardware into the minorVersion and the hardware type in the memory pointed to by hardwareT ype Refer to the macros starting with HT_ for the various hardware types The function returns TRUE if the hardware version and type was placed in the passed variables Otherwise FALSE is returned Notes This function is currently only supported on the SCADAPack 350 and 4203 Document Version 1 61 5 19 2011 252 Function Specifications getlOErrorlIndication Get I O Module Error Indication Syntax include lt ctools h gt BOOLEAN getlOErrorIndication void Description The getlOErrorIndication function returns the state of the I O module error indication TRUE is returned if the I O module communication status is currently reported in the controller status register and Status LED FALSE is returned if the I O module communication status is not reported Notes Refer to the 5203 4 System Manual SCADAPack 32 System Manual or the SCADAPack 350 System Manual for further information on the Status LED and Status Output See Also setlOErrorindi
456. pies the protocol settings into the structure pointed to by settings and returns a pointer to that structure Refer to the ctools h file for a Description of the fields in the prot_settings structure Refer to the Overview of Functions section for detailed information on communication protocols See Also set_protocol Example This program displays the protocol configuration for com1 include lt ctools h gt int main void struct prot_settings settings get_protocol coml amp settings fprintf com1 Type sd r n settings type fprintf com1 Station d r n settings station fprintf com1 Priority d r n settings priority Document Version 1 61 5 19 2011 261 Function Specifications getProtocolSettings Get Protocol Extended Addressing Configuration Syntax include lt ctools h gt BOOLEAN getProtocolSettings FILE stream PROTOCOL SETTINGS settings Description The getProtocolSettings function reads the protocol parameters for a serial port This function supports extended addressing The function has two parameters portis one of com1 com2 or com3 and settings a pointer to a PROTOCOL_SETTINGS structure Refer to the Description of the structure for an explanation of the parameters The function returns TRUE if the structure was changed It returns FALSE if the stream is not valid Notes Extended addressing is available on the Modbus RTU and Modbus ASCI
457. plication Framework Begin by making a copy of the SCADAPack C application framework using the IEC 61131 1 sample application or the Telepace sample application By default the samples are installed at C Program Files Control Microsystems CTools Controller Framework Applications Make a copy of one of the following directories e C Program Files Control Microsystems CTools Controller Framework Applications Telepace e C Program Files Control Microsystems CTools Controller Framework Applications IEC 61131 1 Changes to appstart cpp The new appstart cpp assigns the stack size as well as the main task priority Task priorities are discussed under changes to the function create_task The heap size is no longer configurable The C application has access to the entire system heap Open the sample appstart cpp to review these application settings Priority of the task main Priority 100 is recommended for a continuously running task UINT32 mainPriority 100 Stack space allocated to the task main Note that at least 5 stack blocks are needed to call fprintf UINT32 mainStack 5 Application group assigned to the task main A unique value is assigned by the system to the applicationGroup for this application Use this variable in calls to create_task by this application UINT32 applicationGroup 0 A C application should not require any further modifications to appstart cpp Note that there
458. pointer to the address structure where the address information will be stored addressLengthPtr The length of the address structure Returns 0 Success 1 An error occurred getsockname can fail for any of the following reasons EBADF socketDescriptor is not a valid descriptor EINVAL One of the passed parameters is not valid Document Version 1 61 5 19 2011 269 Function Specifications getsockopt Syntax include lt ctools h gt int getsockopt int socketDescriptor int protocollLevel int optionName char optionValuePtr int optionLengthPtr i Description getsockopt is used retrieve options associated with a socket Options may exist at multiple protocol levels they are always present at the uppermost socket level When manipulating socket options the level at which the option resides and the name of the option must be specified To manipulate options at the socket level protoco Level is specified as SOL_SOCKET To manipulate options at any other level protocolLevel is the protocol number of the protocol that controls the option For Example to indicate that an option is to be interpreted by the TCP protocol protocol Level is set to the TCP protocol number For getsockopt the parameters option ValuePtr and optionLengthPtr identify a buffer in which the value s for the requested option s are to be returned For getsockopt optionLengthPtr is a value result parameter initially contain
459. pplication Test the Application Existing programs may use some functions that are partially supported or unsupported on the SCADAPack 350 and 4203 controllers The program must be changed to use the new functions For a list of the functions affected refer to the sections Partially Supported C Tools Functions The SCADAPack C Tools use a command line to compile and link a C application The sample application includes the command file build bat to do this Please see the section Application Development for more details on editing build bat command line options and loading the application into the controller This step is specific to the application It must be tested to confirm it operates correctly on the SCADAPack 350 and 4203 controllers You also should pay attention to the following e SCADAPack 350 and 4203 controllers have higher performance than do SCADAPack controllers Check that any I O operations allow enough time for field signals to change state Some timing relationships in the existing program may not be true in the new program depending on how you have implemented them For example a calculation done between two I O operations may execute faster and cause the second I O operation to take place sooner than you want e Check that any periodic functions execute at the correct rate If you ve used standard timing functions this should not be a problem If you ve used delay loops then these will execute faster You should
460. pplications in SCADAPack 330 350 controllers These registers cannot be used for other purposes in logic or C C application This includes the following uses e masterMessage function that uses 39800 to 39999 as destination registers e setForceFlag function that use 39800 to 39999 as destination registers e Any registerAssignment that uses registers 39800 to 39999 39800 uchar 8 Controller ID padded with nulls 0 first byte in lowest register one byte per register 39808 Firmware version major 100 minor 39809 Firmware version build number if applicable 39810 uint 3 Logic application 1 identifier see format below 39813 uint 3 Logic application 2 identifier see format below 39816 uint Number of applications identifiers used 0 to 32 Identifiers are listed sequentially starting with identifier 1 Unused identifiers will return 0 39817 uint 3 Application identifier 1 see format below 39820 uint 3 Application identifier 2 see format below Document Version 1 61 5 19 2011 121 Function Specifications Application identifier 8 see format below Application identifier 9 see format below Application identifier 13 see format below Application identifier 15 see format below Application identifier 16 see format below Application identifier 22 see format below Application identifier 29 see format below Application identifier 32 see format below 39913 to Reserved for future expansion 39
461. processor with the difference that the CPU is released for at least msTime which represents milliseconds Tasks of the same priority run ina round robin fashion as each releases the processor to the next Notes The call sleep_processor 0 has the same effect as the call release_processor Internally the sleep time msTime will be converted into ticks With a 60 Hz system clock the minimum wait time is 16 6 ms Wait times will be rounded up to the next tick value Refer to the Real Time Operating System section for more information on tasks and task scheduling See Also release_processor Document Version 1 61 5 19 2011 546 Function Specifications sleepMode Suspend Controller Operation Syntax include lt ctools h gt UINT16 sleepMode void Description The sleepMode function puts the controller into a sleep mode Sleep mode reduces the power consumption to a minimum by halting the microprocessor clock All programs halt until the controller resumes execution All output points turn off while the controller is in sleep mode The controller resumes execution under the conditions shown in the table below The application program may disable some wake up conditions If a wake up condition is disabled the controller will not resume execution when the condition occurs All wake up conditions will be enabled by default Refer to the Description of the setWakeSource function for details sleepMode returns the source
462. provide parallel execution of multiple tasks The application program can be event driven or tasks can execute round robin one after another Task execution is based upon the priority of tasks There are 256 priority levels Application programs can use levels 100 to 0 The main task is created at priority level 100 Task level 0 is the highest priority task Tasks that are not running are held in queues The Ready Queue holds tasks that are ready to run Event queues hold tasks that are waiting for events Message queues hold tasks waiting for messages Resource queues hold tasks that are waiting for resources The envelope queue holds tasks that are waiting for envelopes Priority Inversion Prevention When a higher priority task Task H requests a resource which is already obtained by a lower priority task Task L the higher priority task is blocked until Task L releases the resource If Task L is unable to execute to the point where its releases the resource Task H will remain blocked This is called a Priority Inversion To keep this from occurring the prevention method known as Priority Inheritance has been implemented In the example already described the lower priority task Task L is promoted to the priority of Task H until it releases the needed resource At this point Task L is returned to its original priority Task H will obtain the resource now that it is available Document Version 1 61 5 19 2011 45 Real Time
463. pulse Retrigger Watchdog Timer Syntax include lt ctools h gt void wd pulse void Description The wd_pulse function retriggers the watchdog timer Notes The wd_pulse function needs to execute at least every 0 5 seconds to avoid a controller reset if the wd_manual function has been executed Refer to the Functions Overview section for more information Example See the Example for the wd_manual function Document Version 1 61 5 19 2011 562 Function Specifications writeBoolVariable Write to IEC 61131 1 Boolean Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN writeBoolVariable UCHAR varName UCHAR value Description This function writes to the specified boolean variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified value is written to the variable If the variable is not found or if the IEC 61131 1 Symbols Status is invalid nothing is done and FALSE is returned The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum TRUE is written when value is any non zero value FALSE is written when value is 0 Notes This function requires the IEC 61131 1 Application Symbols to be dow
464. r The I O database contains user assigned registers and general purpose registers Assigned registers map directly to the I O hardware or system parameter in the controller General purpose registers can be used by ladder logic and C application programs to store processed information and to receive information from a remote device Document Version 1 61 5 19 2011 72 Overview of Programming Functions The TeleBUS protocols operate on a wide variety of serial data links These include RS 232 serial ports RS 485 serial ports radios leased line modems and dial up modems The protocols are generally independent of the communication parameters of the link with a few exceptions Application programs can initiate communication with remote devices A multiple port controller can be a data concentrator for remote devices by polling remote devices on one port s and responding as a slave on another port s The protocol type communication parameters and station address are configured separately for each serial port on a controller One controller can appear as different stations on different communication networks The port configuration can be set from an application program from the IEC 61131 1 programming software or from another Modbus or DF1 compatible device Protocol Type The protocol type may be set to emulate the Modbus ASCII and Modbus RTU protocols or it may be disabled When the protocol is disabled the port functions
465. r company version is the version of your application in the format major 100 minor Valid values are 0 to 65535 The function returns TRUE if the action was successful and FALSE if an error occurred Document Version 1 61 5 19 2011 120 Function Specifications Register Mapping The Device configuration is stored in Modbus input 8xxxx registers as shown below The registers are read with standard Modbus commands These registers cannot be written to Device configuration registers used fixed addresses This facilitates identifying the applications in a standard manner The Device configuration registers can be enabled or disabled by entering a 0 or 1 in the Start Register They are disabled until enabled by a logic application This provides compatibility with controllers that have already used these registers for other purposes The application IDs are cleared on every controller reset Applications need to run and set the application ID for it to be valid These data types are used Unsigned 16 bit integer Unsigned 8 bit character type n n element array of specified data type The following information is stored in the device configuration 2 logic application identifiers are provided for compatibility with SCADAPack ES ER controllers that provide 2 IEC 61131 1 applications The second logic application identifier is not used with other controllers 32 application identifiers are provided to accommodate C a
466. r linger time in seconds The following options are recognized at the socket level SOL_SOCKET protocolLevel options SO_DONTROUTE Enable disable routing bypass for outgoing messages Default 0 SO_KEEPALIVE Enable disable keep connections alive Default 0 SO_LINGER Linger on close if data is present Default is on with 60 seconds timeout SO_OOBINLINE Enable disable reception of out of band data in band Default 0 SO_REUSEADDR Enable disable local address reuse Default 0 disable Document Version 1 61 5 19 2011 536 Function Specifications SO_RCVLOWAT The low water mark for receiving data SO_SNDLOWAT The low water mark for sending data SO_R CVBUF Set buffer size for input Default 8192 bytes SO_SNDBUF Set buffer size for output Default 8192 bytes SO_REUSEADDR indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses SO_KEEPALIVE enables the periodic transmission of messages on a connected socket If the connected party fails to respond to these messages the connection is considered broken SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities Instead messages are directed to the appropriate network interface according to the network portion of the destination address SO_LINGER controls the action taken when unsent messages are queued on a socket and a close on the socket is performed If the socket promises reliable
467. r use in an application program This function can be called from application and interrupt code See Also poll_event Example This program creates a task to wait for an event then signals the event include lt ctools h gt void taskl void while TRUE wait event 20 fprintf coml Event 20 occurred r n int main void UINT32 startTime create task taskl 75 applicationGroup 4 while TRUE body of main task loop Document Version 1 61 5 19 2011 544 Function Specifications The body of this main task is intended solely for signaling the event waited for by taskl Normally main would be busy with more important things to do otherwise the code in taskl could be executed within main s wait loop startTime readStopwatch while readStopwatch startTime lt 1000 wait for 1s Allow other tasks to execute release processor signal event 20 Document Version 1 61 5 19 2011 545 Function Specifications sleep_processor Release Processor to other Tasks for a certain time Syntax include lt ctools h gt void sleep processor UINT32 msTime Description The sleep_processor function releases control of the CPU to other tasks for a certain time Other tasks of the same priority get a chance to run or when no such task is in a ready state lower priority tasks will run This function is similar to release_
468. rRegAssignments cah cer nani E SEE iene tn 114 ClearSFTranslationT able nista aeaa aaan ia eaaa aa Aaaa Aa a a aeaeaie 115 ClearStatus Bitis ach aeiae Ae a ian inte Gti aed la 116 Clear o 2 ie ei eee eee in eee dee ei ieee tis 117 ClOSE AEE EE ah Sainte a oni ite ae E RTS 118 configurationRegisterMapping cceseseceeeeeneeeeeenneeeeeeaeeeseeaaeeeeeeaaeeeeeeaaeeeeseaas 119 configurationSetApplication D eeeccecceeeeeeeeneeceeeeeceaeeeseaeeeeeeeseaeeeseaeeneneeenaees 120 CONNEC CES tes ccd E eesti Mucsbee rest A E T 124 COPY sesisteiiistects diabetes A A A Inia ania larga iniabangia 126 CIC TOVGISO AE E E ice ace Stas E edennace dad T A Mees hveestas 127 CE ALS te Ke aE A hiss EA nest aves lo eat Ieee ae ces 128 databaseRe ad cis tif accin seep ie R vache stipe held 130 datapase Wile aiia aia araa a a ANE EA E ARA A PAI EE 131 data logGredtov iniii tienata aia beaded bapa de diva alee 132 datalog DEINE aaea vacbacs fee AE Ea a aches a AI E 134 CatalogPurge caia A a E AN AA A A eee 136 CatalogReadNe xt 0 eeccccessecceeeeseceeeeeseceeeenseaeeeeneeceeeeneaeeeenseaeeesseeeeeesneeaeeeenanes 138 AatalogReadStart ecccescceeseecsecceceeececeseeeeaceseeeaesnaeeeeaaeseeaaeseeesaaeseeaaesseeaeenaees 140 AatalogRecordSiZe cceccccccceceeeeeceeeeceeeeeeaeeeeaeeseeeesaaesesaaeseeeeeseaeeesaeeseneeesaees 142 datalog Setting Sini eras ee aR Ea aE e NA A EO asses a a R E 143 CatalOQW ite isis tce aeticetis aaa E T S 144
469. ransferStatus DNP_ADDRESS_MAP_TABLE The dnpAddressMapTable type describes an entry in the DNP Address Mapping Table typedef struct dnpAddressMapTable type UINT16 address CHAR objectType UINT16 remoteObjectStart UINT16 numberOfPoints UINT16 localModbusAddress dnpAnalogInput dnpAddressMapTable address is the DNP station address of the remote station objectType is the DNP object type remoteObjectStart is the DNP address of first object in the remote station numberOfPoints is the number of points localModbusAddress is the Modbus address of first object in local station The dnpAnaloginput type describes a DNP analog input point This type is used for both 16 bit and 32 bit points typedef struct dnpAnalogInput_type UINT16 modbusAddress UCHAR class UINT32 deadband dnpAnalogiInput modbusAddress is the address of the Modbus register number associated with the point class is the reporting class for the object It may be set to CLASS _1 CLASS_2 or CLASS _3 deadband is the amount by which the analog input value needs to change before an event will be reported for the point Document Version 1 61 5 19 2011 592 Structures and Types DnpAnaloginputShortFloat dnpAnalogOutput dnpBinarylnput dnpBinarylnputEx The dnpAnaloginputShortFloat type describes a DNP analog input point The format of this point complies with the
470. ration Delete a data log and associated resources except log files Delete data logs and associated resources except log files Return the ID of an existing data log Write to a data log Return the space available in the data log buffer Document Version 1 61 5 19 2011 79 Overview of Programming Functions dlogFlush Flush data log buffer contents to log file dlogNewFile Create a new data log file dlogSuspend Suspend writing to the data log file from the data log buffer dlogResume Resume writing to a suspended data log file dlogGetStatus Return the auto transfer and media status information of a data log Data Log Enumeration Types Sockets API The ctools h file defines the following enumeration types dlogStatus Type dlogTransferStatus Type dlogConfiguration Type dlogRecordElement Type dlogCMITime Type Refer to the C Tools Structures and Types section for complete information on structures and enumeration types These functions provide support for the BSD 4 4 Socket API Additional Socket Extension functions are also provided These apply specifically to the SCADAPack 350 TCP IP Stack Refer to the Function Specification section for details on each function listed accept listen bind ntohl connect ntohs getpeername readv getsockname recv getsockopt recvfrom htonl rresvport htons select inet_addr send inet_aton sendto setsockopt shutdown socket Document Version 1 61 5 19
471. recommended uses for com3 are for local operator display terminals and for programming and diagnostics using the IEC 61131 1 program Do not call this function in a task exit handler Example Refer to the Examples in the Connecting with a Remote Controller Example section Document Version 1 61 5 19 2011 421 Function Specifications modemDialEnd Terminate Dial up Connection Syntax include lt ctools h gt void modemDialEnd FILE port reserve id id enum DialError error Description The modemDialEnd function terminates a dial up connection or connection in progress port specifies the serial port the where the modem is installed id is the port reservation identifier returned by the modemDial function The function sets the variable pointed to by error If no error occurred DE_NoError is returned Any other value indicates an error Refer to the Structures and Types section for a complete Description of error codes Notes The serial port type must be set to RS232_MODEM A connection can be terminated by any of the following events Once terminated another modem function or incoming call can take control of the serial port e Execution of the modemDialEnd function e Execution of the modemAbort or modemAbortAll functions e The remote device hangs up the phone line e An accidental loss of carrier occurs due to phone line problems A pause of a few seconds is required between terminating a c
472. reference to an array of four UINT32 variables If the moduleAddress is valid data are copied to the array The valid range for moduleAddress is 0 to 15 The maximum count is 4 294 967 295 Counters roll back to 0 when the maximum count is exceeded The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 350 Function Specifications ioReadCounterSP2 Read Data From the SCADAPack 350 Counter Inputs Syntax include lt ctools h gt BOOLEAN ioReadCounterSP2 UINT32 amp data 3 Description This function reads buffered data from the SCADAPack 350 counter inputs Buffered data are updated when an I O request for the module is processed The function has one parameter a reference to an array of three UINT32 variables The buffered data are copied to the array The maximum count is 4 294 967 295 Counters roll back to 0 when the maximum count is exceeded The function returns TRUE Document Version 1 61 5 19 2011 351 Function Specifications ioReadDin16 Read Data From 16 point Digital Input Module Syntax include lt ctools h gt BOOLEAN ioReadDinl6 UINT16 moduleAddress UINT16 amp data Description This function reads buffered data from the 16 point digital input module at the specified module address Buffered data are updated when an I O request for the module is processed The function has two parameters the module
473. replace them with standard timing functions Partially Supported C Tools Functions The following sections describe functions that are supported by the Telepace C Tools and IEC 61131 1 C Tools but are only partially supported by the Document Version 1 61 5 19 2011 681 Porting Existing C Tools Applications SCADAPack C Tools The following features are similar to existing C Tools features but require some source code modification Refer to these sections when porting existing SCADAPack C Tools Applications Event Numbers for SCADAPack C Applications The SCADAPack 350 and 4203 support up to 32 separate user loaded C Applications Event numbers 0 to 31 were made available to the SCADAPack C application This same event number range needs to be shared on the SCADAPack 350 and 4203 among the user loaded C Applications The Realflo C Application uses events 20 21 or 22 These events may not be used by other C Applications when the Realflo C Application is loaded in the SCADAPack 350 and 4203 Stack used by fprintf Function Tasks that call the function fprintf require at least 5 stack blocks This function required only 4 stack blocks when used in SCADAPack C applications As a general rule add 1 stack block to the amount used in a SCADAPack application Macro stdout is Disabled The macro stdout is disabled in the SCADAPack C Tools Instead use the serial port macros com1 com2 or com3 This means that the
474. ressPrtr int addressLength Description bind assigns an address to an unnamed socket When a socket is created with socket it exists in an address family space but has no address assigned bind requests that the address pointed to by addressPtr be assigned to the socket Clients do not normally require that an address be assigned to a socket However servers usually require that the socket be bound to a well known address The port number may be any port number between 0 and 65535 Multiple sockets cannot bind to the same port with different IP addresses as might be allowed in UNIX Parameters socketDescriptor The socket descriptor to assign an IP address and port number to addressPtr The pointer to the structure containing the address to assign addressLength The length of the address structure Returns 0 Success 1 An error occurred bind can fail for any of the following reasons EADDRINUSE The specified address is already in use EBADF socketDescriptor is not a valid descriptor EINVAL One of the passed parameters is invalid or socket is already bound EINPROGRESS bind is already running Document Version 1 61 5 19 2011 105 Function Specifications check_error Get Error Code for Current Task Syntax include lt ctools h gt UINT32 check_error void Description The check_error function returns the error code for the current task The error code is set by various I O routines when err
475. ription The installModbusHandler function allows user defined extensions to standard Modbus protocol This function specifies a function to be called when a Modbus message is received for the station but is not understood by the standard Modbus protocol The installed handler function s is called only if the message is addressed to the station and the message checksum is correct The function has one parameter a pointer to a function to handle the messages See the section Handler Function for a full Description of the function and it s parameters The function has no return value Notes This function is used to create a user defined extension to the standard Modbus protocol Call the removeModbusHandler function to remove a previously installed handler This needs to be done when the application program is ended with an exit handler Use the installExitHandler function to install the exit handler If the Modbus handler is not removed within an exit handler it will remain installed and continue to operate until the controller power is cycled Changing the protocol type or Erasing the C Program from IEC 61131 1 Initialize dialog will not remove the Modbus handler If the handler is located in a RAM based application and left enabled while a different C application is downloaded the original handler will be corrupted and the system will likely not work See Also removeModbusHandler Handler Function installExitHandler Documen
476. rites an entry in the DNP address mapping table The function returns TRUE if successful FALSE otherwise Notes DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 221 Function Specifications dnpWriteMasterApplicationLayerConfig Write DNP Master Application Layer Configuration Syntax include lt ctools h gt BOO EAN dnpWriteMasterApplicationLayerConfig UINT16 basePollInterval UINT 16 mimicMode Description This function writes DNP Master application layer configuration Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns TRUE if successful FALSE otherwise Document Version 1 61 5 19 2011 222 Function Specifications dnpWriteMasterPollTableEntry Write DNP Master Poll Table Entry Syntax include lt ctools h gt BOOLEAN dnpWriteMasterPollTableEntry UINT16 index UINT16 dnpAddress UINT16 classOPollRate UINT16 class1lPollRate UINT16 class2PollRate UINT16 class3PollRate UINT16 timeSyncRate UINT16 unsolicitedResponseFlags Description This function writes an entry in the DNP master poll table Notes DNP needs to be enabled before calling this function in order to create the DNP configuration The function returns TRUE if successful FALSE otherwise Document Versio
477. rm settings e Configure serial ports with default parameters e Configure serial ports with default protocols e Clear serial port event counters e Clear store and forward configuration e Enable LED power by default and return to default state after 5 minutes e Set Outputs on Stop settings to Hold e Set 5904 HART modem configuration for all modems e Set Modbus TCP default configuration e Write new default data to Flash Notes This function can be used to restore the controller to its default state ioDatabaseReset has the same effect as selecting the Initialize Controller option from the Initialize command in the IEC 61131 1 program The IO_SYSTEM resource needs to be requested before calling this function Example include lt ctools h gt Document Version 1 61 5 19 2011 312 Function Specifications int main void Power Up Initialization request resource IO SYSTEM ioDatabaseReset release resource IO SYSTEM the rest of the program Document Version 1 61 5 19 2011 313 Function Specifications ioGetConfiguration Get I O Controller Configuration Syntax include lt ctools h gt IO_CONFIG amp ioGetConfiguration void Description This function returns the I O controller configuration The function has no arguments The function returns an IO_CONFIG structure containing the configuration Document Version 1 61 5 19 2011 314 Function Specificat
478. rom a pool for all data logs If there is insufficient memory the creation operation fails The function returns DLS_NOMEMORY If the data log already exists the creation operation fails The function returns DLS_EXISTS If the log ID is not valid the creation operation fails The function returns DLS_BADID If the configuration is not valid the creation operation fails The function returns DLS_BADCOMFIG See Also See example DataLog program in the Example Programs section datalogDelete datalogSettings Example This program creates a data log and writes one record to it include lt ctools h gt Structure used to copy one record into data log struct dataRecord Document Version 1 61 5 19 2011 132 Function Specifications UINT16 valuel INT32 value2 double value3 float value4 float valued e int main void UINT16 lLogID DATALOG CONFIGURATION dLogConfig log configuration struct dataRecord data sample record Assign a number to the data log logID 10 Fill in the log configuration structure dLogConfig records 200 dLogConfig fields 5 dLogConfig typesOfFields 0 DLV_UINT16 dLogConfig typesOfFields 1 DLV_INT32 dLogConfig typesOfFields 2 DLV DOUBLE dLogConfig typesOfFields 3 DLV_FLOAT dLogConfig typesOfFields 4 DLV_FLOAT Assign some data for the log data valuel 100 data value2 200 data
479. ror occurred during creation of the log The dlogID is not valid e DLOGS_WRONGPARANM if an error occurred due to a wrong parameter Description A data log has to be created before any client can log data records The configuration structure contains a data log name It is a string which is used to build the log file names Each data log name has to be unique a data log creation will fail if one already exists with the same name A data log name can also contain a path Therefore it is possible to have log files with the same prefix naming but in different directories e g DIR1 LOG1 and DIR2 LOG1 The Document Version 1 61 5 19 2011 149 Function Specifications relative data log name will be combined with the drive name depending on the configuration The dlogCreate call creates a data log instance The data log specific buffer configuration and run time data are allocated in dynamic non volatile memory Data log files are not created these are created as needed by the data log server If dlogCreate is called for an existing data log the configuration parameters are compared If they are the same the function returns a valid dlogID with a warning return value DLOGS_EXISTS If they are different the function returns with the error DLOGS_DIFFERENT Data Log data is stored in non volatile memory If this memory cannot be allocated dlogCreate returns DLOGS_ NOMEMORY dlogCreate returns in an output parame
480. rough the underlying protocol then 1 is returned with the socket error being set to EMSGSIZE and the message is not transmitted A return value of 1 indicates locally detected errors only A positive return value does not implicitly mean the message was delivered but rather that it was sent If the socket does not have enough buffer space available to hold the message being sent and is in blocking mode sendto blocks If it is in non blocking mode or the MSG_DONTWAIT flag has been set in the flags parameter 1 is returned with the socket error being set to EWOULDBLOCK The select call may be used to determine when it is possible to send more data Parameters socketDescriptor The socket descriptor to use to send data bufferPtr The buffer to send bufferLength The length of the buffer to send toPtr The address to send the data to toLength The length of the to area pointed to by toPtr flags See below The flags parameter is formed by ORing one or more of the following MSG_DONTWAIT Don t wait for data send to complete but rather return immediately MSG_DONTROUTE The SO _DONTROUTE option is turned on for the duration of the operation Only diagnostic or routing programs use it Document Version 1 61 5 19 2011 503 Function Specifications Returns Value Meaning gt 0 Number of bytes actually sent on the socket 1 An error occurred sendto will fail if EBADF The socket descriptor is invalid ENOBUFS
481. rror occurred close can fail for the following reasons TM_EBADF The socket descriptor is invalid TM_ESHUTDOWN A write shutdown has already been performed on the socket TCP socket only TM_EALREAY A previous close call is already in progress TM_ECONNABORTED The TCP connection was reset because the linger option was on with a timeout value of 0 TCP socket only TM_ETIMEDOUT The linger option was on with a non zero timeout value and the linger timeout expired before the TCP close handshake with the remote host could complete blocking TCP socket only Document Version 1 61 5 19 2011 118 Function Specifications configurationRegisterMapping Enable or disable mapping of device configuration registers Syntax include lt ctools h gt void configurationRegisterMapping BOOLEAN enabled Description This function enables or disables mapping of device configuration registers These registers are located at a fixed location in the input register area enabled selects if the registers are mapped Valid values are TRUE and FALSE Selecting FALSE hide the configuration data but does not change it See Also configurationSetApplicationID Document Version 1 61 5 19 2011 119 Function Specifications configurationSetApplicationID Set an application ID Syntax include lt ctools h gt BOOLEAN configurationSetApplicationID UINT16 applicationType UINT16 action UINT16 companyID UINT16
482. rt register specifies the first register of an unused block of consecutive registers for each type of input or output on the module Refer to the list of modules in the Register Assignment Reference for the module I O types Specify 0 for startingRegister2 startingRegister3 or startingRegister4 if not applicable Document Version 1 61 5 19 2011 93 Function Specifications Notes Up to 150 modules may be added to the Register Assignment If the Register Assignment is full or if an incorrect value is specified for any argument this function returns FALSE otherwise TRUE is returned Output registers specified for certain CNFG type modules are initialized with the current parameter values when the module is added to the Register Assignment e g CNFG_realTimeClock Call clearRegAssignment first before using the addRegAssignment function when creating a new Register Assignment Duplicate or overlapping register assignments are not checked for by this function Overlapping register assignments may result in unpredictable I O activity To obtain error checking that avoids invalid register assignments such as these use the Telepace Register Assignment dialog to build the Register Assignment Then save the Register Assignment in a Ladder Logic file e g filename lad and download it with the C program or transfer the Register Assignment to the C program using the clearRegAssignment and addRegAssignment functions To save the Regis
483. s typedef UINT16 userType 10 Structure used to copy one record into data log typedef struct dataRecord UINT16 valuel INT32 value2 double value3 float value4 Document Version 1 61 5 19 2011 590 Structures and Types dlogStatus Type userType valued dlogRecord Variables for data log configuration dlogConfiguration dLogConfig dlogRecordElement recordElement 5 define the data log records recordElement 0 type DLOG UINT16 recordElement 0 size sizeof UINT16 recordElement 0 offset offsetof dlogRecord valuel recordElement 1 type DLOG_INT32 recordElement 1 size sizeof INT32 recordElement 1 offset offsetof dlogRecord value2 recordElement 2 type DLOG DOUBLE recordElement 2 size sizeof double recordElement 2 offset offsetof dlogRecord value3 recordElement 3 type DLOG FLOAT recordElement 3 size sizeof float recordElement 3 offset offsetof dlogRecord value4 recordBlement 4 type DLOG FIRST _USER_TYPE recordElement 4 size sizeof userType recordElement 4 offset offsetof dlogRecord valued insert the record list into the data log configuration dLogConfig recordList recordElement The dlogStatus enumerated type indicates the status of a data log operation The specific meaning may vary according to the function returning the status
484. s 10 1 4 to 20 mA outputs addRegAssignmentEx SCADAPack 560610 0 1 10001 30001 40001 parameters release resource IO SYSTEM Document Version 1 61 5 19 2011 100 Function Specifications save register assignment with controller settings request _resourc E ASH MI EMO flashSettingsSave CS_ PER release resourc E ASH MI EMO ANI RY ENT RY Document Version 1 61 5 19 2011 101 Function Specifications alarmin Determine Alarm Time from Elapsed Time Syntax include lt ctools h gt ALARM SETTING alarmIn UINT16 hours UINT16 minutes UINT16 seconds Description The alarmin function calculates the alarm settings to configure a real time clock alarm to occur in hours minutes and seconds from the current time The function returns an ALARM_SETTING structure suitable for passing to the setClockAlarm function The structure specifies an absolute time alarm at the time offset specified by the call to alarmin Refer to the Structures and Types section for a description of the fields in the ALARM_SETTING structure Notes If second is greater than 60 seconds the additional time is rolled into the minutes If minute is greater than 60 minutes the additional time is rolled into the hours If the offset time is greater that one day then the alarm time will roll over within the current day The IO_SYSTEM resource needs to
485. s 438 melcpMasterMeSSage ree aneren seisedisesteendanessnddivaevtadeateate ddusteuadatevandideaisia saneeaddadsts 439 MA CPMasterOpe ny isc cccegccesevaccieaesdedevays cdesesacdevae vee aeenddevare ndatevseteevirseadaeeniecens 441 IMT CPMAStCrStAtUs aaeei ieee tearestagcanneetcvagteatedsnste tevguehaddcusrth tentedcans 443 MI CPRUNSCVE EE TE E EEA EN 444 o i EELE A FE TE E A EEA E T EEE A TEE E E E 445 PIONS FANTE E I ATENE PEET AEE A ETE T A TTET E EE EEE 446 pvearidoD DASE eoa r a EAA A SAO 447 PIDEXGSCULC pioak kanaa eaaa aaaea aai EAR a aaa aaia Sania EANAN ORERE ETAR aai aA 449 PIMA Ze iskisa annisa eaaa aana ETa denA ana EANA EARNE EARE naa aA 451 otolla ree N E ATA E E A Scans hee the aie 452 POM event iiaiai aaan died scayash ach iuadasbvapnahensaaiis a nA aia EANA A AAEE KEARE aai aRt 453 poll messaga neriesi iiaia aana Ana e aiaa AAS ata EANES RANEE EARE aai AA 455 poll rosor COE ise ccascehantici sank ccs adhes secapashccsiiahasgeapasheescaiis saeeppaacduaindeadeegesanneasaeasasiag 456 PONER o epee rer Peer r etree epee ote arre errr eee ein Preeerripet etree erent rercrrererererrineee rect 457 oyeg eeii CSN ia EE cig saves vd skates aut sat auldecyaphain AR 458 CUCTY StaCkK A EETA attic cere ears A ons eect Alt oat Ue San ee Nee oe 459 QUEUS MOOS eset eset ecsld eget cbs sinh aati T SA 460 PEAUMBOoIlVariable cceeesecceeeeeeeceeeeeeneeeeeeeeeeseceaeeeeeeaaeeeseeaaeeeseeaeeeseeseneeeeeseneees 461 read Battery c2cvs e cies E
486. s a value in milliseconds to the specified timer variable The maximum value that may be written is 86399999 ms or 24 hours If the value is greater than 86399999 ms the value modulus 86399999 is written to the timer variable The specified timer may be active or stopped The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified unsigned long value is written to the variable If the variable is not found or if the IEC 61131 1 Symbols Status is invalid nothing is done and FALSE is returned The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the setdbase function The lO_SYSTEM system resource needs to be requested before calling this function Example This program writes the value 10000 ms to the timer
487. s function in order to create the DNP configuration Document Version 1 61 5 19 2011 173 Function Specifications dnpGetBiConfig Get DNP Binary Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetBIConfig UINT16 point dnpBinarylInput pBinarylInput Description The dnpGetBIConfig function reads the configuration of a DNP binary input point The function has two parameters the point number and a pointer to a binary input point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveBlConfig Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 174 Function Specifications dnpGetBiConfigEx Read DNP Binary Input Extended Point Syntax BOOLEAN dnpGetBIConfigEx UINT16 point dnpBinarylInputEx pBinarylInput Description This function reads the configuration of an extended DNP Binary Input point The function has two parameters the point number and a pointer to an extended binary input point configuration structure The function returns TRUE if the configuration was successfully read It returns FALSE if the point number is not valid if the config
488. s of a modem initialization started by the modemInit function port specifies the serial port where the modem is installed id is the port reservation identifier returned by the modemInit function The function sets the variable pointed to by error If no error occurred DE_NoError is returned Any other value indicates an error Refer to the Structures and Types section for a complete Description of error codes The function sets the variable pointed to by state to the current execution state of the dialing operation The state value is not valid if the error code is DE_NotInControl Refer to the dialup h section for a complete Description of state codes Notes The serial port type must be set to RS232_MODEM The port will remain in the DS_Calling state until modem initialization is complete or fails The application should wait until the state is not DS_Calling before calling the modemlnitEnd function The reservation identifier is valid until the initialization is complete or terminated and another modem function or an incoming call takes control of the port Do not call this function in a task exit handler Document Version 1 61 5 19 2011 427 Function Specifications modemNotification Notify the modem handler of an important event Syntax include lt ctools h gt void modemNotification UINT16 port index Description The modemNotification function notifies the dial up modem handler that an interesting event has
489. s the data pointed to by string string may be modified after the function is called The result is cleared when the controller is reset The application program needs to initialize the salve ID string each time it is run Document Version 1 61 5 19 2011 416 Function Specifications modemAbort Unconditionally Terminate Dial up Connection Syntax include lt ctools h gt void modemAbort FILE port Description The modemAbort function unconditionally terminates a dial up connection connection in progress or modem initialization started by the C application port specifies the serial port where the modem is installed The connection or initialization is terminated only if it was started from a C application Connections made from a Ladder Logic application and answered calls are not terminated This function can be used in a task exit handler Notes The serial port type needs to be set to RS232_ MODEM A pause of a few seconds is required between terminating a connection and initiating a new call This pause allows the external modem time to hang up Use this function in a task exit handler to clean up any open dial up connections or modem initializations If a task is ended by executing end_task from another task modem connections or initializations needs to be aborted in the exit handler Otherwise the reservation ID for the port remains valid No other task or Ladder Logic program may use modem functions on t
490. sSave as shown in the example for addRegAssignment The IO_SYSTEM resource must be requested before calling this function See Also addRegAssignment Example See example for addRegAssignment Document Version 1 61 5 19 2011 114 Function Specifications clearSFTranslationTable Clear Store and Forward Translation Configuration Syntax include lt ctools h gt void clearSFTranslationTable void Description The clearSFTranslationTable function clears all entries in the store and forward translation table To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Notes The TeleBUS Protocols User Manual describes store and forward messaging mode The IO_SYSTEM resource needs to be requested before calling this function See Also checkSFTranslationTable Document Version 1 61 5 19 2011 115 Function Specifications clearStatusBit Clear Bits in Controller Status Code Syntax include lt ctools h gt UINT16 clearStatusBit UINT16 bitMask Description The clearStatusBit function clears the bits indicated by bitMask in the controller status code When the status code is non zero the STAT LED blinks a binary sequence corresponding to the code If code is zero the STAT LED turns off The function returns
491. sed Once the desired serial communication parameters have been set click on the OK button The serial ports are set to their default parameters when a Cold Boot is done These settings are 9600 baud 8 data bits no parity 1 stop bit Modbus RTU protocol and station address 1 Loading the Application To load the Hello C application into the controller e Select Controller gt C C Program Loader e Click Add e Click Browse e Locate the application file built earlier For example C Applications Telepace Hello myApp out and click OK You need to use a file built using a Telepace framework with Telepace firmware Document Version 1 61 5 19 2011 28 Getting Started Executing the Program Click Write to write the file to the controller Connect a terminal to com2 on the controller It will display the output of the program Set the communication parameters to 9600 baud 8 data bits 1 stop bit and no parity From the C C Program Loader dialog click on the Run button to execute the program The hello world message will be displayed on the terminal When multiple C Applications are loaded and the controller is power cycled the C Applications are restarted in the order they were first loaded to the controller Loading and Executing the C Application Using IEC 61131 1 The IEC 61131 1 C C Program Loader transfers executable files from a PC to the controller and controls execution of programs in
492. signment Add Register Assignment Telepace firmware only Syntax include lt ctools h gt BOOLEAN addRegAssignment UINT INTL UINT UINT UINT UINT Description 16 moduleType 6 moduleAddress 16 startingRegisterl 16 startingRegister2 16 startingRegister3 16 startingRegister4 The addRegAssignment function adds one I O module to the current Register Assignment of type moduleType The following symbolic constants are valid values for moduleType AIN_520xT CNTR_ emperature 5410 AIN_520xR DIAG_c AMBattery ommst atus AIN_5501 DIAG_c ontrolle rStatus AIN_5502 DIAG_f orceLE D AIN_5503 DIAG_ PConn ections AIN_5504 DIAG __ Modbus Status AIN_5505 DIAG_p rotocol Status AIN_ 5506 DIN_54 01 AIN_ 5521 DIN_54 02 AIN_generi DIN_54 c8 03 Document Version 1 61 5 19 2011 91 Function Specifications AOUT_530 1 AOUT_530 2 AOUT_530 4 AOUT_gen eric2 AOUT_gen eric4 CNFG_590 4Modem CNFG_clea rPortCounte rs CNFG_clea rProtocolCo unters CNFG_IPS ettings CNFG_LED Power CNFG_mod buslpProtoc ol CNFG_MT CPlfSetting s CNFG_MT CPSettings CNFG_PID Block CNFG_port Settings CNFG_prot ocolExtend ed CNFG_prot ocolExtend edEx DIN_54 04 DIN_54 05 DIN_54 14 DIN_54 21 DIN_ge neric16 DIN_ge neric8 DOUT _ 5401 DOUT _ 5402 DOUT_ 5406 DOUT_ 5407 DOUT_ 5408 DOUT_ 5409 DOUT_ 5411 DOUT_ 5415 DOUT_ generic
493. sion 1 61 5 19 2011 73 Overview of Programming Functions getProtocolSettings Reads extended addressing protocol parameters for a serial port get_protocol status Reads protocol message and error counters getSFTranslation Read store and forward translation table entry installModbusHandler This function allows user defined extensions to standard Modbus protocol master_message Sends a protocol message to another device modbusExceptionStatus Sets response for the read exception status function modbusSlavelD Sets response for the read slave ID function set_protocol Sets protocol parameters and starts protocol setProtocolSettings Sets extended addressing protocol parameters for a serial port setSFTranslation Write store and forward translation table entry start_protocol Starts protocol execution based on stored parameters Communication Protocols Enumeration Types The ctools h file defines the enumeration type ADDRESS_MODE Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Communication Protocols Structures The ctools h file defines the structures Protocol Status Information Protocol Settings Extended Protocol Settings Store and Forward Message and Store and Forward Status Refer to the C Tools Structures and Types section for complete information on structures and enumeration types DNP Communication Protocol DNP the Distributed Network Protocol is
494. ss for developing end user applications in C for the SCADAPack 350 and 4203 controllers The SCADAPack C Tools are based on the GNU Compiler Collection GCC for the Arm7 processor Users will be able to create compile and debug applications using these tools There are two files associated with the startup structure appstart cpp and nvMemory h Each is described below Application Startup Function appstart cpp The start up code has the following major functions e initialize application program variables e execute the main function Source code for the appstart function is supplied with the C Tools sample application in the file appstart cpp The following discussion refers to statements found in this file At the top of appstart cpp are initialized global variables used to configure settings for the main task These parameters are used when the task main is created Priority of the task main Priority 100 is recommended for a continuously running task A task with priority gt 100 will never be given the CPU See manual for details UINT32 mainPriority 100 Stack space allocated to the task main Note that at least 5 stack blocks are needed when calling fprintf UINT32 mainStack 5 Application group assigned to the task main A unique value is assigned by the system to the applicationGroup for this application Use this variable in all calls to create _task
495. ss to a resource and wait if the resource is not available poll_ resource Request access to a resource Continue execution if the resource is not available release_resource Free a resource for use by other tasks 10 SYSTEM Resource The lO_SYSTEM resource regulates access to functions using the I O system C application programs ladder logic programs communication protocols and background I O operations share the I O system It is imperative the resource is obtained to avoid a conflict as protocols and background operations are interrupt driven Retaining control of the resource for more that 0 1 seconds will cause background operations to not execute properly The IO_SYSTEM resource needs to be obtained before using any of the following functions readRegAssignment read the register assignment readRegAssignmentEx read the register assignment alarmin configure the alarm in parameters clearAllForcing clear all forcing flags clear_errors clear serial port error counters clear_protocol_status clear protocol status clearRegAssignment clear register assignment clearSFTranslationTable clear the Store and Forward translation table databaseRead read a value from the database databaseWrite write a value to the database dbase read a value from the database getclock read the system clock getClockAlarm read the clock alarm settings getClockTime read the system clock time ioClear clear the I O Document Version 1 61 5 19 2011 47
496. ssPtr is a pointer to the IP address and port number of the remote or local socket If socketDescriptor is not bound then it will be bound to an address selected by the underlying transport provider Generally stream sockets may successfully connect only once datagram sockets may use connect multiple times to change their association Datagram sockets may dissolve the association by connecting to a null address Aa non blocking connect is allowed In this case if the connection has not been established the connect call will fail with a EINPROGRESS error code Additional calls to connect will fail with EALREADY error code as long as the connection has not completed When the connection has completed additional calls to connect will return with no error to indicate that the connection is now established Parameters socketDescriptor The socket descriptor to assign a name port number to addressPtr The pointer to the structure containing the address to connect to for TCP For UDP it is the default address to send to and the only address to receive from addressLength The length of the address structure Returns 0 Success 1 An error occurred connect can fail for any of the following reasons EADDRINUSE The socket address is already in use The calling program should close the socket descriptor and issue Document Version 1 61 5 19 2011 124 Function Specifications EADDRNOTAVAIL EAFNOSUPPORT EINPROGRESS EAL
497. ssage has been received The current task always continues to execute Notes Refer to the Real Time Operating System section for more information on messages See Also poll_event Example This task performs a function continuously and processes received messages from higher priority tasks when they are received include lt ctools h gt void task void nvelope letter while TRUE letter poll message if letter NULL process the message now more code here Document Version 1 61 5 19 2011 455 Function Specifications poll_resource Test Resource Availability Syntax include lt ctools h gt BOOLEAN poll resource UINT32 resource Description The poll_resource function tests if the resource specified by resource is available If the resource is available it is given to the task The poll_resource function returns TRUE if the resource is available It returns FALSE if it is not available The current task always continues to execute Notes Refer to the Real Time Operating System section for more information on resources See Also poll_ event poll_ message Document Version 1 61 5 19 2011 456 Function Specifications portindex Get Index of Serial Port Syntax include lt ctools h gt UINT16 portIndex FILE stream Description The portIndex function returns an array index for the serial port specified by strea
498. struct hartDevice t Document Version 1 61 5 19 2011 609 Structures and Types HART_RESPONSE HART_RESULT manufacturerID manufacturerDeviceType preamblesRequested commandRevision transmitterRevision softwareRevision hardwareRevision flags 2 devicelID HQAQQAQaQaQAQQ Hpepppprprpr ep U DIDIT Bn Rel C G Re E Er ee D RT_DEVICE The HART_RESPONSE type is a structure containing a response from a HART slave device The command field contains the HART command number The length field contains the length of the data string to be transmitted the byte count in HART documentation The data field contains the data to be sent to the slave typedef struct hartResponse t UINT16 code UINT16 length CHAR pData HART RESPONSE e response is the response code from the device e length is the length of response data e data DATA_SIZE is the data field for the response The HART_RESULT enumeration type defines a list of results of sending a command typedef enum hartResult_t HR_NoModuleResponse 0 HR CommandPending HR CommandSent HR Response HR_NoResponse HR WaitTransmit HART RESULT e HR_NoModuleResponse returns no response from HART modem module e HR_CommandPending returns command ready to be sent but not sent e HR _CommandSent returns command sent e HR_Response returns response received Document Version 1 61 5 19
499. t 30 tenths of seconds function read holding registers slaveStation 1 slaveRegister 40155 masterRegister 40001 length 2 main loop mode MIP OPEN CONNECTION while TRUE switch mode case MIP OPEN CONNECTION open a connection status mTcpMasterOpen remotelIP protocolType appType timeout amp connectID amp cmdStatus if status mode MIP CONNECTING break case MIP_CONNECTING check master command status status mTcpMasterStatus connectID amp cmdStatus if status switch cmdStatus case MM CONNECTING break case MM CONNECTED mode MIP SEND MESSAGE break default remaining status codes are error codes mode MIP DISCONNECT break Document Version 1 61 5 19 2011 666 Example Programs sent successfully error codes amp cmdStatus response break case MIP SEND MESSAGE send master IP message cmdStatus mTcpMasterMessage connectID remotelIP protocolType function slaveStation slaveRegister masterRegister length timeout switch cmdStatus case MM CONNECTING case MM DISCONNECTING case MM DISCONNECTED last command is still being not ready for new message break case MM SENT message send started mo
500. t Version 1 61 5 19 2011 267 Function Specifications getSFTranslationEx Read Store and Forward Translation Method 2 Syntax include lt ctools h gt void getSFTranslationEx UINT16 index SF TRANSLATION EX pfranslation Description The getSFTranslationEx function copies the entry from the store and forward translation table at index to the structure pointed to by pTransiation If index is invalid a disabled table entry is copied The disabled table entry has both station fields set to 65535 If the userName parameter is non NULL then the user name used for authentication purposes will be copied into the array pointed to by userName userName must point to an array of 16 unsigned characters The SF_TRANSLATION_EX structure supports a timeout and is described in the Structures and Types section Notes The TeleBUS Protocols User Manual describes the store and forward messaging mode See Also setSFTranslationEx clearSFTranslationTable checkSFTranslationTable Document Version 1 61 5 19 2011 268 Function Specifications getsockname Syntax include lt ctools h gt int getsockname int socketDescriptor struct sockaddr myAddressPtr int addressLengthPtr Description This function returns to the caller the Local IP Address Port Number that we are using on a given socket Parameters socketDescriptor The socket descriptor that we wish to inquire about myAddressPtr The
501. t Version 1 61 5 19 2011 308 Function Specifications installRTCHandler Install User Defined Real Time Clock Handler Syntax include lt ctools h gt void installRTCHandler void rtchandler TIME now TIME newTime Description The installRTCHandler function allows an application program to override Modbus protocol and DNP protocol commands to set the real time clock This function specifies a function to be called when a Modbus or DNP message is received for the station The installed handler function is called only if the message is to set the real time clock The function has one parameter a pointer to a function to handle the messages See the section RTCHandler Function for a full Description of the function and its parameters If the pointer is NULL no function is called for set the real time clock commands and the default method is used set the real time clock The function has no return value Notes Call this function with the NULL pointer to disable processing of Set Real Time Clock messages This needs to be done when the application program is ended with an exit handler Use the installExitHandler function to install the exit handler If the RTC handler is not disabled within an exit handler it will remain installed and continue to operate until the controller power is cycled Changing the protocol type or Erasing the C Program from the Telepace Initialize dialog will not remove the handler If
502. t analog output module at the specified module address Buffered data are written using the ioWriteAout4 function The function has two parameters the module address and a reference to an array of four INT16 variables If the moduleAddress is valid data are copied to the array The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 348 Function Specifications ioReadAout5303 Read Data From 2 point 5303 Analog Output Module Syntax include lt ctools h gt BOOLEAN ioReadAout5303 INT16 amp data 2 Description This function reads buffered data used for the 2 point 5303 analog output module Buffered data are written using the ioWriteAout5303 function The function has one parameter a reference to an array of two INT16 variables The buffered data are copied to the array The function needs to returns TRUE Document Version 1 61 5 19 2011 349 Function Specifications ioReadCounter4 Read Data From 4 point Counter Input Module Syntax include lt ctools h gt BOOLEAN ioReadCounter4 UINT16 moduleAddress UINT32 amp data 4 Description This function reads buffered data from the 4 point counter input module at the specified module address Buffered data are updated when an I O request for the module is processed The function has two parameters the module address and a
503. t rresvport int portToReservePtr Document Version 1 61 5 19 2011 489 Function Specifications Description rresvport is used to create a TCP socket and bind a reserved port to the socket starting with the port to reserve given by the user The portToReservePtr parameter is a value result parameter The integer pointed to by portToReservePrtr is the first port number that the function attempts to bind to The caller typically initializes the starting port number to IPPORT_RESERVED 1 IPPORT_RESERVED is defined as 1024 If the bind fails because that port is already used then rresvport decrements the port number and tries again If it finally reaches IPPORT_RESERVEDSTART defined as 600 and finds it already in use it returns 1 and set the socket error to EAGAIN If this function successfully binds to a reserved port number it returns the socket descriptor to the user and stores the reserved port that the socket is bound to in the integer cell pointed to by portToReservePtr Parameters portToReservePtr Pointer to the port number to reserve and to the port number reserved on success Returns gt 0 Valid socket descriptor 1 An error occurred If an error occurred the socket error can be retrieved by calling getErrorCode socketDescriptor rresvport will fail if EAGAIN The TCP IP stack could not find any port number available between IPPORT_RESERVEDSTART and the port number to reserve EINVAL Bad p
504. t timeout values for different IP addresses each time the function is called If a TCP protocol connection is left idle and the master idle timeout occurs the connection is closed to conserve resources at the remote slave The connection is automatically re established the next time mTcpMasterMessage is called Master idle timeout is set using the function mTcpSetProtocol Closing the TCP IP connection in an idle timeout does not return the connection ID to the pool of available connections The connection ID remains allocated to this master session until mTcpMasterClose is called An error code is returned if the specified connectiD is invalid or if a command argument is invalid otherwise MM_SENT is returned If the last command message is still in progress the command status is returned and a new message is not sent The mTcpMasterMessage returns immediately It is the mastering task created in the background that services the IP connection The command status returned by this function is set to MM_SENT if a valid master message was sent Other values returned for the command status are described for the enumeration type MODBUS_CMD_STATUS in the Structures and Types section Use the function mTcpMasterStatus to determine the progress of the Modbus IP command and the slave response The command status will be set to MM_RECEIVED when the response to the message is received Notes Refer to the communication protocol manual for more informati
505. tClockAlarm Set the Real Time Clock Alarm Syntax include lt ctools h gt UINT16 setClockAlarm ALARM SETTING alarm Description The setClockAlarm function configures the real time clock to alarm at the specified alarm setting The ALARM_SETTING structure alarm specifies the time of the alarm Refer to the ctools h section for a Description of the fields in the structure The function returns TRUE if the alarm can be configured and FALSE if there is an error in the alarm setting No change is made to the alarm settings if there is an error Notes An alarm will occur only once but remains set until disabled Use the resetClockAlarm function to acknowledge an alarm that has occurred and re enable the alarm for the same time Set the alarm type to AT_NONE to disable an alarm It is not necessary to specify the hour minute and second when disabling the alarm The IO_SYSTEM resource needs to be requested before calling this function See Also getClockAlarm Document Version 1 61 5 19 2011 510 Function Specifications setdbase Write Value to I O Database Syntax include lt ctools h gt void setdbase UINT16 type UINT16 address INT16 value Description The setdbase function writes value to the I O database type specifies the method of addressing the database address specifies the location in the database The table below shows the valid address types and ranges Type Address Ranges Register Size
506. ta Log Function Syntax include lt ctools h gt BOOLEAN datalogWrite UINT16 logID UINT16 pData Description This function writes a record to the specified data log The log needs to have been previously created with the datalogCreate function The function has two parameters og D specifies the data log The valid range is 0 to 15 pData is a pointer to the data to be written to the log The amount of data copied using the pointer is determined by the configuration of the data log The function returns TRUE if the data is added to the log The function returns FALSE if the log ID is not valid or if the log does not exist Notes Refer to the datalogCreate function for details on the configuration of the data log If the data log is full then the oldest record in the log is replaced with this record See Also See example DataLog program in the Example Programs section datalogReadStart datalogReadNext datalogPurge Example See the example for datalogReadStart Document Version 1 61 5 19 2011 144 Function Specifications dbase Read Value from I O Database Syntax include lt ctools h gt INT16 dbase UINT16 type UINT16 address Description The dbase function reads a value from the database type specifies the method of addressing the database address specifies the location in the database The table below shows the valid address types and ranges Type Address Ranges Register Size
507. tate for a Register Telepace firmware only Syntax include lt ctools h gt BOOLEAN getForceFlag UINT16 type UINT16 address UINT16 value Description The getForceFlag function copies the value of the force flag for the specified database register into the integer pointed to by value The valid range for address is determined by the database addressing type The force flag value is either 1 or 0 or a 16 bit mask for LINEAR digital addresses If the address or addressing type is not valid FALSE is returned and the integer pointed to by value is 0 otherwise TRUE is returned The table below shows the valid address types and ranges Type Address Ranges Registe r Size MODBUS 00001 to NUMCOIL 10001 to 10000 NUMSTATUS 30001 to 30000 NUMINPUT 40001 to 40000 NUMHOLDING LINEAR 0 to NUMLINEAR 1 16 bit Notes Force Flags are not modified when the controller is reset Force Flags are ina permanent storage area which is maintained during power outages Refer to the I O Database and Register Assignment chapter for more information See Also setForceFlag clearAllForcing overrideDbase Example This program obtains the force flag state for register 40001 for the 16 status registers at linear address 302 i e registers 10737 to 10752 and for the holding register at linear address 1540 i e register 40005 include lt ctools h gt int main void UINT 16 flag bitmask Document Versio
508. tation will be forwarded Serial Modbus Interface as Forwarding Interface The forward lPAddress field in the SF_TRANSLATION structure should be set to zero when the forwardinterface field is a Serial Modbus interface Set forward PAddress to zero as follows SF_TRANSLATION sfTranslation sfTranslation forwardIPAddress s addr 0 See Also getSFTranslation Document Version 1 61 5 19 2011 532 Function Specifications setSFTranslationEx Write Store and Forward Translation method 2 Syntax include lt ctools h gt struct SFTranslationStatus setSFTranslationEx UINT16 index SF_TRANSLATION EX pfranslation Description The setSFTranslationEx function copies the structure pointed to by pTranslation into the store and forward translation table at the location specified by index Valid values for index are 0 to 127 The function checks for invalid translations The translation is stored even if invalid If the userName parameter is non NULL then the Store and Forward entry will be set to use authentication with the user name set to the contents of the array pointed to by userName and the password set to the contents of the array pointed to by password Both userName and password need to point to arrays of 16 characters User names and passwords shorter than 16 characters should be padded to 16 characters with spaces If the userName parameter is NULL then no authentication information will be stored with the Store an
509. te_task Create a New Task Syntax include lt ctools h gt INT32 create_task void function UINT32 priority UINT32 type UINT32 stack Description The create_task function allocates stack space for a task and places the task on the ready queue function specifies the start address of the routine to be executed The task will execute immediately if its priority is lower than the current executing task priority is an execution priority between 0 and 254 for the created task The lowest priority is 254 and the highest priority is 0 The 255 task priority levels aid in scheduling task execution See the notes below for recommended priority values type specifies if the task is ended when an application program is stopped Valid values for type are SYSTEM System tasks do not terminate when the program stops applicationGroup Application tasks terminate when the program stops Use this global variable for all calls to create_task by the same application The operating system assigns a unique value to applicationGroup when it is defined in appstart cpp It is recommended that only application type tasks be created The stack parameter specifies how many stack blocks are allocated for the task Each stack block is 512 bytes The create_task function returns the task ID TID of the task created If an error occurs 1 is returned Notes Refer to the Real Time Operating System section for more information on tasks The main t
510. tel bebelvendsl eh cetewnstevlasteedeaeties 228 QMO QrOUP N OEE EP A E A CT tebeavanesl axial N A 229 ONG e E E E EE ET bul cote ane lied lt des ahas 230 end Timed Evon sieer e T EE TAE EAS ER EA EEEE SEET 231 enronlnstallCommandHandler ssssssseesseeeseeen eeen esen nesr nesnnssrnssrnssrnnsrnssrnnsrnsnnns 232 ethermetGetl Pita a see lesses tale de enor iat Aaddpniete do r aaao aan aarda a raa ddan aeiaai aa diak 236 ethernetGetMACAddress ccecccecececeeeeeeeeeeeceeeeecaeeeeaaeseeneeseaeeesaaeeeeaaesseneessaes 237 ethernetSetlP vss te iceeceleusts Glee teleee Wade eana Gv ahve aiatecvadieivtasanneddicevs 238 flash Settings Load Aes ceeeet lee have iad endive Cove helena taari aad aoii raiki idae 239 flaShSettingSSave 0 ecccceccceeseecsecceceeececeaeeeeaaeseeeaesaceeeaaeseeaaesaneesaeseeaeesseeaeenaees 240 EES EE a E EEEE EE ET E TEE A OEE EN EEE AT oaths 241 TFEGMEINOLY EEE EE E E EN TEE EN ES de T T 242 getABConfiguration 00 eeeececeeeceeneeeeeeee cee eeeeaeeeeaeeceaeeesaaeeesaaeseeeeeseaeeesaeeseneeenaees 243 GOICIOCK TEA E E T EN TEE AEE Aten et T age 244 getClockAla nene weet rai inte tied an die Lara aoaaa aP ETELA Erai iiei 245 getClock Time daaa aa a raa aa Grd aaa aa aA aao EaP SEAE iTos 246 geConroe rD a a a E aaa Mog Dera es 247 QSL OrCe Fa erra A E A E T TRESE 248 GEIR ONCE LOO eE AT E AAEE E 250 getFtpServerState eeceeccecccceeseecseeeeceeeeeeeaeeeeaeeceeeeeseaeseseaeseeeeeseeeseaesseneessaees 251 QGetHar
511. ter Assignment with the controller settings in flash memory so that it is loaded on controller reset call flashSettingsSave as shown in the example below The IO_SYSTEM resource needs to be requested before calling this function See Also clearRegAssignment Example include lt ctools h gt int main void request resource IO SYSTEM Create the Register Assignment clearRegAssignment addRegAssignment SCADAPack 210 0 1 10001 30001 40001 addRegAssignment AOUT_ 5302 1 40003 0 0 0 addRegAssignment DIAG forceLED 1 10017 0 0 0 addRegAssignment DIAG controllerStatus 1 30009 0 0 addRegAssignment DIAG protocolStatus 2 30010 0 0 0 release resource IO SYSTEM save register assignment with controller settings Document Version 1 61 5 19 2011 94 Function Specifications request resource FLASH MEMORY flashSettingsSave CS_ PERMANENT release resource FLASH MEMORY Document Version 1 61 5 19 2011 95 Function Specifications addRegAssignmentEx Add Register Assignment Telepace firmware only Syntax include lt ctools h gt BOOLEAN addRegAssignmentEx UINT16 moduleType INT16 moduleAddress UINT16 startingRegisterl UINT16 startingRegister2 UINT16 startingRegister3 UINT16 startingRegister4 UINT16 parameters 16 i Description The addRegAssignmentEx function adds one I O
512. ter a data log ID which is used for further operations on the data log A newly created data log won t reuse a recently deleted ID although the ID will eventually recycle if enough logs are created Document Version 1 61 5 19 2011 150 Function Specifications dlogDelete Delete a data log and all associated resources except log files Syntax include lt ctools h gt dlogStatus dlogDelete UINT32 dlogID Parameters The function has these parameters e dlogID is the ID of the data log to be deleted The function returns e DLOGS_SUCCESS if the data log was deleted e DLOGS_BADID if the data log ID is not valid e DLOGS_FAILURE if the data log could not be deleted Description This function deletes a data log The memory for the log is freed The data log ID is marked as invalid The data log server will not collect further records for this log ID The directory file is deleted if it is accessible This might be not the case if data log files were written to removable media The data log name is removed from the master log file Data Log files are not deleted If the log was created with a path the created directory still exists after the log is deleted Document Version 1 61 5 19 2011 151 Function Specifications dlogDeleteAll Delete all data logs and all associated resources except log files Syntax include lt ctools h gt dlogStatus dlogDeleteAl1 Parameters The function has no parameters T
513. ter station must send messages to this address Valid values are 0 to 65534 e datalinkConfirm enables requesting data link layer confirmations Valid values are TRUE and FALSE e datalinkRetries is the number of times the data link layer will retry a failed message Valid values are 0 to 255 e datalinkTimeout is the length of time the data link layer will wait for a response before trying again or aborting the transmission The value is measured in milliseconds Valid values are 100 to 60000 in multiples of 100 milliseconds e operateTimeout is the length of time an operate command is valid after receiving a select command The value is measured in seconds Valid values are 1 to 6500 e applicationConfirm enables requesting application layer confirmations Valid values are TRUE and FALSE e maximumResponse is the maximum length of an application layer response Valid values are 20 to 2048 The recommended value is 2048 unless the master cannot handle responses this large e applicationRetries is the number of times the application layer will retry a transmission Valid values are 0 to 255 e applicationTimeout is the length of time the application layer will wait for a response before trying again or aborting the transmission The value is measured in milliseconds Valid values are 100 to 60000 in multiples of 100 milliseconds This value must be larger than the data link timeout e timeSynchronization defines how often the RT
514. ter time will consist of a start bit 7 or 8 data bits an optional parity bit and a stop bit The number of bits per byte needs to be calculated for the serial port configuration that is being used When the specified timeout has elapsed the installed character hander for that port will be called for each of the received characters Notes This function is useful for message framing based on the receive line being idle for a fixed minimum time between messages The Example below shows a simple method using the sysSerialSetRxTimeout function to control when serial data is reported Example This program specifies a timeout of 8 character times on com 1 five seconds after the program starts assuming that the port is setup for 8 N 1 operation include lt ctools h gt define COM1 INDEX 0 BOOLEAN dataToProcess 3 FALSE FALSE FALSE BOOLEAN informOfCharacterArrival int arg int c BOOLEAN retval UINT32 previousIntMask switch arg case 0 case 1 case 2 Notify of the arrival if dataToProcess arg FALSE Document Version 1 61 5 19 2011 553 Function Specifications switch arg case 0 interrupt signal event COM1 RCVR break case 1 interrupt signal event COM2 RCVR break case 2 interrupt signal event COM3 RCVR break default Do nothing this case should be impossible to each break Prevent
515. ter to an UINT16 variable If the moduleAddress is valid digital input data are copied to the variable The valid range for moduleAddress is 0 to 15 The function returns FALSE if the module address is invalid otherwise TRUE is returned Document Version 1 61 5 19 2011 356 Function Specifications ioReadDout32 Read from 32 Digital Outputs Syntax include lt ctools h gt BOOLEAN ioReadDout3Z2 UINT16 moduleAddress UINT32 amp data Description The ioReadDout32 function reads buffered data for a 32 bit digital output module Buffered data are written using the ioWriteDout32 function The function has two parameters moduleAddress is the address of the module The valid range is 0 to 15 data is reference to a UINT32 variable If the module address is valid data are copied to this variable The function returns FALSE if the moduleAddress is invalid otherwise TRUE is returned See Also ioReadDout8 ioReadDout16 Document Version 1 61 5 19 2011 357 Function Specifications ioReadDout8 Read Data From 8 point Digital Output Module Syntax include lt ctools h gt BOOLEAN ioReadDout8 UINT16 moduleAddress UCHAR amp data Description This function reads buffered data used for the 8 point digital output module at the specified module address Buffered data are written using the ioWriteDout8 function The function has two parameters the module address and a reference to an UC
516. ternal analog inputs and external analog input modules Refer to the SCADAPack 350 System Hardware Manual or the SCADAPack 4203 Hardware Manual for further information on controller analog inputs and analog input modules There are several library functions related to internal analog inputs and analog input modules Refer to the Function Specification section for details on each function listed readBattery Read the controller RAM battery voltage Document Version 1 61 5 19 2011 61 Overview of Programming Functions readThermistor ioRead4Ain ioRead8Ain ioRead5505Inputs ioRead5505Outputs ioRead5506Inputs ioRead5506Outputs ioWrite5505Outputs ioWrite5506Outputs ioRead5601Inputs ioRead5604Inputs ioRead5606Inputs ioRead5606Outputs ioRead5607Inputs ioRead56070utputs ioRead4203DRinputs ioRead4203DSInputs Analog Output Functions Read the controller ambient temperature sensor Read 4 analog inputs into I O database Read 8 analog inputs into I O database Read the digital and analog inputs from a 5505 I O Module Read the configuration data from a 5505 I O Module Read the digital and analog inputs from a 5506 I O Module Read the configuration data from a 5506 I O Module Write the configuration data to a 5505 I O Module Write the configuration data to a 5506 I O Module Read the digital and analog inputs from a SCADAPack 5601 I O Module Read the digital and analog inputs from a SCADAPack 5604 I O Mo
517. that woke the controller from sleep See Also getWakeSource setWakeSource Document Version 1 61 5 19 2011 547 Function Specifications socket Syntax include lt ctools h gt int socket int family int type int protocol Description socket creates an endpoint for communication and returns a descriptor The family parameter specifies a communications domain in which communication will take place this selects the protocol family that should be used The protocol family is generally the same as the address family for the addresses supplied in later operations on the socket These families are defined in the include file lt ctools h gt If protocol has been specified but no exact match for the tuplet family type and protocol is found then the first entry containing the specified family and type with zero for protocol will be used The currently understood format is PF_INET for ARPA Internet protocols The socket has the indicated type which specifies the communication semantics Currently defined types are SOCK_STREAM SOCK_DGRAM SOCK_RAW A SOCK_STREAM type provides sequenced reliable two way connection based byte streams An out of band data transmission mechanism is supported A SOCK_DGRAM socket supports datagrams connectionless unreliable messages of a fixed typically small maximum length a SOCK_DGRAM user is required to read an entire packet with each recv call or variation of recv cal
518. the address of the Modbus register associated with the point class is the reporting class for the object It may be set to CLASS _1 CLASS_2 or CLASS _3 debounceTime is the debounce time for thebinary input The dnpBinaryOutput type describes a DNP binary output point typedef struct dnpBinaryOutput_type UINT16 modbusAddress1 UINT16 modbusAddress2 UCHAR controlType dnpBinaryOutput modbusAddress1 is the address of the first Modbus register associated with the point This field is always used modbusAddressz2 is the address of the second Modbus register associated with the point This field is used only with paired outputs See the controlType field controlType determines if one or two outputs are associated with this output point It may be set to PAIRED or NOT_PAIRED A paired output uses two Modbus registers for output The first output is the Trip output and the second is the Close output This is used with Control Relay Output Block objects A non paired output uses one Modbus register for output This is used with Binary Output objects dnpConnectionEventType This enumerated type lists DNP events typedef enum dnpConnectionEventType DNP_CONNECTED 0 DNP_ DISCONNECTED DNP_ CONNECTION REQUIRED DNP_MESSAGE_COMPLETE DNP_MESSAGE TIMEOUT DNP_CONNECTION_EVENT The DNP_CONNECTED event indicates that the
519. the addressing mode standard or extended PROTOCOL_SETTINGS_EX Type This structure contains serial port protocol settings including Enron Modbus support typedef struct protocolSettingsEx t UCHAR type UINT16 station UCHAR priority UINT16 SFMessaging ADDRESS MODE mode BOOLEAN enronEnabled UINT16 enronStation PROTOCOL SETTINGS EX type is the protocol type It may be one of NO PROTOCOL MODBUS_RTU or MODBUS_ ASCII AB_FULL_BCC AB_FULL_CRC AB_HALF_BCC DNP or AB_HALF_CRC macros To set the remaining settings use the function mTcpSetInterfaceEx Document Version 1 61 5 19 2011 623 Structures and Types prot_settings prot_status station is the station address of the controller Each serial port may have a different address The valid values are determined by the communication protocol This field is not used if the protocol type is NO_PROTOCOL priority is the task priority of the protocol task This field is not used if the protocol type is NO_ PROTOCOL SFMessaging is the enable Store and Forward messaging control flag ADDRESS_MODE is the addressing mode AM_standard or AM_extended enronEnabled determines if the Enron Modbus station is enabled It may be TRUE or FALSE enronStation is the station address for the Enron Modbus protocol It is used if enronEnabled is set to TRUE Valid values are 1 to 255 for standard addressing and 1 to 65534 for extended
520. the flag However the application program may make whatever use of the flag it sees fit NEW_PROGRAM indicates the program is newly loaded PROGRAM_EXECUTED indicates the program has been executed PROGRAM_NOT_LOADED indicates that the requested program is not loaded See Also getProgramStatus Example See Get Program Status Example Document Version 1 61 5 19 2011 524 Function Specifications set_protocol Set Communication Protocol Configuration Syntax include lt ctools h gt INT16 set protocol FILE stream struct prot _settings settings Description The set_protocol function sets protocol parameters port needs to specify one of com1 com2 or com3 settings references a protocol configuration structure Refer to the Description of the prot_settings structure for an explanation of the fields The set_protocol function returns TRUE if the settings were changed It returns FALSE if there is an error in the settings or if the protocol does not start The IO_SYSTEM resource needs to be requested before calling this function To save these settings with the controller settings in flash memory so that they are loaded on controller reset call flashSettingsSave as shown below request_resource FLASH_MEMORY flashSettingsSave CS_RUN release_resource FLASH_MEMORY Notes Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it Add a call to mod
521. the handler is located in a RAM based application and left enabled while a different C application is downloaded the original handler will be corrupted and the system will likely not work See Also RTCHandler Function installExitHandler Document Version 1 61 5 19 2011 309 Function Specifications RTCHandler Function User Specified Real Time Clock Handler Function The handler function is a user specified function that handles processing of Modbus messages or DNP messages for setting the real time clock The function can have any name rtchandler is used in the Description below Syntax include lt ctools h gt void rtchandler TIME now TIME newTime Description This function rtchandler is a user defined handler for processing Modbus messages or DNP messages The function is called only for messages that set the real time clock The rtchandler function should set the real time clock to the requested time If there is a delay before this can be done the time when the message was received is provided so that a correction to the requested time can be made The function has two parameters e The now parameter is a pointer to the structure containing the time when the message was received e The new parameter is a pointer to the structure containing the requested time The function does not return a value Notes The lO_SYSTEM resource has already been requested before calling this function If
522. the value of the status register Notes The status output opens if code is non zero Refer to the System Hardware Manual for more information The binary sequence consists of short and long flashes of the error LED A short flash of 1 10th of a second indicates a binary zero A longer flash of approximately 1 2 of a second indicates a binary one The least significant digit is output first As few bits as possible are displayed all leading zeros are ignored There is a two second delay between repetitions The STAT LED is located on the top left hand corner of the controller board Bits 0 1 and 2 of the status code are used by the controller firmware Attempting to control these bits will result in indeterminate operation See Also setStatusBit getStatusBit Document Version 1 61 5 19 2011 116 Function Specifications clear_tx Clear Serial Port Transmit Buffer Syntax include lt ctools h gt void clear tx FILE stream Description The clear_tx function clears the transmit buffer for the serial port specified by port If port is not a valid serial port the function has no effect Document Version 1 61 5 19 2011 117 Function Specifications close Syntax include lt ctools h gt int close int socketDescriptor Description This function is used to close a socket Parameters socketDescriptor The socket descriptor to close Returns 0 Operation completed successfully 1 An e
523. ther priority 1 tasks release processor Document Version 1 61 5 19 2011 336 Function Specifications ioRead5606Inputs Read 5606 Inputs Syntax include lt ctools h gt BOOLEAN ioRead5606Inputs UINT16 moduleAddress UCHAR amp dinData 5 INT1L6 amp ainData 8 Description This function reads buffered data from the digital and analog inputs of a 5606 I O module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5606 module Valid values are 0 to 7 dinData is a reference to an array of five UCHAR variables Digital data for the 32 external and 8 internal inputs are written to this array One bit in the array represents each input point The 8 internal inputs indicate if the corresponding analog input value is over range ainData is a reference to an array of eight INT16 variables Analog data are written to this array The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5606Inputs ioRead5606Outputs Example This program displays the values of the first 8 digital inputs and the 5th analog input read from 5606 I O at address 5 include lt ctools h gt define MY EVENT aL int main void UCHAR dinData 5 INT16 ainData 8 IO_ STATUS io_status BOOLEAN status BOOLEAN done main loop while TRUE add module scan to queue
524. this function calls other functions that require the O_SYSTEM resource e g setclock there is no need to request or release the resource This function must not request or release the O_SYSTEM resource See Also installRTCHandler Document Version 1 61 5 19 2011 310 Function Specifications ioClear Turn Off all Outputs Syntax include lt ctools h gt void ioClear void Description The ioClear function turns off all outputs as follows e areset of all I O modules is added to the I O System queue e analog outputs are set to 0 e digital outputs are set to O turned off Notification of the completion of I O requests made by this function may be obtained using the ioNotification function Notes The IO_SYSTEM resource needs to be requested before calling this function Document Version 1 61 5 19 2011 311 Function Specifications ioDatabaseReset Initialize O Database with Default Values Syntax include lt ctools h gt void ioDatabaseReset void Description The ioDatabaseReset function resets the target controller to default settings e Configuration parameters are reset to the default values e Communication status counters are reset to zero e Output I O points are cleared e Locked variables are unlocked e Clear all I O forcing e Clear all I O points e Set all database locations to zero e Set I O database for real time clock to current time e Clear real time clock ala
525. tile dynamic memory need to be statically allocated in a non volatile data section Otherwise they will be initialised at reset and the non volatile dynamic memory will be lost See the Example for the function allocateMemory which demonstrates how to create a non volatile data section to save pointers to non volatile dynamic memory See Also allocateMemory Document Version 1 61 5 19 2011 242 Function Specifications getABConfiguration Get DF1 Protocol Configuration Syntax include lt ctools h gt struct ABConfiguration getABConfiguration FILE stream struct ABConfiguration ABConfig Description The getABConfiguration function gets the DF1 protocol configuration parameters for the stream lf stream does not point to a valid serial port the function has no effect ABConfig must point to a DF1 protocol configuration structure The getABConfiguration function copies the DF1 configuration parameters into the ABConfig structure and returns a pointer to it See Also setABConfiguration Example This program displays the DF1 configuration parameters for com1 include lt ctools h gt int main void struct ABConfiguration ABConfig getABConfiguration coml amp ABConfig fprintf coml Min protected address Su r n ABConfig min_ protected address fprintf coml Max protected address Su r n ABConfig max_protected_address Document Version 1 61 5 19 2011 243 Function Specifications
526. tingTableEntryEx Reads an extended entry from the DNP routing table dnpReadRoutingTableEntry_DialString Reads a primary and secondary dial string from an entry in the DNP routing table dnpReadRoutingTableSize Reads the total number of entries in the routing table dnpSaveAl16Config Sets the configuration of a DNP 16 bit analog input point Document Version 1 61 5 19 2011 76 Overview of Programming Functions dnpSaveAl32Config Sets the configuration of a DNP 32 bit analog input point dnpSaveAlSFConfig Sets the configuration of a DNP 32 bit short floating analog input point dnpSaveAO16Config Sets the configuration of a DNP 32 bit analog output point dnpSaveAO32Config Sets the configuration of a DNP 32 bit analog output point dnpSaveAOSFConfig Sets the configuration of a DNP 32 bit short floating analog output point dnpSaveBlConfig Sets the configuration of a DNP binary input point dnpSaveBOConfig Sets the configuration of a DNP binary output point dnpSaveCli6Config Sets the configuration of a DNP 16 bit counter input point dnpSaveCl32Config Sets the configuration of a DNP 32 bit counter input point dnpSaveConfiguration Defines DNP protocol configuration parameters dnpSaveConfigurationEx Writes the extended DNP configuration parameters dnpSendUnsolicitedResponse Sends an Unsolicited Response message in DNP protocol dnpSearchRoutingTable Searches the routing table for a specific DNP address d
527. tion Specifications memoryPoolUsage Return amount of non volatile memory in bytes Syntax UINT32 memoryPoolUsage UINT16 taskGroup Description The function has one parameter The taskGroup to report the non volatile memory usage for the task group specified by taskGroup A taskGroup of ALL_TASK_GROUPS will report the total non volatile memory allocation for all tasks The function returns the amount of non volatile memory allocated by the specified task group or 0 if the specified group was invalid See Also allocateMemory freeMemory memoryPoolSize Document Version 1 61 5 19 2011 413 Function Specifications memoryPoolSize Return the size of non volatile memory pool in bytes Syntax UINT32 memoryPoolSize void Description The function takes no input parameters and returns the size of the non volatile memory pool in bytes See Also allocateMemory freeMemory memoryPoolUsage Document Version 1 61 5 19 2011 414 Function Specifications modbusExceptionStatus Set Response to Protocol Command Syntax include lt ctools h gt void modbusExceptionStatus UCHAR status Description The modbusExceptionStatus function is used in conjunction with the Modbus compatible communication protocol It sets the result returned in response to the Read Exception Status command This command is provided for compatibility with some Modbus protocol drivers for host computers The value
528. tion Specifications status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_EVENT read input data from last scan check status of last scan if ioStatus MT _54150utputs 0 amp io status status FALSE else if io status commStatus status FALSE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 378 Function Specifications ioWrite5505Outputs Write 5505 Configuration Syntax include lt ctools h gt BOOLEAN ioWrite55050utputs UINT16 moduleAddress UINT16 amp inputType 4 UINT16 inputFilter Description This function writes configuration data to the I O Table for a 5505 I O module Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5505 module Valid values are 0 to 15 inputType is a reference to an array of four UINT16 variables selecting the input range for the corresponding analog input Valid values are e 0 RTD in deg Celsius e 1 RTD in deg Fahrenheit e 2 RTD in deg Kelvin e 3 resistance measurement in ohms inputFilter selects input filter selection is written to this variable e 0 0 5s e q1 i1s e 2 2sS e 3 4s The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5505Inputs ioRead5505O
529. tion for details on each function listed mTcpSetConfig mTcpGetConfig mTcpSetinterface mTcpGetinterface mTcpSetinterfaceEx mTcpGetinterfaceEx Set Modbus IP protocol settings Get Modbus IP protocol settings Set interface settings used by the Modbus IP protocols Get interface settings used by the Modbus IP protocols Set interface settings used by the Modbus IP protocols including Enron Modbus settings Get interface settings used by the Modbus IP protocols including Enron Modbus settings mTcpSetProtocol Get interface settings used by the Modbus IP protocols mTcpGetProtocol Get interface settings used by the Modbus IP protocols mTcpMasiterOpen Allocates a connection ID and creates a task to service a Modbus IP master messaging connection mTcpMasterMessage Builds the Modbus command and sends a message to the mastering task to tell it to send the command mTcpMasterStatus Returns the master command status for the specified connection mTcpMasterDisconnect Tells a Modbus IP master task to disconnect and mTcpMasterClose Data Log to File end the task Returns a master connection ID to the connection pool The SCADAPack 330 and SCADAPack 350 controllers 4203 support data logging to the internal file system and data logging to a mass storage device connected via the USB host port Data Log Functions dlogCreate dlogDelete dlogDeleteAll dlogID dlogWrite dlogSpace Create a data log using the specified configu
530. tion function reads the DNP configuration The function has one parameter a pointer to a DNP configuration structure The function returns TRUE if the configuration was read and FALSE if an error occurred Notes This function does not return the configuration for the Unsolicited Back Off Time Use the function dnpGetUnsolicitedBackoffTime to get the Unsolicited Back Off Time configuration See Also dnpSaveConfiguration Example The following program demonstrates how to configure DNP for operation on com2 To illustrate creation of points it uses a sequential mapping of Modbus registers to points This is not required Any mapping may be used int main void UINT16 index loop index struct prot settings settings protocol settings dnpConfiguration configuration configuration settings Ay dnpBinaryInput binaryInput binary input settings xy dnpBinaryOutput binaryOutput binary output settings he dnpAnalogInput analogInput analog input settings Ej dnpAnalogOutput analogOutput analog output settings yf dnpCounterInput counterInput counter input settings ey Stop any protocol currently active on com port 2 get_protocol com2 amp settings settings type NO PROTOCOL set_protocol com2 amp settings Document Version 1 61 5 19 2011 179 Function Specifications Load the Configuration Parameters configuration masterAddress DEFAULT
531. tion function section Document Version 1 61 5 19 2011 215 Function Specifications dnpSaveConfigurationEx Write DNP Extended Configuration Syntax BOOLEAN dnpSaveConfigurationEx dnpConfigurationEx pDnpConfigurationEx Description This function writes the extended DNP configuration parameters The function has one parameter a pointer to the DNP extended configuration structure The function returns TRUE if the configuration was successfully written or FALSE otherwise if the pointer is NULL or if the DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration This function does not write the configuration for the Unsolicited Back Off Time Use the function dnpSaveUnsolicitedBackoffTime to save the Unsolicited Back Off Time configuration This function supersedes the dnpSaveConfiguration function Document Version 1 61 5 19 2011 216 Function Specifications dnpSaveUnsolicitedBackoffTime Set the DNP unsolicited resend time Syntax BOOLEAN dnpSaveUnsolicitedBackoffTime UINT16 backoffTime i Description The dnpSaveUnsolicitedBackoffTime function writes the unsolicited resend time to the controller The time is in seconds and the allowed range is 0 65535 seconds A value of zero indicates that the unsolicited resend timer is disabled The function returns TRUE if the function was suc
532. tion message in DNP to a DNP slave slaveAddress specifies the DNP station address of the slave The DNP slave slaveAddress needs to be configured in the DNP Master Poll Table prior to calling this function The function returns TRUE if the DNP clock sync message was successfully triggered It returns FALSE if the specified slave address has not been configured in the DNP Routing Table or the DNP configuration has not been created Notes This function is only available on the SCADAPack 32 SCADAPack 350 and 4203 DNP needs to be enabled before calling this function in order to create the DNP configuration Document Version 1 61 5 19 2011 192 Function Specifications dnpPortStatus Get communication status for a port Syntax include lt ctools h gt DNP_ PROTOCOL STATUS dnpPortStatus COM INTERFACE ifType BOOLEAN clear Description The dnpPortStatus function returns the DNP message statistics for the specified communication port IfType specifies the communication interface Valid values are CIF_Com1 CIF_Com2 CIF_Com3 CIF_Com4 and CIF_Lan1 If ifType does not point to a valid communications interface the function has no effect If clear is TRUE the DNP message counters are reset to zero after they are read Document Version 1 61 5 19 2011 193 Function Specifications dnpReadAddressMappingTableEntry Read DNP Address Mapping Table entry Syntax include
533. to select a listening socket for the purpose of an accept by selecting it for a read However this will only indicate when a connect indication is pending it is still necessary to call accept Parameters socketDescriptor The socket descriptor that was created with socket and bound to with bind and is listening for connections with listen addressPtr The structure to write the incoming address into addressLengthPtr Initially it contains the amount of space pointed to by addressPtr On return it contains the length in bytes of the address returned Returns New Socket Descriptor or 1 on error If accept fails the errorCode can be retrieved with getErrorCode socketDescriptor which will return one of the following error codes EBADF The socket descriptor is invalid EINVALaddressPtr was a null pointer Document Version 1 61 5 19 2011 89 Function Specifications EINVAL addressLengthPtr was a null pointer EINVAL The value of addressLengthPtr was too small ENOBUFS There was insufficient user memory available to complete the operation EPERM Cannot call accept without calling listen first EOPNOTSUPP The referenced socket is not of type SOCK_STREAM EPROTO A protocol error has occurred for example the connection has already been released EWOULDBLOCK The socket is marked as non blocking and no connections are present to be accepted Document Version 1 61 5 19 2011 90 Function Specifications addRegAs
534. tocol according to stored parameters mTcpRunServer Starts or stops the Modbus TCP Server task runMasterlpStartTask Starts or stops the Modbus TCP Master support task runBackgroundlO Starts or stops background I O task e g Dialup support pushbutton LED power control runTarget Starts or stops the run time engine Ladder Logic or IEC 61131 1 executeConstructors Execute user created global class object constructors executeDestructors Execute user created global class object destructors The ctools h file defines the following macros for use with the start up task Refer to the C Tools Macros section for details on each macro listed STARTUP_APPLICATION Specifies the application start up task STARTUP_SYSTEM Specifies the system start up task Document Version 1 61 5 19 2011 59 Overview of Programming Functions Start Up Task Info Structure The ctools h file defines the structure TASKINFO for use with the startup_task function Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Program Status Information Functions There are two library functions related to controller program status information Refer to the Function Specification section for details on each function listed getProgramStatus Returns the application program execution status setProgramStatus Sets the application program execution status Controller Information Functions There are n
535. tools h gt queryStack d0 myStack csv Document Version 1 61 5 19 2011 459 Function Specifications queue_mode Control Serial Data Transmission Syntax include lt ctools h gt void queue _mode FILE stream INT16 mode Description The queue_mode function controls transmission of the serial data Normally data output to a serial port are placed in the transmit buffer and transmitted as soon as the hardware is ready If queuing is enabled the characters are held in the transmit buffer until queuing is disabled If the buffer fills queuing is disabled automatically port specifies the serial port If it is not valid the function has no effect mode specifies the queuing control It may be DISABLE or ENABLE Notes Queuing is often used with communication protocols that use character timing for message framing Its uses in an application program are limited Document Version 1 61 5 19 2011 460 Function Specifications readBoolVariable Read IEC 61131 1 Boolean Variable IEC 61131 1 firmware only Syntax include lt ctools h gt BOOLEAN readBoolVariable UCHAR varName UCHAR value Description This function returns the current value of the specified boolean variable The variable is specified by its name expressed as a character string The name is case insensitive The IEC 61131 1 Dictionary also treats variable names as case insensitive If the variable is found TRUE is ret
536. tput Macros The ctools h file defines the following macros for use with the status LED and digital output Refer to the C Tools Macros section for details on each macro listed S MODULE_FAILURE Status LED code for I O module communication failure S_ NORMAL Status LED code for normal status LED Indicators Functions An application program can control three LED indicators The RUN LED green indicates the execution status of the program The LED can be on or off It remains in the last state until changed The STAT LED yellow indicates error conditions It outputs an error code as a binary sequence The sequence repeats until a new error code is output If the error code is zero the status LED turns off The FORCE LED yellow indicates locked I O variables Use this function with care in application programs There are two library functions related to the LED indicators Refer to the Function Specification section for details on each function listed runLed Controls the RUN LED status forceLed Sets state of the force LED LED Power Control Functions The controller board can disable the LEDs on the controller board and I O modules to conserve power This is particularly useful in solar powered or unattended installations Refer to the hardware manual for further information on LED power control There are four library functions related to LED power control Refer to the Function Specification section for details on each functio
537. tput Module Syntax include lt ctools h gt BOOLEAN ioWriteDout8 UINT16 moduleAddress UCHAR data Description This function writes data to the I O tables for the 8 point digital output module at the specified module address Data are written to the module when an I O request for the module is processed The function has two parameters the module address and the data to be written Data are read from the 8 bit data value and written to the I O table The valid range for moduleAddress is 0 to 15 The function returns TRUE if the data was written The function returns FALSE if the module address is invalid Document Version 1 61 5 19 2011 394 Function Specifications ioWriteSP2Outputs Write SCADAPack 350 Outputs Syntax include lt ctools h gt BOOLEAN ioWriteSP20utputs UCHAR amp doutData 2 INT16 amp aoutData 2 Description This function writes data to the I O table for the 10 digital outputs and 2 analog outputs of the SCADAPack 350 I O Data are written to the module when an I O request for the module is processed doutData is a reference to an array of two UCHAR variables Digital data for the 10 outputs are read from this array One bit in the array represents each output point aoutData is a reference to an array of two INT16 variables Analog data for the two analog outputs are read from this array The function returns TRUE See Also ioReadSP2Ouiputs ioReadSP2Inputs
538. tream specifies the serial port This function applies to the DF1 Half Duplex protocols only The function returns FALSE if the protocol currently installed on the specified serial port is not a DF1 Half Duplex protocol otherwise it returns TRUE Notes The purpose of this command is to re synch slaves with the master if the master has lost track of the order of responses to poll This situation may exist if the master has been power cycled for Example See the Example in the Example Programs chapter under the section Master Message Example Using DF1 Protocol The resetAll ABSlaves function should not normally be needed if polling is done using the sample polling function poll_for_response shown in this example See Also pollABSlave Example This program segment will cause all slaves communicating on the com2 serial port to erase all pending responses include lt ctools h gt resetAllABSlaves com2 Document Version 1 61 5 19 2011 487 Function Specifications resetClockAlarm Acknowledge and Reset Real Time Clock Alarm Syntax include lt ctools h gt void resetClockAlarm void Description Real time clock alarms occur once after being set The alarm setting remains in the real time clock The alarm needs to be acknowledged before it can occur again The resetClockAlarm function acknowledges the last real time clock alarm and re enables the alarm Notes This function should be called after a re
539. ts Syntax include lt ctools h gt BOOLEAN ioRead5505Inputs UINT16 moduleAddress UINT16 amp dinData float amp ainData 4 Description This function reads buffered data from the digital and analog inputs of a 5505 I O module Buffered data are updated when an I O request for the module is processed moduleAddress is the address of the 5505 module Valid values are 0 to 15 dinData is a reference to a UINT16 variable Digital data for the 16 internal inputs are written to this variable One bit in the variable represents each input point The function of the 16 digital inputs is described in the table below Sm ea Offset OFF channel 0 RTD is good ON orame o RTD opono wR iusan 1 OFF channel 0 data in range N orameocaasoworanoe 2 OFF channel 0 RTD is using 3 wire measurement ON crame o RTD s ving re measurement 4 OFF channel 1 RTD is good ON channel 1 RTD is open or PWR input is off 5 7 reserved for future use OFF channel 2 RTD is good ON channel 2 RTD is open or PWR input is off OFF channel 1 data in range ON channel 1 data is out of range OFF channel 1 RTD is using 3 wire measurement OFF channel 2 data in range 10 OFF channel 2 RTD is using 3 wire measurement ae ON channel 2 RTD is using 4 wire measurement Document Version 1 61 5 19 2011 328 Function Specifications Point Offset 11 reserved for future use 2 for future reserved for
540. ttings duplex FULL portSettings parity NONE portSettings data_bits DATA8 portSettings stop bits STOP1 portSettings flow_rx RFC_MODBUS RTU portSettings flow tx TFC_NONE portSettings type RS232 portSettings timeout 600 set_port coml amp portSettings Document Version 1 61 5 19 2011 52 Real Time Operating System Install handler for received character install handler coml signalCharacter while TRUE Wait for a character to be received wait event CHARACTER RECEIVED Echo the character back character fgetc coml if character EOF clear overflow error flag to re enable coml clearerr coml fputc character coml auxiliary The auxiliary function is a task that performs some action required by the program It does not have specific function so that the real time operating system features are clearer x7 void auxiliary void _ 7 while TRU Fl add application specific code here Allow other tasks of this priority to run release processor This function creates two tasks one at priority three and one at priority 1 to demonstrate the functions of the RTOS void main void Document Version 1 61 5 19 2011 53 Real Time Operating System Create serial communication task create task echoData 3 applicationGro
541. ttings priority 250 settings SFMessaging FALSE set_protocol com2 amp settings set communication parameters for com2 portset baud BAUD9600 portset duplex FULL portset parity NONE portset data_bits DATA8 portset stop bits STOPI portset flow_rx RFC_MODBUS_RTU portset flow_ tx TFC_NONE portset type RS232 portset timeout 600 set_port com2 amp portset release resource IO SYSTEM start second polling task example create task master2 100 applicationGroup 4 Document Version 1 61 5 19 2011 662 Example Programs define master message to read slave analog inputs message stream com2 message function 4 message slaveStation 2 message slaveRegister 30001 message masterRegister 40001 message length 8 message timeout 30 messag ventRequest FALSE message eventNo 0 main communication loop while TRUE send a new command request resource IO SYSTEM status serialModbusMaster amp message masterSessionl release resource IO SYSTEM if status wait for response or timeout while masterSessionl masterCmdStatus MM SENT do other things here allow other tasks to execute while waiting release processor if masterSessionl masterCmdStatus MM RECEIVED goodt else bad allow other tasks to execute rel
542. tures and Types section for complete information on structures and enumeration types The event notification functions provide a mechanism for communicating the occurrence of events without specifying the task that will act upon the event This is different from inter task communication which communicates to a specific task Multiple occurrences of a single type of event are queued by the RTOS until a task waits for or polls the event Event Notification Functions There are four RTOS functions for event notification Refer to the Function Specification section for details on each function listed wait_event Wait for an event to occur Document Version 1 61 5 19 2011 49 Real Time Operating System System Events Error Reporting poll_ event Check if an event has occurred Continue execution if one has not occurred signal_event Signal that an event has occurred interrupt_signal_event Signal that an event has occurred from an interrupt handler This function should only be called from within an interrupt handler There are two support functions which are not part of the RTOS that may be used with events startTimedEvent Enables signaling of an event at regular intervals endTimedEvent Terminates signaling of a regular event The RTOS defines events for communication port management and background I O operations An application program may define other events as required Care needs to be taken not to duplicate
543. turning a SFTranslation structure the new functions pass a pointer to a SF_TRANSLATION structure See the new function syntax in the sections following getSFTranslation Read Store and Forward Translation setSFTranslation Write store and forward translation table entry The previous structure struct SFTranslation shown below is no longer supported struct SFTranslation unsigned portA unsigned stationA unsigned portB unsigned stationB i Document Version 1 61 5 19 2011 687 Porting Existing C Tools Applications This structure is replaced with the structure SF_TRANSLATION which includes an IP address field to accommodate store and forward involving the Ethernet port The structure is defined as typedef struct st_SFTranslationMTcp COM_INTERFACE slavelnterface slave interface type UINT16 slaveStation slave station address COM_INTERFACE forwardinterface forwarding interface type UINT16 forwardStation forwarding station address IP_ADDRESS forward PAddress forwarding IP address SF_TRANSLATION The following table explains how to correct existing programs that use the older structure The new SF_TRANSLATION structure is documented following this table Item to be replaced Replacement struct SFTranslation The new structure has the macro name SF_TRANSLATION portA field Set slavelnterface field portA 1 1 com1 2 com2 3 coms 100 Ethernet1 portB field S
544. uct ledControl_ tag UINT16 state UINT16 time e state is the default LED state It is either the LED_ON or LED_OFF macro e time is the period in minutes after which the LED power returns to its default state MASTER_MESSAGE The MASTER_MESSAGE structure defines a Modbus serial master message typedef struct st_masterMessage FILE stream serial port UINT16 function Modbus function code UINT16 slaveStation slave station address UINT16 slaveRegister slave Modbus register UINT16 masterRegister master Modbus register UINT16 length number of registers UINT16 timeout time to wait for response in tenths of seconds BOOLEAN eventRequest signal event on completion optional UINT32 eventNo event to signal when timeout or response received optional MASTER MESSAGE e streamis the serial port to send the command message Valid values are com1 com2 and com3 e function specifies the Modbus function code Refer to the communication protocol manual for supported function codes Document Version 1 61 5 19 2011 615 Structures and Types slaveStation specifies the address of the slave station slaveRegister specifies the location of data in the slave station Depending on the Modbus function code data may be read or written at this location masterRegister specifies the location of data in the master this controller Depending on the fun
545. uct myDatabase pNvMemory gt pAllocatedMem if pMyDatabase NULL database could not be allocated return FALSE if address gt 1000 amp amp address lt 1000 SAMPLE SIZE if value 0 pMyDatabase gt coilDbase address 1001 FALSE e pMyDatabase gt coilDbase address 1001 TRUE return TRUE else if address gt 11000 amp amp address lt 11000 SAMPLE_SIZE if value 0 pMyDatabase gt statusDbase address 11001 FALSE e pMyDatabase gt statusDbase address 11001 TRUE return TRUE else if address gt 31000 amp amp address lt 31000 SAMPLE SIZE pMyDatabase gt inputDbase address 31001 value return TRUE else if address gt 41000 amp amp address lt 41000 SAMPLE SIZE pMyDatabase gt holdingDbase address 41001 value return TRUE all other addresses are not handled return FALSE Document Version 1 61 5 19 2011 655 Example Programs static void myshutdown void remove database handlers installDbaseHandler NULL installSetdbaseHandler NULL This routine initializes the custom database The database memory is allocated if application has just been downloaded The exit handler is installed and the database handlers are installed static void initia
546. ue if ioRequest MT_SP2Inputs 0 status FALSE Document Version 1 61 5 19 2011 359 Function Specifications printNow wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioReadSP2Inputs dinData check status of last scan if io0Status MT SP2Inputs 0 FALSE status else if io status commStatus FALSE status print data when coil register 100 request resource IO SYSTEM dbase MODBUS 100 release resourc if printNow IO_SYSTEM if done fprintf coml Dins 0 to 7 status dinData 0 done TRUE else done FALSE status SX Ain 4 ainData amp io status is selected release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 360 Function Specifications ioReadSP2Outputs Read SCADAPack 350 Outputs Syntax include lt ctools h gt BOOLEAN ioReadSP20utputs UCHAR amp doutData 2 INT16 amp aoutData 2 Description This function reads buffered data from the digital and analog outputs of a SCADAPack 350 I O module Buffered data are written using the ioWriteSP2Outputs function doutData is a reference to an array of two UCHAR variables Digital data for the 10 outputs are written to this
547. ule Data are written to the module when an I O request for the module is processed moduleAddress is the address of the 5506 module Valid values are 0 to 15 inputType is a reference to an array of eight UINT16 variables selecting the input range for the corresponding analog input Valid values are e O0 0to 5V e 1 1to5V e 2 0to20mA e 3 4to 20 mA inputFilter selects input filter selection is written to this variable e 0 3 Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency selects the scan frequency setting Valid values are e 0 60Hz e 1 50 Hz The function returns FALSE if the module address is invalid otherwise TRUE is returned See Also ioRead5506lnputs ioRead5506Outputs Example This program writes configuration data to the 5506 module at address 5 Document Version 1 61 5 19 2011 381 Function Specifications include lt ctools h gt define MY EVENT at int main void UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency IO_ STATUS io_status BOOLEAN status main loop whil inputFilte le TRUE set analog input types to 4 20 mA inputType 0 3 inputType 1 3 inputType 2 3 inputType 3 Sy inputType 4 3 inputType 5 3 inputType 6 3 inputType 7 3 set filter and frequency inputFilter 3 minimum filter scanFrequency 0 60 Hz status ioWrite55060utputs 5 inputType r scanFreque
548. ules with checksum support Some modules such as the 5304 can use this module type Example This Example sets all four outputs of any analog output module to half scale include lt ctools h gt int main void INT16 dataArray 4 set all output values to one half scale dataArray 0 16384 dataArray 1 16384 dataArray 2 16384 dataArray 3 16384 Write data to analog output module at module address 0 ioWriteAout4 0 dataArray ioRequest MT Aout4 0 Document Version 1 61 5 19 2011 390 Function Specifications ioWriteAout5303 Write Data to 5303 Analog Output Module Syntax include lt ctools h gt BOOLEAN ioWriteAout5303 INT16 amp data 2 Description This function writes data to the I O tables for the 2 point 5303 analog output module Data are written to the module when an I O request for the module is processed The function has one parameter a reference to an array of two INT16 variables Data are read from the array and written to the I O table The function returns TRUE Document Version 1 61 5 19 2011 391 Function Specifications ioWriteDout16 Write Data to 16 Point Digital Output Module Syntax include lt ctools h gt BOOLEAN ioWriteDout16 UINT16 moduleAddress UINT16 data Description This function writes data to the I O tables for the 16 point digital output module at the specified module address Data are written to the module w
549. umber or registers The master_message function returns the command status from the protocol driver MM_EXCEPTION_FUNCTION Master message status Modbus slave returned a function exception MM_EXCEPTION_ADDRESS Master message status Modbus slave returned an address exception MM_EXCEPTION_VALUE Master message status Modbus slave returned a value exception The calling task monitors the status of the command sent using the get_protocol_status function The command field of the prot_status structure is Document Version 1 61 5 19 2011 411 Function Specifications set to MM_SENT if a master message is sent It will be set to MM_RECEIVED when the response to the message is received The command status will be set to MM_RSP_TIMEOUT if the response is not received within 10 seconds Sending a retry master message before this timeout will abort the previous message To use a timeout other than 10 seconds use the serialModbusMaster function The master_message function may be used at the same time on the same serial port as a Telepace MSTR element or IEC 61131 1 master function block Notes Refer to the communication protocol manual for more information The IO_SYSTEM resource needs to be requested before calling this function See Also modbusSlavelD Example See the Example in the Example Programs chapter under the section Master Message Example Using Modbus Protocol Document Version 1 61 5 19 2011 412 Func
550. unction is a user defined function that handles writing to Modbus addresses not assigned in the IEC 61131 1 Dictionary The function can have any name setdbaseHandler is used in the Description below Syntax include lt ctools h gt BOOLEAN setdbaseHandler UINT16 address INT16 value Description This function is called by the setdbase function when one of the following conditions apply e There is no IEC 61131 1 application downloaded or e There is no IEC 61131 1 variable assigned to the specified Modbus address The function has two parameters e The address parameter is the Modbus address to be written e The value parameter is the integer value to write to the Modbus address lf the address is to be handled the handler function needs to return TRUE and write value to the current value at the Modbus address If the address is not to be handled the function needs to return FALSE and do nothing Notes The lO_SYSTEM resource must be requested before calling setdbase which calls this handler Requesting the O_SYSTEM resource provides that only one task may call the handler at a time Therefore the function does not have to be re entrant An array may be defined to store the current values for all Modbus addresses handled by this function See the section Data Storage if a non initialized data array is required See Also installSetdbaseHandler Document Version 1 61 5 19 2011 513 Function Specificatio
551. unction the first time or e put the PID algorithm in manual mode autoMode FALSE in PID_DATA for the first call to the pidExecute function Example This Example initializes one PID control structure and executes the control algorithm continuously Input data is read from analog inputs Output data is written to analog outputs include lt ctools h gt event number to signal when I O scan completes define IO COMPLETE 0 int main void INT16 ainData 4 analog input data INT16 aoutData 4 analog output data PID DATA pidData PID algorithm data BOOLEAN executed indicates if PID executed read analog input ioRequest MT Ain4 0 ioNotification IO COMPLETE wait event IO COMPLETE ioReadAin4 0 ainData get initial process value from analog input pidData pv ainData 0 Document Version 1 61 5 19 2011 449 Function Specifications configure PID block pidDa pidDa pidDa pidDa pidDa pidDa pidDa pidDa pidDa pidDa initialize the PID block ta sp 1000 ta gain 1 ta reset 100 ta rate 0 ta deadband 10 ta fullScale 32767 ta zeroScale 0 ta manualOutput 0 ta period 1000 ta autoMode TRUE pidInitialize amp pidData main loop while TRUE execute all I O requests ioRequest MT Ain4 0 ioNotification IO COMPLETE wait event IO COMPLETE
552. up 3 Create a task same priority as main task create task auxiliary 1 applicationGroup 2 while TRUE add application specific code here Allow other tasks of this priority to execute o release processor Explanation of Task Execution Execution Point 1 SCADAPack 350 and 4203 controllers can execute one task at a time The Real Time Operating System RTOS switches between the tasks to provide parallel execution of multiple tasks The application program can be event driven or tasks can execute round robin one after another This program illustrates both types of execution Task execution is based upon the priority of tasks There are 256 priority levels Level 255 is reserved for the null task This task runs when there are no other tasks available for execution Application programs can use levels 100 to 0 The main task is created at priority level 100 Tasks that are not running are held in queues The Ready Queue holds tasks that are ready to run Event queues hold tasks that are waiting for events Message queues hold tasks waiting for messages Resource queues hold tasks that are waiting for resources The envelope queue holds tasks that are waiting for envelopes The execution of the tasks is illustrated by examining the state of the queues at various points in the program These points are indicated on the program listing above The examples show only the Ready queu
553. upported and Unsupported Functions Existing programs may use some functions that are partially supported or unsupported on the SCADAPack 350 4203 controllers The program needs to be changed to use the new functions of the SCADAPack 350 4203 controllers For a list of the functions affected refer to the sections Partially Supported C Tools Functions Document Version 1 61 5 19 2011 673 Porting Existing C Tools Applications Build the Application The SCADAPack C Tools use a command line to compile and link a C application The sample application includes the command file build bat to do this Please see the section Application Development for more details on editing build bat command line options and loading the application into the controller Test the Application This step is specific to the application It needs to be tested to confirm it operates correctly on the SCADAPack controllers e SCADAPack 32 controllers have higher performance than do SCADAPack 350 4203 controllers Check that any I O operations allow enough time for field signals to change state Some timing relationships in the existing program may not be true in the new program depending on how you have implemented them For example a calculation done between two I O operations may execute slower and cause the second I O operation to take place later than you want e Check that any periodic functions execute at the correct rate If you ve used standard
554. uration is not valid or if the DNP configuration has not been created This function supersedes dnpGetBIConfig Document Version 1 61 5 19 2011 175 Function Specifications dnpGetBOConfig Get DNP Binary Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetBOConfig UINT16 point dnpBinaryOutput pBinaryOutput Description The dnpGetBOConfig function reads the configuration of a DNP binary output point The function has two parameters the point number and a pointer to a binary output point configuration structure The function returns TRUE if the configuration was read It returns FALSE if the point number is not valid if the pointer is NULL or if DNP configuration has not been created Notes DNP needs to be enabled before calling this function in order to create the DNP configuration See Also dnpSaveBOConfig Example See example in the dnpGetConfiguration function section Document Version 1 61 5 19 2011 176 Function Specifications dnpGetCl1 6Config Get DNP 16 bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetCI16Config UINT16 point dnpCounteriInput pCounterInput Description The dnpGetCl16Config function reads the configuration of a DNP 16 bit counter input point The function has two parameters the point number and a pointer to a counter input point configuration structure The function returns TRUE if the
555. ure NV_MEMORY is defined in the file nvMemory h and is discussed in the next section applicationType and applicationTypeLimit appstart The variables applicationType and applicationTypeLimit may be used to limit the number of instances of a C Application that may be executed on the same SCADAPack 350 and 4203 For example to load another instance of a C Application simply rename the application file before loading it to the controller By default there is no instance limit set To limit the number of instances to one for example select a unique value for applicationType and set applicationTypeLimit 1 The appstart function is the entry point for the C Application This function begins by initializing the global pointer to static non volatile data The main task is called next If the main task returns the application including tasks created by main is ended Non Volatile Memory nvMemory h Version 1 C Applications may declare variables as non volatile by locating them in SRAM There is 8 KB of SRAM available for static non volatile variables And if this is not enough up to 1 MB of SRAM is available for dynamic non volatile memory allocation For more details see the function allocateMemory Only non initialized variables are defined as non volatile Initialized variables are not need to be non volatile since they are initialized to the same value on application startup The following example describes the procedure
556. urned and the variable value is written to the unsigned char value pointed to by value If the variable is not found or if the IEC 61131 1 Symbols Status is invalid FALSE is returned and the current value is left unchanged The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the dbase function The lO_SYSTEM system resource needs to be requested before calling this function See Also readintVariable readRealVariable Example This program displays the contents of the boolean variable named Switch1 include lt ctools h gt int main void BOOLEAN status UCHAR char value request_resource IO SYSTEM status readBoolVariable Switchl amp value release resource IO SYSTEM Document Version 1 61 5 19 2011 461 Function Specifications fprintf coml status u Switchl Sd r n status value Document Vers
557. usy DE_CallAborted A call in progress was aborted by the user DE_CarrierLost The connection to the remote site was lost modem reported NO CARRIER Carrier is lost for a time exceeding the S10 setting in the modem Phone lines with call waiting are very susceptible to this condition Document Version 1 61 5 19 2011 573 Macro Definitions DE_FailedToConnect The modem could not connect to the remote site DE_InitError Modem initialization failed the modem may be turned off DE_NoDialTone Modem did not detect a dial tone or the S6 setting in the modem is too short DE NoEnor DE_NoModem The serial port is not configured as a modem port type must be RS232_MODEM Or no modem is connected to the controller serial port DE_NotInControl The serial port is in use by another modem function or has answered an incoming call DIN_END Number of last regular digital input channel DIN_START Number of first regular digital input channel DIO_SUPPORTED If defined indicates digital I O hardware supported DISABLE Specifies flow control is disabled DNP Specifies the DNP protocol for the serial port Variable name decrease output DOUT_END Number of last regular digital output channel DOUT_START Number of first regular digital output channel DS_Calling The controller is making a connection to a remote controller DS_ Connected The controller is connected to a remote controller DS_Inactive remote controller funct
558. utputs Example This program writes configuration data to the 5505 module at address 5 include lt ctools h gt define MY EVENT 1 int main void UINT16 inputType 4 Document Version 1 61 5 19 2011 379 Function Specifications UINT16 inputFilter IO_STATUS io_ status BOOLEAN status main loop while TRUE set analog input types to RTD in deg F inputType 0 1 inputType 1 1 inputType 2 1 inputType 3 1 set filter inputFilter 3 minimum filter status inputFilter ioWrite55050utputs 5 inputType add module scan to queue if ioRequest MT_55050utputs status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_EVENT check statu if ioStatus s of last scan T 55050utputs 5 amp io_ status FALSE status else if io status commStatus FALSE status release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 380 Function Specifications ioWrite5506Outputs Write 5506 Configuration Syntax include lt ctools h gt BOOLEAN ioWrite5506O0utputs UINT16 moduleAddress UINT16 amp inputType 8 UINT16 inputFilter UINT16 scanFrequency Description This function writes configuration data to the I O Table for a 5506 I O mod
559. vOperation Register bulk device operation Syntax include lt ctools h gt BOOLEAN registerBulkDevOperation char extDriveName Description registerBulkDevOperation function registers that the removable bulk memory device is about to be used for an operation Registration is necessary prior to using the device in case the device is un mounted before the operation completes This provides that internal resources used for the bulk device are correctly released The unregisterBulkDevOperation should be called after the operation is completed Parameters extDriveName The mounted bulk device drive name typically bd0 Returns TRUE Registration was successful FALSE The drive name was invalid Notes The registerBulkDevOperation and unregisterBulkDevOperation should only be used with a dynamically mounted bulk device such as a USB memory stick The unregisterBulkDevOperation needs to be called with the same device drive name as the registerBulkDevOperation See Also unregisterBulkDevOperation Example include lt ctools h gt int main void if registerBulkDevOperation bd0 FALSE printf registerBulkDevOperation bd0 failed r n Copy d0 logs log1 bd0 logs 1log1 if unregisterBulkDevOperation bd0 FALSE Document Version 1 61 5 19 2011 480 Function Specifications printf unregisterBulkDevOperation bd0 failed r n
560. value is written to the signed long value pointed to by value If the variable is not found or if the IEC 61131 1 Symbols Status is invalid FALSE is returned and the current value is left unchanged The IEC 61131 1 Symbols Status is invalid if the Application TIC code download and Application Symbols download are not sharing the same symbols CRC checksum Notes This function requires the IEC 61131 1 Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access IEC 61131 1 variables by name however because the variable name needs to be looked up in the IEC 61131 1 variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable s network address and the dbase function The lO_SYSTEM system resource needs to be requested before calling this function See Also readRealVariable Example This program displays the contents of the integer variable named Temperature include lt ctools h gt int main void BOOLEAN status INT32 value request_resource IO_ SYSTEM status readIntVariable Temperature amp value release resource IO SYSTEM Document Version 1 61 5 19 2011 465 Function Specifications fprintf coml status u Temp Sld r n status value Document Version 1 61 5 19 2011 466 Function Specificatio
561. value3 30000 data value4 40 data value5 50 if datalogCreate logID amp dLogConfig DLS CREATED Start writing records in log if datalogWrite logID UINT16 amp data one record was written in data log Document Version 1 61 5 19 2011 133 Function Specifications datalogDelete Delete Data Log Function Syntax include lt ctools h gt BOOLEAN datalogDelete UINT16 og D Description This function destroys the specified data log The memory used by the data log is returned to the freed The function has one parameter og D specifies the data log to be deleted The valid range is 0 to 15 The function returns TRUE if the data log was deleted The function returns FALSE if the log ID is not valid or if the log had not been created Example See example DataLog program in the Example Programs section This program shows the only way to change the configuration of an existing log which is to delete the log and recreate the data log include lt ctools h gt int main void UINT16 lLogID DATALOG CONFIGURATION dLogConfig Select logID 10 logID 10 Read the configuration of logID 10 if datalogSettings logID amp dLogConfig if dLogConfig typesOfFields 0 DLV_INT16 Wrong type Delete log and create new one xy if datalogDelete logID Re enter the log configuration dLogConfig records 200 dLogCon
562. values of the 8 internal digital inputs and the 5th analog input read from 5506 I O at address 5 include lt ctools h gt define MY EVENT aL int main void UCHAR dinData INT16 ainData 8 IO_ STATUS io_status BOOLEAN status BOOLEAN done main loop while TRUE add module scan to queue Document Version 1 61 5 19 2011 333 Function Specifications if ioRequest MT 5506Inputs 5 status FALSE wait for scan to complete ioNotification MY EVENT wait event MY_ EVENT read input data from last scan status ioRead5506Inputs 5 dinData ainData check status of last scan if ioStatus MT 5506Inputs 5 amp io status status FALSE else if io status commStatus status FALSE print data if done fprintf coml status u Dins 0 to 7 X Ain 4 d r n status dinData ainData 4 done TRUE release processor to other priority 1 tasks release processor Document Version 1 61 5 19 2011 334 Function Specifications ioRead5506Outputs Read 5506 Configuration Syntax include lt ctools h gt BOOLEAN ioRead55060utputs UINT16 moduleAddress UINT16 amp inputType 8 UINT16 amp inputFilter UINT16 amp scanFrequency Description This function reads configuration data from the I O Table for a 5506
563. version is available It returns FALSE if the firmware version has not been read from the I O controller Document Version 1 61 5 19 2011 369 Function Specifications ioWrite4203DROutputs Write 4203 DR Outputs Syntax include lt ctools h gt BOOLEAN ioWrite4203DROutputs UCHAR amp doutData INT16 S amp aoutData Description This function writes data to the I O table for the digital output and analog output of the 4203 DR I O Data is written to the module when an I O request for the module is processed doutData is a reference to a UCHAR variable Digital data for the output is read from this variable One bit in the array represents each output point aoutData is a reference to a INT16 variable Analog data for the analog output is read from this variable The function returns TRUE if the supplied data was written to the I O table FALSE is returned if the data could not be written to the I O table See Also ioRead4203DRInputs Example This program turns on the digital output and sets the analog output to full scale on the 4203 DR include lt ctools h gt define MY EVENT 1 int main void UCHAR doutData INT16 aoutData I0_STATUS io_ status main loop while TRUE write data to output tables for next scan doutData 0x01 aoutData 32767 ioWrite4203DROutputs doutData aoutData add module scan to queue if ioRequest MT_4203DROutputs 0
564. x 224 is A E leon ach es the eee hh Mea as Ue AT 193 dnpReadAddressMappingTableEnty cccceeeeeseeeceeeeeeeeeeeaeeeeeenaeeeeeeaeeeeseaas 194 dnpReadAddressMappingTableSize ccccesceceeceeseeeeeeeeeeeeeeeseaeeeseaeeseneeenaees 195 dnpReadMasterPollTableEntry eeececeeeeseeceeeenneeeeeeaeeeeeeaaeeeeeeaeeeseeaeeeeseaas 196 dnpReadMasterPollTableEntryEx eee ceeeecnceeeeenneeeeeeeaeeeeeeaeeeeeeaeeeeseaeeeeseaas 197 dnpReadMasterPollTableSiZe c cccecccccesceeeeceeeeeeeeeeeeeseeeeeceeeesaeeneeeeesaees 198 dnpReadRoutingTableEntry DialStringS cccccccceeeeeeeeeceeeeeseeeeeseaeeeeeeesaees 199 AnpReadRoutingTableEntry eecceeeeseceeeenneeeeeeeeeeceeaeeeseeaeeeeeeaeeeeeenaeeeeeeaas 200 AnpReadRoutingTableEntryEx ee eeceeceeeaeeeeeeneeeeeeaeeeeeeaeeeeeeaeeeeeeaeeeeseaas 201 AnpReadRoutingT ableSiZe cccccccecececeeeeeeeeneeceeeeeseaeeesaaeseeeeeceaeeeseaeeseeeeeaees 202 AnpSaveAl1 GCONAIG ai a a a a a aa a a aia kniei 203 ANPpSaveAl32Contig cccccececcceeseeceecceceeeeeeaaeeeeneeceeeeeaaeeseaaesseeeeseeeeeaesteneeesaees 204 dnpSaveAISFGON Gda aaaea ee hel Gite da ia ia ada eens 205 dnpSaveAOT6CoOnfig ineanii aaaeei aaaea a ia iaa a a 206 dnpSaveAO3Z2CONfig Ja anana aai ii ean darida riaa tda i eniai 207 AnpSaveAOSF Contligs iiiaae enced aaae aiia riaa A a ai 208 AnpSaveBl Contig sisi heels caedesv ena darida riaa i a eaaa 209 dnpSaveBIConfig Exsel iaa oid a aaia
565. x To support multiple C applications these functions now have an argument to specify the application The new syntax for these functions is documented in the Function Specifications section Freeing Dynamic Memory When a C Application is ended e g by using the STOP button from the C C Program Loader memory allocated by using the malloc function is not freed automatically An exit handler must be installed to free allocated memory Please see the documentation for installExitHandler in the Function Specifications section for more details Non Volatile Data Sections I O System Functions C Tools applications could make any variable non volatile by renaming the memory section where it was located This was done using a compiler pragma directive This is not supported on the SCADAPack 350 and 4203 SCADAPack C Tools applications can make variables non volatile by locating them in SRAM There is 8 KB of SRAM available for static application variables If this is not enough up to 1 MB of SRAM is available for dynamic non volatile memory allocation See the function allocateMemory To create a non volatile section refer to the section Non Volatile Memory nvMemory h The SCADAPack 350 SCADAPack 4203 and SCADAPack 32 use a different I O system architecture than the SCADAPack I O operations can be performed in parallel with application program execution This improves the performance of IEC 61131 1 and Telepace applications an
566. xample Using mTcpMasterMessage This program sends master messages on the LAN interface using Modbus TCP protocol SCADAPack 350 C Application Main Program Copyright 2001 2004 Control Microsystems Inc Be ete ee ee include lt ctools h gt master IP modes typedef enum masterIPModes t MIP_OPEN CONNECTION 0 MIP CONNECTING MIP _ SEND MESSAGE MIP WAIT FOR RESPONSE MIP DISCONNECT MIP CLOSE MIP_MODE E E E EE main This routine is the main application loop r A a o a AT a E int main void MIP MODE mode IP_SETTINGS ipSettings IP_ADDRESS remoteIP IP_ PROTOCOL TYPE protocolType CONNECTION TYPE appType UINT16 timeout UINT32 connectID ODBUS_CMD STATUS cmdStatus BOOLEAN status UINT16 function UINT16 slaveStation UINT16 slaveRegister UINT16 masterRegister UINT16 length IP settings for SCADAPack LAN interface ipSettings ipConfigMode IPConfig GatewayOnLAN ipSettings ipAddress 0 inet_addr 172 16 10 0 ipSettings gateway 0 inet_addr 172 16 0 1 ipSettings netMask inet_addr 255 255 0 0 ipSettings ipVersion 4 status ethernetSetIP amp ipSettings master IP command definition remoteIP s addr inet_addr 172 16 3 8 destination IP address Document Version 1 61 5 19 2011 665 Example Programs protocolType IPP _ModbusTcp appType CT MasterCApp timeou
567. xecution Point 7 This point is just after the auxiliary task has started to run The main and auxiliary tasks will continue to alternate execution as each task releases the processor to the other Ready Queue Event 10 Queue Running Task 5 auxiliary echoData main 255 nullTask Figure 7 Queue Status at Start of auxiliary Task Execution Point 8 This point occurs just after a character has been received The signalCharacter function executes and signals an event The RTOS checks the event queue for the event and makes the highest priority task ready to execute In this case the echoData task is made ready The RTOS then determines if the new task is higher priority than the executing task Since the echoData task is higher priority than the auxiliary task a task switch occurs The auxiliary task is placed on the Ready queue The echoData task executes Observe the position of auxiliary in the Ready queue The main task will execute before it at the next task switch Document Version 1 61 5 19 2011 57 Real Time Operating System Ready Queue Event 10 Queue Running Task echoData auxiliary Figure 8 Queue Status after Character Received Execution Point 9 This point occurs just after the echoData task waits for the character received event It is placed on the event 10 queue The highest priority task on the ready queue main
568. y variable read primary variable current and percent of span read primary variable current and dynamic variables read unique identifier associated with tag read specified transmitter variables return status of last HART command sent read HART module settings write HART module settings convert string to HART packed string convert HART packed string to string The ctools h file defines the following macro of interest to a C application DATA_SIZE HART Command Enumeration Types program Refer to the C Tools Macros section for details Maximum length of the HART command or response field The ctools h file defines one enumeration type The HART_RESULT enumeration type defines a list of results of sending a command Refer to the C Tools Structures and Types section for complete information on structures and enumeration types HART Command Structures The ctools h file defines five structures Refer to the C Tools Structures and Types section for complete information on structures and enumeration types HART_DEVICE HART_VARIABLE HART_SETTINGS HART_COMMAND HART_RESPONSE type is a structure containing information about the HART device type is a structure containing a variable read from a HART device type is a structure containing the configuration for the HART modem module type is a structure containing a command to be sent to a HART slave device type is a structure containing a response from a HART sl
569. zation used in task exit handler modemAbortAll unconditionally terminate connections with external device or modem initializations used in task exit handler modemNotification notify the dial up modem handler that an interesting event has occurred This function is usually called whenever a message is received by a protocol Dial Up Modem Macros The ctools h file defines the following macros of interest to a C application program Refer to the C Tools Macros section for details on each macro listed MODEM_CMD_ MAX_LEN Maximum length of the modem initialization command string PHONE_NUM_MAX_LEN Maximum length of the phone number string Dial Up Modem Enumeration Types The ctools h file defines the enumerated types DialError and DialState Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Dial up Modem Structures The ctools h file defines the structures ModemInit and ModemSetup Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Serial Communication Protocols The TeleBUS protocols are compatible with the widely used Modbus RTU and ASCII protocols The TeleBUS communication protocols provide a standard communication interface to SCADAPack controllers Additional TeleBUS commands provide remote programming and diagnostics capability The TeleBUS protocols provide access to the I O database in the controlle
Download Pdf Manuals
Related Search
Related Contents
RAPPORT ACCIDENT Especificaciones Técnicas Philips Disney 2-in-1 Projector and night light 71769/28/16 contrato de mantenimiento ferroli MPC823E62J13ER Errata - Freescale Semiconductor sur ce lien JUIN 2010 - Université Libre de Bruxelles Sony HT-4850DP User's Manual instructions for safe operations lm3000 Juillet 2011 Copyright © All rights reserved.
Failed to retrieve file