Home
ISaGRAF C Tools User Manual
Contents
1. 100 1 FALSE DEFAULT_DLINK_RETRIES DEFAULT_DLINK_TIMEOUT DEFAULT_OPERATE_TIMEOUT FALSE DEFAULT_MAX_RESP_LENGTH DEFAULT_APPL_RETRIES DEFAULT_APPL_TIMEOUT O_TIME_SYNC 2 0 REPORT _ALL EVENTS 1000 0 0 0 0 REPORT _ALL EVENTS 0 0 hb ie O d ISaGRAF C Tools User and Reference Manual 139 configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration dnpSaveConfigura Start DNP pro get_protocol com4 protocolSettings type set_protocol com4 EV CI32_reportingMethod CI32_bufferSize CI32_wordOrder AIl6_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_nu
2. e pSettings is a pointer to a PROTOCOL_SETTINGS_EX 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 fails to start Notes The IO_SYSTEM resource must 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 Be sure to add a call to modemNot ification 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 See Also getProtocolSettingsEx 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 settings station Ty settings priority 37 settings SFMessaging FALSE settings mode AM_standard settings enronEnabled TRUE settings enronStation 4 request_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 358 May 8 2007 setProtocolSettingsEx com2 amp settings release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 359 May 8 2007 setSFTranslation Write Store and Forward Translation Syntax include lt ctools h gt struct SF
3. if dbase MODBUS GENERATE_AI16_EVENT setdbase MODBUS GENERATE_AI16_EVENT 0 ail6_event_flag FALSE if dbase MODBUS CLASSO_REPORT setdbase MODBUS CLASSO_R PORT 0 classO_report_flag FALSE r a a release IO resource release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 141 May 8 2007 Clear DNP Event Log buffer if requested if clear_events_flag dnpClearEventLogs Generate a DNP Change Event for BI Point 0 if requested if bi_event_flag dnpGenerateEventLog BI_POINT 0 Generate a DNP Change Event for 16 bit AI Point 0 if requested if ail _event_flag dnpGenerateEventLog AI16_POINT 0 Send DNP Class 0 Unsolicited Report if requested if classO_report_flag dnpSendUnsolicitedResponse CLASSO_FLAG release processor to other tasks release_processor ISaGRAF C Tools User and Reference Manual 142 May 8 2007 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 class specifies the class or classes of event data to include in the message It can contain any combination of the following values if
4. Allow other tasks to execute release_resource IO_SYSTEM release_processor request_resource IO_SYSTEM if dbase MODBUS 10001 0 puts tank is not filling r n else puts tank full r n setdbase MODBUS 1 0 close valve release_resource IO_SYSTEM 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 alarmin Returns absolute time of alarm given elapsed time getclock Read the real time 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 ISaGRAF C Tools User and Reference Manual 43 May 8 2007 setClockA
5. Description The dnpGenerateEventLog 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 AI32_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 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 must be enabled before calling this function in order to create the DNP configuration Example See the example in the dnpSendUnsolicited section ISaGRAF C Tools User and Reference Manual 104 May 8 2007 dnpGetAl16Config Get DNP 16 bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAI16Config UINT16 point dnpAnalogInput pAnalogInput i Description This 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 struct
6. ISaGRAF C Tools User and Reference Manual May 8 2007 isaWrite4Aout Write to 4 Analog Outputs Syntax include lt ctools h gt unsigned isaWrite4Aout unsigned moduleAddress int dataArray Description The isaWrite4Aout function writes data to any 4 point Analog Output Module at the specified moduleAddress Data is read from the array pointed to by dataArray and written to the 4 analog outputs dataArray must point to an array of four 16 bit integers The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAdadress is 0 to 15 The lO_SYSTEM resource must be requested before calling this function See Also isaWrite2Aout isaWrite5303Aout Example This program sets all 4 analog outputs to half scale on a 4 point Analog Output Module at module address 0 include lt ctools h gt void main void int dataArray 4 dataArray 0 16384 dataArray 1 16384 dataArray 2 16384 dataArray 3 16384 Write data to analog output module request_resource IO_SYSTEM isaWrite4Aout 0 dataArray release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 259 May 8 2007 isaWrite4AoutChecksum Write to 4 Point Analog Output Module with Checksum Syntax include lt ctools h gt UINT16 isaWrite4AoutChecksum UINT16 moduleAddress INT16 dataArray Description The isaWrit
7. Sa Erene oepa ISaGRAF C Tools User and Reference Manual 287 May 8 2007 poll_for_response The poll_for_response function polls the specified slave for a response to a master message sent on the serial port specified by stream It returns when the correct respons is received or when the period specified by time in tenths of a second expires af unsigned poll_for_response FILE stream unsigned slave unsigned time struct prot_status status unsigned done static unsigned long good bad set timeout timer interval 0 10 settimer 0 time do wait until command status changes or timer expires do status get_protocol_status stream release_processor while timer 0 amp amp status command MM_SENT command has been ACKed send poll if status command MM_CMD_ACKED pollABSlave stream slave done FALSE rvesponse command mismatch poll again else if status command MM_WRONG_RSP pollABSlave stream slave done FALSE correct response was received else if status command MM_RECEIVED goodt done TRUE timer has expired or status is MM_EOT else bad done TRUE while done fprintf coml Good 8lu Bad 8lu r good bad ISaGRAF C Tools User and Reference Manual 288 May 8 2007 modbusExceptionStatus Set Response to Protocol Command Syntax include lt
8. struct pconfig settings get_port coml amp amp settings printf Baud rate d r n settings baud printf Duplex d r n settings duplex ISaGRAF C Tools User and Reference Manual 162 May 8 2007 getProgramStatus Get Program Status Flag Syntax include lt ctools h gt unsigned getProgramStatus void Description The getProgramStatus function returns the application program status flag The status flag is set to NEW_PROGRAM when the C program is erased or downloaded to the controller from the program loader The application program may modify the status flag with the setProgramStatus function See Also setProgramStatus 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_ALARM 41000 define ALARM_OUTPUT 1026 void main void int inputValue if getProgramStatus 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 PROGRAM_EXECUTED while TRUE request_resource IO_SYSTEM Test input against alarm limits if ain INPUT gt dbase MOD
9. turn on all digitalData 0 digitalData 1 set ana analogData analogData 0 1 8 set ana nput Type nput Type nput Type nput Type nput Type t7 t7 t7 d 0 3 T TEAT nputType nputType nputType WWW WWW Ww H H H H H H H H N WA UF WD t T T set filter and inputFilter 07 scanFrequency 0 external digital outputs 2 2 8 GF ncy xf OxFF OxFF log outputs to full scale 2767 21673 log input types to 4 20 mA frequency maximum filter 60 Hz F set analog output type to 4 20 mA outputType 1 Write output d request_resource isaWrite56060utputs 1 scanFrequency inputFilter releas _resourc ISaGRAF C Tools User and Reference Manual May 8 2007 ata to 5606 I O module IO_SYSTEM digitalData outputType IO_SYSTEM analogData inputType 274 isaWrite8Dout Write to 8 Digital Outputs Syntax include lt ctools h gt unsigned isaWrite8Dout unsigned moduleAddress unsigned char data Description The isaWrite8Dout function writes data to any 8 point Digital Output Module at the specified moduleAddress Data from the specified 8 bit value is written to the 8 digital outputs The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAda
10. AD_BATTERY Internal AD channel connected to lithium battery AD_THERMISTOR Internal AD channel connected to thermistor T_CELSIUS Specifies temperatures in degrees Celsius T_FAHRENHEIT Specifies temperatures in degrees Fahrenheit T_KELVIN Specifies temperatures in degrees Kelvin T_RANKINE Specifies temperatures in degrees Rankine ISaGRAF C Tools User and Reference Manual 37 May 8 2007 Analog Output Functions The controller supports external analog output modules Refer to the SCADAPack System 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 isaWriteAout Writes data to an analog output module isaWrite2Aout Write data to any 2 point analog output module isaWrite4Aout Write data to any 4 point analog output module IsaWrite4202Outputs Write data to the digital and analog outputs of the SCADASense Series of controllers isaWrite5505Outputs Write configuration data to the 5505 module isaWrite5506Outputs Write configuration data to the 5506 module isaWrite5606Outputs Write data to the digital and analog outputs of the 5606 module isaWrite5303Aout Write data to the two points of the 5303 module isaWriteLPOutputs Write data to the digital and analog outputs of the SCADAPack LP I O isaWriteSP1000utputs Write data to the digital and analog outputs of the SCADAPack 100
11. Notes It is recommended the get_port and set_port functions be used to access the configuration table ISaGRAF C Tools User and Reference Manual 310 May 8 2007 portindex Get Index of Serial Port Syntax include lt ctools h gt unsigned portIndex FILE stream Description The portindex function returns an array index for the serial port specified by stream It is guaranteed to 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 ISaGRAF C Tools User and Reference Manual May 8 2007 311 portStream Get Serial Port Corresponding to Index Syntax include lt ctools h gt FILE portStream unsigned 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 portindex ISaGRAF C Tools User and Reference Manual May 8 2007 312 processModbusCommand Process a Modbus Command and Return the Response Syntax include lt ctools h gt BOOLEAN processModbusCommand FILE stream UCHAR pCommand UINT16 commandLength UINT16 responseSize UCHAR pResponse UINT16 pResponseLength Description The processModbusCommand function processes a Modbus protocol
12. TRUE is written when value is any non zero value FALSE is written when value is 0 Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 must be requested before calling this function See Also setdbase readBoolVariable Example This program writes a TRUE state to the boolean variable named Switch1 include lt ctools h gt void main void BOOLEAN status request_resource IO_SYSTEM status writeBoolVariable Switch1 TRUE release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 384 May 8 2007 writelntVariable Write to ISaGRAF Integer Variable Syntax include lt ctools h gt BOOLEAN writeIntVariable unsigned char varName signed 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 ISaGRAF Dictionary also treats variable names as case insensitive If the variable is found TRUE is
13. include lt ctools h gt SoS oe Seen 2eseecece e522 55 The shutdown function aborts any active ISaGRAF C Tools User and Reference Manual 294 May 8 2007 modem connections when the task is ended i void shutdown void modemAbortAll void main void TASKINFO taskStatus set up exit handler for this task taskStatus getTaskInfo 0 installExitHandler taskStatus taskID shutdown while TRUE rest of main task here Allow other tasks to execute release_processor ISaGRAF C Tools User and Reference Manual 295 May 8 2007 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 all 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 ensures that no other modem control function can access the serial port This parameter must be suppl
14. void main void unsigned point int dataArray 4 Read data from analog input module request_resource IO_SYS isaRead4Ain 0 dataArray EM release_resource IO_SYS Print module data fprintf coml Point for point 0 point lt fprintf coml Sd EM Value n r 4 point t Sd n r point dataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 231 isaRead4Counter Read 4 Counter Inputs Syntax include lt ctools h gt unsigned isaRead4Counter unsigned moduleAddress unsigned long dataArray Description The isaRead4Counter function reads any 4 point Counter Input Module at the specified moduleAddress Data is read from all 4 counter inputs and copied to the array pointed to by dataArray dataArray must point to an array of four 32 bit integers 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 moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function Example This program displays the values of the 4 counter inputs read from a 4 point Counter Input Module at module address 0 include lt ctools h gt void main void unsigned point unsigned long dataArray 4 Read data from counter input mo
15. Action for command data pMessagett ak o request_resource IO_SYSTI pMessage 0 eal ES setdbase MODBUS 1 0 release_resource IO_SYSTEM pResponse response pResponse 71 pResponset t pResponse O pResponset t pResponse F pResponset t pResponse F pResponse t XT sponseLength 4 return NORMAL if pMessage 1 ISaGRAF C Tools User and Reference Manual May 8 2007 205 request_resource IO_SYSTEM setdbase MODBUS 1 1 release_resource IO_SYSTEM pResponse response pResponse 71 pResponset t pResponse 0O pResponset t pResponse N pResponset t ry responseLength 3 return NORMAL static void shutdown void installModbusHandler NULL main 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 sy void main void TASKINFO taskStatus struct pconfig portSettings struct prot_settings protSettings portSettings baud BAUD9600 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATA7 portSettings stop_bits STOP1 portSettings flow_rx DISABLE portSettings flow_tx DISABLE portSettings type
16. Syntax include lt ctools h gt DATALOG_STATUS datalogCreate UINT16 logID DATALOG_CONFIGURATION pLogConfiguration i 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 logID specifies the data log to be created The valid range is 0 to 15 phogConfiguration 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 must be deleted and recreated to change the configuration All data logs are stored in memory from 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_BADTD If the configuration is not valid the creation operation fails The function returns DLS_BADCONFIG See Also datalogDelete datalogSettings Example The following code shows how to create a data log and how to write one record into it a include ctools h Structure used only to copy one record into data log struct dataRecord UINT16 valuel int value2 double value3 float value4 ISaGRAF C Tools User and
17. below fe ais See Soe eee as et SA datalog c This file contains the global variable definitions for a datalogger database These global variables are placed in a non initialized section called savedata All data in these variables will be maintained over powerup include lt datalog h gt define a non initialized section c pragma option NZsavedata pragma option Xp Global variable definitions log index unsigned logIndex log database struct dataLog logData DATA_LOG_SIZI x7 alled savedata E Any variable defined in this file datalog c will be placed in the non initialized section arbitrarily named savedata Code operating on thes separate file which references these global variables header file e g datalog h e variables should be placed in a through external definitions placed in a The pragma option directive is documented in the Microtec MCCM77 Documentation Set Compiling Source Code The C Compiler converts source code into object files The basic command line and options required to compile code for the controller are nQ M1 mccm77 Sy c filename c A complete description of the command line options is given in the Microtec MCCM77 User s Guide The options used here are v Issue warnings for features in source file This option allows you to detect potential errors in your source code before running the program Do not suppress diagnost
18. All timers operate in the background from a hardware interrupt generated by the main system clock Once loaded they count without intervention from the main program 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 tenths 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 Software Timer Macros The ctools h file defines the following macros for use with timers Refer to the C Tools Macros section for details on each macro listed NORMAL Specifies normal count down timer TIMED_OUT Specifies timer is has reached zero TIMER_BADINTERVAL Error code indicating invalid timer interval TIMER_BADTIMER Error code indicating invalid timer TIMER_BADVALUE Error code indicating invalid time value TIMER_MAX Number of last valid 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 Timer Example Programs Example 1 Turn on a digital output assigned to coil register 1 and wait 5 seconds before turning it off interval 0 10 timer 0 tick rate 1 second request_resource IO_SYSTEM setdbase MODBU
19. 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 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 HART 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 must be initialized using hartCommandoO or hartCommand1 1 The function returns immediately after the command is sent The calling program must 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
20. The IO_SYSTEM resource must be requested before calling this function Notes Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it Be sure to add a call to modemNot ification 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 See Also getProtocolSeitings start_protocol get_protocol set_protocol modemNotification 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 3 settings SFMessaging FALSE settings mode AM_extended request_resource IO_SYSTEM setProtocolSettings com2 amp settings release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 357 May 8 2007 setProtocolSettingsEx Sets extended protocol settings for a serial port Syntax include lt ctools h gt BOOLEAN setProtocolSettingsEx FILE stream PROTOCOL_SETTINGS_EX pSettings 3 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 stream specifies the serial port It is one of com1 com2 coms3 or com4
21. define EVENTS _CLASS3 112 Status Registers x define EVENT_COUNT_AI16 40102 define EVENT_COUNT_BI 40104 define EVENT_COUNT_CLASS1 40106 define EVENT_COUNT_CLASS2 40108 define EVENT_COUNT_CLASS3 40110 main This routine is the main application loop void main void UINT16 index struct prot_settings protocolSettings ai loop index dnpConfiguration configuration dnpBinaryInput binaryInput dnpAnalogInput analogInput DNP_RUNTIME_STATUS dnpStatus int int int int clear_events_flag bi_event_flag ail6_event_flag classO_report_flag Set DNP Configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration configuration masterAddress rtuAddress datalinkConfirm datalinkRetries datalinkTimeout operateTimeout applicationConfirm maximumResponse applicationRetries applicationTimeout timeSynchronization BI_number BI_startAddress BI_reportingMethod BI_soeBufferSiz BO_number BO_startAddress CI16_number CI16_startAddress CI16_reportingMethod CI16_bufferSize CI32_number C1I32_startAddress protocol settings
22. 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 e flags is the timer type and status bits NORMAL PULSE TRAIN DUTY_CYCLE TIMEOUT and TIMED_OUT More than one condition may be true at any time e duty_on is the length of the on high portion of the square wave output This is used only by the pulse function e duty_period is the period of the square wave output This is used only by the pulse function e channel and bit specify the digital output point This is used by pulse pulse_train and timeout functions VERSION The Firmware Version Information Structure holds information about the firmware typedef struct versionInfo_tag unsigned version unsigned 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 WRITESTATUS The WRITESTATUS enumerated type indicates the status of an I C bus message read and may have one of the following values enum WriteStatus ISaGRAF C Tools User and Reference Manual 424 May 8 2007 typedef enum WriteStatus WRIT ISaGRA
23. include lt ctools h gt BOOLEAN writeTimerVariable unsigned char varName unsigned long value Description This function writes 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 ISaGRAF 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 ISaGRAF Symbols Status is invalid nothing is done and FALSE is returned The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 IO_SYSTEM system resource must
24. installExitHandler thisTask taskID mainExitHandler install handler for Enron Modbus enroniInstallCommandHandler commandHandler infinite loop of main task while TRUE add application code here ISaGRAF C Tools User and Reference Manual 151 May 8 2007 forceLed Set State of Force LED Syntax include lt ctools h gt void forceLed unsigned 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 caution in application programs See Also setStatus ISaGRAF C Tools User and Reference Manual 152 May 8 2007 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 f stream does not point to a valid serial port the function has no effect ABConfig must point to an AB protocol configuration structure The getABConfiguration function copies the AB 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 void main void struct ABConfig
25. isaReadSP100Inputs Read the digital and analog inputs from SCADAPack 100 I O Digital Output Functions The controller supports external digital output modules Refer to the SCADAPack 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 isaWrite16Dout Write data to any 16 point Digital output module isaWrite32Dout Writes data to any 32 point Digital Output Module at the specified moduleAddress IsaWrite4202OutputsEx Write the digital output of a SCADASense 4203 DR or 4202 DR with a digital output Extended I O IsaWrite4202DSOutputs Write the digital outputs of a SCADASense 4202 or 4203 DS isaWrite5601 Outputs Write data to the digital outputs of a 5601 I O Module isaWrite5602Outputs Write data to the digital outputs of a 5601 I O Module isaWrite5604O0utputs Writes data to the digital and analog outputs of the 5604 I O module isaWrite5606Outputs Writes data to the digital and analog outputs of the 5606 I O module isaWrite8Dout Write data to any 8 point Digital output module isaWriteLPOutputs Write data to the digital and analog outputs of the SCADAPack LP I O isaWriteSP1000utputs Write data to the digital and analog outputs of the SCADAPack 100 I O Counter Input Functions The controller supports internal counters and external counter module
26. 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 datalogReadStart datalogReadNext datalogPurge Example See the example for datalogCreate ISaGRAF C Tools User and Reference Manual 94 May 8 2007 dbase Read Value from I O Database Syntax include lt ctools h gt int dbase unsigned type unsigned 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 If the specified address is not valid then the variable pointed to by value is left unchanged The table below shows the valid address types and ranges 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 If the specified address is in the valid range but it has not been defined by an application then the address is also invalid An address is defined if any of the following is true 1 The address has been assigned
27. s network address and the dbase function The IO_SYSTEM system resource must be requested before calling this function See Also writeBoolVariable Example This program displays the contents of the boolean variable named Switch1 include lt ctools h gt void main void BOOLEAN status unsigned char value request_resource IO_SYSTEM status readBoolVariable Switchl amp value release_resource IO_SYSTEM printf status Su Switchl d r n status value ISaGRAF C Tools User and Reference Manual 316 May 8 2007 readCounter Read Accumulator Input Syntax include lt ctools h gt unsigned long readCounter unsigned counter unsigned clear Description The readCounter routine reads the digital input counter specified by counter The counter may be 0 1 or 2 If clearis TRUE the counter is cleared after reading otherwise if it is FALSE the counter continues to accumulate If counter is not valid a BAD_COUNTER error is reported for the current task Notes The three DIN counter inputs are located on the 5203 or 5204 controller board Refer to the System Hardware Manual for more information on the hardware The counter increments on the rising edge of the input signal See Also readCounterlnput check_error ISaGRAF C Tools User and Reference Manual 317 May 8 2007 readCounter Input Read Counter Input Status Syntax include lt ctools h gt unsig
28. ISaGRAF C Tools User and Reference Manual May 8 2007 247 isaRead5606Inputs Read 5606 Inputs Syntax include lt ctools h gt unsigned isaRead5606Inputs UINT16 moduleAddress UCHAR dinDataArray INT16 ainDataArray Description The isaRead5606Inputs function reads the digital and analog inputs from the specified 5606 I O module Data is read from all 40 digital inputs and copied to the array pointed to by dinDataArray Data is read from all 8 analog inputs and copied to the array pointed to by ainDataArray moduleAddress is the address of the 5606 module Valid values are 0 to 7 dinDataArray must point to an array of five 8 bit unsigned characters Each bit in the array represents one input point ainDataArray must point to an array of eight 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaWrite5606Outputs Example This program displays the values of the 40 digital inputs and 8 analog inputs read from 5606 I O module 3 include lt ctools h gt void main void UINT16 point UCHAR dinData 5 INT16 ainDataArray 8 Read input data from 5606 I O module request_resource IO_SYSTEM isaRead5606Inputs 3 dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value
29. ISaGRAF message variables have the following format Byte Description Location Maximum length as declared in ISaGRAF 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 function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 must be requested before calling this function See Also writeMsgVariable ISaGRAF C Tools User and Reference Manual 322 May 8 2007 Example This program displays the contents of the message variable named msgData of maximum length 20 include lt ctools h gt void main void BOOLEAN status unsigned char msg 23 request_resource IO_SYSTEM status readMsgVariable msgData msg release_resource IO_SYSTEM printf status Su max length d current length d message s r n status msg 0 msg 1
30. The ctools h file defines the structures ModemInit and ModemSet up Refer to the C Tools Structures and Types section for complete information on structures and enumeration types 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 ISaGRAF C Tools User and Reference Manual 50 May 8 2007 void main void struct ModemInit initSettings reserve_id portID enum DialError status enum DialState state struct pconfig portSettings Configure serial port 1 portSettings baud BAUD1200 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATA8 portSettings stop_bits STOP1 portSettings flow_rx DISABLE portSettings flow_tx DISABLE 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 coml strcpy initSettings modemCommand F1QOV1X1 S0O 1 if modemInit amp initSettings amp portID DE_NoError do Allow other tasks to execute release_processor j Wait for the initialization to complete modemInitStatus coml portID amp status amp state while s
31. amp amp address lt 31100 xvalue inputDbase address 31001 return TRUE else all other addresses are not handled return FALSE static BOOLEAN setdbaseHandler unsigned address Modbus register address int value value to write at address if address gt 1000 amp amp address lt 1100 if value 0 coilDbase address 1001 FALSE else coilDbase address 1001 TRUE return TRUE else if address gt 31000 amp amp address lt 31100 inputDbase address 31001 value return TRUE else all other addresses are not handled return FALSE static void shutdown void ISaGRAF C Tools User and Reference Manual 198 remove database handlers installDbaseHandler NULL installSetdbaseHandler NULL main This routine is the main program The exit handler is installed The database handlers are installed The database is then updated continuously with I O data in the main loop void main void int ainData 8 unsigned char doutData unsigned index TASKINFO taskStatus taskStatus getTaskInfo 0 installExitHandler taskStatus taskID installDbaseHandler dbaseHandler S shutdown installSetdbaseHandler setdbaseHandler while TRUE request_resource IO_SYSTEM isaRead8Ain 0 ainData
32. command to send If so this command is written to the 5904 interface The function has one parameter the module number of the 5904 HART Interface 0 to 3 The function returns TRUE if the 5904 HART Interface responded and FALSE if it did not or if the module number is not valid Notes This function is called automatically if the 5904 module is in the register assignment Use this function to implement communication with the 5904 if register assignment is not used See Also hartSetConfiguration hartGetConfiguration hartCommand ISaGRAF C Tools User and Reference Manual 176 May 8 2007 hartCommand Send Command using HART Interface Module Syntax include lt ctools h gt BOOLEAN hartCommand unsigned module HART_DEVICE const device HART_COMMAND const command void processResponse unsigned 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 HART 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
33. error EVEN Specifies even parity Variable name automatic execution period Number of last extended digital input channel ED_DIN_START Number of first extended digital input channel Number of last extended digital output channel Number of first extended digital output channel I Redefinition of macro from stdio h E MUL TIPLE _ Modbus function code Modbus function code Specifies full duplex Gas Flow calculation firmware option SCADASense 4202 DR controller SCADASense 4202 DS controller Specifies half duplex IO_SYSTEM System resource for all I O hardware functions Specifies LED is to be turned off Specifies LED is to be turned on Specifies linear database addressing D_MULTIE E Modbus function code D_SINGLE_RE E Modbus function code LOCAL_COUNTERS Number of 5203 4 counter inputs ISaGRAFCToolsUserandReferenceManul S M May 8 2007 M BAD_ADDRESS MM_BAD_FUNCTION MM_BAD_ LENGTH MM_BAD_SLAVE IM _NO_MESSAGE M_PROTOCOL_NOT_SUPPORTED IM_RECEIV MM_RECEIVED_BAD_LENGTH OD MODBUS_ASCII ED E l E FAILURE EXCEPTION MM_EXCEPTION_VALU DATA ISaGRAF C Tools User and Reference Manual May 8 2007 MAX PRIORIT
34. hartStatus Return Status of Last HART Command Sent Syntax include lt ctools h gt BOOLEAN hartStatus unsigned module HART_RESULT status unsigned 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 a command 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 module is HR_NoModuleResponse not communicating Command ready to be sent HR_CommandPending Command sent to device HR_CommandSent current attempt number Response received HR_Response response code from HART device see Notes No valid response received HR_NoResponse O no response from HART after all attempts made device Other error response code from HART device see Notes HART interface module is HR_WaitTransmit not used 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 If bit 7 of the high byte is set the high byte contains a communication error summary This field is bit m
35. locate the Modbus RTU command in the command buffer pCommandData commandBuffer PROTOCOL_HEADER_SIZE get length of Modbus RTU command from the packet header commandLength commandBuffer DATA_SIZE 2 locate the Modbus RTU response in the response buffer leaving room for the packet header pResponseData responseBuffer PROTOCOL_HEADER_SIZE process the Modbus message if processModbusCommand stream pCommandData commandLength MODBUS_BUFFER_SIZE pResponseData amp responseLength put the response length in the header responseBuffer DATA_SIZE responseLength fill in rest of packet header transmit the encapsulated response ISaGRAF C Tools User and Reference Manual 314 May 8 2007 queue_mode Control Serial Data Transmission Syntax include lt ctools h gt void queue_mode FILE stream int 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 stream 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
36. readintVariable ISaGRAF C Tools User and Reference Manual May 8 2007 readintVariable Read ISaGRAF Integer Variable Syntax include lt ctools h gt BOOLEAN readIntVariable unsigned char varName signed long 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 ISaGRAF Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the variable value is written to the signed long value pointed to by value If the variable is not found or if the ISaGRAF Symbols Status is invalid FALSE is returned and the current value is left unchanged The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 IO_SYSTEM system resource must be requested before calling this function See Also writ
37. 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 HART interface module The primaryVariable must be a static modular or 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 must be initialized using hartCommandoO or hartCommand1 1 The function returns immediately after the command is sent The calling program must 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 hartCommandz2 hartStatus hartSetConfiguration ISaGRAF C Tools User and Reference Manual 179 May 8 2007 hartCommand2 Read Primary Variable Current and Percent of Range Syntax include lt ctools h gt BOOLEAN hartCommand2 unsigned module HART_DEVICE const device HART_VARIABLE pvCurrent HART_VARIABLE pvPercent
38. their values from output tables in memory Notes This function is normally only used by the sleep function to restore output states when the controller wakes The IO_SYSTEM resource must be requested before calling this function ISaGRAF C Tools User and Reference Manual 227 May 8 2007 ioReset Reset 5000 Series I O Modules Syntax include lt ctools h gt void ioReset unsigned state Description The ioReset function sets the state of the 5000 Series I O bus reset signal state may be TRUE or FALSE The reset signal restarts all devices on the 5000 Series I O bus Output modules clear all their output points Input modules restart their input scanning All modules remain in the reset state until the reset signal is set to FALSE Notes Do not leave the reset signal in the TRUE state This will disable I O The ioClear function provides a more effective method of resetting the I O system The IO_SYSTEM resource must be requested before calling this function See Also ioRefresh ioClear ISaGRAF C Tools User and Reference Manual May 8 2007 228 isaRead16Din Read 16 Digital Inputs Syntax include lt ctools h gt unsigned isaReadl6Din unsigned moduleAddress unsigned data Description The isaRead16Din function reads any 16 point Digital Input Module at the specified moduleAddress Data is read from all 16 digital inputs and copied to the 16 bit value pointed to by data The function returns FALSE
39. there is an error in the settings or if the protocol fails to start The IO_SYSTEM resource must be requested before calling this function Notes Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it Be sure to add a call to modemNot ification when writing a custom protocol See Also get_protocol start_protocol modemNotification 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 ISaGRAF C Tools User and Reference Manual 356 May 8 2007 setProtocolSettings Set Protocol Extended Addressing Configuration Syntax include lt ctools h gt BOOLEAN setProtocolSettings FILE stream PROTOCOL_SETTINGS settings i Description The setProtocolSettings function sets protocol parameters for a serial port This function supports extended addressing The function has two arguments stream is one of com1 com2 com3 or com4 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 fails to start
40. 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 hartSetConfiguration ISaGRAF C Tools User and Reference Manual 180 May 8 2007 hartCommand3 Read Primary Variable Current and Dynamic Variables Syntax include lt ctools h gt BOOLEAN hartCommand3 unsigned 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 Variable Contains variables 0 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 mod
41. 0 5 s wd_pulse code executing in less than 0 5 s wd_auto as much code as you wish ISaGRAF C Tools User and Reference Manual 382 May 8 2007 wd_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 must execute at least every 0 5 seconds to prevent an controller reset if the wd_manual function has been executed Refer to the Functions Overview section for more information See Also wd_auto wd_manual Example See the example for the wd_manual function ISaGRAF C Tools User and Reference Manual May 8 2007 383 writeBoolVariable Write to SaGRAF Boolean Variable Syntax include lt ctools h gt BOOLEAN writeBoolVariable unsigned char varName unsigned char 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 ISaGRAF 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 ISaGRAF Symbols Status is invalid nothing is done and FALSE is returned The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum
42. 38400 baud port speed Specifies 57600 baud port speed Specifies 115200 baud port speed Points to a file object for com serial port Points to a file object for com2 serial port Points to a file object for com3 serial port Points to a file object for com4 serial port Specifies 7 bit world length Specifies 8 bit word length Specifies flow control is disabled Specifies flow control is enabled Specifies even parity Specifies full duplex Redefinition of macro from stdio h Specifies half duplex Specifies no parity Specifies serial port type is not known Specifies odd parity Receiver disabled after receipt of a message Receiver Xon Xoff flow control Transmitter flow control ignores CTS 48 PC_FLOW_TX_XON_XOFF RS232 RS232_MODEM RS485_4WIRE RS232_COLLISION_AVOIDANCE SERIAL_PORTS SIGNAL_CTS SIGNAL_DCD SIGNAL_OFF SIGNAL_OH SIGNAL_ON SIGNAL_RING SIGNAL_VOICE STOP1 STOP2 Transmitter Xon Xoff flow control Specifies serial port is an RS 232 port Specifies serial port is an RS 232 dial up modem Specifies serial port is a 4 wire RS 485 port Specifies serial port is RS232 and uses CD for collision avoidance Number of serial ports I O line bit mask clear to send signal I O line bit mask carrier detect signal Specifies a signal is de asserted I O line bit mask off hook signal Specifies a signal is asserted I O line bit mask ring signal I O line bit mask voice data switch signal Specifi
43. C Tools User and Reference Manual May 8 2007 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 pointed 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 ISaGRAF C Tools User and Reference Manual May 8 2007 97 dnpinstallConnectionHandler Configures the connection handler for DNP Syntax include lt ctools h gt void dnpInstallConnectionHandler void function 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 function 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 must process the event and return immediately If the required action involves waiting this must be done outside of the handler function See the example below for one possible implementation The application must disable the handler when the application ends This prevents the protocol driver from calling the handler while the application is stopped Call the dnpInstallConnectionHandler with a NULL pointer The usual
44. 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 cre_reverse function See Also crc_reverse Example This function displays two types of checksums include lt ctools h gt void checksumExample void char str This is a test unsigned sum Display additive checksum sum checksum str str strlen str ADDITIVE printf Additive checksum u r n sum Display CRC 16 checksum sum checksum str str strlen str CRC_16 printf CRC 16 checksum u r n sum ISaGRAF C Tools User and Reference Manual May 8 2007 checkSFTranslationTable Test for Store and Forward Configuration Errors Syntax include lt ctools h gt struct SFTranslationStatus checkSFTranslationTable void Description The checkSFTranslationTable function checks all entries in the address translation table for validity It detects the following errors The function returns a SFTrans ationStatus structure Refer to the Structures and Types section for a description of the fields in the SFTranslationStatus structure The code field of the structure is set to one of the following If there is an error
45. E E e E e A D A include lt ctools h gt VE A E eseaetense eb sees sent seebse es seas se esse esse at Sees sees see se ness Constants Ser es Seen aaa Sea ee eee See see eee eee es ee eee eee ee eee ee eee Se SES Se ose 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 9 ET ee EE EE EEE EE ENEE E EE Private Functions SSeS na ante eA Ss SEA EA NOON SAE GI GSI aI IN IER ICAI CREE RR CRE Sie SaE REY SRN DEEN A SIE SI CISA ION eae OR SIS ae Yo cms St ELS EA Sa AE eh AB a Sah a St a a Sat EN 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 The function takes a variable of type DNP_CONNECTION_EVENT as an input This input instructs the handler as to what functionality is required The valid choices are connection required DNP_CONNECTION_REQUIRED message confirmation received DNP_MESSAGE_COMPLETE and timeout occurred DNP_MESSAGE_TIMEOUT The function does not return any values static void sampleDNPHandler DNP_CONNECTION_EVENT event Determine what connection event i
46. Function Specification section for details on each function listed modeminit send initialization string to dial up modem modeminitStatus read status of modem initialization operation modemlnitEnd terminate modem initialization operation 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 initialization 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
47. Get DNP Binary Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetBIConfig UINT16 point dnpBinaryInput pBinaryInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveBlConfig Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetBIConfigEx Read DNP Binary Input Extended Point Syntax BOOLEAN dnpGetBIConfigEx UINT16 point dnpBinaryInputEx pBinaryInput 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 configuration is not valid or if the DNP configuration has not been created This function supersedes dnpSaveBIConfig ISaGRAF C Tools User and Reference Manual 112 May 8 2007 dnpGe
48. I O Digital Input Functions The controller supports internal digital inputs and external digital input modules Refer to the SCADAPack 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 interruptinput Read the controller interrupt input readCounterlnput Read the status of the counter input points on the controller board isaRead16Din Read any 16 point Digital input module isaRead32Din Read any 32 point Digital Input Module IsaRead4202Inputs Read the digital and analog inputs from a SCADASense 4202 DR IsaRead4202DSInputs Read the digital and analog inputs from a SCADASense 4202 DS isaRead5505Inputs Read the digital and analog inputs from a 5505 I O Module isaRead5506Inputs Read the digital and analog inputs from a 5506 I O Module isaRead5601Inputs Read the digital and analog inputs from a 5601 I O Module isaRead5602Inputs Read the digital and analog inputs from a 5602 I O Module isaRead5604Inputs Read the digital and analog inputs from 5604 I O Module isaRead5606Inputs Read the digital and analog inputs from a 5606 I O Module isaRead8Din Read any 8 point analog input module isaReadLPInputs Read the digital and analog inputs from SCADAPack LP I O ISaGRAF C Tools User and Reference Manual 38 May 8 2007
49. MSW first e A0O16_number is the number of 16 bit analog output points Valid values are 0 to 9999 e AO16_startAddress is the DNP address of the first AO16 point e AO32_number is the number of 32 bit analog output points Valid values are 0 to 9999 e AO32_startAddress is the DNP address of the first AO32 point e AO32_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 ISaGRAF C Tools User and Reference Manual 411 May 8 2007 e autoUnsolicitedClass1 enables or disables automatic Unsolicited reporting of Class 1 events e holdTimeClassi isthe maximum period to hold Class 1 events befor 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 e holdTimeClass3 is the maximum period to hold Class 3 events before reporting e HoldCountClass3 is the maximum number of Class 3 events to hold before reporting e Enab
50. Manual 28 May 8 2007 Ready Queue Event 10 Queue Running Task gt main echoData Figure 4 Queue Status After echoData Task Waits for Event Execution Point 5 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 Ready Queue Event 10 Queue Running Task gt main I echoData J lt A 3 2J auxiliary gt 0 E null gt Figure 5 Queue Status after Creation of auxiliary Task Execution Point 6 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 ISaGRAF C Tools User and Reference Manual 29 May 8 2007 Ready Queue Event 10 Queue Running Task 4 3 3 echoData 2 1 auxiliary main o null Lo Figure 6 Queue Status After main Task Releases Processor Execution 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 t
51. O routines to return error codes to the task using the routine Some functions supplied with 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 See also check_error ISaGRAF C Tools User and Reference Manual 334 May 8 2007 req uest_resou rce Obtain Control of a Resource Syntax include lt ctools h gt void request_resource int 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 poll_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 ISaGRAF C Tools User and Reference Manual 335 May 8 2007 resetAllIABSlaves Erase All AB Slave Responses Syntax include lt ctools h gt unsigned resetAllABSlaves FILE stream Description The resetAllABSlaves function is used to
52. Registers then a Modbus Exception Registers response may be returned 2 C C 00001 to 09999 If the address is not assigned to a Application 10001 to 19999 register in a database handler by a ISaGRAF C Tools User and Reference Manual 57 May 8 2007 The setResp function is used to control the exception response If the address is not found in the ISaGRAF dictionary or the C C Application Database Handler a Modbus Exception response may be returned An address is not found when it has not been defined with one of the above listed categories If the address is defined in more than one category the first occurrence of the address in the order listed is used The user can configure the setResp function to do one of the following e An exception is sent when an unavailable register is read or written e A zero is returned when an unavailable register is read and writing an unavailable register has no effect Each category is described in the following sections ISaGRAF Dictionary Variables When an ISaGRAF application is being downloaded or re started the Dictionary variables are temporarily undefined If a protocol accesses the controller while the Dictionary is undefined the protocol will return a Modbus Exception Most polling masters will simply log this as a command error and retry the protocol command until the Dictionary is no longer undefined When an address from the range of Permanent Non Volatile Registers is us
53. See Also datalogCreate datalogSettings Example See the example for datalogReadStart ISaGRAF C Tools User and Reference Manual 92 May 8 2007 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 must have been previously created with the datalogCreate function The function has two parameters 1ogID 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 must be deleted and recreated to change the configuration See Also datalogCreate datalogRecordSize Example See example for datalogDelete ISaGRAF C Tools User and Reference Manual 93 May 8 2007 datalogWrite Write Data Log Function Syntax include lt ctools h gt BOOLEAN datalogWrite UINT16 logID UINT16 pData i Description This function writes a record to the specified data log The log must have been previously created with the datalogCreate function The function has two parameters logID specifies the data log The valid range is 0 to 15
54. See Also hartGetConfiguration ISaGRAF C Tools User and Reference Manual 187 May 8 2007 hartPackString Convert String to HART Packed String Syntax include lt ctools h gt void hartPackString char pPackedString const char pString unsigned 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 must be a multiple of three in size The unpacked array must 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 ISaGRAF C Tools User and Reference Manual 188 May 8 2007 hartUnpackString Convert HART Packed String to String Syntax include lt ctools h gt void hartUnpackString char pString const char pPackedString unsigned 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 must be a multiple of three in size The unpacked array must be a multiple of four in size The function has no return value See Also hartPackString ISaGRAF C Tools User and Reference Manual 189 May 8 2007 install_ handler
55. TIME_TO_PRINT events S Za re Se ees OAE EE e void shutdown void endTimedEvent TIME_TO_PRINT arto Stes ede es The main function sets up signalling of a timed event then waits for that event The time is printed each time the event occurs te te Se se ee ee void main void struct prot_settings settings struct clock now ISaGRAF C Tools User and Reference Manual 373 May 8 2007 TASKINFO taskStatus Disable the protocol on serial port 1 settings type NO_PROTOCOL settings station 1 settings priority 3 settings SFMessaging FALSE request_resource IO_SYSTEM set_protocol coml amp settings release_resource IO_SYSTEM set up task exit handler to stop signalling of events when this task ends taskStatus getTaskInfo 0 installExitHandler taskStatus taskID shutdown start timed event startTimedEvent TIME_TO_PRINT 100 while TRUE wait_event TIME_TO_PRINT request_resource IO_SYSTEM now getclock j release_resource IO_SYSTEM fprintf coml Time 02u 02u 02u r n now hour now minute now second E ISaGRAF C Tools User and Reference Manual 374 May 8 2007 timer Read a Timer Syntax include lt ctools h gt unsigned timer unsigned timer Description The timer function returns the time remaining in timer timer must be in the r
56. 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 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 HART interface module 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 must 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 must initialize the link before executing any other commands See Also hartCommand11 hartStatus hartSetConfiguration ISaGRAF C Tools User and Reference Manual 178 May 8 2007 hartCommand1 Read Primary Variable Syntax include lt ctools h gt BOOLEAN hartCommandl1 unsigned 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
57. always called with a Modbus address Linear addresses are converted to Modbus addresses before calling the handler Use the installSetdbaseHandler function to install a write access handler for the same addresses handled by the dbase handler Note that 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 must 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 See Also setdbase Example See example for Dbase Handler Function ISaGRAF C Tools User and Reference Manual 194 May 8 2007 installSetdbaseHandler Install User Defined Setdbase Handler Syntax include lt ctools h gt void installSetdbaseHandler BOOLEAN handler unsigned address int value Description The installSetdbaseHandler function allows an extension to be defined for the setdbase function If a handler is
58. 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 0 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 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 ISaGRAF C Tools User and Reference Manual 417 May 8 2007 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 unsigned char type unsigned station unsigned char priority unsigned SFMessaging ADDRESS_MODE mode PROTOCOL_SETTINGS e type is the protocol type It may be one of NO_PROTOCOL MODBUS_RTU or MODBUS_ASCII macros e station is the station address of the controlle
59. aoutData is the analog output value The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function writes data to the SCADASense 4202 DS I O it also processes the transmit buffer for the com3 serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaRead4202Inputs isaWrite4202OutputsEx Example This program sets the analog output to full scale include lt ctools h gt void main void int analogData set analog output to full scale analogData 32767 Write output data to 4202 DR output request_resource IO_SYSTEM isaWrite42020utputs analogData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 261 May 8 2007 isaWrite4202OutputsEx Write to SCADASense 4202 DR with Extended Outputs Syntax include lt ctools h gt unsigned isaWrite42020utputsEx unsigned doutData int aoutData Description The isaWrite42020utputsEx function writes data to the outputs of a SCADASense 4202 DR equipped with a digital output Extended I O doutData is the digital output value Bit 0 of the value controls the digital output If this bit is 1 the digital output is turned on aoutData
60. as the Network Address for an ISaGRAF Dictionary variable The address is defined in a database handler installed by a C or C application The address is within the default range of the Permanent Non volatile Modbus Registers 40001 to 40000 NUMHOLDING_PERMANENT and 00001 to NUMCOIL_PERMANENT When this function is called the specified address is searched for under these three categories in the order listed above until the address is found If the address is not found then the variable pointed to by value is left unchanged If the address is defined in more than one of these categories the first occurrence of the address in the order listed is always used Refer to the section Permanent Non Volatile Modbus Registers for details on potential addressing conflicts during application downloading The IO_SYSTEM resource must be requested before calling this function See Also setdbase databaseRead databaseWrite Example include lt ctools h gt void main void ISaGRAF C Tools User and Reference Manual 95 May 8 2007 int a 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 a dbase LINEAR START_STATUS Read 6th input register a dbase LINEAR START_INPUT 5 release_resource IO_SYSTEM ISaGRAF
61. command lnkm77 c filename cmd Sample command files for RAM and ROM based applications are located in the telepace ctools isagraf directory Example The hello c program is found in the telepace ctools isagraf directory To compile and link the program e switch to the telepace ctools isagraf directory e enter the commands mccm77 v nQ M1 c hello c inkm77 c hello cmd The file hello abs contains the executable code in a format ready to load into the controller Loading and Executing The ISaGRAF C Program Loader transfers executable files from a PC to the controller and controls execution of programs in the controller The loader can also initialize program memory and serial port configuration Controller Initialization The memory of the controller has to 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 initialize the controller first perform a SERVICE boot A SERVICE boot preserves programs and data in nonvolatile RAM but does not start the programs running Default communication parameters are used To perform a service boot e Remove power from the controller e Press and hold the LED POWER switch e Apply power to the controller e Wait until the STAT LED on the top of the board turns on e Release the LED POWER switch Second initialize the program and data m
62. 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 ISaGRAF C Tools User and Reference Manual 406 May 8 2007 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 BI_number is the number of binary input points Valid values are 0 to 9999 e BI_startAddress is the DNP address of the first Binary Input point e BI_reportingMethod determines how binary inputs are reported either Change Of State or Log All E
63. configuration data to a 5505 I O module at address 1 include lt ctools h gt void main void UINT16 inputType 4 UINT16 inputFilter set analog input types to RTD deg F inputType 0 1 inputType 1 1 inputType 2 1 ISaGRAF C Tools User and Reference Manual 265 May 8 2007 inputType 3 1 set filter inputFilter 0 mimimum filter Write configuration data to 5505 I O module request_resource IO_SYSTEM isaWrite55050utputs 1 inputType inputFilter release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 266 isaWrite5506Outputs Write to 5506 Configuration Syntax include lt ctools h gt unsigned isaWrite5506Outputs UINT16 moduleAddress UINT16 inputType UINT16 inputFilter UINT16 scanFrequency Description The isaWrite55060utputs function writes configuration data to the 5506 I O module moduleAddress Is the address of the 5506 module Valid values are 0 to 15 inputType must point to an array of 8 unsigned integers that select the type of analog inputs on the module Valid values for each integer are e 0 0to5V e 1 1to5V e 2 0to20mA e 3 41to20 mA inputFilter selects the analog input filter This is used for all inputs Valid values are e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30Hz scanFrequency is the scan frequency setting Valid values are e 0 60Hz e 1 50Hz The function returns FALSE i
64. create the DNP configuration See Also dnpGetAl32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpSaveAlSFConfig Save Short Floating Point Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAISFConfig UINT16 point dnpAnalogInput pAnalogInput Description This 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 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 must be enabled before calling this function in order to create the DNP configuration ISaGRAF C Tools User and Reference Manual 126 May 8 2007 dnpSaveA0O16Config Save DNP 16 Bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAO16Config UINT16 point dnpAnalogOutput pAnalogOutput i Description This 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 configuratio
65. ctools h gt void modbusExceptionStatus unsigned char 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 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 must initialize the status each time it is run See Also modbusSlavelD ISaGRAF C Tools User and Reference Manual 289 May 8 2007 modbusSlavelD Set Response to Protocol Command Syntax include lt ctools h gt void modbusSlaveID unsigned char string unsigned 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 ength characters The contents of the string is determined by the requirements of the host computer The string is not NULL terminated and may contain multiple NULL characters The ength specifies how many chara
66. diagnostics using the ISaGRAF program Default Serial Parameters All 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 Databis 8 J8 J8 Je off RS 232 ISaGRAF C Tools User and Reference Manual 46 May 8 2007 Serial Communication Time Out When the controller is transmitting data on the communication ports the transmit buffer may become full due to receipt of an XOFF character a slow baud rate or improper hardware handshaking If the transmit buffers become full the task transmitting data is blocked until space is available or the serial time out period expires If no space is available at the conclusion of this time period the transmit buffer is emptied The task then continues execution Debugging Serial Communication Serial communication can be difficult to debug This section describes the most common causes of communication failures e To communicate the controller and an external device must use the same communication parameters Check the parameters in both units e f 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
67. dial up connections or modem initializations If executing end_task from another task ends a task 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 Failing to call 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 ISaGRAF 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 safely call this function instead of multiple calls to modemAbort if all the connections or initializations were started from the same task All reservation IDs returned by the modemDial and modemlnit functions are invalid after calling modemAbort See Also modemAbort modemDial modemDialEnd modemDialStatus modemInit modemlnitEnd modemInitStatus modemNotification 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 ISaGRAF 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
68. executable program Example The following commands are required to compile the program described in the previous sections mccm77 v nQ M1 c main c mccm77 v nQ Ml c funcl c mcem77 v nQ M1 c func2 c This produces three output files main ob 4 func1 obj and func2 obj In the next section these object files will be combined into an executable program Linking Object Files The linker converts object files and object file libraries into an executable program The basic command line and options to link a program are lnkm77 c filename cmd Controller programs can execute from RAM Flash or ROM The linker command file determines the location of the program RAM Based Applications A sample linker command file for a RAM based program is appram cma located in the telepace ctools 520x directory The file begins by specifying the location and order of memory sections The far_appcode section is the first section in all controller C programs It contains the start up code that calls the main function In a RAM based program the start up code is located at the start of C application program RAM This address is fixed at 00400000h ISaGRAF C Tools User and Reference Manual 14 May 8 2007 The order commands specify the order of the sections The sections are grouped so all the code and static data sections are first The variable data sections follow The heap is the last section It is allowed to grow from the end of the pr
69. field in an envelope contains a pointer RTOS_ENVELOPES Number of RTOS envelopes Inter task Communication Structures The ctools h file defines the structure Message Envelope Structure for inter task communication information Refer to the C Tools Structures and Types section for complete information on structures and enumeration types Event Notification The event notification functions provide a mechanism for communicating the occurrence 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 ISaGRAF C Tools User and Reference Manual 21 May 8 2007 wait_event Wait for an event to occur 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_eventSignal that an event has occurred from an interrupt handler This function must 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 sig
70. for index 0 index lt 8 index copy Ain data to the database setdbase MODBUS 31001 index ainData index get Dout data from the database doutData lt lt 1 doutData dbase MODBUS 1008 index isaWrite8Dout 0 doutData release_resource IO_SYSTEM release_processor ISaGRAF C Tools User and Reference Manual May 8 2007 199 Setdbase Handler Function User Defined Setdbase Handler Function The setdbase handler function is a user defined function that handles writing to Modbus addresses not assigned in the ISaGRAF Dictionary The function can have any name setdbaseHandler is used in the description below Syntax include lt ctools h gt BOOLEAN setdbaseHandler unsigned address int value Description This function is called by the setdbase function when one of the following conditions apply e There is no ISaGRAF application downloaded or e There is no ISaGRAF 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 If the address is to be handled the handler function must return TRUE and write value to the current value at the Modbus address If the address is not to be handled the function must return FALSE and do nothing Notes The IO_SYSTEM resource must be requested before
71. i Description This 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 configuration is not valid or if DNP configuration has not been created Notes DNP must be enabled before calling this function in order to create the DNP configuration See Also dnpGetCl16Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpSaveCl32Config Save DNP 32 Bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveC132Config UINT32 point dnpCountertInput pCounterInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetCl32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Referen
72. in an application program ISaGRAF C Tools User and Reference Manual May 8 2007 372 startTimedEvent Enable Signaling of a Regular Event Syntax include lt ctools h gt unsigned startTimedEvent unsigned event unsigned 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 functions 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 ctools 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 example below shows a simple method using the installExitHandler function See Also endTimedEvent signal_event Example The program prints the time every 10 seconds include lt string h gt include lt ctools h gt define TIME_TO_PRINT T5 Ree Sas Bee 225 zoa zog The shutdown function stops the signalling of
73. installed it is called by the setdbase function when one of the following conditions apply e There is no ISaGRAF application downloaded or e There is no ISaGRAF variable 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 always 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 Note that 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 must 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
74. 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 data field from the message The function returns TRUE if the 5904 HART 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 must 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 must 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 0 and 11 The functions hartCommand0 hartCommand1 etc are used to send commands provided by the Network Layer See Also hartStatus hartSetConfiguration hartCommand0O hartCommand1 ISaGRAF C Tools User and Reference Manual 177 May 8 2007 hartCommand0 Read Unique Identifier Syntax include lt ctools h gt BOOLEAN hartCommand0O unsigned module unsigned address HART_DEVICE const device Description
75. is off ON channel 0 data is out of rango ETE E ON channel 0 RTD is using 4 wire measurement reserved for future use T ON channel 1 RTD is open or PWR input is off ON channel 1 data is out of range ON channel 1 RTD is using 4 wire measurement A OFF channel 2 RTD is good ON channel 2 RTD is open or PWR input is off O E e ON channel 2 data is out of range O e E ON Thar 2 RTD is using 4 wire measurement reserved for future use 12 OFF channel 3 RTD is good ON channel 3 RTD is open or PWR input is off ISaGRAF C Tools User and Reference Manual May 8 2007 237 ON channel 3 data is out of range ON channel 3 RTD is using 4 wire measurement reserved for future use ainDataArray must point to an array of four floating point values T The function returns FALSE if an I O error occurs otherwise TRUE Notes is returned The IO_SYSTEM resource must be requested before calling this function See Also isaWrite5505Outputs Example This program displays the values of the 16 digital inputs and 4 analog inputs read from 5505 I O module 3 include lt ctools h gt void main void UINT16 point UINT16 dinData float ainDataArray 4 Read input data from 5505 I O module request_resource IO_SYSTEM isaRead5505Inputs 3 dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r for poi
76. message received on com4 It can be used in a custom character handler see install_handler NEVER This event is guaranteed never to 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 ISaGRAF C Tools User and Reference Manual 22 May 8 2007 Error Reporting Sharable I O drivers to return error information to the calling task use the error reporting functions These functions ensure 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 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 Error Reporting Macros The ctools h file defines the following macro used for error reporting Refer to the C Tools Macros section for details NO_ERROR Error code indicating no error has occurred ISaGRAF C Tools User and Reference Manual May 8 2007 SCADAPack Task Architecture The diagram shows the tasks present in the SCADAPack controller Background I O Task Executes every 0 1 s Processes e software timers e dialup modem e PID controllers Prio
77. not be used because a late command response received after the variable is freed will 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 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 must be initialized using hartCommandoO or hartCommand1 1 The pointer variables must point to an array with at least four elements The function returns immediately after the command is sent The calling program must 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 always requests four variables and expects four variables in the response See Also hartCommand3 hartStatus hartSetConfiguration ISaGRAF C Tools User and Reference Manual 183 May 8 2007
78. not needed This may be useful in host devices that don t create a Modbus RTU message with checksum prior to encapsulation ISaGRAF C Tools User and Reference Manual 291 May 8 2007 The Modbus RTU checksum is included in the response to support encapsulating a complete Modbus RTU format message If the checksum is not needed by the encapsulating protocol the checksum bytes may be ignored See Also set_protocol Example This example is taken from a protocol driver than encapsulates Modbus RTU messages in another protocol It shows how to pass the Modbus RTU command to the Modbus driver and obtain the response The example assumes the Modbus RTU messages are transmitted with the checksum The length of the checksum is subtracted when calling the processModbusCommand function The checksum is included when responding receive the packet in the encapsulating protocol verify the packet is valid locate the Modbus RTU command in the command buffer pCommandData commandBuffer PROTOCOL_HEADER_SIZE get length of Modbus RTU command from the packet header commandLength commandBuffer DATA_SIZE 2 locate the Modbus RTU response in the response buffer leaving room for the packet header pResponseData responseBuffer PROTOCOL_HEADER_SIZE process the Modbus message if processModbusCommand stream pCommandData commandLength MODBUS_BUFFER_S
79. 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 must be enabled before calling this function in order to create the DNP configuration ISaGRAF C Tools User and Reference Manual 107 May 8 2007 dnpGetAO16Config Get DNP 16 bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetA016Config UINT16 point dnpAnalogOutput pAnalogOutput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAO16Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual 108 May 8 2007 dnpGetAO32Config Get DNP 32 bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetA032
80. retries is the number of data link retires for this table entry e timeout is the timeout in milliseconds SF Translation The SFTranslation structure contains Store and Forward Messaging translation information This is used to define an address and port translation struct SFTranslation unsigned portA unsigned stationA unsigned portB unsigned stationB e portA isthe index of the first serial port The index is obtained with the port Index function e stationA is the station address of the first station e portB is the index of the second serial port The index is obtained with the port Index function ISaGRAF C Tools User and Reference Manual May 8 2007 422 e stationB is the station address of the second station SFTranslationStatus 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 unsigned index unsigned code e index is the location in the store and forward table to which the status code applies e 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 or SF_ALREADY_DEFINED macros TASKINFO The TASKINFO type is a structure containing information about a task Task Information Structure typedef struct taskInformation_tag unsigned taskID unsi
81. returned and the specified signed long value is written to the variable If the variable is not found or if the ISaGRAF Symbols Status is invalid nothing is done and FALSE is returned The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 must be requested before calling this function See Also setdbase readintVariable Example This program writes the value 120 000 to the integer variable named Pressure1 include lt ctools h gt void main void BOOLEAN status request_resource IO_SYSTEM status writeIntVariable Pressurel 120000 release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 385 May 8 2007 writeRealVariable Write to ISaGRAF Real Variable Syntax include lt ctools h gt BOOLEAN writeRealVariable unsigned char varName float value Description This function
82. select the Initialize command e Select all options Erase IEC 1131 Application Erase C Program Initialize Controller e Click on the OK button Loading Programs into RAM The C Program Loader dialog transfers executable files from a PC to the controller To load a program into RAM e Initialize the controller see Controller Initialization section above e Load the program into the controller e Run the ISaGRAF program e From the Controller menu select the C Program Loader command e Enter the executable abs file in the edit box for the C Program file name e Select the C Program write option and any other write options desired e Click on the Write button The file will be downloaded A checksum is calculated for the complete C program The checksum is verified each time the program is run This prevents a damaged program from running Executing Programs C application programs are executed when a run program command is received from the ISaGRAF C Program Loader or power is applied to the controller except when a SERVICE boot is performed To start a program from the program loader e Run the ISaGRAF program e From the C Program Loader dialog click on the Run button to execute the program The controller will execute either the program in RAM or the program in ROM It chooses the program to execute in the following order e C application program in RAM e C application program in ROM e noC application standard start u
83. send a protocol message to all slaves communicating on the specified port to erase all responses not yet polled stream 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 an 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 This function should not normally be needed if polling is done using the sample polling function poll_for_response shown in the example for the master_message function Example This program segment will cause all slaves communicating on the com2 serial port to erase all pending responses include lt protocol h gt resetAlLLABSlaves com2 ISaGRAF C Tools User and Reference Manual 336 May 8 2007 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 must be acknowledged before it can occur again The resetClockAlarm function acknowledges the last real time clock alarm and re enables the alarm Calling the function after waking up from an alarm will reset the alar
84. set up exit handler for this task taskStatus getTaskInfo 0 installExitHandler taskStatus taskID shutdown Connect to the remote controller if modemDial amp dialSettings amp portID DE_NoError do Allow other tasks to execute release_processor j 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 Note that 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 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 full access to the I O database in the controller 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 informat
85. 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 Notes Refer to the 5203 4 System Manual or the SCADAPack System Manual for further information on the Status LED and Status Output See Also getlOErrorlIndication ISaGRAF C Tools User and Reference Manual 352 May 8 2007 setPowerMode Set Current Power Mode Syntax include lt ctools h gt BOOLEAN setPowerMode UCHAR cpuPower UCHAR lan UCHAR usbPeripheral UCHAR usbHost Description The setPowerMode function returns TRUE if the new settings were successfully applied The setPowerMode function allows for power savings to be realized 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 Macro Meaning S PM_CPU_FULL The CPU is set to run at full speed PM_LAN_ENABLED The LAN is enabled The USB peripheral port is disabled The USB host port is enabled PM_USB_HOST_DISABLED The USB host port is disabled The current value will be used 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 setWake
86. task On the next instruction it will create the echoData task ISaGRAF C Tools User and Reference Manual 27 May 8 2007 Ready Queue Event 10 Queue Running Task 4 main 3 a 2 1 Loy 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 4 b gt echoData 3 gt gt 2 ee 0 Figure 3 Queue Status after Creation of echoData Task Execution Point 4 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 ISaGRAF C Tools User and Reference
87. task is not blocked by the send_message function Notes Envelopes are obtained from the operating system with the allocate_envelope function See Also receive_message poll_message allocate_envelope Example This program creates a task to display a message and sends a message to it include lt ctools h gt void showIt void envelope msg while TRUE msg receive_message printf Message data ld r n msg gt data deallocate_envelope msg void main void envelope msg message pointer unsigned tid task ID tid create_task showIt 2 APPLICATION 1 msg allocate_envelope msg gt destination tid msg gt type MSG_DATA msg gt data 1002 send_message msg wait for ever so that main and other APPLICATION tasks won t end while TRUE Allow other tasks to execute ISaGRAF C Tools User and Reference Manual 342 May 8 2007 release_processor ISaGRAF C Tools User and Reference Manual 343 May 8 2007 setABConfiguration Set DF1 Protocol Configuration Syntax include lt ctools h gt int setABConfiguration FILE stream struct ABConfiguration ABConfig Description The setABConfiguration function sets DF1 protocol configuration parameters stream specifies the serial port ABConfig references an DF1 protocol configuration structure Refer to the description of the ABConfiguration structure for an explanation of the f
88. 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 ISaGRAF C Tools User and Reference Manual 400 May 8 2007 clock The clock structure contains time and date for reading or writing the real time clock struct clock UINT16 year UINT16 month UINT16 day UINT16 dayofweek UINT16 hour UINT16 minute UINT16 second year is the current year It is two digits in the range 00 to 99 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 Monday 7 Saturday 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 DATALOG_CONFIGURATION dayofweek is the current day of the week It is in the range 1 to 7 1 Sunday 2 The data log configuration structure holds the configuration of the data log Each record in a data log may hold up to eight fields Not all the fields are used if fewer than eight variables are declared 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 typedef struct datalogConfiguration_type UINT16 records of records UINT16 fields of fields per record DATALOG_VAR
89. the index field is set to the location of the translation that is not valid Result code g 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_RANGE One or both of the serial port indexes is not valid ae eee One or both of the stations is not valid Notes The TeleBUS Protocols User Manual describes store and forward messaging mode See Also getSFTranslation checkSFTranslationTable Example See the example for the setSFTranslation function ISaGRAF C Tools User and Reference Manual May 8 2007 68 clear_errors Clear Serial Port Error Counters Syntax include lt ctools h gt void clear_errors FILE stream Description The clear_errors function clears the serial port error counters for the serial port specified by stream f stream does not point to a valid serial port the function has no effect The lO_SYSTEM resource must be requested before calling this function See Also get_status ISaGRAF C Tools User and Reference Manual May 8 2007 69 clear_protocol_status Clear Protocol Counters Syntax include lt ctools h gt void clear_protocol_status FILE stream Description The clear_protocol_status function clears the error and message counters for the serial port specified by stream If stream does not point to a valid serial port the function has no effect The lO_SYSTEM resource must be r
90. 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 Example handler c ISaGRAF C Tools User and Reference Manual 204 May 8 2007 This is a sample program for the sample program uses function code 71 to demonstrate a for using the installModbusHandler function InstallModbusHandler function This simple method 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 47 is the 01 is the B7 is the station address function code in hex command for the function code 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 B8 is the message checksum ee include lt ctools h gt static unsigned myModbusHandler unsigned char message unsigned messageLength unsigned char response unsigned responseLength unsigned char pMessage unsigned char pResponse pMessage message if pMessage 71
91. unsigned data Description The isaWrite16Dout function writes data to any 16 point Digital Output Module at the specified moduleAddress Data from the specified 16 bit value is written to the 16 digital outputs The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAdadress is 0 to 15 The lO_SYSTEM resource must be requested before calling this function See Also isaWrite8Dout Example This program turns ON all 16 digital outputs of a 16 point Digital Output Module at module address 0 include lt ctools h gt void main void Write data to digital output module request_resource IO_SYSTEM isaWritel 6Dout 0 OxFFFF release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 isaWrite2Aout Write to 2 Analog Outputs Syntax include lt ctools h gt unsigned isaWrite2Aout unsigned moduleAddress int dataArray Description The isaWrite2Aout function writes data to any 2 point Analog Output Module at the specified moduleAddress Data is read from the array pointed to by dataArray and written to the 2 analog outputs dataArray must point to an array of two 16 bit integers The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAdadress is 0 to 15 The lO_SYSTEM resource must be requested
92. writelntVariable Writes to the 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 TeleSAFE Micro16 and 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 ISaGRAF C Tools User and Reference Manual 61 May 8 2007 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 hartCommand send a HART command string and specify a function to handle the response hartCommand0 read unique identifier using short address algorithm hartCommand1 read primary variable hartCommand2 read primary variable current and percent of span hartCommand3 read primary variable current and dynamic variables hartCom
93. writes to the specified real i e floating point variable The variable is specified by its name expressed as a character string The name is case insensitive The ISaGRAF Dictionary also treats variable names as case insensitive If the variable is found TRUE is returned and the specified floating point value is written to the variable If the variable is not found or if the ISaGRAF Symbols Status is invalid nothing is done and FALSE is returned The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 IO_SYSTEM system resource must be requested before calling this function See Also setdbase readRealVariable Example This program writes the value 25 607 to the real variable named Flowrate include lt ctools h gt void main void BOOLEAN status request_resource IO_SYSTEM status writeRealVariable Flowrate 25 607 release_resource IO_SY
94. 0 and store its sequence number into sequenceNumber ISaGRAF C Tools User and Reference Manual 90 May 8 2007 if datalogReadStart logID amp sequenceNumber Get the size of this record if datalogRecordSize logID amp recordSize Allocate memory of size recordSize pData UINT16 malloc recordSize Read all records from data log 10 while datalogReadNext logID sequenceNumber amp sequenceNumber amp nextSequenceNumber pData Use pData and its contents Set next sequence number of record to be read sequenceNumber nextSequenceNumber ISaGRAF C Tools User and Reference Manual 91 May 8 2007 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 must have been previously created with the datalogCreate function The function has two parameters logID specifies the data log The valid range is 0 to 15 pRecordSize points to a variable that will hold the size of a record in the log 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 This function is useful in determining how much memory must be allocated for a call to datalogReadNext or datalogWrite
95. 007 ve COUNTER_0_OVERFLO roll over of low word of counter 0 every 65536 transitions COUNTER_1_OVERFLO roll over of low word of counter 1 every 65536 transitions WS_COUNTER_2_OVERFLO roll over of low word of counter 2 every 65536 w transitions The IO_SYSTEM resource must be requested before calling this function See Also setclock alarmin setWakeSource getWakeSource Example See the examples for the setClockAlarm and alarmin functions ISaGRAF C Tools User and Reference Manual May 8 2007 370 start_protocol Enable Protocol Task Syntax include lt ctools h gt int start_protocol FILE stream Description The start_protocol function enables a protocol task on the port specified by stream The protocol configuration settings stored in memory are used The start_protocol function returns TRUE if the protocol started and FALSE if there was an error Notes The start_protocol function is used by the system start up routine Application programs should use the set_protocol function to control protocol operation See Also get_protocol set_protocol ISaGRAF C Tools User and Reference Manual May 8 2007 371 startup_task Identify Start Up Task Syntax include lt ctools h gt void 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
96. 03 May 8 2007 dnpBinarylnputEx_type The dnpBinaryInputEx type describes an extended DNP Binary Input point typedef struct dnpBinarylInputEx_type UINT16 modbusAddress UCHAR eventClass UCHAR debounce dnpBinaryInputEx 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 e debounceTime is the debounce time for thebinary input dnpBinaryOutput The dnpBinaryOutput type describes a DNP binary output point typedef struct dnpBinaryOutput_type UINT16 modbusAddress1l UINT16 modbusAddress2 UCHAR controlType dnpBinaryOutput e modbusAddress1 is the address of the first Modbus register associated with the point This field is always used e modbusAddress2 is the address of the second Modbus register associated with the point This field is used only with paired outputs See the cont rolType field e controlType determines if one or two outputs are associated with this output point It may be set to PAIRED or NOT_PAIRED e 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 e Anon paired output uses one Modbus register for output This is used with Binary Output objects DNP_CONNECTION EVENT Type This enumerated type lists DNP events typed
97. 07 ioBusReadByte Read One Byte from PC Slave Device Syntax include lt ctools h gt unsigned char ioBusReadByte void Description The ioBusReadByte function returns one byte read from an I C slave device The byte is acknowledged by the master receiver This function can be used multiple times in sequence to read data from a slave device The last byte read from the slave must be read with the ioBusReadLastByte function If only one byte is to be read from a device the ioBusReadLastByte function must be used instead of this function Notes The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusSelectForWrite ioBusWriteByte ioBusWriteMessage Example include lt ctools h gt void main void unsigned char data 3 unsigned char ioBusAddress 114 request_resource IO_SYSTEM ioBusStart if ioBusSelectForRead ioBusAddress data 0 ioBusReadByte data 1l ioBusReadByte reading the last byte terminates read data 2 ioBusReadLastByte ioBusStop release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 216 May 8 2007 ioBusReadLastByte Read Last Byte from PC Slave Device Syntax include lt ctools h gt unsigned char ioBusReadLastByte void Description The ioBusReadLastByte function returns one byte read from a
98. 2 translation stationB 3 setSFTranslation 0 translation translation portA portIndex coml translation stationA 4 translation portB portIndex com2 translation stationB 5 setSFTranslation 1 translation Enable store and forward messaging settings type MODBUS_RTU settings station 1 settings priority 3 settings SFMessaging TRUE set_protocol coml amp settings settings type MODBUS_ASCIT settings station 1 settings priority 3 settings SFMessaging TRUE set_protocol com2 amp settings release_resource IO_SYSTEM Check if everything is correct status checkSFTranslationTable if status code SF_VALID Blink the error code on the status LED setStatus status code ISaGRAF C Tools User and Reference Manual 361 May 8 2007 ISaGRAF C Tools User and Reference Manual May 8 2007 else while setStatus 0 TRUI E main loop of application program 362 setStatus Set Controller Status Code Syntax include lt ctools h gt void setStatus unsigned code Description The setStatus function sets 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 Notes The status output opens if code is non zero Refer to the System Hardware Manual for more informati
99. 4 getProtocolSettings Get Protocol Extended Addressing Configuration Syntax include lt ctools h gt BOOLEAN getProtocolSettings FILE stream PROTOCOL_SETTINGS settings i Description The getProtocolSettings function reads the protocol parameters for a serial port This function supports extended addressing The function has two parameters stream is one of com1 com2 com3 or com4 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 ASCII 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 void main void PROTOCOL_SETTINGS settings if getProtocolSettings coml amp settings printf Type d r n settings type printf Station d r n settings station printf Address Mode d r n settings mode printf SF Messaging d r n settings SFMessaging printf Priority d r n settings priority else printf Serial port is not valid r n ISaGRAF C Too
100. 6 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 must be requested before calling this function See Also setclock getclock ISaGRAF C Tools User and Reference Manual 157 May 8 2007 getConirollerID 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 void main void char ctlrID CONTROLLER_ID_LEN unsigned index getControllerID ctlrID fprintf coml r nController ID for index 0 index lt CONTROLLER_ID_LEN index t fputc ctlrID index coml ISaGRAF C Tools User and Reference Manual 158 May 8 2007 getlOErroriIndication Get I O Module Erro Syntax r Indication include lt ctools h gt unsigned getIOl Description The getlOErrorIndication function returns the state of the I O module error indication TRUE is returned controller status r ErroriIndication void if the I O module communication status is currently reported i
101. 6_number AO16_startAddress AO32_number AO32_startAddress AO32_wordOrder AOSF_number AOSF_startAddress AOSF_wordOrder autoUnsolicitedClass1 holdTimeClass1l holdCountClass1l autoUnsolicitedClass2 holdTimeClass2 holdCountClass2 autoUnsolicitedClass3 holdTimeClass3 holdCountClass3 dnpConfiguration C H ZZ de A kd D ao C C Se Fad C TA HH O OV OV OY pine J zl Oo C Q c HHHHHHHHHTHHTHHHHTHTH sad agada nanaon aada woes o i FI 7 Fi m H 7 Fi 7 Ft 7 Fi J DDDAAAA DA zy H zl Oo e 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 e xrtuAddress is the address of the RTU The master 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
102. 6_startAddress HAR AI16_reportingMethod T16 AI16_bufferSize 16 AI32_ number T16 AI32_startAddress AI32_reportingMethod 16 AI32_bufferSize AR AI32_wordOrder T16 AISF_number T16 AISF_startAddress HAR AISF_reportingMethod T16 AISF_bufferSize AISF_wordOrder 6 AO16_number 6 AO16_startAddress T16 AO32_ number 6 AO32_startAddress AO32_wordOrder T16 AOSF_number 16 AOSF_startAddress AR AOSF_wordOrder autoUnsolicitedClass1 holdTimeClassl holdCountClass1l autoUnsolicitedClass2 holdTimeClass2 holdCountClass2 autoUnsolicitedClass3 holdTimeClass3 holdCountClass3 enableUnsolicitedOnStartup sendUnsolicitedOnStartup level2Compliance masterAddressCount masterAddress 8 maxEventsInResponse dialAttempts dialTimeout pauseTime onlineInactivity dialType Char modemInitString 64 dnpConfigurationEx e rtuAddress is the address of the RTU The master station must send messages to this address Valid values are 0 to 65534 a Ov 0 OV OO Ges ae et ZZ De TA a ve H Oy Oy Oy Oy Oy Oy zZ AA A A z oe G44 fo 2A D A LL A A C HHHHHHHHHHHHHHHHHHHHAHHQAHHHHAHQAHHAHAHHHAHHAHQAHHHQAHHHHHQAN I gt ve J OV OV OV OV OV OV OY OV OV OV OV OV OV OD OY OV OV OD OD OV AA ISaGRAF C Tools User and Reference Manual 409 May 8 2007 e datalinkConfirm enables requesting data link layer confirm
103. 8 2007 getPowerMode Get Current Power Mode Syntax include lt ctools h gt BOOLEAN getPowerMode UCHAR cpuPower UCHAR lan UCHAR usbPeripheral 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 Macro Meaning i PM PUET ULL TRUE is returned if the values placed in the passed parameters are valid otherwise FALSE is returned The application program may set the current power mode with the setPowerMode function See Also setPowerMode setWakeSource getWakeSource ISaGRAF C Tools User and Reference Manual 161 May 8 2007 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 stream If stream does not point to a 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 void main void
104. BUS HI_ALARM setdbase MODBUS ALARM_OUTPUT 1 else setdbase MODBUS ALARM OUTPUT 0 release_resource IO_SYSTEM Allow other tasks to execute release_processor ISaGRAF C Tools User and Reference Manual 163 May 8 2007 get_protocol Get Protocol Configuration Syntax include lt ctools h gt struct prot_settings get_protocol FIL settings Description EF x ry stream struct prot_settings The get_protocol function gets the communication protocol configuration for the stream If stream 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 copies the protocol settings and returns a pointer to that structure Refer to the ctools h file for a description of the settings into the structure pointed to by 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 configuratio include lt ctools h gt void main void struct prot_settings settings get_protocol coml amp settings printf Type sd r n printf Station d r n printf Priority d r n ISaGRAF C Tools User and Reference Manual May 8 2007 n for com1 settings type settings station settings priority 16
105. C checksum Specifies the DF1 Half Duplex protocol emulation for the serial port CRC checksum AB_PROTOCOL DF1 protocol firmware option AD_BATTERY Internal AD channel connected to lithium battery AD_THERMISTOR Internal AD channel connected to thermistor Additive checksum AIN_END Number of last analog input channel Number of first analog input channel AIO_BADCHAN Error code bad analog input channel specified AIO_SUPPORTED If defined indicates analog I O supported AIO_TIMEOU Error code input device did not respond AO Variable name alarm output address Number of last analog output channel AOUT_START Number of first analog output channel APPLICATION 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 System event background I O requested The background I O task uses this event It should not be used in an application program Controller type bit mask Specifies 110 baud port speed B Specifies 1200 baud port speed Specifies 150 baud port speed Specifies 19200 baud port speed Specifies 2400 baud port speed AC AS AU Specifies 115200 baud port speed AU AU AU AU Specifies 300 baud port speed ISaGRAF C Tools User and Reference Manual 391 May 8 2007 BAUD38400 Specifies 38400 baud port speed Specifies 4800 baud port speed D57600 Specifies 57600 baud port s
106. Config UINT32 point dnpAnalogOutput pAnalogOutput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAO32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual 109 May 8 2007 dnpGetAOSFConfig Get Short Floating Point Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAOSFConfig UINT16 point dnpAnalogOutput pAnalogOutput Description This 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 must be enabled before calling this function in order to create the DNP configuration ISaGRAF C Tools User and Reference Manual 110 May 8 2007 dnpGetBIConfig
107. CountClass1 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 number 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 HoldCountClass3 is the maximum number of Class 3 events to hold before reporting dnpConfigurationEx The dnpConfigurationEx type includes extra parameters in the DNP Configuration typedef struct dnpConfigurationEx_type zZ 16 rtuAddress datalinkConfirm datalinkRetries L6 datalinkTimeout T16 operateTimeout AR applicationConfirm maximumResponse AR applicationRetries T16 applicationTimeout 16 timeSynchronization 16 BI_number T16 BI_startAddress Th ee Ep Z H Oy c HC C HEH A E OE O HA AO O H C 220H20 Oy ISaGRAF C Tools User and Reference Manual 408 May 8 2007 HAR BI_reportingMethod BI_soeBufferSize BO_number BO_startAddress CI16_number L6 CI16_startAddress AR CI16_reportingMethod T16 CI16_bufferSize 16 CI32_number T16 CI32_startAddress AR CI32_reportingMethod L6 CI32_ bufferSize HAR CI32_wordOrder T16 AI16_number 16 AI1
108. DASense 4202 DS I O Data is read from the digital input and copied to the 16 bit value pointed to by dinData Data is read from 3 analog inputs and copied to the value pointed to by ainData Data is read from 2 counter inputs and copied to the array pointed to by counterDataArray dinData must point to a 16 bit unsigned integer ainData must point to an array of three 16 bit integers couterDataArray must point to an array of two 32 bit unsigned integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function reads data from the SCADASense 4202 DS O it also processes the receiver buffer for the com3 serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaWrite4202DSOutputs Example This program displays the values of the digital input 2 counter inputs and 3 analog input read from the SCADASense 4202 DS I O include lt ctools h gt void main void unsigned point unsigned dinData int ainData unsigned long counterData 2 Read input data from 4202 DS I O request_resource IO_SYSTEM isaRead4202DSInputs amp dinData amp ainData counterData ISaGRAF C Tools User and Reference Manual 235 May 8 2007 release_resou
109. Din isaRead16Din 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 void main void UINT16 point UINT32 dinData Read data from digital input module request_resource IO_SYSTEM isaRead32Din 0 amp dinData release_resource IO_SYSTEM nas Print module data fprintf coml Point Value for point 0 point lt 32 point fprintf coml n r d point putchar dinData amp 0x0001 1 O dinData gt gt 1 ISaGRAF C Tools User and Reference Manual 230 May 8 2007 isaRead4Ain Read 4 Analog Inputs Syntax include lt ctools h gt unsigned isaRead4Ain unsigned moduleAddress Description int dataArray The isaRead4Ain function reads any 4 point Analog Input Module at the specified moduleAddress Data is read from all 4 analog inputs and copied to the array pointed to by dataArray dataArray must point to an array of four 16 bit integers The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function See Also isaRead8Ain Example This program displays the values of the 4 analog inputs read from a 4 point Analog Input Module at module address 0 include lt ctools h gt
110. F C Tools User and Reference Manual May 8 2007 WS_success WS_selectFailed WS_noAcknowledge ESTATUS WS_success returns write was successful WS_selectFailed returns slave could not be selected WS_noAcknowledge returns slave failed to acknowledge data 425 C Compiler Known Problems The C compiler supplied with the ISaGRAF C Tools is a product of Microtec There is two known problems with the compiler Use of Initialized Static Local Variables The compiler incorrectly allocates storage for initialized static local variables The storage is allocated incorrectly in memory reserved for constant string data The storage should be allocated in memory for initialized variables Problems Caused A program loaded in ROM cannot modify a variable declared in this fashion A program loaded in RAM can modify the variable However the variable is in a section of program memory that the operating system expects to remain constant Modifying the variable causes the operating system to think the program has been modified The program continues to run correctly but will not run again if it is stopped by the C Program Loader or if the controller is reset The operating system detects that the program memory is corrupt and does not execute the program Example The compiler generates incorrect code for the following example Storage for the variable a is allocated in the strings section It should be in the initvars section If
111. However when a SCADAPack I O module is placed in the Register Assignment option switch 1 selects the input range for analog inputs on this module When the SCADAPack AOUT module is placed in the Register Assignment option switch 2 selects the output range for analog outputs on this module Refer to the SCADAPack System Hardware Manual for further information on option switches ISaGRAF C Tools User and Reference Manual 305 May 8 2007 pollABSlave Poll DF1 Slave for Response Syntax include lt ctools h gt unsigned pollABSlave FILE stream unsigned 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 specified 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 using the pollABSlave function in the sample polling function poll_for_response shown in the example for the master_message function See Also master_message 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 ISaGRAF C Tools User and Reference Manual 306 May 8 2007 poll event Test for Even
112. IABLE typesOfFields MAX_NUMBER_OF_FIELDS DATALOG_ CONFIGURATION DATALOG_STATUS The data log status enumerated type is used to report status information typedef enum DLS_CREATED data log created DLS_BADID invalid log ID DLS_EXISTS log already exists DLS_NOMEMORY insufficient memory for log DLS_BADCONFIG invalid configuration DLS_BADSEQUENCE sequence number not in use DATALOG_STATUS DATALOG_VARIABLE The data log variable enumerated type is specify the type and size of variables to be recorded in the log ISaGRAF C Tools User and Reference Manual May 8 2007 typedef enum DLV_UINT16 0 16 bit unsigned integer DLV_INT16 16 bit signed integer DLV_UINT32 32 bit unsigned integer DLV_INT32 32 bit signed integer DLV_FLOAT 32 bit floating point DLV_CMITIME 64 bit time DLV_DOUBLE 64 bit floating point DATALOG_ VARIABLE DialError The DialError enumerated type defines error responses from the dial up modem functions and may have one of the following values enum DialError FE NoError 0 E_BadConfig E_NoModem BE InitError E_NoDialTone E_BusyLine E_CallAborted E_FailedToConnect E_CarrierLost E_NotInControl E_CallCut vuvuvuvuvuvuvuvvuv e DE_NoError retur
113. ISaGRAF C Tools User and Reference Manual CONTROL MICROSYSTEMS SCADA products for the distance 48 Steacie Drive Telephone 613 591 1943 Kanata Ontario Facsimile 613 591 1022 K2K 2A9 Technical Support 888 226 6876 Canada 888 2CONTROL ISaGRAF C Tools User and Reference Manual 2007 Control Microsystems Inc All rights reserved Printed in Canada Trademarks TelePACE SCADASense SCADAServer SCADALog RealFLO TeleSAFE TeleSAFE Micro16 SCADAPack SCADAPack Light SCADAPack Plus SCADAPack 32 SCADAPack 32P SCADAPack 350 SCADAPack LP SCADAPack 100 SCADASense 4202 DS SCADASense 4202 DR SCADASense 4203 DS SCADASense 4203 DR SCADASense 4102 SCADASense 4012 SCADASense 4032 and TeleBUS are registered trademarks of Control Microsystems All other product names are copyright and registered trademarks or trade names of their respective owners Material used in the User and Reference manual section titled SCADAServer OLE Automation Reference is distributed under license from the OPC Foundation ISaGRAF C Tools User and Reference Manual 1 May 8 2007 Table of Contents TABLE OF CONTENTS aoassehsusinsscasssutsssasnapcistuatasnsuuansinsantbsssnga dbaausiuasssbaasbudyenivuns Sipit Triias 2 ISAGRAF C TOOLS OVERVIEW iss cisiscsutnsasatasseasssaniesacaninopsnndiansnisiuensninantuibanuatiansatuatanaaiion 3 GETTING STARTED sisspainesdcainsnassscniitutianscusssstuahasenaondosicausaqpnesabcasiuessainintuibaniuannassaaiatonpa
114. ISaGRAF C Tools User and Reference Manual May 8 2007 msg 2 323 readRealVariable Read ISaGRAF Real Variable Syntax include lt ctools h gt BOOLEAN readRealVariable unsigned char varName float value Description This function returns the current value of the specified real i e floating point variable The variable is specified by its name expressed as a character string The name is case insensitive The ISaGRAF 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 SaGRAF Symbols Status is invalid FALSE is returned and the current value is left unchanged The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 IO_SYSTEM system resource must be requested before calling this function
115. IZE pResponseData amp responseLength put the response length in the header responseBuffer DATA_SIZE responseLength fill in rest of packet header transmit the encapsulated response ISaGRAF C Tools User and Reference Manual 292 May 8 2007 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 the 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 must be set to RS232_MODEM Note that 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 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 o
116. Information Functions There is one library function related to controller information Refer to the Function Specification section for details on the function listed getControllerlD Returns the controller ID string Controller Information Macros The ctools h file defines the following macros for use with controller information Refer to the Function Specification section for details on each macro listed AB_PROTOCOL DF1 protocol firmware option BASE_TYPE_MASK Controller type bit mask FT_NONE Unknown firmware type FT_TELEPACE TelePACE firmware type FT_ISAGRAF ISaGRAF firmware type GASFLOW Gas Flow calculation firmware option RUNS 2 Set if Gas Flow supports two meter runs SCADAPACK SCADAPack controller SCADAPACK_LIGHT SCADAPack LIGHT controller SCADAPACK_PLUS SCADAPack PLUS controller UNKNOWN_CONTOLLER Unknown controller type 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 Macros The ctools h file defines the following macros for use with the firmware version function Refer to the C Tools Macros section for details on each macro listed VI_DATE_SIZE Number of characters in the version information date field VI_STRING_SIZE Number of characters in the version information copyright field ISaGRAF C Tools User and Referen
117. Install Serial Port Handler Syntax include lt ctools h gt void install_handler FILE stream void function unsigned unsigned 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 serial port the function has no effect function specifies the handler function which takes two arguments The first argument is the received character The second argument is an error flag A non zero value indicates an error 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 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and diagnostics using the ISaGRAF program Example include lt ctools h gt define CHAR_RECEIVED 11 signal This routine signals an event when a character is r
118. Manual 18 May 8 2007 create_task Create a task and make it ready to execute end_task Terminate a task and free the resources and envelopes allocated to it end_application Terminate all 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 Macros The ctools h file defines the following macros used for task management Refer to the C Tools Macros section for details on each macro listed RTOS_PRIORITIES Number of RTOS task priorities RTOS_TASKS Number of RTOS tasks STACK_SIZE Size of the machine stack TS_EXECUTING Task status indicating task is executing TS_READY Task status indicating task is ready to execute TS_WAIT_RESOURCE Task status indicating task is blocked waiting for a resource 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 blocked waiting for a message 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 Re
119. Memory allocation functions HART HART modem resource 10_SYSTEM I O system hardware functions ISaGRAF C Tools User and Reference Manual 20 May 8 2007 MODBUS_PARSER Modbus protocol message parser RTOS_RESOURCES Number of RTOS resource flags 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 Macros The ctools h file defines the following macros used for inter task communication Refer to the C Tools Macros section for details on each macro listed MSG_DATA Specifies the data field in an envelope contains a data value MSG_POINTER Specifies the data
120. NK_RETRIES DEFAULT_DLINK_TIMEOUT dnpWriteRoutingTableEntry 1 101 CIF_Com4 DEFAULT_DLINK_RETRIES DEFAULT_DLINK_TIMEOUT main loop af while TRUE request IO resource request_resource IO_SYSTEM read DNP status dnpGetRuntimeStatus dnpStatus setdbase MODBUS EVENTS_CLASS1 dnpStatus eventCountClassl 1 0 setdbase MODBUS EVENTS_CLASS2 dnpStatus eventCountClass2 1 0 setdbase MODBUS EVENTS_CLASS3 dnpStatus eventCountClass3 1 0 setdbase MODBUS EVENT_COUNT_AI16 dnpStatus eventCountAI16 setdbase MODBUS EVENT_COUNT_BI dnpStatus eventCountBI setdbase MODBUS EVENT_COUNT_CLASS1 dnpStatus eventCountClass1 setdbase MODBUS EVENT_COUNT_CLASS2 dnpStatus eventCountClass2 setdbase MODBUS EVENT_COUNT_CLASS3 dnpStatus eventCountClass3 release_resource IO_SYSTI Gl i E3 clear_events_flag FALSI bi_event_flag FALSE ail6_event_flag FALSE class0_report_flag FALSE Read Event Triggers if dbase MODBUS CLEAR_EVENTS setdbase MODBUS CLEAR_EVENTS 0 clear_events_flag TRUE if dbase MODBUS GENERATE_BI_EVENT setdbase MODBUS GENERATE_BI_EVENT 0 bi_event_flag FALSE
121. NTIME_STATUS status Description The dnpGetRuntimeStatus function reads the current status of all DNP change event buffers and returns information in the status structure DNP must be enabled before calling this function in order to create the DNP configuration Example See the example in the dnpSendUnsolicited section ISaGRAF C Tools User and Reference Manual May 8 2007 120 dnpReadRoutingTableDialStrings Read DNP Routing Table Entry Dial Strings Syntax BOOLEAN dnpReadRoutingTableDialStrings 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 prevent overflowing the storage passed to the function primaryDialString returns the primary dial string of the target station It must 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 prevent overflowi
122. O Appstart obj This file contains the application program start up routine see Program Architecture section above If you modify the start up routine for a particular application be sure to specify the path to the modified routine Romfunc obj This file contains addresses of the jump table for calling functions in the operating system ROM Only the symbols are loaded as only the addresses are needed Ctools lib This is the C Tools library which contains C Tools functions not found in the operating system ROM This is the standard Microtec floating point library This is the standard Microtec function library ISaGRAF C Tools User and Reference Manual 15 May 8 2007 load_symbols c telepace ctools 520x romfunc load c telepace ctools 520x ctools lib load c mccm77 cm77islf lib load c mccem77 cm77islc lib The final section of the command file specifies the output file format The 1istmap command specifies what information is to be included in the map file Refer to the Microtec manuals for more information on map files The format command specifies the executable output will be in Motorola S2 record format The ISaGRAF C Program Loader requires this format Specify output file formats and options listmap nopublics nointernals nocrossref format S2 Example The standard command file must be modified to link the application described in the previous example Copy the appram cmd file to my
123. O LSW first 1 MSW first e AI16_number is the number of 16 bit analog input points Valid values are 0 to 9999 e AI16_startAddress is the DNP address of the first Al16 point e AI16_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 AI16_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 e AI32_bufferSize is the number of events in the 32 bit analog input change buffer Valid values are 0 to 9999 e AI32_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 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
124. ON STATUS READ _HOLDING_REGISTER READ_INPUT_REGISTER READ_INPUT_STATUS REPORT_SLAVE_ID SF_ALREADY_DEFINED SF_INDEX_OUT_OF_RANGE SF_NO_TRANSLATION ISaGRAF C Tools User and Reference Manual May 8 2007 Modbus function code Master message status invalid database address Master message status invalid function code Master message status invalid message length Master message status invalid slave station address Master message status no message was sent Master message status selected protocol is not supported Master message status response was received Master message status response received with incorrect amount of data Master message status message was sent Master message status AB slave response was an EOT message Master message status AB slave response did not match command sent Master message status AB half duplex command has been acknowledged by slave Master may now send poll command Master message status Modbus slave returned a function exception Master message status Modbus slave returned an address exception Master message status Modbus slave returned a value exception Specifies the Modbus ASCII protocol emulation for the serial port Specifies the Modbus RTU protocol emulation for the serial port Specifies no communication protocol for the serial port Modbus function code Modbus function code Modbus function code Modbus function code Modbus function code Modbus funct
125. ORY Resource The DYNAMIC_MEMORY resource regulates access to all memory allocation functions These functions allocate memory from the system heap The heap is shared amongst all tasks The allocation functions are non reentrant The DYNAMIC_MEMORY resource must be obtained before using any of the following functions calloc allocates data space dynamically free frees dynamically allocated memory malloc allocates data space dynamically realloc changes the size of dynamically allocated space AB_PARSER Resource This resource is used by the DF1 communication protocol tasks to allocate access to the common message parser for each serial port This resource is of no interest to an application program However an application program may not use the resource number assigned to it MODBUS_PARSER Resource This resource is used by Modbus communication protocol drivers to allocate access to the common message parser by tasks for each serial port This resource is of no interest to an application program Resource Management Macros The ctools h file defines the following macros used for resource management Refer to the C Tools Macros section for details on each macro listed AB_PARSER DF1 protocol message parser COM1_DIALUP Resource for dialing functions on com1 COM2_DIALUP Resource for dialing functions on com2 COM3_DIALUP Resource for dialing functions on coms COM4_DIALUP Resource for dialing functions on com4 DYNAMIC_MEMORY
126. Queuing is most often used with communication protocols that use character timing for message framing lts uses in an application program are limited ISaGRAF C Tools User and Reference Manual 315 May 8 2007 readBoolVariable Read ISaGRAF Boolean Variable Syntax include lt ctools h gt BOOLEAN readBoolVariable unsigned char varName unsigned char 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 ISaGRAF 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 char value pointed to by value If the variable is not found or if the SaGRAF Symbols Status is invalid FALSE is returned and the current value is left unchanged The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF variable list each call the performance of the function may be slow for large numbers of variables For better performance use the variable
127. RAF C Tools User and Reference Manual 280 May 8 2007 ledPowerSwitch Read State of the LED Power Switch Syntax include lt ctools h gt unsigned ledPowerSwitch void Description 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 The program for user input may use this switch However pressing the switch will have the side effect of changing the LED power state See Also ledPower ledSetDefault ISaGRAF C Tools User and Reference Manual 281 May 8 2007 ledSetDefault Set Default Parameters for LED Power Control Syntax include lt ctools h gt unsigned ledSetDefault struct ledControl_tag ledControl j Description The ledSetDefault routine sets default parameters for LED power control The controller controls LED power to 5000 series 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 ledContro _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 i
128. RS232 portSettings timeout 600 set_port com2 amp portSettings get_protocol com2 amp protSettings protSettings station 1 protSettings type MODBUS_ASCITI set_protocol com2 amp protSettings Configure Register Assignment clearRegAssignment addRegAssignment DIN_generic8 0 10017 0 0 0 addRegAssignment SCADAPack_lowerI0O 0 1 10001 30001 addRegAssignment DIAG_protocolStatus 1 31000 0 0 0 Install Modbus Handler request_resource IO_SYSTEM installModbusHandler myModbusHandler release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 206 Install Exit Handler taskStatus getTaskInfo 0 installExitHandler taskStatus taskID shutdown while TRUE release_processor ISaGRAF C Tools User and Reference Manual 207 May 8 2007 installRTCHandler Install User Defined Real Time Clock Handler Syntax include lt ctools h gt void installRTCHandler void rtchandler TIME now IME new i 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 intended to set the real time clock The function has one par
129. Reference Manual 83 May 8 2007 float int logID valued Declare a structure for the log DATALOG_CONFIGURATION dLogConfig Declare a struture to hold the data that will be copied in log struct dataRecord data Function declaration Ej void ConfigureLog void void InitRecord void void main void ConfigureLog InitRecord if datalogCreate logID AL function call to cofigure log amp dLogConfig DLS_CREATED Start writing records in log if datalogwWrite logID UINT16 amp data one record was written in data log Log configuration void ConfigureLog void Assign a number to the data log logID 10 Fill in 2 2 0 0 0 0 2 LogConfig LogConfig LogConfig LogConfig LogConfig LogConfig LogConfig the log configuration structure records 200 fields 5 typesOfFields 0 typesOfFields 1 typesOfFields 2 typesOfFields 3 typesOfFields 4 One record initialization void InitRecord void Assign some data for the data valuel data value2 data value3 data value4 data value5 100 200 30000 40 3 50 75 ISaGRAF C Tools User and Reference Manual May 8 2007 ll EA GDO LV_UINT16 LV_INT32 LV_DOUBLE OAT OAT iV_F iV_F log 84 datalo
130. S 1 1 turn on output release_resource IO_SYSTEM settimer 0 5 load timer 0 with 5 seconds while timer 0 wait until time expires Allow other tasks to execute release_processor request_resource IO_SYSTEM setdbase MODBUS 1 0 shut off output release_resource IO_SYSTEM Example 2 Time the duration a contact is on but wait in loop to measure time Contact is assigned to status register 10001 interval 0 1 tick rate 0 1 second ISaGRAF C Tools User and Reference Manual 42 May 8 2007 request_resource IO_SYSTEM if dbase MODBUS 10001 test if contact is on settimer 0 63000 start timer while dbase MODBUS 10001 wait for turn off Allow other tasks to execute release_resource IO_SYSTEM release_processor request_resource IO_SYSTEM printf time period u r n 63000 timer 0 release_resource IO_SYSTEM Example 3 Open valve to fill tank and print alarm message if not full in 1 minute Contact is assigned to status register 10001 Valve is controlled by coil register 1 interval 0 10 timer 0 tick rate 1 second request_resource IO_SYSTEM setdbase MODBUS 1 1 open valve settimer 0 60 set timer for 1 minute tank not full if contact is off while dbase MODBUS 10001 0 amp amp timer 0
131. SE ISaGRAF C Tools User and Reference Manual 418 May 8 2007 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 prot_settings 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 unsigned char type unsigned char station unsigned char priority unsigned SFMessaging hi e type is the protocol type It may be one of NO_PROTOCOL MODBUS_RTU MODBUS_ ASCII AB_FULL_BCC AB_HALF_BCC AB_FULL_CRC AB_HALF_CRC or DNP macros e station is the station address of the controller Note that 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 e priority is the task priority of the protocol task This field is not used if the protocol type is NO_PROTOCOL e SFMessaging is the enable Store and Forward messaging control flag prot_status The prot_status structure contains protocol status information struct prot_status unsigned command_errors unsigned format_errors unsigned checksum_errors unsigned cmd_received unsigned cmd_sent unsigned rsp_received unsigned rsp_sent unsigned command int task_id unsigne
132. 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 BI_number is the number of binary input points Valid values are 0 to 9999 e BI_startAddress is the DNP address of the first Binary Input point e BI_reportingMethod determines how binary inputs are reported either Change Of State or Log All Events e BI_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 CI16_number is the number of 16 bit counter input points Valid values are 0 to 9999 e CI16_startAddress is the DNP address of the first C116 point e CI16_reportingMethod determines how Cl16 inputs are reported either Change Of State or Log All Events e CI16_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 CI32_startAddress is the DNP address of the first C132 point ISaGRAF C Tools User and Reference Manual 410 May 8 2007 e CI32_reportingMethod determines how Cl32 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 C132 points
133. STEM ISaGRAF C Tools User and Reference Manual 386 May 8 2007 writeMsgVariable Write to ISaGRAF Message Variable Syntax include lt ctools h gt BOOLEAN writeMsgVariable unsigned char varName unsigned char 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 ISaGRAF 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 ISaGRAF Symbols Status is invalid nothing is done and FALSE is returned The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share 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 ISaGRAF message variables have the following format Byte Description Location Lo Maximum length as declared in ISaGRAF Dictionary 1 to 255 Current Length location of first null byte 0 to maximum length First message data byte max 1 L
134. S_2 or CLASS_3 e threshold is the amount by which the counter input value must change before an event will be reported for the point dnpPointType The enumerated type DNP_POINT_TYP typedef enum dnpPointType BI_PO AI16_ AI32_ AISF_ AILF_ CITE C132 BO_PO AO16_ A032_ AOSF_ ROLF E includes all allowed DNP data point types INT 0 binary input POINT 16 bit analog input POINT 32 bit analog input POINT short float analog input POINT long float analog input POINT 16 bit counter output POINT 32 bit counter output INT binary output POINT 16 bit analog output POINT 32 bit analog output POINT short float analog output POINT long float analog output DNP_POINT_TYPE DNP_RUNTIME_STATUS The DNP_RUNTIME_STATUS type describes a structure for holding status information about DNP event log buffers DNP Runt typedef str ime Status uct dnp_runtime_status UINT16 eventCountBI number of binary UINT16 eventCountCI16 number of 16 bit UINT16 eventCountC132 number of 32 bit UINT16 eventCountAI16 number of 16 bit ei UINT16 eventCountAI32 number of 32 bit DNP_RUNTIME_STATUS e eventCou e eventCou e eventCou e eventCou e eventCou ntBI is number of binary input events ntC1I16 is number of 16 bit counter events n
135. See Also writeRealVariable Example This program displays the contents of the real variable named Flow include lt ctools h gt void main void BOOLEAN status float value request_resource IO_SYSTEM status readRealVariable Flow amp value release_resource IO_SYSTEM printf status Su Flow f r n status value ISaGRAF C Tools User and Reference Manual 324 May 8 2007 readRoutingTableEntry Read Routing Table entry Syntax include lt ctools h gt BOOLEAN readRoutingTableEntry UINT16 index routingTable pRoute Description 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 must 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 ISaGRAF C Tools User and Reference Manual May 8 2007 325 readRoutingTableSize Read Routing Table size Syntax include lt ctools h gt UINT16 readRoutingTableSize void Description This function reads the total number of entries in the routing table Notes DNP must be enabled before calling this function in order to create the DNP configuration The function returns the total number of entries in the routing table ISaGRAF C Too
136. Source getWakeSource ISaGRAF C Tools User and Reference Manual 353 May 8 2007 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 stream must specify one of com1 com2 com3 or com4 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 To optimize performance minimize the length of messages on com3 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and diagnostics using the ISaGRAF program The IO_SYSTEM resource must be requested before calling this function 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 serial h gt include lt primitiv h gt struct pconfig s
137. TOS envelopes Number of RTOS events Number of RTOS task priorities Number of RTOS resource flags Number of RTOS tasks Run Service switch is in RUN position S_MODULE_FATLURE S_NORMA SCADAPACK SCADAPACK_LIGHT PACK_PL SF_INDEX_OUT_OF_RANGE SF_NO_TRANSLATION SF_STATION_OUT_OF_RANGE NAL_DCD SIGNAL_OFF SIGNAL_OH SIGNAL_OH ISaGRAF C Tools User and Reference Manual May 8 2007 Status LED code for I O module communication failure Status LED code for normal status SCADAPack controller SCADAPack LIGHT controller SCADAPack PLUS controller Number of serial ports Run Service switch is in SERVICE position Result code translation is already defined in the table Result code invalid translation table index Result code entry does not define a translation Result code serial port is not valid Result code station number is not valid Number of entries in the store and forward table Result code translation is valid I O line bit mask clear to send signal Matches status of CTS input I O line bit mask carrier detect signal Matches status of DCD input Specifies a signal is de asserted I O line bit mask off hook signal Not supported forced low 1 397 SIGNAL_ON SIGNAL_RING SIGNAL_RING SIGNAL_VOICE Not supported forced low 0 SLI EEP_MODE_SUPPORTI STAR START_
138. 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 pulse A watchdog reset pulse must 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 Note Always 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 checksu
139. TranslationStatus setSFTranslation unsigned index struct SFTranslation translation Description The setSFTranslation function writes translation into the store and forward address translation table at the location specified by index translation consists of two port and station address pairs The function checks for invalid translations if the translation is not valid it is not stored 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 Result code Meaning S O 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_RANGE One or both of the serial port indexes is not valid SF_STATION_OUT_OF_RANG One or both of the stations is not valid E The translation already exists in the table The entry referenced by index does not exist in the table Notes The TeleBUS Protocols User Manual describes store and forward messaging mode Writing a translation with both stations set to station 256 can clear a translation in the table Station 256 is not a valid station The protocol type and communication parameters may differ between serial ports The store and forward messaging will translate the protocol messages The IO_SYSTEM resourc
140. U framing 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_ENABLED The USB peripheral port is enabled PM_USB_PERIPHERAL_DISABLED The USB peripheral port is disabled PM_USB_HOST_ENABLED The USB host port is enabled PM_USB_HOST_DISABLED The USB host port is disabled PM_UNAVAILABLE The status of the device could not be read PM_NO_CHANGE The current value will be used EX PROGRAM_EX ED Application program has been executed PROGRAM_NOT_LOADI The requested application program is not loaded ISaGRAF C Tools User and Reference Manual 396 May 8 2007 EAD_INPU BAD _INPU1 READSTATUS STATUS R CE TOS F W V RTOS_PRIORITIES RTOS_RESOURCES RTOS_TASKS Modbus function code Modbus function code Modbus function code Modbus function code Modbus function code enum ReadStatus Modbus function code Specifies serial port is an RS 232 port Specifies serial port is RS232 and uses CD for collision avoidance Specifies serial port is an RS 232 dial up modem Specifies serial port is a 4 wire RS 485 port Number of R
141. Unsolicited section ISaGRAF C Tools User and Reference Manual May 8 2007 101 dnpConnectionEvent Report a DNP connection event Syntax include lt ctools h gt void dnpConnectionEvent DNP_CONNECTION_EVENT event Description dnpConnectionEvent 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 event is current connection status The valid connection status settings are DNP_CONNECTED and DNP_DISCONNECTED See Also dnpInstallConnectionHandler Example See the dnpinstallConnectionHandler example ISaGRAF C Tools User and Reference Manual May 8 2007 102 dnpCreateRoutingTable Create Routing Table Syntax include lt ctools h gt BOOLEAN createRoutingTable 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 must 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 section Error Reference source not found ISaGRAF C Tools User and Reference Manual May 8 2007 103 dnpGenerateEventLog Generate DNP Event Log Syntax include lt ctools h gt BOOLEAN dnpGenerateEventLog UINT16 pointType UINT16 pointAddress
142. Y The maximum task priority Master message status invalid database address Master message status invalid function code Master message status invalid message length Master message status invalid slave station address Master message status no message was sent Master message status selected protocol is not supported Master message status response received Master message status response received with the incorrect amount of data Master message status message was sent Specifies Modbus database addressing Specifies the Modbus ASCII protocol emulation for the serial port Master message status DF1 slave response was an EOT message Master message status DF1 slave response did not match command sent MM Master message status DF1 half duplex command has been acknowledged by slave Master may now send poll command Master message status Modbus slave returned an address exception Master message status Modbus slave returned a Device Busy exception Master message status Modbus slave returned a Device Failure exception M FUNCTION Master message status Modbus slave returned a function exception Master message status Modbus slave returned a value exception System resource Modbus protocol message parser Specifies the Modbus RTU protocol emulation for the serial port Maximum length of the modem initialization command string MODEM_MSG MSG_ MODEM_MSG System event new modem message gener
143. 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 must 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 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 crash ISaGRAF C Tools User and Reference Manual 211 May 8 2007 See Also RTCHandler Function installExitHandler ISaGRAF C Tools User and Reference Manual 212 May 8 2007 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 descriptio
144. age fprintf coml hello world r n Wait here forever while TRUE NULL The hello world message will be output to the com serial port of the controller A terminal connected to the port will display the message The controller normally communicates on all ports using the TeleBUS communication protocol The first section of the program disables the com protocol so the serial port can be used as a normal RS 232 port The fprintf function prints the message to the com1 serial port When you have completed examining the program close the hello c file It is now ready to be compiled and linked Compiling and Linking Compiling and linking convert the source code into executable code for the controller The ISaGRAF C Tools use a C cross compiler and linker from Microtec a respected supplier of embedded system tools The compiler produces tight well optimized code The compiler and linker run under the Microsoft MS DOS operating system ISaGRAF C Tools User and Reference Manual 7 May 8 2007 The compiler has many command line options The basic command line and options required to compile code for the controller are mccm77 v nQ M1 c filename c This should be repeated for each file in the application Note that the command line options are case sensitive The character following the M is a lower case ell Files are linked together using linker command files To link a program execute the
145. al port type must be set to RS232_MODEM Use the port Index function to obtain the index of the serial port The dial up connection handler prevents 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 prevents problems with 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 See Also modemAbort modemAbortAll modemDial modemDialEnd modemDialStatus modemlnit modemlnitEnd modemInitStatus ISaGRAF C Tools User and Reference Manual 304 May 8 2007 optionSwitch Read State of Controller Option Switches Syntax include lt ctools h gt unsigned optionSwitch unsigned option Description The optionSwitch function returns the state of the controller option switch specified by option option may be 1 2 or 3 The function returns OPEN if the switch is in the open position It returns CLOSED if the switch is in the closed position Notes The option switches are located under the cover of the controller module The SCADAPack LP SCADAPack 100 and SCADASense series of controllers do not have option switches All options are user defined
146. aling 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 modemInitEnd 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 See Also modemAbort modemAbortAll modemDial modemDialEnd modemDialStatus modemlnit modemInitEnd modemNotification ISaGRAF C Tools User and Reference Manual 303 May 8 2007 modemNotification Notify the modem handler of an important event Syntax include lt ctools h gt void modemNotification UINT16 port_index Description The modemNot ification function notifies the dial up modem handler that an interesting event has 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 seri
147. am is stopped Valid values for type are SYSTEM system tasks do not terminate when the program stops APPLICATION application tasks terminate when the program stops 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 256 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 Note that the main task and the Ladder Logic and I O scanning task have a priority of 1 If the created task is continuously running processing code create the task with a priority of 1 and call release_processor periodically otherwise the remaining priority 1 tasks will be blocked from executing For tasks such as a protocol handler that wait for an event using the wait_event or receive_message function a priority greater than 1 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 Most tasks require 2 stack blocks If any of the printf functions are used then at least 4 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 best handled as static global variables within the task s
148. ameter 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 must 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 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 crash See Also RTCHandler Function installExitHandler ISaGRAF C Tools User and Reference Manual 208 May 8 2007 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
149. 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 dnpSaveBIConfig ISaGRAF C Tools User and Reference Manual 131 May 8 2007 dnpSaveBOConfig Save DNP Binary Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveBOConfig UINT16 point dnpBinaryOutput pBinaryOutput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetBOConfig Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpSaveCl16Config Save DNP 16 Bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveCI16Config UINT16 point dnpCountertInput pCounterInput
150. ands broadcast to all stations 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 all stations and cannot be used as a station number Each serial port may have a unique station number The TeleBUS DF1 protocols allow up to 255 devices on a network Station numbers identify each device A device responds to commands addressed to it or to commands broadcast to all stations The station number is in the range 0 to 254 Address 255 indicates a command broadcast to all stations 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 re transmits messages received by a controller Messages may be re transmitted on any serial port 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 Store and forward messaging is not supported by TeleBUS DF1 protocol Communication Protocols 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 clearSFTransla
151. ange 0 to 31 A zero value means that the timer has finished counting down If the timer number is invalid the function returns 0 and the task s error code is set to TIMER_BADTIMER Notes See Also interval settimer Example This code fragment sets a timer then displays the time remaining until it reaches 0 include lt ctools h gt interval 0 1 settimer 0 10 while timer 0 printf Time d r n timer 0 ISaGRAF C Tools User and Reference Manual 375 May 8 2007 timeoutCancel Cancel Timeout Notification Function Syntax include lt ctools h gt unsigned timeoutCancel unsigned timeoutID Description This function cancels a timeout notification that was requested with the t imeoutRequest function No notification will be sent The envelope provided when the request was made is de allocated The function has one parameter the ID of the timeout request This is the value returned by the timeoutRequest function The function returns TRUE if the request was cancelled and FALSE if the timeout ID is not currently active Notes The function will return FALSE if the timeout notification has already been made In this case the envelope will not be de allocated as it has already been given to the destination task That task is responsible for de allocating the envelope This function cannot be called from a task exit handler See installExitHandler function for details of exit handlers See Also
152. any RTOS functions from the exit handler Example See the example for startTimedEvent ISaGRAF C Tools User and Reference Manual 201 May 8 2007 installModbusHandler Install User Defined Modbus Handler Syntax include lt ctools h gt void installModbusHandler unsigned handler unsigned char unsigned unsigned char unsigned i Description 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 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 If the pointer is NULL no function is called for non standard messages The function has no return value Notes This function is used to create a user defined extension to the standard Modbus protocol Call this function with the NULL pointer to disable processing of non standard Modbus messages This must 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 disabled within an exit handler it will remain installed and conti
153. app cmd Modify the application object modules section to read Load application program object modules eee load main load funcl load func2 Link the file with the command inkm77 c myapp cmd This will produce one output file myapp abs The next step is to load it into the controller using the ISaGRAF C Program Loader Controller Initialization You should initialize the memory of the controller when beginning a new programming project or when you wish to start from default conditions It is not necessary to initialize the controller before every program load To initialize the controller first perform a SERVICE boot A SERVICE boot preserves programs and data in nonvolatile RAM but does not start the programs running Default communication parameters are used To perform a service boot e Remove power from the controller e Press and hold the LED POWER switch e Apply power to the controller e Wait until the STAT LED on the top of the board turns on e Release the LED POWER switch Second initialize the program and data memory in the controller A new controller will require all initializations be performed Selected initializations can be performed ona controller that is in use e Run the ISaGRAF program under Microsoft Windows ISaGRAF C Tools User and Reference Manual 16 May 8 2007 e Connect the PC to the controller with the appropriate serial cable null modem e From the Tools Controller menu
154. apped 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 Bit Description __ O 16 vertical parity error overrun error 4 framing error 3 longitudinal parity error 2 reserved alwaysO _ 1 buffer overflow o Undefined _ _ _ i y O ISaGRAF C Tools User and Reference Manual 184 May 8 2007 e If 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 Code Description O 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 Bit Description i O 6 configuration changed ____ more status available use command 48 to read primary variable analog output saturated non primary variable out of limits primary variable out of limits primary variable analog output fixed See Also hartSetConfiguration ISaGRAF C Tools User and Reference Manual 185 May 8 2007 hartGetConfiguratio
155. aseRead LINEAR START_INPUT 5 amp value ase_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 80 databaseWrite Write Value to I O Database Syntax include lt ctools h gt BOOLEAN databaseWrite UINT16 type UINT16 address INT16 value Description The databaseWrite function writes value to the I O database type specifies the method of addressing the database address specifies the location in the database If the specified address is valid then TRUE is returned and the value is written If the specified address is not valid then FALSE is returned and nothing is done 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 If the specified address is in the valid range but it has not been defined by an application then the address is also invalid An address is defined if any of the following is true 1 The address has been assigned as the Network Address for an ISaGRAF Dictionary variable The address is defined in a database handler installed by a C or C application The address is within the default range of the Permanent Non volatile Modbus Registers 40001 to 40000 NUMHOLDING_PERMANENT and 00001 to NUMCOIL_PERMANENT When this function is called the specifie
156. ask releases the processor to the other Ready Queue Event 10 Queue Running Task 4 gt 4 gt auxiliary 35 3 echoData B zh main lib nullTask 0 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 Note the position of auxiliary in the Ready queue The main task will execute before it at the next task switch Ready Queue Event 10 Queue Running Task 4 gt 4 gt echoData gt ie gt gt 3 3 2 2 1 main auxiliary 1 a o Ea null Figure 8 Queue Status after Character Received ISaGRAF C Tools User and Reference Manual 30 May 8 2007 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 th
157. ast byte in message buffer Null termination byte Terminates a message having the maximum length Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF 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 IO_SYSTEM system resource must be requested before calling this function See Also setdbase readMsgVariable ISaGRAF C Tools User and Reference Manual 387 May 8 2007 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 void main void BOOLEAN unsigned msg msg msg msg msg msg msg msg msg msg msg msg msg PRPrFPODMDIAUOBWNEO ll NRO ro OG QO a Bea h Ne Ne Ne Ne status char msg 13 10 as request status source IO_SYSTEM writeMsgVariable TextData msg release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 388 writeTimerVariable Write to SaGRAF Timer Variable Syntax
158. ataArray point ISaGRAF C Tools User and Reference Manual 243 May 8 2007 isaRead5602Inputs Read SCADAPack Upper I O Module Inputs Syntax include lt ctools h gt unsigned isaRead5602Inputs unsigned char dinData int ainDataArray Description The isaRead5602Inputs function reads the inputs from a 5602 I O Module SCADAPack Upper I O module as digital or analog inputs Data is read from all 5 analog inputs and copied to the array pointed to by ainDataArray The same 5 analog inputs are also read as 5 digital inputs and copied to the 8 bit value pointed to by dinData A digital input is ON if the corresponding filtered analog input value is greater than or equal to 20 of its full scale value otherwise it is OFF Analog inputs 0 to 4 correspond to digital inputs O to 4 dinData must point to an 8 bit value ainDataArray must point to an array of five 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes Note that when this function reads data from the 5602 it also processes the receiver buffer for the com4 serial port If the controller type is a SCADAPack LIGHT or SCADAPack PLUS the com 4 serial port is also continuously processed automatically The additional service to the com4 receiver caused by this function does not affect the normal automatic operation of com4 The IO_SYSTEM resource must be requested before calling this function See Also isaWrite5602Outpu
159. ate the envelope passed to timeoutRequest in the calling function After a call to timeoutRequest either use timeoutCancel to free the envelope if the timeout has not occurred yet or call deallocate_envelope in the destination task after the envelope has been delivered The timeout may be cancelled using the timeoutCancel function The task that receives the notification message must de allocate the envelope after receiving it No checking is done on the task ID The caller must ensure it is valid If the delay is zero the message is sent immediately provided an envelope is available This function cannot be called from a task exit handler See installExitHandler function for details of exit handlers See Also timeoutCancel ISaGRAF C Tools User and Reference Manual 377 May 8 2007 Example This example shows a task that acts on messages received from other tasks and when a timeout occurs The task waits for a message for up to 10 seconds If it does not receive one it proceeds with other processing anyway The task shows how to deal with notifications from older timeout requests These occur when the notification was send before the timeout was cancelled The task ignores timeout notifications that don t match the last timeout request include lt mriext h gt include lt ctools h gt void aTask void envelope pEnvelope TASKINFO thisTask unsigned timeoutID unsigned done get the task ID
160. ated Specifies the data field in an envelope contains a data value SG_POINTER Specifies the data field in an envelope contains a pointer 395 System event this event will never occur Application program is newly loaded NO_ERROR Error code indicates no error has occurred NO_PROTOCOL Specifies no communication protocol for the serial Specifies no parity Specifies normal count down timer NORMAL Specifies normal count down timer NOTYPE Specifies serial port type is not known NUMAB Number of registers in the Allan Bradley database NUMCOIL Number of registers in the Modbus coil section NUMCOIL_PERMANENT Number of coil registers in the Permanent Non Volatile Modbus Registers section NUMHOLDING Number of registers in the Modbus holding register section NUMHOLDING_PERMANENT Number of holding registers in the Permanent Non Volatile Modbus Registers section NUMINPUT Number of registers in the Modbus input register section Number of registers in the linear database NUMSTATUS Number of registers in the Modbus status section O ODD Specifies odd parity Specifies switch is in open position Macro PC_FLOW_RX_RECEIVE_STOP Receiver disabled after receipt of a message PC_FLOW_RX_XON_XOFF Receiver Xon Xoff flow control PC_FLOW_TX_IGNORE_CTS Transmitter flow control ignores CTS PC_FLOW_TX_XON_XOFF Transmitter Xon Xoff flow control PC_PROTOCOL_RTU_FRAMING Modbus RT
161. atic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaWrite4202Outputs Example This program displays the values of the 1 digital input 2 counter inputs and 1 analog input read from SCADASense 4202 DR I O include lt ctools h gt void main void unsigned point unsigned dinData int ainData unsigned long counterData 2 Read input data from 4202 DR I O request_resource IO_SYSTEM isaRead4202Inputs amp dinData amp ainData counterData ISaGRAF C Tools User and Reference Manual 233 May 8 2007 release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r fprintf coml n r d me Oy putchar dinData amp 0x0001 1 O Print analog input data fprintf coml r nAin Point Value n r fprintf coml d Sd n r 0 ainData Print counter input data fprintf coml r nAin Point Value n r for point 0 point lt 2 point fprintf coml Sd d n r point counterData point ISaGRAF C Tools User and Reference Manual May 8 2007 234 isaRead4202DSInputs Read SCADASense 4202 DS Inputs Syntax include lt ctools h gt unsigned isaRead4202DSInputs unsigned dinData tnt ainData unsigned long counterDataArray Description The isaRead4202DSInputs function reads the digital counter and analog inputs from the SCA
162. ations 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 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
163. ave 10 The data will be read from registers 127 to 139 master_address 127 and stored into registers 180 to 192 address 180 in the slave station The command will be transmitted on com2 stream com2 master_message com2 0 10 180 127 13 This code fragment uses the unprotected read command function 1 to read 74 length 74 16 bit registers from slave station 37 slave 37 The data will be read from registers 300 to 373 in the slave address 300 and stored in registers 400 to 473 in the master master_address 400 The command will be transmitted on com2 stream com2 master_message com2 1 37 300 400 74 This code fragment will send specific bits from a single 16 bit register in the master to slave station 33 The unprotected bit write command function 5 will be used Bits 0 1 7 12 and 15 of register 100 master_address 100 will be sent to register 1432 address 1432 in the slave The ength parameter is used as a bit mask and is evaluated as follows bit mask 1001 0000 1000 0011 in binary 9083 in hexadecimal 36 995 in decimal Therefore the command sent on com2 is master_message com2 5 33 1432 100 36995 Half Duplex The example program is the same as for Full Duplex except that instead of waiting for a response after calling master_message the slave must be polled for a response Add the following function poll_for_response to the example program above and call it instead of wait_for_response
164. be requested before calling this function See Also setdbase readTimerVariable Example This program writes the value 10000 ms to the timer variable named Delay include lt ctools h gt void main void BOOLEAN status request_resource IO_SYSTEM status writeTimerVariable Delay 10000 release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 389 May 8 2007 writeRoutingTableEntry Write Routing Table Entry Syntax include lt ctools h gt BOOLEAN writeRoutingTableEntry UINT16 index UINT16 dnpAddress UINT16 commPort UINT16 DataLinkRetries UINT16 DataLinkTimeout Description This function writes an entry in the DNP routing table Notes DNP must 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 dnpSendUnsolicited section ISaGRAF C Tools User and Reference Manual May 8 2007 390 ISaGRAF C Tools Macro Definitions Macro B Specifies Allan Bradley database addressing AB_PARSER System resource DF1 protocol message parser Specifies the DF1 Full Duplex protocol emulation for the serial port BCC checksum Specifies the DF1 Full Duplex protocol emulation for the serial port CRC checksum Specifies the DF1 Half Duplex protocol emulation for the serial port BC
165. before calling this function See Also isaWrite4Aout isaWrite5303Aout Example This program sets both analog outputs to half scale on a 2 point Analog Output Module at module address 0 include lt ctools h gt void main void int dataArray 2 dataArray 0 16384 dataArray 1 16384 Write data to analog output module request_resource IO_SYSTEM isaWrite2Aout 0 dataArray release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 257 May 8 2007 isaWrite32Dout Write to 32 Digital Outputs Syntax include lt ctools h gt unsigned isaWrite32Dout UINT16 moduleAddress UINT32 data Description The isaWrite32Dout function writes data to any 32 point Digital Output Module at the specified moduleAddress Data from the specified 32 bit value is written to the 32 digital outputs The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function See Also isaWrite8Dout isaWrite16Dout 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 void main void Write data to digital output module request_resource IO_SYSTEM isaWrite32Dout 0 OxXFFFFFFFF release_resource IO_SYSTEM
166. 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 the LED located on the top left hand corner of the 5203 or 5204 controller board The Register Assignment uses bits 0 and 1 of the status code See Also setStatusBit setStatus getStatusBit ISaGRAF C Tools User and Reference Manual 72 May 8 2007 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 stream If stream does not point to a valid serial port the function has no effect See Also get_status ISaGRAF C Tools User and Reference Manual May 8 2007 73 cre_reverse Calculate a CRC Checksum Syntax include lt ctools h gt unsigned crc_reverse unsigned char start unsigned char end unsigned poly unsigned 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 must 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 d
167. calling setdbase which calls this handler Requesting the O_SYSTEM resource ensures 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 Example See example for Dbase Handler Function ISaGRAF C Tools User and Reference Manual 200 May 8 2007 installExitHandler Install Handler Called when Task Ends Syntax include lt ctools h gt unsigned installExitHandler unsigned taskID void function void Description The installExitHandler function defines a function that is called when the task specified by taskID 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 function e the end_application function is executed and the function is an APPLICATION type function e the program is stopped from the ISaGRAF program and the task is an APPLICATION type function e the C program is erased by the ISaGRAF program The exit handler function is not called if power to the controller is removed In this case all execution stops when power fails The application program starts from the beginning when power is reapplied Do not call
168. calling this function See Also isaWrite2Aout isaWrite2Aout Example This program sets both analog outputs to half scale on a 5303 Analog Output Module include lt ctools h gt void main void int dataArray 2 dataArray 0 16384 dataArray 1 16384 Write data to analog output module request_resource IO_SYSTEM isaWrite5303Aout dataArray release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 264 May 8 2007 isaWrite5505Outputs Write 5505 Configuration Syntax include lt ctools h gt unsigned isaWrite55050utputs UINT16 moduleAddress UINT16 inputType UINT16 inputFilter Description The isaWrite55050utputs function writes configuration data to the 5505 I O module moduleAddress Is the address of the 5505 module Valid values are 0 to 15 inputType must point to an array of 4 unsigned integers that select the type of analog inputs on the module Valid values for each integer are 0 RTD in deg Celsius 1 RTD in deg Fahrenheit 2 RTD in deg Kelvin 3 resistance measurement in ohms inputFilter selects the analog input filter This is used for all inputs Valid values are e 0 0 5s e 1 15 e 2 2s e 3 4s The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaRead5505Inputs Example This program writes the
169. ce Manual May 8 2007 dnpSaveConfiguration Save DNP Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveConfiguration dnpConfiguration pConfiguration Description This function sets the DNP configuration The function 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 must be called before enabling DNP 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 must be disabled in order to make a change involving these parameters e BI_number e BI_cosBufferSize e BI_soeBufferSize e BO_ number e CIl6_number e CIl6_bufferSize e CI32_number e CI32_bu e AIl6_nu m f m fferSize m e AI16_reportingMethod f m P E ber e AI1l6_bu e AI32_number e AI32_reportingMethod e AI32_bufferSize e AOl6_number e A032_number ferSize The following parameters can be changed when DNP is enabled e masterAddress e rtuAddress e datalinkConfirm e datalinkRetries e datalinkTimeout e operateTimeout e applicationConfirm ISaGRAF C Tools User and Reference Manual 135 May 8 2007 e maximumResponse e applicationRetries e applicationTimeout e timeSynchronization e unsolicited e holdT
170. ce Manual 33 May 8 2007 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 Sleep Mode Functions SCADAPack controllers are capable of extremely low power operation when in sleep mode SCADAPack controllers enter the sleep mode under control of the application program Refer to the SCADAPack System Hardware Manual for further information on controller sleep mode There are three library functions related to sleep mode Refer to the Function Specification section for details on each function listed getWakeSource Gets wake up sources setWakeSource Sets wake up sources sleep Put controller into sleep mode Sleep Mode Macros The ctools h file defines the following macros for use in sleep mode functions Refer to the C Tools Macros section for details on each macro listed SLEEP_MODE_SUPPORTED Defined if sleep function is supported WS_ALL All wake up sources enabled WS_COUNTER_0_OVERFLOW Bit mask to enable counter 0 overflow as wake up source WS_COUNTER_1_OVERFLOW Bit mask to enable counter 1 overflow as wake up source WS_COUNTER_2_OVERFLOW Bit mask to enable counter 2 overflow as wake up source WS_INTERRUPT_INPUT Bit mask to enable interrupt input as wake up source WS_LED_POWER_SWITCH Bit mask to enable LED power switch as wa
171. ce 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 must be requested before calling this function See Also writeTimerVariable Example This program displays the contents of the timer variable named Time1 include lt ctools h gt void main void BOOLEAN status unsigned long value request_resource IO_SYSTEM status readTimerVariable Timel amp value release_resource IO_SYSTEM printf status Su Timel Slu r n status value ISaGRAF C Tools User and Reference Manual 329 May 8 2007 read_timer_info Get Timer Status Syntax include lt ctools h gt struct timer_info read_timer_info unsigned timer Description The read_timer_info function gets status information for the timer specified by timer The read_timer_info function returns a timer_info structure with information about the specified timer Refer to the description of the t imer_info structure for information about the fields See Also settimer Example This program starts a pulse train and displays timer information include lt ctools h gt void main void struct timer_info tinfo Start Pulse Train interval 10 1 multiplier 1 pulse_train 3 5 10 500 while timer 10 gt 100 wait a while Allow other tasks to execute release_proces
172. 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 void main void UINT16 index struct prot_settings settings dnpConfiguration configuration dnpBinaryInput binaryInput dnpBinaryOutput binaryOutput dnpAnalogInput analogInput dnpAnalogOutput analogOutput dnpCounterInput counterInput loop index protocol settings configuration settings binary input settings binary output settings analog input settings analog output settings counter input settings Stop any protocol currently active on com port 2 get_protocol com2 amp settings settings type set_protocol com2 amp settings con con con con con con con con con con con con con con con con con con figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration figuration NO_PROTOCOL masterAddress rtuAddress datalinkConfirm datalinkRetries datalinkTimeout operateTimeout applicationConfirm maximumResponse applicationRetries applicationTimeout timeSynchronization BI_number BI_cosBufferSize BI_soeBufferSize BO_number CI16_number CI16_bufferSize C1I32_number ISaGRAF C Tools User and Reference Manual Ma
173. command and returns the response The function can be used by an application to encapsulate Modbus RTU commands in another protocol stream is a FILE pointer that identifies the serial port where the command was received This is used for to accumulate statistics for the serial port pCommand is a pointer to a buffer containing the Modbus command The contents of the buffer must be a standard Modbus RTU message The Modbus RTU checksum is not required commandLength is the number of bytes in the Modbus command The length must include all the address and data bytes It must not include the checksum bytes if any in the command buffer responseSize is the size of the response buffer in bytes A 300 byte buffer is recommended If this is not practical in the application a smaller buffer may be supplied Some responses may be truncated if a smaller buffer is used pResponse is a pointer to a buffer to contain the Modbus response The function will store the response in this buffer in standard Modbus RTU format including two checksum bytes at the end of the response pResponseLength is a pointer to a variable to hold response length The function will store the number of bytes in the response in this variable The length will include two checksum bytes The function returns TRUE if the response is valid and can be used It returns FALSE if the response is too long to fit into the supplied response buffer Notes To use the function on a s
174. cters are returned by the protocol command ength 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 copies 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 must initialize the salve ID string each time it is run See Also modbusExceptionStatus ISaGRAF C Tools User and Reference Manual 290 May 8 2007 modbusProcessCommand Function Process a Modbus command and return the response Syntax include lt ctools h gt BOOLEAN processModbusCommand FILE stream UCHAR pCommand UINT16 commandLength UINT16 responseSize UCHAR pResponse UINT16 pResponseLength Description The processModbusCommand function processes a Modbus protocol command and returns the response The function can be used by an application to encapsulate Modbus RTU commands in another protocol stream is a FILE pointer that identifies the serial port where the command was received This is used for to accumulate statistics for the serial port pCommand is a pointer to a buffer containing the Modbus command The contents of the buffer must be a standard Modbus RTU message Th
175. cture for details on editing appstart c See the function create_task to specify the stack used by other tasks 2 The powf function may be used instead of pow where double precision is not required Correction to the Problem This problem exists with the C Compiler supplied by Microtec It will not be corrected Users must work around the problem as described above ISaGRAF C Tools User and Reference Manual May 8 2007 428 ISaGRAF C Tools Warranty and License Warranty Disclaimer Control Microsystems makes no representation or warranty with respect to the ISaGRAF C Tools The sole obligation of Control Microsystems shall be to make available all published updates or modifications to the ISaGRAF C Tools at a price which will not exceed the current market price Limitation of Liability The foregoing warranty is in lieu of all other warranties expressed or implied including but not limited to the implied warranties of merchantability and fitness for a particular purpose The user shall at their own discretion determine the suitability of the ISaGRAF C Tools for their intended use In no event will Control Microsystems its agents distributors representatives employees officers directors or contractors be liable for any special direct indirect or consequential damages losses costs claims demands or claim for lost profits fees or expenses of any nature or kind arising from the use of the ISaGRAF C Tools In accepting
176. d function unsigned slave_station unsigned slave_address unsigned master_address unsigned 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 stream 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 number or registers The master_message function returns the command status from the protocol driver Value Description was an EOT message did not match command sent MM_CMD_ACKED Master message status AB half duplex command has been acknowledged by slave Master may now send poll command returned a function exception returned an address exception returned a value exception MM_RECEIVED_BAD_LENGTH Master message status response received with incorrect amount of data ISaGRAF C Tools User and Ref
177. d SCADASense series of programmable controllers do not support 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 The table below shows the effect of disabling the various wake up conditions All wake up conditions will be enabled by default Refer to the description of the setWakeSource function for details Allowed Application programs Not applicable Reset execute from start of program External Program execution Yes Interrupt input ignored Interrupt continues from point sleep function was executed Real Time Program execution Yes Alarm ignored Clock Alarm continues from point sleep function was executed LED Power Program execution Yes LED power button Button continues from point ignored sleep function was executed es Hardware Software portion of Y Software portion of Counter counter is incremented counter is incremented Rollover Program execution Controller returns to continues from point sleep mode sleep function was executed The sleep function returns a wake up code indicating which condition caused the controller to resume execution Condition WS_REAL_TIME_CLOCK real time clock alarm rising edge of interrupt input LED Power switch pushed ISaGRAF C Tools User and Reference Manual 369 May 8 2
178. d address is searched for under these three categories in the order listed above until the address is found If the address is not found FALSE is returned If the address is defined in more than one of these categories the first occurrence of the address in the order listed is always used Notes Refer to the section Permanent Non Volatile Modbus Registers for details on potential addressing conflicts during application downloading 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 invalid only the valid registers are written and FALSE is returned The IO_SYSTEM resource must be requested before calling this function See Also databaseRead setdbase ISaGRAF C Tools User and Reference Manual 81 May 8 2007 Example include lt ctools h gt void main void BOOLEAN status request_resource IO_SYSTEM status databaseWri Turn ON the first status databaseWri Write to a 16 bit status databaseWri Write to the 12th status databaseWri release_resource IO_ ISaGRAF C Tools User and Reference Manual May 8 2007 te MODBUS 400 16 coils register te LINEAR 302 holding regis SYSTI Gl i 01 102 te LINEAR START_COIL 255 0 240 ter te LINEAR START_HOLDING 11 330 82 datalogCreate Create Data Log Function
179. d byte wise exclusive OR The CRC algorithms are particularly reliable employing various polynomial methods to detect nearly all communication errors Additional types of checksums are easily implemented using library functions ISaGRAF C Tools User and Reference Manual 4 May 8 2007 Standard I O Functions The ISaGRAF C Tools are an enhanced version of standard C libraries Most of the usual C programming techniques apply However with respect to I O there are some differences The C Tools function library supports all the standard I O functions There are no disk drives or peripherals associated with the controller Thus many file handling functions return fixed responses indicating that the operation could not be performed All standard devices are opened automatically by the operating system and cannot be closed The route function may be used to redirect stdin stdout and stderr The ISaGRAF Workbench Control Microsystems IEC 1131 3 implementation enables the programming of SCADAPack and Micro16 controllers using the IEC 1131 3 programming languages The programming environment uses the ISaGRAF Workbench to create load and debug IEC 1131 3 application programs The ISaGRAF Workbench is a powerful programming environment providing among several other features a C Program Loader On line help provides a full reference to all the features of the ISaGRAF Workbench ISaGRAF runs on the Microsoft Windows operating system This man
180. d in the log The function has five parameters logID 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 pNext SequenceNumber 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 must 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 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 See Also datalogReadStart datalogPurge datalogWrite Example See the example for datalogRea
181. d stored_messages unsigned 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 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 xrsp_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 ISaGRAF C Tools User and Reference Manual 419 May 8 2007 e task_idis 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 pconfig The pconfig structure contains serial port settings struct pconfig unsigned baud unsigned duplex unsigned parity unsigned data_bits unsigned stop_bits unsigned flow_rx unsigned flow_tx unsigned type unsigned timeout e baud is the communication speed It is one of the BAUD_xxx 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 It is either the STOP1 o
182. dStart ISaGRAF C Tools User and Reference Manual 89 May 8 2007 datalogReadStart Read Data Log Start Function Syntax include lt ctools h gt BOOLEAN datalogReadStart UINT16 logID UINT32 pSequenceNumber i 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 logID 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 datalogReadNext datalogPurge datalogWrite Example ROKR K RR KKK KK KK OK KK OK RK KK OK OK KK The following code shows how to read records from data log HK KR I I I I I OK OK KK include ctools h include lt stdlib h gt UINT16 recordSize logID pData Pointer to memory to hold data read from log UINT32 sequenceNumber Sequence number of record to be read nextSequenceNumber Sequence number of next record void main void Select data log 10 logID 10 Find first record in data log 1
183. datalogWrite Example include lt ctools h gt int logID sequenceNumber Declare flag to purge entire of data log or part of it BOOLEAN purgeAll Which data log to purge logID 10 Set flag to purge only part of data log purgeAll FALSE How many of the oldest records to purge sequenceNumber 150 ISaGRAF C Tools User and Reference Manual 87 May 8 2007 i1f datalogPurge logID purgeAll sequenceNumber Successful at purging the first 150 records of log Start writing records again To purge the entire data log simply set flag to TRUE purgeAll TRUE Call up function with same parameters if datalogPurge logID purgeAll sequenceNumber Successful at purging the entire data log Start writing records again ISaGRAF C Tools User and Reference Manual May 8 2007 88 datalogReadNext Read Data Log Next Function This function returns the next record in the data log Syntax include lt ctools h gt BOOLEAN datalogReadNext UINT16 logID UINT32 sequenceNumber UINT32 pSequenceNumber UINT32 pNextSequenceNumber UINT16 pData i 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 recor
184. ded addressing protocol parameters for a serial port Sets extended addressing and Enron Modbus protocol parameters for a serial port This function is a stub and no longer performs a necessary operation Write store and forward translation table entry Starts protocol execution based on stored parameters Communication Protocols Macros The ctools h file defines macros for specifying communication protocol parameters Refer to the C Tools Macros section for details on each macro listed AB_FULL_BCC AB_FULL_CRC AB_HALF_BCC AB_HALF_CRC FORCE_MULTIPLE_COILS FORCE_SINGLE_COIL LOAD_MULTIPLE_REGISTERS ISaGRAF C Tools User and Reference Manual May 8 2007 Specifies the DF1 Full Duplex protocol emulation for the serial port BCC checksum Specifies the DF1 Full Duplex protocol emulation for the serial port CRC checksum Specifies the DF1 Half Duplex protocol emulation for the serial port BCC checksum Specifies the DF1 Half Duplex protocol emulation for the serial port CRC checksum Modbus function code Modbus function code Modbus function code 54 LOAD_SINGLE_REGISTER MM_BAD_ADDRESS MM_BAD_FUNCTION MM_BAD_LENGTH MM_BAD_SLAVE MM_NO_MESSAGE MM_PROTOCOL_NOT_SUPPORTED MM_RECEIVED MM_RECEIVED_BAD_LENGTH MM_SENT MM_EOT MM_WRONG_RSP MM_CMD_ACKED MM_EXCEPTION_FUNCTION MM_EXCEPTION_ADDRESS MM_EXCEPTION_VALUE MODBUS_ASCII MODBUS_RTU NO_PROTOCOL READ _COIL_STATUS READ EXCEPTI
185. details on each function listed Save Writes configuration data from RAM to EEPROM load Reads configuration data from EEPROM into RAM ISaGRAF C Tools User and Reference Manual 35 May 8 2007 Configuration Data EEPROM Macros The ctools h file defines the following macros for use with the configuration data EEPROM Refer to the C Tools Macros section for details on each macro listed EEPROM_EVERY EEPROM section loaded to RAM on every CPU reboot EEPROM_RUN EEPROM section loaded to RAM on RUN type boots only EEPROM_SUPPORTED If defined indicates that there is an EEPROM in the controller 1 O Bus Communication Functions The ctools h file defines the following functions that access the I O bus The I O bus is C compatible Refer to the Function Specification section for details on each function listed ioBusReadByte Reads one byte from an I C slave device ioBusReadLastByte Reads one byte from an I C slave device and terminates read ioBusReadMessage Reads a message from an IC slave device ioBusSelectForRead Selects an IC slave device for reading ioBusSelectForWrite Selects an C slave device for writing ioBusStart Issues an I C bus START condition ioBusStop Issues an I C bus STOP condition ioBusWriteByte Writes one byte to an I C slave device ioBusWriteMessage Writes a message to an IC slave device 1 O Bus Communication Macros The ctools h file defines the following macros for use with I O Bus Communication Refer to
186. digital output is turned on The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function writes data to the SCADASense 4202 DS I O it also processes the transmit buffer for the com3 serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaRead4202DSinputs Example This program turns on the digital outputs include lt ctools h gt void main void unsigned digitalData turn on digital outputs digitalData 0x02 Write output data to 4202 DS outputs request_resource IO_SYSTEM isaWrite4202DSOutputs digitalData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 263 May 8 2007 isaWrite5303Aout Write to 5303 Analog Outputs Syntax include lt ctools h gt unsigned isaWrite5303Ao0ut int dataArray Description The isaWrite5303Aout function writes data to the 2 points on a 5303 SCADAPack Analog Output Module Data is read from the array pointed to by dataArray and written to the 2 analog outputs dataArray must point to an array of two 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned The IO_SYSTEM resource must be requested before
187. dler UINT16 function UINT16 length UCHAR pCommand UINT16 responseSize UINT16 pResponseLength UCHAR pResponse i 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 must disable the handler when the application ends This prevents the protocol driver from calling the handler while the application is stopped Call the enronInstal1lCommmandHandler 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 xresponseSize 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 must set this variable e pResponse is a pointer to a buffer that will hold the response message The buffer size is responseSize characters The
188. dnpSaveCl16Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetCl32Config Get DNP 32 bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetC1I32Config UINT32 point dnpCountertInput pCounterInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveCl32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetConfiguration Get DNP Configuration Syntax include lt ctools h gt BOOLEAN dnpGetConfiguration dnpConfiguration pConfiguration i Descripti on This 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 See Also dnpSaveConfiguration Example The following program demonstrates how to configure DNP for operation on
189. dress is 0 to 15 The lO_SYSTEM resource must be requested before calling this function See Also isaWrite16Dout Example This program turns ON all 8 digital outputs of an 8 point Digital Output Module at module address 0 include lt ctools h gt void main void Write data to digital output module request_resource IO_SYSTEM isaWrite8Dout 0 OxFF release_resource IO_SYSTEM isaWriteAout Write to Analog Output Module Syntax include lt ctools h gt unsigned isaWriteAout UINT16 moduleAddress enum ioModuleType moduleType INT16 pData Description The isaWriteAout function writes data to an analog output module The function has three parameters moduleAddress is the address of the module The valid range is 0 to 15 ISaGRAF C Tools User and Reference Manual 275 May 8 2007 moduleType is the type of the module It must be one of 105301 105302 105303 SCADAPack Analog Output or 105304 pData is a pointer to an array of INT16 variables The size of the array depends on the module type e If moduleType iS i05301 or 105303 pData must point to an array of two INT16 variables e If moduleType iS i05302 or 105304 pData must point to an array of four INT16 variables The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this f
190. dule request_resource IO_SYSTEM isaRead4Counter 0 dataArray release_resource IO_SYSTEM Print counter data fprintf coml Point Value n r for point 0 point lt 4 point fprintf coml d Slu n r point dataArray point ISaGRAF C Tools User and Reference Manual 232 May 8 2007 isaRead4202Inputs Read SCADASense 4202 DR Inputs Syntax include lt ctools h gt unsigned isaRead4202Inputs unsigned dinData tnt ainData unsigned long counterDataArray Description The isaRead4202Inputs function reads the digital counter and analog inputs from the SCADASense 4202 DR I O Data is read from the digital input and copied to the 16 bit value pointed to by dinData Data is read from the analog input and copied to the value pointed to by ainData Data is read from 2 counter inputs and copied to the array pointed to by counterDataArray dinData must point to a 16 bit unsigned integer ainData must point to a 16 bit integer couterDataArray must point to an array of two 32 bit unsigned integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function reads data from the transmitter it also processes the receiver buffer for the com serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal autom
191. e hello world message will be displayed on the terminal Serial Communication Parameters When the controller is powered up in the SERVICE mode the serial ports are configured as e 9600 baud e 8data bits e 1 stop bit e no parity e Modbus RTU protocol emulation e station address 1 A program may change these settings with the set_port function When the controller is powered up in RUN position the custom parameters as stored by the most recent save function are used ISaGRAF C Tools User and Reference Manual 9 May 8 2007 C Program Development Program Architecture AC application program may be contained in a single file or in a number of separate files called modules A single file is simple to compile and link It can become cumbersome to edit and time consuming to compile as the file grows in size An application stored in separate modules by function is easier to edit promotes function re use and is quicker to compile when only a few modules are changed Compiled modules can be combined into object libraries and shared among users The ISaGRAF C Tools support both single file and multiple module programs A C application program consists of support functions provided by the C Tools and the main and other functions written by the user Main Function Structure The program sample below shows a typical structure for the main function void main void Perform initialization actions Start suppo
192. e and a pointer to a HART_DEVICE structure The information read by command 11 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 Notes The function returns immediately after the command is sent The calling program must 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 must initialize the link before executing any other commands See Also hartCommand60O hartStatus hartSetConfiguration ISaGRAF C Tools User and Reference Manual 182 May 8 2007 hartCommand33 Read Transmitter Variables Syntax include lt ctools h gt BOOLEAN hartCommand33 unsigned module HART_DEVICE const device unsigned 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
193. e Modbus RTU checksum is not required commandLength is the number of bytes in the Modbus command The length must include all the address and data bytes It must not include the checksum bytes if any in the command buffer responseSize is the size of the response buffer in bytes A 300 byte buffer is recommended If this is not practical in the application a smaller buffer may be supplied Some responses may be truncated if a smaller buffer is used pResponse is a pointer to a buffer to contain the Modbus response The function will store the response in this buffer in standard Modbus RTU format including two checksum bytes at the end of the response pResponseLength is a pointer to a variable to hold response length The function will store the number of bytes in the response in this variable The length will include two checksum bytes The function returns TRUE if the response is valid and can be used It returns FALSE if the response is too long to fit into the supplied response buffer Notes To use the function on a serial port a protocol handler must be created for the encapsulating protocol Set the protocol type for the port to NO_ PROTOCOL to allow the custom handler to be used The function supports standard and extended addressing Configure the protocol settings for the serial port for the appropriate protocol The Modbus RTU checksum is not required in the command so the encapsulating protocol may omit them if they are
194. e information on events Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in ctools h are not valid events for use in an application program See Also Example This program creates a task to wait for an event then signals the event include lt ctools h gt void task1 void while TRUE wait_event 20 printf Event 20 occurred r n void main void create_task task1l 3 APPLICATION 4 while TRUE body of main task loop 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 settimer 0 10 1 second interval while timer 0 wait for 1s Allow other tasks to execute release_processor Signal_event 20 ISaGRAF C Tools User and Reference Manual 367 May 8 2007 ISaGRAF C Tools User and Reference Manual 368 May 8 2007 sleep Suspend Controller Operation Syntax include lt ctools h gt unsigned sleep void Description The sleep function puts the controller into a sleep mode Sleep mode reduces the power consumption to a minimum by halting the microprocessor clock and shutting down the power supply All programs halt until the controller resumes execution All output points turn off while the controller is in sleep mode The SCADAPack 100 an
195. e interrupt input is located on the 5203 or 5204 controller board Refer to the System Hardware Manual for more information on the hardware The counter increments on the rising edge of the input signal The maximum input frequency that can be counted by the interrupt input is 200 Hz See Also interruptinput readBoolVariable ISaGRAF C Tools User and Reference Manual May 8 2007 210 interruptinput Read State of Interrupt Digital Input Syntax include lt ctools h gt unsigned interruptInput void Description The interruptinput function reads the status of the interrupt input point on the controller It returns TRUE if the input is energized and FALSE if it is not Notes The interrupt input can be used as wake up source for the controller or as an additional a digital input Refer to the System Hardware Manual for wiring details See Also installRTCHandler Install User Defined Real Time Clock Handler Syntax include lt ctools h gt void installRTCHandler void rtchandler TIME now IME new i 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 intended to set the real time clock The function has one parameter
196. e must be requested before calling this function See Also getSFTranslation clearSFTranslationTable checkSFTranslationTable Example This program enables store and forward messaging on com1 and com2 Two entries are placed into the store and forward table Note that the communication parameters and protocol type on com2 are different from comi include lt ctools h gt void main void struct prot_settings settings ISaGRAF C Tools User and Reference Manual 360 May 8 2007 struct pconfig portset struct SFTranslation translation struct SFTranslationStatus status request_resource IO_SYSTEM 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 DISABLE portset flow_tx DISABLE portset typ RS232 portset timeout 600 set_port coml amp portset Set communication parameters for port 2 portset baud BAUD1200 portset duplex HALF portset parity NONE portset data_bits DATA8 portset stop_bits STOP1 portset flow_rx DISABLE portset flow_tx DISABLE portset typ RS232 portset timeout 600 set_port com2 amp portset Set up the translation table clearSFTranslationTable translation portA portIndex coml1 translation stationA 2 translation portB portIndex com
197. e ready queue main is given the processor and executes Ready Queue Event 10 Queue Running Task Ea ab main k echoData gt 3 2 auxiliary 1 gt o null gt Figure 9 Queue Status after echoData Waits for Event ISaGRAF C Tools User and Reference Manual 31 May 8 2007 Overview of Programming Functions This section of the User Manual provides and 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 section of this manual for detailed explanations of the Functions Macros Structure and Types described here Controller Operation This section of the manual provides an overview of the ISaGRAF functions relating to controller operation These functions are provided in addition to the run time library supplied with the Microtec C compiler Start Up Functions There are two library functions related to the system or application start up task Refer to the Function Specification section for details on each function listed startup_task Returns the address of the system start up routine system_start The default start up routine Start Up Macros The ctools h file defines the following macros for use with the start up
198. e strings strcpy type APPLICATION Application strcpy type SYSTEM System Disable the protocol on serial port 1 settings type NO_PROTOCOL settings station 1 settings priority 3 settings SFMessaging FALSE request_resource IO_SYSTEM set_protocol coml amp settings release_resource IO_SYSTEM display information about all tasks for task 0 task lt RTOS_TASKS task taskStatus getTaskInfo task if taskStatus taskID 0 show information for valid task ISaGRAF C Tools User and Reference Manual 172 May 8 2007 fprintf coml Resource d r n while TRUE Allow other tasks to execute release_processor ISaGRAF C Tools User and Reference Manual May 8 2007 fprintf com1 r n r nInformation about task d r n fprintf comli T Task ID d r n taskStatus taskID taskStatus requirement fprintf coml Priority d r n taskStatus priority fprintf coml T Status Ss r n state taskStatus status if taskStatus status TS_WAIT_EVENT fprintf coml Event Sda r n if taskStatus status TS_WAIT_RESOURCE taskStatus requirement fprintf coml Error Sd r n taskStatus error fprintf com1 Type s r n type taskStatus type 173 getVersion Get Firmware Version Information Syntax include lt ctools h gt VERSION getVersion void Description The
199. e the driver will wait when the transmit buffer fills before it clears the buffer PORT_CHARACTERISTICS The PORT_CHARACTERISTICS type is a structure that contains serial port characteristics typedef struct portCharacteristics_tag unsigned dataflow unsigned buffering unsigned protocol unsigned long 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 pstatus The pstatus structure contains serial port status information struct pstatus unsigned framing unsigned parity unsigned c_overrun unsigned b_overrun unsigned rx_buffer_size unsigned rx_buffer_used unsigned tx_buffer_size unsigned tx_buffer_used unsigned io_lines hi e framing is the number of received characters with framing errors e parity is the number of received characters with parity errors e c_overrun is the number of received character overrun errors e b_overrun is the number of receive buffer overrun erro
200. e4AoutChecksunm function writes data to a 4 point analog output module with checksum support The function can be used with 5304 analog output modules Use the isaWrite4Aout function for all other analog output modules The function has two parameters e moduleAddress is the address of the module The valid range is 0 to 15 e dataArray must point to an array of four INT16 variables The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaWrite2Aout isaWrite4Aout isaWrite5303Aout Example This program sets all 4 analog outputs to half scale on a 5304 Analog Output Module at module at address 0 include lt ctools h gt void 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 5304 analog output module request_resource IO_SYSTEM isaWrite4AoutChecksum 0 dataArray release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 260 May 8 2007 isaWrite42020utputs Write to SCADASense 4202 DR Analog Output Syntax include lt ctools h gt unsigned isaWrite42020utputs int aoutData Description The isaWrite42020utputs function writes data to the analog output of the SCADASense 4202 DR I O
201. eC1I16Config 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 dnpSaveC132Config index amp counterInput add additional initialization code for your application here loop forever while TRUE add additional code for your application here allow other tasks of this priority to execute release_processor j return ISaGRAF C Tools User and Reference Manual May 8 2007 118 dnpGetConfigurationEx Read DNP Extended 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 must be enabled before calling this function in order to create the DNP configuration This function supersedes the dnpGetConfiguration function ISaGRAF C Tools User and Reference Manual 119 May 8 2007 dnpGetRuntimeStatus Get DNP Runtime Status Syntax include lt ctools h gt BOOLEAN dnpGetRuntimeStatus DNP_RU
202. eceived on coml If there is an error the character is ignored oats pes eee void signal unsigned character unsigned error if error 0 interrupt_signal_event CHAR_RECEIVED character This program displays all characters received on coml using an installed handler to signal ISaGRAF C Tools User and Reference Manual 190 May 8 2007 the reception of a character void main void struct prot_settings protocolSettings int character Disable protocol get_protocol coml amp protocolSettings protocolSettings type NO_PROTOCOL request_resource IO_SYSTEM set_protocol coml amp protocolSettings release_resource IO_SYSTEM Enable character handler install_handler coml signal Print each character as it is recevied while TRUE wait_event CHAR_RECEIVED character fgetc coml fputs character coml fputc character coml fputs r n coml ISaGRAF C Tools User and Reference Manual 191 May 8 2007 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 funct
203. ecific variable ID ledControl_tag The ledControl_tag structure defines LED power control parameters struct ledControl_tag unsigned state unsigned time e state is the default LED state It is either the LED ON or LED_OFF macro ISaGRAF C Tools User and Reference Manual 416 May 8 2007 e time is the period in minutes after which the LED power returns to its default state ModemInit The ModemInit structure specifies modem initialization parameters for the modemInit function struct ModemInit FILE port char modemCommand MODEM_CMD_MAX_LEN 2 e port is the serial port where the modem is connected e modemCommand is the initialization 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 ModemSetup The ModemSetup structure specifies modem initialization and dialing control parameters for the modemDial function struct ModemSetup FILE port unsigned short dialAttempts unsigned short detectTime unsigned short pauseTime unsigned short dialmethod char modemCommand MODEM_CMD_MAX_LEN 2 char phoneNumber PHONE_NUM_MAX_LEN 2 e port is 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
204. ectionState 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 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 setdbase MODBUS MESSAGE_COMPLETE 0 setdbase MODBUS MESSAGE_FAILED 0 save the new state lastConnectionState currentConnectionState release the processor so other tasks can run release_resource IO_SYSTEM release_processor j ISaGRAF C Tools User and Reference Manual 100 May 8 2007 dnpClearEventLog Clear DNP Event Log Syntax include lt ctools h gt BOOLEAN dnpClearEventLog void Description The dnpClearEventLogs function deletes all change events from the DNP change event buffers for all point types Example See the example in the dnpSend
205. ed as the Network Address for a variable in the ISaGRAF Dictionary Modbus protocols will access this address from the Dictionary instead of from the Permanent Registers However when the ISaGRAF application is being downloaded or re started the Dictionary will be temporarily undefined If a protocol accesses the controller while the Dictionary is undefined the protocol will search and find a different value for the register under the Permanent Non Volatile Registers If this scenario is expected assign Dictionary network addresses outside the range of Permanent Registers C C Application Database Handler A C C application may install a Database Handler to define Modbus registers This creates registers without having to create an ISaGRAF Dictionary of variables When a C C application is being downloaded or is stopped the database handler is temporarily uninstalled If a protocol accesses the controller while the handler is uninstalled the protocol will return a Modbus Exception Most polling masters will simply log this as a command error and retry the protocol command until the database handler is installed When an address from the range of Permanent Non Volatile Registers is also defined in a database handler in a C C application Modbus protocols will access this address from the database handler instead of from the Permanent Registers However when the C C application is being downloaded or is stopped the database handler wi
206. ed position OPEN Specifies switch is in open position 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 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 ISaGRAF C Tools User and Reference Manual 40 May 8 2007 The FORCE LED indicates locked I O variables Use this function with caution in application programs There are three 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 setStatus Sets controller status code forceLed Sets state of the force LED LED Indicators Macros The ctools h file defines the following macros for use with LED power control Refer to the C Tools Macros section for details on each macro listed LED_OFF Specifies LED is to be turned off LED_ON Specifies LED is to be turned on LED Power Control Functions The controller board can disable the LEDs on the controller board the upper and lower I O modules and the 5000 Series I O modules to conserve power This is particularly useful in solar powered or unattended installations Refer to the SCADAPack System Hardware Manual for fur
207. ee ote ee define CHARACTER_RECEIVED 10 a eS Es es signalCharacter The signalCharacter function signals an event when a character is received This function must be called from an interrupt handler See Pee oe ee be ee ee ee ee eee ee ee void signalCharacter unsigned character unsigned error If 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 ISaGRAF C Tools User and Reference Manual 25 May 8 2007 echoData The echoData function is a task that waits for a character to be received on com6 and echoes the character back It installs a character handler for com6 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 com6 amp protocolSettings protocolSettings type NO_PROTOCOL set_protocol com6 amp protocolSettings Set serial communication parameters portSettings baud BAUD9600 portSettings duplex FULL portSettings parity NONE portSettings data_bits DATA8 portSettings stop_bits STOP1 portSettings flow_rx DISABLE portSettings flow_tx DISABLE portSettings type RS232 portSettings timeout 600 set_port com6 amp portSettings Install handler for
208. ef enum dnpConnectionEventType DNP_CONNECTED 0 DNP_DISCONNECTED DNP_CONNECTION_REQUIRED DNP_MESSAGE_ COMPLETE DNP_MESSAGE_TIMEOU DNP_CONNECTION_EVENT e The DNP_CONNECTED event indicates that the handler has connected to the master station The application sends this event to DNP When DNP receives this event it will send unsolicited messages ISaGRAF C Tools User and Reference Manual 404 May 8 2007 e 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 e 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 e 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 e The DNP_MESSAGE_TIMEOUT event indicates that DNP has attempted to send an unsolicited message but did not receive co
209. elntVariable Example This program displays the contents of the integer variable named Temperature include lt ctools h gt void main void BOOLEAN status signed long value request_resource IO_SYSTEM status readIntVariable Temperature amp value release_resource IO_SYSTEM printf status Su Temp ld r n status value ISaGRAF C Tools User and Reference Manual 321 May 8 2007 readMsgVariable Read ISaGRAF Message Variable Syntax include lt ctools h gt BOOLEAN readMsgVariable unsigned char varName unsigned char 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 ISaGRAF 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 f the variable is not found or if the ISaGRAF Symbols Status is invalid FALSE is returned and the buffer is left unchanged The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share 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
210. em Hardware Manual for further information on the status LED and digital output There are two 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 clearStatusBit Clears bits in controller status code Status LED and Output 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 Options Switches Functions The controller has three option switches located under the cover of the controller module These switches are labeled OPTION 1 2 and 3 The option switches are user defined except when a SCADAPack I O module or SCADAPack AOUT module used In this case option switches 1 and 2 select the analog ranges Refer to the SCADAPack System Hardware Manual for further information on option switches There is one library function related to the controller option switches Refer to the Function Specification section for details optionSwitch Read option switch states Option Switches Macros The ctools h file defines the following macros for use with option switches Refer to the C Tools Macros section for details on each macro listed CLOSED Specifies switch is in clos
211. emory in the controller A new controller will require all initializations to be performed Selected initializations can be performed on a controller that is in use ISaGRAF C Tools User and Reference Manual May 8 2007 e Run the ISaGRAF program under Microsoft Windows e Connect the PC to the controller with the appropriate serial cable The hello world program will print data on the com serial port Therefore connect to the com2 serial port on the controller All communication ports work the same We use com2 here because the sample program is using com7 e From the Tools Controller menu select the Initialize command e Select all options Erase IEC 1131 Application Erase C Program and Initialize Controller e Click on the OK button The controller is now ready for a program Loading the Program To load the hello world program into the controller To load the hello world program into the controller e Run the ISaGRAF program e From the Tools menu select Controller and then select the C Program Loader command e Enter hello abs in the edit box for the C Program file name e Click on the Write button The file will be downloaded Executing the Program e Connect a terminal to com 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 Program Loader dialog click on the Run button to execute the program Th
212. endasm statements are used to enclose in line assembly language code which is then assembled without passing through the compiler C programs are converted to assembly language by the MCCM77 compiler and this code may be viewed and modified The resulting code may also be combined with programs written directly in assembler Program Options AC application program may reside in RAM or ROM The normal method of program development has the program in RAM The program may call library routines in the operating system ROM The RAM is nonvolatile battery backed so the program may remain in RAM once development is completed and the unit is installed Application programs may also be committed to EPROM The RAM is used for data storage in this case ISaGRAF C Tools User and Reference Manual 3 May 8 2007 Supported Language Features The ISaGRAF C Tools use the Microtec MCCM77 C compiler The compiler is ANSI C compliant and provides a code optimizer and assembler In addition to the standard C operators data types and library functions the C tools provide a set of routines specifically designed for control applications Some applications and the descriptions of these functions may be found on the following pages Serial Communication An extensive serial communication library supports simple ASCII communication communication protocols and serial port configuration The default communication mode uses the TeleBUS RTU communication pr
213. equested before calling this function See Also ISaGRAF C Tools User and Reference Manual May 8 2007 70 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 Notes The TeleBUS Protocols User Manual describes store and forward messaging mode The IO_SYSTEM resource must be requested before calling this function See Also getSFTranslation checkSFTranslationTable Example See the example for the setSFTranslation function ISaGRAF C Tools User and Reference Manual 71 May 8 2007 clearStatusBit Clear Bits in Controller Status Code Syntax include lt ctools h gt unsigned clearStatusBit unsigned 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 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
214. er 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 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 invalid only the valid registers are written Refer to the Functions Overview section for more information If the specified address is in the valid range but it has not been defined by an application then the address also is invalid An address is defined if any of the following is true 1 The address has been assigned as the Network Address for an ISaGRAF Dictionary variable The address is defined in a database handler installed by a C or C application The address is within the default range of the Permanent Non volatile Modbus Registers 40001 to 40000 NUMHOLDING_PERMANENT and 00001 to NUMCOIL_PERMANENT When this function is called the specified address is searched for under these three categories in the order listed above until the address is found If the address is not found nothing is done If the address is defined in more than one of these categories the first occurrence of the address in the order listed is always used Refer to the section Permanent Non Volatile Modbus Registers for details on potential addressing conflicts during application downloading The IO_SYSTEM resource must be requested before calling
215. erence Manual 284 May 8 2007 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 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 with the proper length It will be set to MM_RECEIVED_BAD_LENGTH when a response to the message is received with the improper length Notes Refer to the communication protocol manual for more information Users of TeleSAFE BASIC and the TeleSAFE 6000 C compiler should note that the address parameter now specifies the actual database address when used with the Modbus protocol This parameter specified the address offset on these older TeleSAFE products To optimize performance minimize the length of messages on com3 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and diagnostics using the ISaGRAF program The IO_SYSTEM resource must be requested before calling this function See Also clear_protocol_status Example 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 25 gt poll c Polling program for Modbus slave include lt ctools h gt es wait_for_response The wait_for_response function waits for a re
216. erence Manual 338 May 8 2007 runLed Control Run LED State Syntax include lt ctools h gt void runLed unsigned 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 ladder logic is installed in the controller a C program should not use this function The SCADASense series of programmable controllers do not have a Run Led Example include lt ctools h gt void main void runLed LED_ON program is running the rest of the code ISaGRAF C Tools User and Reference Manual 339 May 8 2007 save Write Parameters to EEPROM ISaGRAF Syntax include lt ctools h gt void save unsigned section Description The save function writes data from RAM to the specified section of the EEPROM Valid values for section are EEPROM_EVERY and EEPROM_RUN Notes The EEPROM_EVERY section is loaded whenever the controller is reset It is not used The EEPROM_RUN section is loaded from EEPROM to RAM when the controller is reset and the Run Service switch is in the RUN position Otherwise default information is used for this section This section contains e serial port configuration tables e protocol c
217. erial port a protocol handler must be created for the encapsulating protocol Set the protocol type for the port to NO_PROTOCOL to allow the custom handler to be used The function supports standard and extended addressing Configure the protocol settings for the serial port for the appropriate protocol The Modbus RTU checksum is not required in the command so the encapsulating protocol may omit them if they are not needed This may be useful in host devices that don t create a Modbus RTU message with checksum prior to encapsulation ISaGRAF C Tools User and Reference Manual 313 May 8 2007 The Modbus RTU checksum is included in the response to support encapsulating a complete Modbus RTU format message If the checksum is not needed by the encapsulating protocol the checksum bytes may be ignored See Also setProtocolSettings Example This example is taken from a protocol driver than encapsulates Modbus RTU messages in another protocol It shows how to pass the Modbus RTU command to the Modbus driver and obtain the response The example assumes the Modbus RTU messages are transmitted with the checksum The length of the checksum is subtracted when calling the processModbusCommand function The checksum is included when responding Contact Control Microsystems technical support department for a complete program that uses this function receive the packet in the encapsulating protocol verify the packet is valid
218. 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 Note that 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 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 See Also modemAbort modemAbortAll modemDial modemDialStatus modemlnit modemlnitEnd modemInitStatus modemNotification ISaGRAF C Tools User and Reference Manual 298 May 8 2007 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 s
219. es 1 stop bit Specifies 2 stop bits 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 Microtec Serial I O Functions These library functions are related to serial communication They are documented in the Microtec MCCM77 Documentation Set May 8 2007 fgetc reads a character from a stream fgets reads a string from a stream fputc writes a character to a stream fputs writes a string to a stream fread reads from a stream fwrite writes to a stream getc reads a character from a stream getchar reads a character from standard input device gets reads a string from a stream initport re initializes serial port printf formatted output to a stream putc writes a character to a stream putchar reads a character to standard output device ISaGRAF C Tools UserandReferenceManualssssi is sSsSSSSSS A puts writes a string to a stream scanf formatted input from a stream 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
220. ettings request_resource IO_SYSTEM set_port com2 get_port coml amp settings release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 354 May 8 2007 setProgramStatus Get Program Status Flag Syntax include lt ctools h gt void setProgramStatus unsigned 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 Notes There are two pre defined values for 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 See Also getProgramStatus Example See the example for getProgramStatus ISaGRAF C Tools User and Reference Manual 355 May 8 2007 set_protocol Set Communication Protocol Configuration Syntax include lt ctools h gt int set_protocol FILE stream struct prot_settings settings Description The set_protocol function sets protocol parameters stream must specify one of com1 com2 com3 or com4 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
221. f an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaRead5506Inputs Example This program writes the configuration data to a 5506 I O module include lt ctools h gt void main void ISaGRAF C Tools User and Reference Manual 267 May 8 2007 UINT16 inputType 8 UINT16 inputFilter UINT16 scanFrequency set analog input types to 4 20 mA inputType 0 3 inputType 1 3 inputType 2 3 inputType 3 3 inputType 4 3 inputType 5 3 inputType 6 3 inputType 7 3 set filter and frequency inputFilter 0 maximum filter scanFrequency 0 60 Hz Write configuration data to 5506 I O module request_resource IO_SYSTEM isaWrite55060utputs 1 inputType inputFilter scanFrequency release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 268 May 8 2007 isaWrite5601 Outputs Write to SCADAPack Lower I O Module Outputs Syntax include lt ctools h gt unsigned isaWrite56010utputs unsigned data Description The isaWrite5601 Outputs function writes data to the digital outputs of a 5601 I O Module SCADAPack lower I O module The first 12 bits of the specified 16 bit data value are written to the 12 digital outputs The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes Note that whe
222. f they are not If either parameter is not valid the default values are not changed The IO_SYSTEM resource must be requested before calling this function Example include lt ctools h gt void 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 ISaGRAF C Tools User and Reference Manual 282 May 8 2007 load Read Parameters from EEPROM Syntax include lt ctools h gt void load unsigned section Description The load function reads data from the specified section of the EEPROM into RAM Valid values for section are EEPROM_EVERY and EEPROM_RUN The save function writes data to the EEPROM Notes The IO_SYSTEM resource must be requested before calling this function The EEPROM_EVERY section is not used The EEPROM_RUN section is loaded from EEPROM to RAM when the controller is reset and the Run Service switch is in the RUN position Otherwise default information is used for this section This section contains e serial port configuration tables e protocol configuration tables See Also save ISaGRAF C Tools User and Reference Manual 283 May 8 2007 master_message Send Protocol Command Syntax include lt ctools h gt extern unsigned master_message FILE stream unsigne
223. f you find any errors or additional items you feel should be included in our documentation We sincerely hope that the reliability and flexibility afforded by this fully programmable controller enable you and your company to solve your automation problems in a cost effective and efficient manner The ISaGRAF C Tools include an ANSI C cross compiler a customized library of functions for industrial automation and data acquisition a real time operating system and the ISaGRAF C program loader The C function library is similar to many other C implementations but contains additional features for real time control digital and analog I O An overview of the application development environment and its features follows Program Development C programs are written using any text editor The MCCM77 compiler is used to compile assemble and link the programs on a personal computer The memory image which results from this process may then be loaded either into the RAM committed to an EPROM or both may be used together Programs may be executed either manually or automatically at power up Modularity Programs written in ISaGRAF C may be split into many separately compiled modules These modules may be tested individually before being linked together in the final program Command files specify how the various files are to be linked Assembly Language Code Assembly language source code may be included directly within C programs The asm and
224. for this task thisTask getTaskInfo 0 TRUE while allocate an envelope and address it to this task nvelope allocate_envelope nvelope gt destination thisTask taskID P CP Fl P request a timeout in 10 seconds timeoutID timeoutRequest 100 pEnvelope done FALSE while done wait for a message or a timeout pEnvelope receive_message j determine the message type if pEnvelope gt type MSG_TIMEOUT does it match the last request if pEnvelope gt data timeoutID accept the timeout done TRUE else cancel the timeout timeoutCancel timeoutID done TRUE process message from other task here return the envelope to the RTOS deallocate_envelope pEnvelope ISaGRAF C Tools User and Reference Manual 378 May 8 2007 proceed with rest of task s actions here ISaGRAF C Tools User and Reference Manual 379 May 8 2007 wait_event Wait for an Event Syntax include lt ctools h gt void wait_event int 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 informa
225. g call This prevents problems with 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 To optimize performance minimize the length of messages on com3 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and diagnostics using the ISAaGRAF program Do not call this function in a task exit handler ISaGRAF C Tools User and Reference Manual 296 May 8 2007 See Also modemAbort modemAbortAll modemDialEnd modemDialStatus modemInit modemlnitEnd modemInitStatus modemNotification Example Refer to the examples in the Functions Overview section ISaGRAF C Tools User and Reference Manual May 8 2007 297 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
226. gDelete Delete Data Log Function Syntax include lt ctools h gt BOOLEAN datalogDelete UINT16 logID 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 1ogID 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 See Also datalogCreate Example The following code shows the only way to change the configuration of an existing log is to delete the log and recreate the data log KI include lt ctools h gt int logID Declare a structure for the log 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 whole log and start from scratch if datalogDelete logID Re enter the log configuration 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 ISaGRAF C Tools User and Reference Manual 85 May 8 2007 dLogConfig typesOfFields 4 DLV_FLOAT datalogCreate l
227. ge 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 e owner is the task that owns the envelope This field is set by the RTOS and must not be changed by an application program HART_COMMAND 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 unsigned command unsigned length char data DATA_SIZE HART _COMMAND e command is the HART command number e length is the number of characters in the data string ISaGRAF C Tools User and Reference Manual 414 May 8 2007 e data DATA_SIZE is the data field for the command CI HART_DEVICE 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 struct har
228. getStatusBit function returns the values of the bits indicated by bitMask in the controller status code See Also setStatusBit setStatus clearStatusBit ISaGRAF C Tools User and Reference Manual 171 May 8 2007 getTaskinfo Get Information on a Task Syntax include lt ctools h gt TASKINFO getTaskInfo unsigned taskID Description The getTaskInfo function returns information about the task specified by task D If taskID is 0 the function returns information about the current task Notes If the specified task ID does not identify a valid task all fields in the return data are set to zero The calling function should check the taskID field in the TASKINFO structure if it is zero the remaining information is not valid Refer to the Structures and Types section for a description of the fields in the TASKINFO structure Example The following program displays information about all valid tasks include lt string h gt include lt ctools h gt void main void struct prot_settings settings TASKINFO taskStatus unsigned task char state 6 20 char type 2 20 Set up state strings strcpy state TS_READY Ready strcpy state TS_EXECUTING Executing strcpy state TS_WAIT_ENVELOPE Waiting for Envelope strcpy state TS_WAIT_EVENT Waiting for Event strcpy state TS_WAIT_MESSAGE Waiting for Message strcpy state TS_WAIT_RESOURCE Waiting for Resource Set up typ
229. 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 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 void main void struct prot_settings settings VERSION versionInfo Disable the protocol on serial port 1 settings type NO_PROTOCOL settings station T settings priority 3 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 ISaGRAF C Tools User and Reference Manual 174 May 8 2007 getWakeSource Gets Conditions for Waking from Sleep Mode Syntax include lt ctools h gt unsigned getWakeSource void Description The getWakeSource function returns a bit
230. gned priority unsigned status unsigned requirement unsigned error unsigned type TASKINFO e taskID is the identifier of the task e priority is the execution priority of the task e status is the current execution status the task This may be one of TS_READY TS_EXECUTING TS_WAIT_ENVELOPE TS_WAIT_EVENT TS_WAIT_MESSAGE or TS_WAIT_RESOURCE macros e 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 it is waiting If the status field is TS WAIT RESOURCE then requirement indicates on which resource it is waiting e error is the task error code This is the same value as returned by the check_error function e type is the task type It will be either SYSTEM or APPLICATION taskIinfo_tag The taskInfo_tag structure contains start up task information struct taskInfo_tag void address unsigned stack unsigned identity e address is the pointer to the start up routine e stack is the required stack size for the routine ISaGRAF C Tools User and Reference Manual 423 May 8 2007 e identity is the type of routine found STARTUP_APPLICATION or STARTUP_SYSTEM timer_info The timer _info structure contains information about a timer struct timer_info unsigned time unsigned interval unsigned interval_remaining unsigned flags unsigned duty_on unsigned duty_period unsigned channel unsigned bit
231. gram into the controller Each uses separate tools To demonstrate these steps a sample program will be prepared Refer to the C Program Development section for a full description of the program development process ISaGRAF C Tools User and Reference Manual 6 May 8 2007 Traditionally the first program that is run on a new C compiler is the hello world program It prints the message hello world Writing and Editing A controller C program is written using any text editor or word processor in text mode The syntax should correspond to that described in the Microtec MCCM77 Documentation Set and the C Program Development section of this manual This chapter describes non standard functions which are unique to the controller It should be read carefully to make full use of the special purpose routines available Using your text editor open the file he11lo c file It is located in the telepace ctools 520x directory The program looks a little different from the traditional hello world program Pe th er ee ee ee hello c SCADAPack and TeleSAFE Microl6 Test Program The infamous hello world program include lt ctools h gt void main void PROTOCOL_SETTINGS settings Disable the protocol on serial port 1 settings type NO_PROTOCOL settings station 1 settings mode AM_standard settings priority 35 settings SFMessaging setProtocolSettings coml amp settings FALSE Print the mess
232. h 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 Register Assignment uses bits 0 and 1 of the status code See Also clearStatusBit clearStatusBit getStatusBit ISaGRAF C Tools User and Reference Manual 364 May 8 2007 settimer Set a Timer Syntax include lt ctools h gt void settimer unsigned timer unsigned value Description The settimer function loads value into timer specified by timer The timer counts down at the timer interval frequency The settimer function can reset a timer before it has finished counting down Notes The settimer function cancels delayed digital I O actions started with the timeout pulse and pulse_train functions See Also interval Example This code fragment sets timer 8 for 10 seconds using an interval of 0 5 seconds interval 8 5 interval 1 2 second settimer 8 20 10 second timer This code fragment sets timer 9 for 60 seconds using an interval of 1 0 seconds interval 9 10 interval 1 second settimer 9 60 60 second timer ISaGRAF C Tools User and Reference Manual 365 May 8 2007 setWakeSource Sets Conditions for Waking from Sleep Mode Syntax include lt ctools h gt void setWakeSo
233. handler must not write beyond the end of the buffer If the handler returns TRUE it must set this variable The data must start with the function code and end with the last 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 EGAL_FUNCTION Indicates protocol handler should send an Illegal ISaGRAF C Tools User and Reference Manual 149 May 8 2007 EGAL DATA_ADDR EGAL DATA_VALU Function exception response message This response should be used when the function code in the command is not recognized 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 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 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 l
234. handler will be corrupted and the system will likely crash See Also setdbase installDbaseHandler ISaGRAF C Tools User and Reference Manual 195 May 8 2007 Example See example for Setdbase Handler Function ISaGRAF C Tools User and Reference Manual 196 May 8 2007 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 ISaGRAF Dictionary The function can have any name dbaseHandler is used in the description below Syntax include lt ctools h gt BOOLEAN dbaseHandler unsigned address int value Description This function is called by the dbase function when one of the following conditions apply e There is no ISaGRAF application downloaded or e There is no ISaGRAF 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 must return TRUE and the value pointed to by value must be set to the current value for the specified Modbus address If the address is not to be handled the function must return FALSE and the value pointed to by value must be left unchanged Notes The IO_SYSTEM resource must be requested before calling dbase which calls this handler Reque
235. he Network Address for an ISaGRAF Dictionary variable The address is defined in a database handler installed by a C or C application The address is within the default range of the Permanent Non volatile Modbus Registers 40001 to 40000 NUMHOLDING_PERMANENT and 00001 to NUMCOIL_PERMANENT When this function is called the specified address is searched for under these three categories in the order listed above until the address is found If the address is not found FALSE is returned If the address is defined in more than one of these categories the first occurrence of the address in the order listed is always used Notes Refer to the section Permanent Non Volatile Modbus Registers for details on potential addressing conflicts during application downloading The IO_SYSTEM resource must be requested before calling this function See Also databaseWrite setdbase Example include lt ctools h gt void main void ISaGRAF C Tools User and Reference Manual 79 May 8 2007 INT BOO 16 value EAN status req sta sta sta sta sta rel uest_resource IO_SYSTEM Read Modbus status input point tus databaseRead MODBUS 10001 amp value Read 16 bit register tus databaseRead LINEAR 3020 amp value Read 16 bit register beginning at first tus register tus databaseRead LINEAR START_STATUS amp value Read 6th input register tus datab
236. he Structures and Types section Notes The TeleBUS Protocols User Manual describes store and forward messaging mode See Also clearSFTranslationTable checkSFTranslationTable Example See the example for the setSFTranslation function ISaGRAF C Tools User and Reference Manual 169 May 8 2007 g et_stat us 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 stream does not point to 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 that 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 void main void struct pstatus status get_status coml amp status printf Framing Sd r n status framing printf Parity d r n status parity ISaGRAF C Tools User and Reference Manual 170 May 8 2007 getStatusBit Read Bits in Controller Status Code Syntax include lt ctools h gt unsigned getStatusBit unsigned bitMask Description The
237. he controller is making a connection to a remote controller e DS_Connected returns the controller is connected to a remote controller e DS_Terminating returns the controller is ending a connection to a remote controller dnpAnaloginput 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 dnpAnalogInput e modbusAddress is the address of the Modbus register number 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 e deadband is the amount by which the analog input value must change before an event will be reported for the point dnpAnalogOutput 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 dnpBinarylnput The dnpBinaryInput 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 ISaGRAF C Tools User and Reference Manual 4
238. he 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 SCADAPack Real Time Operating System Sample Copyright c 1998 Control Microsystems Inc Version History version 1 00 Wayne Johnston November 10 1998 Beeches Ee SU eee ee eee ee eee ee ee ee fe Versi en I 00 sss ssoss Ses SSS SSS SSS SSS SS SSS SaaS Se SaaS SaaS This program creates several simple tasks for demonstration of the functionality of the real time operation system Bere Se ee ee E E ee ee ee include lt mriext h gt include lt stdio h gt include ctools h Pde pe eR 2 2a 8 Sak Soe Sak SE S258 Bae SoS 52 3E Sank SSE Sank eB See se Constants Soham een Bee ea eee ae ate eae in Aa e
239. ic messages Th is option provides additional warnings that allow you to detect potential errors in your source code before running the program M1 ISaGRAF C Tools User and Reference Manual May 8 2007 Compile for large memory model note that the character following the 13 Mis a lower case ell Compiler output is an object file The following options may be useful Option Description _ o y Specify the directory containing the standard include files Adding Jc telepace ctools 520x to the command line allows you to locate your application program files in a different directory This helps in organizing your files if you have more than one application program Enable standard optimizations This produces smaller and faster executable code Ot Optimize in favor of execution time rather than code size where a choice can be made Pop the stack after each function call This increases code size and execution time This option should only be used if there is a large number of consecutive function calls in your program A large number of consecutive calls requires a large stack allocation for a task Since the number of stack blocks is limited using this option can reduce the stack requirements for a task See the description for the create_task function for more information Each module in an application should be compiled to produce an object file The object files are then linked together to form an
240. ied 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 description in the Structures and Types section for a complete description of error codes Notes The serial port type must be set to RS232_MODEM Note The SCADAPack 100 does not support dial up connections on com port 1 The SCADASense family of controllers also do not support dial up connections The modemDialStatus function returns the status of the connection attempt initiated by modemDial The modemDialEnd function terminates the connection to the remote controller Note that 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 amodemlnit 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 incomin
241. ields 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 ISaGRAF C Tools User and Reference Manual 344 May 8 2007 setBootType Set Controller Boot Up State Syntax include lt ctools h gt void setBootType unsigned type Description The setBootType function defines the controller boot up type code This function is used by the operating system start up routines It should not be used in an application program Notes The value set with this function can be read with the getBootType function ISaGRAF C Tools User and Reference Manual 345 May 8 2007 setclock Set Real Time Clock Syntax include lt ctools h gt void setclock struct clock now Description The setclock function sets the real time clock now references a clock 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 must be set with valid values for the clock to operate properly No
242. if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function See Also isaRead8Din Example This program displays the values of the 16 digital inputs read from a 16 point Digital Input Module at module address 0 include lt ctools h gt void main void unsigned point unsigned dinData Read data from digital input module request_resource IO_SYSTEM isaRead1l6Din 0 amp dinData release_resource IO_SYSTEM Print module data fprintf coml Point Value for point 0 point lt 16 point fprintf coml n r d point putchar dinData amp 0x0001 1l 0 dinData gt gt 1 ISaGRAF C Tools User and Reference Manual 229 May 8 2007 isaRead32Din Read 32 Digital Inputs Syntax include lt ctools h gt unsigned isaRead32Din UINT16 moduleAddress UINT32 data Description The isaRead32Din function reads any 32 point Digital Input Module at the specified moduleAddress Data is read from all 32 digital inputs and copied to the 32 bit value pointed to by data The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The lO_SYSTEM resource must be requested before calling this function See Also isaRead8
243. ifying the statement WORD 4 stack size in blocks Refer to the Real Time Operating System section for more information on the stack required by tasks The appstart function begins by initializing the heap pointers setting all non initialized variables to zero and initializing system variables It then starts the communication protocols for each serial port according to the stored values in the EEPROM or the standard values on a SERVICE boot If your application program never uses the communication protocols some or all of the following commands can be removed to free the stack space used by the protocol tasks start_protocol coml1 start_protocol com2 start_protocol com3 start_protocol com4 The background I O task is required for the timer functions dial up modem communications and PID controller functions to operate If you do not intend to use these functions you can reduce the CPU load by changing TRUE to FALSE in the following statement runBackgroundI0O TRUE The ladder logic interpreter is required for ladder logic programs If you do not intend to use ladder logic you can reduce the CPU load by changing TRUE to FALSE in the following statement RunTarget TRUE r The final operation is execution of the main function The _initcopy function copies the initial values for initialized variables from the __INITDATA section in the program to the variables If there are no errors in the data
244. iiee 6 C PROGRAM DEVELOPMENT si sissaacchssonscasisostuesoinnasdessvsutespninaudooncsiuatsovavaianaindiabcseaiaatsanbead 10 REAL TIME OPERATING SYSTEM siiasssisssshsssctsasesaiestndueuianssscatconsasasaledanntuespsbatisusyatenteaiiens 18 OVERVIEW OF PROGRAMMING FUNCTIONS sscssssssssssesssesseessesssessneeseesneesnessneesneesnss 32 ISAGRAF C TOOLS FUNCTION SPECIFICATIONG ssssssssesssessnsssssssssssessseesseensesseesseenss 63 ISAGRAF C TOOLS MACRO DEFINITIONS scssssssssssssssessnssssssseesseesseenensnensneeseenensneess 391 ISAGRAF C TOOLS STRUCTURES AND TYPES sssssssssssssssssessesssesneesseesseeneesnensneess 400 C COMPILER KNOWN PROBLEMG s ssssssssssesssessnessnsesnsssnsesesssessseensseacesseesseenseenensneees 426 ISAGRAF C TOOLS WARRANTY AND LICENSE ssssssssssssssssesssesssesneessesssenseesnensneess 429 ISaGRAF C Tools User and Reference Manual S 2 May 8 2007 ISaGRAF C Tools Overview The ISaGRAF C Tools are ideal for engineers and programmers who require advanced programming tools for SCADA applications and process control The SCADAPack and Micro16 families of controllers execute ISaGRAF and C application programs simultaneously providing you with maximum flexibility in implementing your control strategy This manual provides full documentation on the ISaGRAF C program loader and the library of C language process control and SCADA functions We strongly encourage you to read it and to notify us i
245. ime e holdCount See Also dnpGetConfiguration Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual 136 May 8 2007 dnpSaveConfigurationEx Write DNP Extended Configuration Syntax BOOLEAN dnpSaveConfiguration dnpConfigurationEx pD Description Ex npConfiguration a 6X 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 must be enabled before calling this function in order to create the DNP configuration This function supersedes the dnpSaveConfiguration function ISaGRAF C Tools User and Reference Manual May 8 2007 137 dnpSendUnsolicited Send DNP Unsolicited Response Syntax include lt ctools h gt UINT16 dnpSendUnsolicitedResponse UINT16 classFlags i Description The dnpSendUnsolicitedResponse function sends an Unsolicited Response message in DNP protocol with data from the specified class es e class specifies the class es of event data to include in the message e Allowed values are define CLASSO_FLAG 0x01 eh define CLASS1_ FLAG 0x02 i define CLASS2_ FLAG 0x04 af define CLASS3_FLAG 0x08 flag for enabling C
246. ime clock as wake up source WS UN DEFINE Undefined wake up source ISaGRAF C Tools User and Reference Manual 399 May 8 2007 ISaGRAF C Tools Structures and Types ABConfiguration The ABConfiguration structure defines settings for DF1 communication protocol DF1 Protocol Configuration struct ABConfiguration unsigned min_protected_address unsigned max_protected_address e min_protected_address is the minimum allowable DF1 physical 16 bit address allowed in all protected commands The default value is 0 e max_protected_address is the maximum allowable DF1 physical 16 bit address allowed in all protected commands The default value is NUMAB ADDRESS_MODE The ADDRESS_MODE enumerated type describes addressing modes for communication protocols typedef enum addressMode_t AM_standard 0 AM_extended ADDRESS_MODE 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 ALARM 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
247. inData gt gt 1 ISaGRAF C Tools User and Reference Manual 251 May 8 2007 isaReadLPinputs Read SCADAPack LP Inputs Syntax include lt ctools h gt unsigned isaReadLPInputs unsigned dinData int ainDataArray Description The isaReadLPInputs function reads the digital and analog inputs from SCADAPack LP I O Data is read from all 16 digital inputs and copied to the 16 bit value pointed to by dinData Data is read from all 8 analog inputs and copied to the array pointed to by ainDataArray dinData must point to a 16 bit integer ainDataArray must point to an array of eight 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function reads data from the SCADAPack LP I O it also processes the receiver buffer for the com3 serial port The com serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaWriteLPOutputs Example This program displays the values of the 16 digital inputs and 8 analog inputs read from the SCADAPack LP I O include lt ctools h gt void main void unsigned point unsigned dinData int ainDataArray 8 Read input data from SCADAPack LP I O request_resource IO_SYSTEM isaReadLPInputs amp dinData ainDataA
248. 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 readThermistor Read the controller ambient temperature sensor readinternalAD Read the controller internal AD converter ioRead4Ain read 4 analog inputs into I O database ioRead8Ain read 8 analog inputs into I O database IsaRead4202Inputs Read the digital and analog inputs from a SCADASense DR Series IsaRead4202DSInputs Read the digital and analog inputs from a SCADASense DS Series isaRead5505Inputs Read the digital and analog inputs from a 5505 I O Module isaRead5506Inputs Read the digital and analog inputs from a 5506 I O Module isaRead5601Inputs Read the digital and analog inputs from a 5601 I O Module isaRead5602Inputs Read the digital and analog inputs from a 5602 I O Module isaRead5604Inputs Read the digital and analog inputs from 5604 I O module isaRead5606Inputs Read the digital and analog inputs from 5606 I O module isaReadLPInputs Read the digital and analog inputs from SCADAPack LP I O isaReadSP100Inputs Read the digital and analog inputs from SCADAPack 100 I O Analog Input Macros The ctools h file defines the following macros for use with controller analog inputs Refer to the C Tools Macros section for details on each macro listed
249. ings priority printf Enron d r n settings enronEnabled printf Enron station d r n settings enronStation else printf Serial port is not valid r n ISaGRAF C Tools User and Reference Manual 166 May 8 2007 ISaGRAF C Tools User and Reference Manual 167 May 8 2007 get_protocol_status Get Protocol Information Syntax include lt ctools h gt struct prot_status get_protocol_status FILE stream Description The get_protocol_status function returns the protocol error and message counters for stream f 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 void main void struct prot_status status status get_protocol_status com2 printf Checksum d r n status checksum_errors ISaGRAF C Tools User and Reference Manual 168 May 8 2007 getSFTranslation Read Store and Forward Translation Syntax include lt ctools h gt struct SFTranslation getSFTranslation unsigned index Description The getSFTranslation function returns the entry at index in the store and forward address translation table If index is invalid a disabled table entry is returned The function returns a SFTranslation structure It is described in t
250. ion e Personal computer using 80386 or higher microprocessor e Microsoft Windows operating system versions including Windows 2000 NT and XP e Minimum 4 MB of memory e Mouse or compatible pointing device e Hard disk with approximately 2 5 Mbytes of free disk space Making Backup Disks You should make a backup copy of the Microtec C compiler disks before using the software A backup copy protects you against damage to the disk Always work with the backup copy if it fails you can make a new copy from the original disk Store the original disk in a safe location To make a backup off a floppy disk on Microsoft Windows XP e Start Windows Explorer Right click on Windows Start and select Explore e Right click on the floppy disk and select Copy Disk e Select the source and destination disk drives Click on the OK button Installation of C Compiler Install the Microtec C compiler as described in the installation manuals supplied with the system Be sure to add all the required variables to the DOS environment Installation of ISaGRAF Install ISaGRAF as described in the installation section of the SaGRAF Reference and User Manual Some virus checking software may interfere with Setup If you experience problems with the Setup disable your virus checker and run Setup again Program Development Tutorial Program development consists of three stages writing and editing compiling and linking and loading the pro
251. ion code Result code translation is already defined in the table Result code invalid translation table index Result code entry does not define a translation 55 SF_PORT_OUT_OF_RANGE Result code serial port is not valid SF_STATION_OUT_OF_RANGE Result code station number is not valid SF_TABLE_SIZE Number of entries in the store and forward table SF_VALID Result code translation is valid 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 Modbus Database The Modbus database is a user defined database that allows data to be shared between ISaGRAF C programs ISaGRAF programs and communication protocols Two modes of addressing are supported for the database Modbus and Linear The following table shows the addresses available for each type of addressing Modbus Address Data Type Linear Word Address 00001 to 09999 boolean 0 to 624 1 returned if any variable is non zero 0 returned if variable is 0 10001 to 19999 boolean 625 to 1249 1 retu
252. ion from a remote device 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 ISaGRAF C Tools User and Reference Manual 52 May 8 2007 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 ISaGRAF programming software or from another Modbus or DF 1 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 as a normal serial port The DF1 option enables the emulation of the DF1 protocols 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 comm
253. ion 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 M a ee a a Se Nm a a Ry Oe a a This program demonstrates how to call a function at a specific time of day gt m bhis araki include lt ctools h gt define ALARM_EVENT 20 See z ERS y This function signals an event when the alarm occurs void alarmHandler void interrupt_signal_event ALARM_EVENT a aS _ Poe This task processes alarms signaled by the clock handler aa aa gp eS E E ER 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 ISaGRAF C Tools User and Reference Manual 192 May 8 2007 fprintf coml It s quitting time r n void 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 3 settings SFMessaging FALSE request_resource IO_SYSTEM set_protocol coml amp setting
254. ion programs because it updates several timers that can be used in application programs It also triggers the background I O task The background I O task is the highest priority task in the system It processes software timers PID controllers and dialup modem control routines There is one protocol task for each serial port where a protocol is enabled The protocol tasks wait for an event signaled by an interrupt handler This event is signaled when a complete message is received The protocol tasks process the received message and transmit a response when needed Protocol tasks may be disabled and replaced with protocol tasks from the application program The Ladder Logic and I O Scan task executes the Ladder Logic program and performs an I O scan based on the register assignment This task is the same priority as the main user application task ISaGRAF C Tools User and Reference Manual 24 May 8 2007 The main task is the central task of the user application It performs the functions required by the user Typically it executes at the same priority as the Ladder Logic and I O Scan task It may start other user tasks if needed 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 T
255. irection 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 ISaGRAF C Tools User and Reference Manual 74 May 8 2007 createRoutingTable Create Routing Table Syntax include lt ctools h gt BOOLEAN createRoutingTable 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 must 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 dnpSendUnsolicited section ISaGRAF C Tools User and Reference Manual May 8 2007 75 create_task Create a New Task Syntax include lt ctools h gt int create_task void function unsigned priority unsigned type unsigned 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 higher than the current task priority is an execution priority between 1 and 4 for the created task The 4 task priority levels aid in scheduling task execution type specifies if the task is ended when an application progr
256. is also continuously processed automatically The additional service to the com4 transmitter caused by this function does not affect the normal automatic operation of com4 The IO_SYSTEM resource must be requested before calling this function See Also isaRead5602Inputs Example This program turns ON both digital outputs of a 5602 I O Module include lt ctools h gt void main void Write output data to 5602 I O module request_resource IO_SYSTEM isaWrite56020utputs 0x03 release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 270 May 8 2007 isaWrite56040Outputs Write to 5604 Outputs Syntax include lt ctools h gt unsigned isaWrite56040utputs UCHAR doutData INT16 aoutData Description The isaWrite56040utputs function writes data to the digital and analog outputs of the 5604 I O module doutData must point to an array of five 8 bit unsigned characters Each bit in the array represents one output point The first 36 bits of the array are written to the 36 digital outputs aoutData must point to an array of two 16 bit integers Analog data from this array are written to the two analog outputs The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function writes data to the 5604 I O it also processes the transmit buffer for the coms serial port The com3 serial port is also continuously processed automatica
257. is function The first four analog inputs are read from the external analog inputs The fifth and sixth analog inputs are read from the temperature sensor and the battery voltage sensor respectively See Also isaWriteSP1000Outputs Example This program displays the values of the 6 digital inputs 6 analog inputs and one counter input read from the SCADAPack 100 I O include lt ctools h gt void main void unsigned point unsigned dinData int ainDataArray 6 unsigned long cinData Read input data from SCADAPack 100 I O request_resource IO_SYSTEM isaReadSP100Inputs amp dinData ainDataArray amp cinData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 254 May 8 2007 Print digital input data for point 0 point lt 6 point if dinData amp 0x0001 fprintf coml DIN d 1 r n point fprintf coml DIN d O r n point dinData gt gt 1 fprintf com1 r n Print analog input data for point 0 point lt 6 point fprintf com1 AIN d Sd n r point ainDataArray point fprintf coml r n Print counter input data fprintf coml r nCounter Sul n r cinData ISaGRAF C Tools User and Reference Manual May 8 2007 255 isaWrite16Dout Write to 16 Digital Outputs Syntax include lt ctools h gt unsigned isaWritel6Dout unsigned moduleAddress
258. is the analog output value The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function writes data to the SCADASense 4202 DR I O it also processes the transmit buffer for the com3 serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaRead4202Inputs Example This program sets the analog output to full scale and turns on the digital output include lt ctools h gt void main void unsigned digitalData int analogData turn on digital output digitalData 0x01 set analog output to full scale analogData 32767 Write output data to 4202 DR outputs request_resource IO_SYSTEM isaWrite42020utputsEx digitalData analogData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 262 May 8 2007 isaWrite4202DSOutputs Write to SCADASense 4202 DS Outputs Syntax include lt ctools h gt unsigned isaWrite4202DSoutputs unsigned doutData Description The isaWrite4202DSOutputs function writes data to the outputs of the SCADASense 4202 DS I O doutData is the digital output value Bits 0 and 1 of the value control the digital outputs If a bit is 1 the corresponding
259. it integer ainDataArray must point to an array of eight 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes Note that when this function reads data from the 5601 it also processes the receiver buffer for the com3 serial port If the controller type is a SCADAPack or SCADAPack PLUS the coms serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaWrite5601 Outputs Example This program displays the values of the 16 digital inputs and 8 analog inputs read from a 5601 I O Module include lt ctools h gt void main void unsigned point unsigned dinData int ainDataArray 8 Read input data from 5601 module request_resource IO_SYSTEM isaRead560lInputs amp dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r for point 0 point lt 16 point fprintf coml n r d M point putchar dinData amp 0x0001 1 0O dinData gt gt 1 ISaGRAF C Tools User and Reference Manual 242 May 8 2007 Print analog input data fprintf com1 r nAin Point Value n r for point 0 point lt 8 point fprintf com1 d Sd n r point ainD
260. ital input channel Number of first regular digital input channel DIO_ DISABLE DO Specifies flow control is disabled Specifies the DNP protocol for the serial port Variable name decrease output as malloc alloc and zalloc Modem initialization failed the modem may be turned off DE_NoDialTone Modem did not detect a dial tone or the S6 setting in DE_NoModem The serial port is not configured as a modem port type must be RS232_MODEM Or no modem is connected DE_Not InControl The serial port is in use by another modem function or ST SUPPORTED If defined indicates digital I O hardware supported DOUT_END Number of last regular digital output channel Number of first regular digital output channel DS_Calling The controller is making a connection to a remote The controller is connected to a remote controller The serial port is not in use by a modem DS_Terminating The controller is ending a connection to a remote DUTY_CYCLE Specifies timer is generating square wave output DYNAMIC_MEMORY System resource all memory allocation functions such ISaGRAF C Tools User and Reference Manual May 8 2007 EEPROM section loaded to RAM on every CPU reboot EE RUN EEPROM section loaded to RAM on RUN type boots only EEPROM_SUPPORTED If defined indicates that there is an EEPROM in the controller 393 Specifies flow control is enabled Variable name
261. kInfo 0 installExitHandler taskStatus taskID shutdown start timed event to occur every 10 sec startTimedEvent TIME_TO_PRINT 100 interval 0 10 while TRUE body of main task loop other processing code Allow other tasks to execute ISaGRAF C Tools User and Reference Manual 77 May 8 2007 release_processor ISaGRAF C Tools User and Reference Manual May 8 2007 78 databaseRead Read Value from I O Database Syntax include lt ctools h gt BOOLEAN databaseRead UINT16 type UINT16 address INT16 value Description The databaseRead function reads a value from the database type specifies the method of addressing the database address specifies the location in the database If the specified address is valid then TRUE is returned and the value is copied to the variable pointed to by value lf the specified address is not valid then FALSE is returned and the variable pointed to by value is left unchanged 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 If the specified address is in the valid range but it has not been defined by an application then the address is also invalid An address is defined if any of the following is true 1 The address has been assigned as t
262. ke up source WS_NONE No wake up source enabled WS_REAL_TIME_CLOCK Bit mask to enable real time clock as wake up source WS_UNDEFINED Undefined wake up source Power Management Functions Under normal operation the SCADAPack 350 operates on a CPU clock frequency of 32 MHz However the SCADAPack 350 controller is capable of operating on a reduced CPU clock frequency of 8 MHz known as Reduced Power Mode Further power savings can be realized on the SCADAPack 350 controller by disabling the LAN or USB peripheral and host ports Activation of Reduced Power mode as well as the deactivation of the communication ports can be performed by the application program The library functions associated with the aforementioned power management allows for the following e The CPU speed can be changed from full speed 32 MHz to reduced speed 8 MHz e The LAN port can be enabled or disabled e The USB peripheral port can be enabled or disabled ISaGRAF C Tools User and Reference Manual 34 May 8 2007 e The USB host port can be enabled or disabled The Power Mode LED blinks once a second when the controller is operating in Reduced Power Mode The library functions associated with the power management features are listed below Refer to the Function Specification section for details on each function listed getPowerMode Gets the current power mode setPowerMode Sets the power mode Power Management Macros The ctools h file defines the following mac
263. l section NUMCOIL_PERMANENT Number of coil registers in the Permanent Non Volatile Modbus Registers section NUMHOLDING Number of registers in the Modbus holding register section NUMHOLDING_PERMANENT Number of holding registers in the Permanent Non Volatile Modbus Registers 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 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 Modbus Addressing When a Modbus protocol accesses a Modbus register in the controller the register address is searched for under three categories in the order listed below until the address is found Search Category Address Search Algorithm Order Range Available ISaGRAF 00001 to 09999 If the address is not assigned to a Dictionary 10001 to 19999 variable in the ISaGRAF Dictionary Variables 30001 to 39999 then search next category 40001 to 49999 Database 30001 to 39999 C C application e g Flow Handler 40001 to 49999 Computer then search next category Permanent 00001 to 00128 If the address is not in the range of Non Volatile 40001 to 40200 Permanent Non volatile Modbus Modbus
264. larm Sets real time clock alarm Real Time Clock Macros The ctools h file defines the following macros for real time clock alarms Refer to the C Tools Macros section for details on each macro listed AT_ABSOLUTE Specifies a fixed time of day alarm AT_NONE Disables alarms 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 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 must be set with valid values for the clock to operate properly include lt ctools h gt void main void struct clock now Set to 12 01 00 on January 1 1994 now hour 2 set the time now minute now second now day now month now year now dayofweek set the date day is Sat request_resource IO_SYSTEM setclock amp now now getclock release_resource IO_SYSTEM Display current hour minute and second printf S2d 2d 52d now hour now minute now second 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 stop
265. lass 0 Unsolicited Responses flag for enabling Class 1 Unsolicited Responses flag for enabling Class 2 Unsolicited Responses flag for enabling Class 3 Unsolicited Responses DNP must be enabled before calling this function in order to create the DNP configuration Example te SCADAPack 32 C Application Main Program Copyright 2001 2002 This app was written for a ScadaPack 32P Control Microsystems Inc Test application for new DNP API Functions written by James Wiles May 2003 running DNP on comm port 5 include lt ctools h gt include lt string h gt fees ae i Tur DET Se ne a te Constants ees 2 ae ae eee fete 2 Event Triggers tects when thes erforms the specified action and clears th This application d then p efi define CLEAR_EVENTS define GENERATE _BI_EVENT channel 0 registers have been set register 100 Clear all DNP Event Log Buffers 101 Generate a change event for BI ISaGRAF C Tools User and Reference Manual May 8 2007 138 define GENERATE_AI16_EVENT bit AI channel 0 define CLASSO_REPORT 0 data Status Flags Kof mi 102 Generate a change event for 16 103 Send an unsolicited report of Class define EVENTS_CLASS1 110 define EVENTS _CLASS2 111
266. lave device ISaGRAF C Tools User and Reference Manual 62 May 8 2007 ISaGRAF C Tools Function Specifications The controller C function specifications are formatted as follows The functions are listed alphabetically Name Each specification begins with the name of the function and a brief description Syntax The syntax shows a prototype for the function indicating the return type and the types of its arguments Any necessary header files are listed Description This defines the calling parameters for the function and its return values Notes This section contains additional information on the function and considerations for its use See Also This section lists related functions Example The example gives a brief sample of the use of the function ISaGRAF C Tools User and Reference Manual May 8 2007 63 alarmin Determine Alarm Time from Elapsed Time Syntax include lt ctools h gt ALARM_SETTING alarmIn unsigned hours unsigned minutes unsigned 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 struc
267. leUnsolicitedOnStartup enables or disables unsolicited reporting at start up e SendUnsolicitedOnStartup sends an unsolicited report at start up e level2Compliance reports only level 2 compliant data types excludes floats AO 32 e MasterAddressCount is the number of master stations e masterAddress 8 is the number of master station addresses e MaxEventsInResponse is the maximum number of change events to include in read response e PSTNDialAttempts is the maximum number of dial attempts to establish a PSTN connection e PSTNDialTimeout is the maximum time after initiating a PSTN dial sequence to wait for a carrier signal e PSTNPauseTime is the pause time between dial events e PSTNOnlineInactivity is the maximum time after message activity to leave a PSTN connection open before hanging up e PSTNDialType is the dial type tone or pulse dialling e modemInitString 64 is the initialization string to send to the modem dnpCounterInput The dnpCounterInput type describes a DNP counter input point This type is used for both 16 bit and 32 bit points typedef struct dnpCounterInput_type UINT16 modbusAddress UCHAR class UINT32 threshold dnpCounterInput ISaGRAF C Tools User and Reference Manual 412 May 8 2007 e modbusAddress is the address of the Modbus register number associated with the point e class is the reporting class for the object It may be set to CLASS_1 CLAS
268. ll be temporarily uninstalled If a protocol accesses the controller while the handler is uninstalled the protocol will search and find a different value for the register under the Permanent Non Volatile Registers If this scenario is expected only define registers in a database handler for addresses outside the range of Permanent Registers Permanent Non Volatile Modbus Registers By default the controller has a selection of Modbus registers already defined These are the Permanent Non volatile Modbus Registers and consist of the following ISaGRAF C Tools User and Reference Manual 58 May 8 2007 Register Type Address Range Coil Registers 00001 to 10128 Holding Registers 40001 to 40200 These registers reside in non volatile memory so they retain their values when the controller is reset or while an ISaGRAF application or C C application is being downloaded These registers may be used to store data during application downloads To initialize all Permanent Registers to zero select Initialize Controller from the Initialize Controller dialog This dialog is selected using the Controller Initialize command from the Tools menu on the Programs window The Permanent Registers are also set to zero ona Cold Boot DNP Communication Protocol DNP the Distributed Network Protocol is a standards based communications protocol developed to achieve interoperability among systems in the electric utility oil amp gas water waste wate
269. lly The additional service to the com3 transmitter caused by this function does not affect the normal automatic operation of coms The IO_SYSTEM resource must be requested before calling this function See Also isaRead5604Inputs Example This program turns on all 32 digital outputs and sets the analog outputs to full scale The internal digital outputs are turned off include lt ctools h gt void main void UCHAR digitalData 5 INT16 analogData 2 turn on all external digital outputs digitalData 0 OxFF digitalData 1 OxFF digitalData 2 OxFF digitalData 3 OxFF turn off all internal digital outputs digitalData 4 0x00 set analog outputs to full scale ISaGRAF C Tools User and Reference Manual 271 May 8 2007 analogData 0 32767 analogData 1 32767 Write output data to 5604 I O request_resource IO_SYSTEM isaWrite56040utputs digitalData analogData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 272 May 8 2007 isaWrite5606Outputs Write to 5606 Outputs Syntax include lt ctools h gt unsigned isaWrite5606O0utputs UINT16 moduleAddress UCHAR doutData INT16 aoutData UINT16 inputType UINT16 inputFilter UINT16 scanFrequency UINT16 outputType Description The isaWrite56060utputs function writes data to the digital and analog outputs of the 5606 I O module and c
270. ls User and Reference Manual 165 May 8 2007 getProtocolSettingsEx Reads extended protocol settings for a serial port Syntax include lt ctools h gt BOOLEAN getProtocolSettingsEx FILE stream PROTOCOL_SETTINGS_EX pSettings i 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 stream specifies the serial port It is one of com1 com2 coms3 or com4 e pSettings is a pointer to a PROTOCOL_SETTINGS_ExX structure Refer to the 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 Example This program displays the protocol configuration for com1 include lt ctools h gt void main void PROTOCOL_SETTINGS_EX settings if getProtocolSettingsEx coml amp settings printf Type d r n settings type printf Station d r n settings station printf Address Mode d r n settings mode printf SF Sd r n settings SFMessaging printf Priority d r n sett
271. ls User and Reference Manual 326 May 8 2007 readStopwatch Read Stopwatch Timer Syntax include lt ctools h gt unsigned long 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 497 days See Also settimer timer Example This program measures the execution time in ms of an operation include lt ctools h gt void main void unsigned long startTime endTime startTime readStopwatch operation to be timed endTime readStopwatch printf Execution time lu ms r n endTime startTime ISaGRAF C Tools User and Reference Manual 327 May 8 2007 readThermistor Read Controller Ambient Temperature Syntax include lt ctools h gt int readThermistor unsigned 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 ctools h gt void void checkTemperatur int temperature readThermistor T_FAHRE temperatur HE if temperature l
272. lustrates both types of execution Task execution is based upon the priority of tasks There are 5 priority levels Level 0 is reserved for the null task This task runs when there are no other tasks available for execution Application programs can use levels 1 to 4 The main task is created at priority level 1 Tasks that are not running are held in queues The Ready Queue holds all 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 queue the Event 10 queue and the executing task These are the only queues relevant to the example Execution Point 1 This point occurs just before the main task begins The main task has not been created by the RTOS The nu11 task has been created but is not running No task is executing Ready Queue Event 10 Queue Running Task 4 gt 4 gt none zpr 3 gt L2 2 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
273. m for 24 hours after the current alarm Notes This function should be called after a real time clock alarm occurs This includes after returning from the sleep function with a return code of WS_REAL_TIME_CLOCK The alarm time is not changed by this function The IO_SYSTEM resource must be requested before calling this function See Also setClockAlarm getClockAlarm alarmin Example See the example for the installClockHandler function ISaGRAF C Tools User and Reference Manual 337 May 8 2007 route Redirect Standard I O Streams Syntax include lt ctools h gt void route FILE logical FILE 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 ogical specifies the stream to redirect hardware specifies the hardware device which will output the data It may be one of com1 com2 coms or com4 Notes This function has a global effect so all tasks must agree on the routing Output streams must be redirected to a device that supports output Input streams must be redirected to a device that supports input Example This program segment will redirect all input output and errors to the com2 serial port include lt ctools h gt route stderr com2 send errors to com2 r route stdout com2 send output to com2 route stdin com2 get input from com2 ISaGRAF C Tools User and Ref
274. mand11 read unique identifier associated with tag hartCommand33 read specified transmitter variables hartStatus return status of last HART command sent hartGetConfiguration read HART module settings hartSetConfiguration write HART module settings hartPackString convert string to HART packed string hartUnpackString convert HART packed string to string HART Command Macros The ctools h file defines the following macro of interest to a C application program Refer to the C Tools Macros section for details DATA_SIZE Maximum length of the HART command or response field HART Command Enumeration Types 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 The HART_DEVICE type is a structure containing information about the HART device The HART_VARIABLE type is a structure containing a variable read from a HART device The HART_SETTINGS type is a structure containing the configuration for the HART modem module The HART_COMMAND type is a structure containing a command to be sent to a HART slave device The HART_RESPONSE type is a structure containing a response from a HART s
275. mask of the active wake up sources Valid wake up sources are listed below e WS_REAL_TIME_CLOCK e WS_INTERRUPT_INPUT e WS_LED_POWER_SWITCH e WS_COUNTER_0_OVERFLOW e WS_COUNTER_1_OVERFLOW e WS_COUNTER_2_OVERFLOW See Also setWakeSource sleep 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_REAL_TIME_CLOCK fputs Real Time Clock r n coml if enabled amp WS_INTERRUPT_INPUT fputs Interrupt Input r n coml if enabled amp WS_LED_POWER_SWITCH fputs LED Power Switch r n coml if enabled amp WS_COUNTER_0_OVERFLOW fputs Counter 0 Overflow r n coml if enabled amp WS_COUNTER_1_OVERFLOW fputs Counter 1 Overflow r n coml if enabled amp WS_COUNTER_2_OVERFLOW fouts Counter 2 Overflow r n coml ISaGRAF C Tools User and Reference Manual 175 May 8 2007 hartlO Read and Write 5904 HART Interface Module Syntax include lt ctools h gt BOOLEAN hartIO unsigned module Description This function reads the specified 5904 HART 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 HART Interface module It checks if there is a new
276. mber AOSF_startAddress AOSF_wordOrder EPORT_ALL_EVENTS r SW_FIRST a PORT_ALL _ 00 S 0 0 0 PORT_ALL_ T S j SW_FIRST 0 EPORT_CHANGE__ ENTS R M 2 R 1 1 R M 2 R LA SW_FIRST rFoOoOO z W_FIRST NO SW_FIRST autoUnsolicitedClassl holdTimeClassl holdcountClass1l autoUnsolicitedClass2 holdTimeClass2 holdCountClass2 autoUnsolicitedClass3 holdTimeClass3 holdCountClass3 tion amp configuration tocol on com port 4 amp protocolSettings DNP protocolSettings Configure Binary Input Points for index binaryInput modbusAddress binaryInput eventClass 0O index lt configuration BI_number index 10001 index CLASS_1 dnpSaveBIConfig configuration BI_startAddress index amp binarylInput Configure 16 Bit Analog Input Points for index 0 index lt configuration AI16_number index analogInput modbusAddress 40002 index 2 analogInput eventClass CLASS_2 analogInput deadband Ty dnpSaveAI16Config configuration AIl6_startAddress index amp analogInput Configure DNP Routing Table station 100 via com4 station 101 via com4 ISaGRAF C Tools User and Reference Manual May 8 2007 140 X7 dnpCreateRoutingTable 2 dnpWriteRoutingTableEntry 0 100 CIF_Com4 DEFAULT_DLI
277. method is to create a task exit handler function to do this See the example below for 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 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 dnp c Demonstration program for using the DNP connection handler ISaGRAF C Tools User and Reference Manual 98 May 8 2007 Copyright 2001 Control Microsystems Inc ee a at e e es ee ee ee Se PRO SCROLE LE REL SLE eRe Le Petre he pe bere pene rene pene pep ere ReneS erase ee sles Include Files Cin E A A E D I e A
278. ms additive CRC 16 CRC CCITT and byte wise exclusive OR The CRC algorithms are particularly reliable employing various polynomial methods to ISaGRAF C Tools User and Reference Manual 45 May 8 2007 detect nearly all 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 Checksum Macros The ctools h file defines macros for specifying checksum types Refer to the C Tools Macros section for details on each macro listed ADDITIVE Additive checksum BYTE_EOR Byte wise exclusive OR checksum CRC_16 CRC 16 type CRC checksum reverse algorithm CRC_CCITT CCITT type CRC checksum reverse algorithm Serial Communication The SCADAPack family of controllers offers three or four RS 232 serial ports The TeleSAFE Micro16 has two RS 232 serial communication ports com1 on all controllers is also available as an RS 485 port The ports are configurable for baud rate data bits stop bits parity and communication protocol To optimize performance minimize the length of messages on com3 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and
279. 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 an unsolicited message of the same class is already pending or if the DNP configuration has not been created Notes DNP must 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 ISaGRAF C Tools User and Reference Manual 143 May 8 2007 dnpWriteRoutingTableEntry Write Routing Table Entry Syntax include lt ctools h gt BOOLEAN dnpWriteRoutingTableEntry UINT16 index UINT16 dnpAddress UINT16 commPort UINT16 DataLinkRetries UINT16 DataLinkTimeout Description This function writes an entry in the DNP routing table Notes DNP must 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 section Error Reference source not found ISaGRAF C Tools User and Reference Manual May 8 2007 144 dnpWriteRoutingTableDialStrings Write DNP Routing Table Entry Dial Strings Syntax BOOLEAN dnpWriteRoutingTableDialStrings UINT16 i
280. n Read HART Module Settings Syntax include lt ctools h gt BOOLI FAN hartGetConfiguration unsigned module Description 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 anda pointer to the settings structure HART_S ETTINGS settings The function returns TRUE if the settings were read The function returns FALSE if the module number is invalid See Also hartSetConfiguration ISaGRAF C Tools User and Reference Manual May 8 2007 186 hartSetConfiguration Write HART Module Settings Syntax include lt ctools h gt BOOLEAN hartSetConfiguration unsigned 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 anda 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 the EERROM_RUN section of the EEPROM 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 If a CNFG 5904 HART Interface module is in the register assignment forced registers from it take precedence over the settings supplied here
281. n getclock Example include lt ctools h gt Peis Soe Bees Soe ase eh a wakeUpAtEight The wakeUpAtEight function sets an alarm for 08 00 AM and puts the controller into sleep mode void wakeUpAtEHight void ALARM SETTING alarm unsigned wakeSource Set alarm for 08 00 alarm type AT_ABSOLUTE alarm hour 8 alarm minute 0 alarm second O Set the alarm request_resource IO_SYSTEM setClockAlarm alarm release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 347 May 8 2007 Sleep until alarm ignoring other wake ups do request_resource IO_SYSTEM wakeSource sleep release_resource IO_SYSTEM until wakeSource WS_REAL_TIME_CLOCK Disable the alarm alarm type AT_NONE request_resource IO_SYS setClockAlarm alarm release_resource IO_SYS ISaGRAF C Tools User and Reference Manual May 8 2007 348 setdbase Write Value to I O Database Syntax include lt ctools h gt void setdbase unsigned type unsigned address int 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 If the specified address is not valid then nothing is done The table below shows the valid address types and ranges Type Address Ranges Regist
282. n I C slave device and terminates reading from the slave The byte is not acknowledged by the master receiver This signals to the slave device that the read is complete This function must be used once at the end of a read Notes The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadByte ioBusReadMessage ioBusSelectForRead ioBusSelectForWrite ioBusWriteByte ioBusWriteMessage Example See example for ioBusReadByte ISaGRAF C Tools User and Reference Manual 217 May 8 2007 ioBusReadMessage Read Message from PC Slave Device Syntax include lt ctools h gt READSTATUS ioBusReadMessage unsigned address unsigned numberBytes unsigned char message Description The ioBusReadMessage function reads a specified number of bytes from an I C slave device The function issues a START condition selects the device for reading reads the specified number of bytes and issues a STOP condition It detects if the device cannot be selected and if so aborts the read The function has three parameters the address of the device the number of bytes to read numberBytes and a pointer to a buffer message capable of holding the data read The function returns the status of the read Value Description ___ RS_success read was successful RS_selectFailed slave device could not be selected Notes The IO_SYSTEM resource must be requested before calling this f
283. n application program must ensure that unneeded envelopes are de allocated Envelopes may be reused See Also deallocate_envelope Example include lt ctools h gt extern unsigned other_task_id void task1 void nvelope letter send a message to another task assume it will deallocate th nvelope 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 ISaGRAF C Tools User and Reference Manual 65 May 8 2007 check_error Get Error Code for Current Task Syntax include lt ctools h gt int 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 errors 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 See Also report_error ISaGRAF C Tools User and Reference Manual 66 May 8 2007 checksum Calculate a Checksum Syntax include lt ctools h gt unsigned checksum unsigned char start unsigned char end unsigned algorithm
284. n below Syntax include lt ctools h gt void rtchandler IME now IME new i 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 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 interruptCounter ISaGRAF C Tools User and Reference Manual 213 May 8 2007 interrupt_signal_event Signal Event in Interrupt Handler Syntax include lt ctools h gt void interrupt_signal_event unsigned event_number Description The interrupt_signal_event function is used in an interrupt handler to signal events The function signals tha
285. n 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 must return 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 not understood The handler function must return this value for all function codes it does not process The Modbus protocol will return an Illegal Function exception response e ILLEGAL_DATA_ADDRESS indicates 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 excep
286. n is not valid or if DNP configuration has not been created Notes DNP must be enabled before calling this function in order to create the DNP configuration See Also dnpGetA0O16Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual 127 May 8 2007 dnpSaveAO32Config Save DNP 32 Bit Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAO32Config UINT32 point dnpAnalogOutput pAnalogOutput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetAO32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual 128 May 8 2007 dnpSaveAOSFContfig Save Short Floating Point Analog Output Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAOSFConfig UINT16 point dnpAnalogOutput pAnalogOutput Description This function sets the configuration of a DNP short floating point analog output point The functi
287. n r for point 0 point lt 40 point t ISaGRAF C Tools User and Reference Manual 248 May 8 2007 fprintf coml n r d point if the point is on if dinData point 8 amp 1 lt lt putchar 1l putchar 0 Print analog input data fprintf coml r nAin Point Value n r for point 0 point lt 8 point fprintf coml sd Sd n r point ainDataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 249 isaRead8Ain Read 8 Analog Inputs Syntax include lt ctools h gt unsigned isaRead8Ain unsigned moduleAddress Description int dataArray The isaRead8Ain function reads any 8 point Analog Input Module at the specified moduleAddress Data is read from all 8 analog inputs and copied to the array pointed to by dataArray dataArray must point to an array of eight 16 bit integers The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function See Also isaRead4Ain Example This program displays the values of the 8 analog inputs read from an 8 point Analog Input Module at module address 0 include lt ctools h gt void main void unsigned point int dataArray 8 Read data from analog input module request_resource IO_SYS isaRead8Ain 0 da
288. n the egister and Status LED FALSE is returned if the I O module communication status is not reported Notes Refer to the 5203 4 System Manual or the SCADAPack System Manual for further information on the Status LED and Status Output See Also setlOErrorIndication ISaGRAF C Tools User and Reference Manual May 8 2007 159 getPortCharacteristics Get Serial Port Characteristics Syntax include lt ctools h gt unsigned getPortCharacteristics FILE stream PORT_CHARACTERISTICS opCharacteristics 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 void 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 ISaGRAF C Tools User and Reference Manual 160 May
289. n the port Failing to call 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 ISaGRAF stops the C application and when the controller is rebooted All reservation IDs returned by the modemDial and modemlnit functions on this port are invalid after calling modemAbort See Also modemAbortAll modemDial modemDialEnd modemDialStatus modeminit modemlnitEnd modemInitStatus modemNotification Example Refer to the examples in the Functions Overview section ISaGRAF C Tools User and Reference Manual 293 May 8 2007 modem AbortaAll Unconditionally Terminate All Dial up Connections Syntax include lt ctools h gt void modemAbort 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 Note that 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
290. n this function writes data to the 5601 it also services the transmit buffer of the com serial port If the controller type is a SCADAPack or SCADAPack PLUS the com3 serial port is also continuously processed automatically The additional service to the com3 transmitter caused by this function does not affect the normal automatic operation of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaRead5601 Inputs Example This program turns ON all 12 digital outputs of a 5601 I O Module include lt ctools h gt void main void Write output data to 5601 I O module request_resource IO_SYSTEM isaWrite56010utputs OxOFFF release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 269 May 8 2007 isaWrite5602O0utputs Write to SCADAPack Upper I O Module Outputs Syntax include lt ctools h gt unsigned isaWrite56020utputs unsigned char data Description The isaWrite5602Outputs function writes data to the digital outputs of a 5602 I O Module SCADAPack upper I O module The first 2 bits of the specified 8 bit data value are written to the 2 digital outputs The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes Note that when this function writes data to the 5602 it also services the transmit buffer of the com serial port If the controller type is a SCADAPack LIGHT or SCADAPack PLUS the com 4 serial port
291. naling of a regular event Event Notification Macros The ctools h file defines the following macro used for event notification Refer to the C Tools Macros section for details RTOS_EVENTS Defines the number of available RTOS events System Events The RTOS defines events for communication port management and background I O operations An application program may define other events as required Care must be taken not to duplicate 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_FREE This event is used by the serial timeout routine for the com1 port 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_FREE This event is used by the serial timeout routine for the com2 port An application program cannot use it COM2_RCVR This event is used by communication protocols to signal a character or message received on comz2 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 com3 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
292. nary Input Points for index O index lt configuration BI_number index binaryInput modbusAddress 10001 index binaryInput class CLASS_1 binaryInput eventType COS dnpSaveBIConfig index amp binaryInput Configure 16 Bit Analog Input Points for index 0 index lt configuration AI16_number index analogInput modbusAddress 30001 index analogInput class CLASS_2 analogInput deadband 1 dnpSaveAI16Config index amp analogInput Configure32 Bit Analog Input Points for index 0 index lt configuration AI32_number index analogInput modbusAddress 30001 index 2 analogInput class CLASS_2 analogInput deadband 1 dnpSaveAI32Config index amp analogInput Configure 16 Bit Analog Output Points for index O index lt configuration AOl6_number index analogOutput modbusAddress 40001 index dnpSaveAOl16Config index amp analogOutput ISaGRAF C Tools User and Reference Manual 117 May 8 2007 Configure 32 Bit Analog Output Points for index 0 index lt configuration AO32_number index analogOutput modbusAddress 40101 index 2 dnpSaveAO32Config index amp analogOutput Configure 16 Bit Counter Input Points for index 0 index lt configuration C1I16_number index counterInput modbusAddress 30001 index counterInput class CLASS_3 counterInput threshold 1 dnpSav
293. nction 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 and com4 Examples of recommended uses for com3 and com4 are for local operator display terminals and for programming and diagnostics using the ISaGRAF program Do not call this function in a task exit handler See Also modemAbort modemAbortAll modemDial modemDialEnd modemDialStatus modemlnitEnd modemInitStatus modemNotification ISaGRAF C Tools User and Reference Manual 300 May 8 2007 Example Refer to the example in the Functions Overview section ISaGRAF C Tools User and Reference Manual 301 May 8 2007 modemiInitEnd Abort Initialization 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 modemlnit 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 mus
294. ndex 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 length 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 Notes This function must be used in conjunction with the dnpWriteRoutingTableEntry function to write a complete entry in the DNP routing table ISaGRAF C Tools User and Reference Manual 145 May 8 2007 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 loadi
295. ned readCounterInput unsigned input Description The readCounterInput function returns the status of the DIN counter input point specified by input It returns TRUE if the input is ON and FALSE if the input is OFF If input is not valid the function returns FALSE Notes The three DIN counter inputs are located on the 5203 or 5204 controller board Refer to the System Hardware Manual for more information on the hardware See Also readBoolVariable ISaGRAF C Tools User and Reference Manual 318 May 8 2007 readBattery Read Lithium Battery Voltage Syntax include lt ctools h gt int 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 ISaGRAF C Tools User and Reference Manual 319 May 8 2007 readinternalAD Read Controller Internal Analog Inputs Syntax include lt ctools h gt int readInternalAD unsigned channel Description The readIinternalAD function reads analog inputs connected to the internal AD converter channel may be 0 to 7 The function returns a value in the range 0 to 32767 Notes There are only two channels with signals connected to them e AD_ THERMISTOR reads the thermistor input e AD_BATTERY reads the battery input See Also readBaitery
296. nfirmation 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 dnpConfiguration The dnpConfiguration type describes the DNP parameters typedef struct dnpConfiguration_type 4 16 masterAddress 16 rtuAddress datalinkConfirm datalinkRetries L6 datalinkTimeout 16 operateTimeout AR applicationConfirm L6 maximumResponse AR applicationRetries T16 applicationTimeout 16 timeSynchronization T16 BI_number BI_startAddress R BI_reportingMethod BI_soebufferSize BO_number BO_startAddress CI16_number CI16_startAddress R CI16_reportingMethod CI16_bufferSize 16 CI32_number T16 CI32_startAddress R CI32_reportingMethod T16 CI32_bufferSize CI32_wordOrder AI16_number T16 AI16_startAddress R AI16_reportingMethod T AI16_bufferSize AI32_number T16 AI32_startAddress R AI32_reportingMethod T16 AI32_bufferSize 7 HAD CAZAaA Prag o aA Fl oO C QAC GH J Oo J DOOD QQ Gie Ave x Gy J J Oo o gt oO C J Oy Qc c HTHHHTHHITIHTIHHHTHHHHHTHHZHQAHQAHHKHTTHH ZPZZZPZZ PZ PZZZPZAZA ZZZ PZA ZHZ Oy ISaGRAF C Tools User and Reference Manual 405 May 8 2007 CHAR AI32_wordOrder AISF_number AISF_startAddress AISF_reportingMethod AISF_bufferSize AISF_wordOrder AO1
297. ng a new program into memory See Also create_task end_task ISaGRAF C Tools User and Reference Manual 146 May 8 2007 end_task Terminate a Task Syntax include lt ctools h gt void end_task unsigned 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 both APPLICATION and SYSTEM type tasks See Also create_task getTaskinfo ISaGRAF C Tools User and Reference Manual 147 May 8 2007 endTimedEvent Terminate Signaling of a Regular Event Syntax include lt ctools h gt unsigned endTimedEvent unsigned 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 valid events for use in an application program Example See the examples for startTimedEvent See Also startTimedEvent ISaGRAF C Tools User and Reference Manual 148 May 8 2007 enroninstallCommandHandler Installs handler for Enron Modbus commands Syntax include lt ctools h gt void enronInstallCommandHan
298. ng the storage passed to the function secondaryDialString returns the secondary dial string of the target station It must point to an array of size maxSecondaryDialStringLength Notes This function must be used in conjunction with the dnpReadRoutingTableEntry function to read a complete entry in the DNP routing table ISaGRAF C Tools User and Reference Manual 121 May 8 2007 dnpReadRoutingTableEntry Read Routing Table entry Syntax include lt ctools h gt BOOLEAN dnpReadRoutingTableEntry UINT16 index routingTable pRoute Description 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 must 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 ISaGRAF C Tools User and Reference Manual May 8 2007 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 must be enabled before calling this function in order to create the DNP configuration The function returns the total number of entries in the routing table ISaGRAF C Tools User and Reference Manual 123 May 8 2007 dnpSa
299. nput point Sets the configuration of a DNP binary output point Reads the configuration of a DNP 16 bit analog input point Sets the configuration of a DNP 16 bit analog input point Reads the configuration of a DNP 32 bit analog input point Sets the configuration of a DNP 32 bit short floating analog input point Reads the configuration of a DNP 32 bit short floating analog input point Sets the configuration of a DNP 32 bit analog input point Reads the configuration of a DNP 16 bit analog output point Sets the configuration of a DNP 32 bit analog output point Reads the configuration of a DNP 32 bit analog output point Sets the configuration of a DNP 32 bit analog output point Sets the configuration of a DNP 32 bit short floating analog output point Sets the configuration of a DNP 32 bit short floating analog output point Reads the configuration of a DNP 16 bit counter input point Sets the configuration of a DNP 16 bit counter input point Reads the configuration of a DNP 32 bit counter input point Sets the configuration of a DNP 32 bit counter input point Reads the current status of all DNP change event buffers Sends an Unsolicited Response message in DNP protocol Sends an Unsolicited Response message in DNP with data from the specified classes ISaGRAF C Tools User and Reference Manual 60 May 8 2007 dnpWriteRoutingTableEntry Wwrites an entry in the DNP routing table dnpReadRoutingTableEntr
300. ns no error has occurred e DE_BadConfig returns 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 e DE_InitError returns modem initialization failed the modem may be turned off e DE_NoDialTone returns modem did not detect a dial tone or the S6 setting in the modem is too short e DE_BusyLine returns the phone number called was busy e DE_CallAborted returns a call in progress was aborted by the user e DE_FailedToConnect returns the modem could not connect to the remote site e 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 e DE_NotInControl returns the serial port is in use by another modem function or has answered an incoming call e DE_CalicCut returns an incoming call was disconnected while attempting to dial out DialState The DialState enumerated type defines the state of the modemDial operation and may have one of the following values enum DialState ISaGRAF C Tools User and Reference Manual 402 May 8 2007 DS_Inactive DS_Calling DS_Connected DS_Terminating e DS_Inactive returns the serial port is not in use by a modem e DS_Calling returns t
301. nswer incoming calls One modemInit function may be active on each serial port The modemlnit function handles all 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 ensures that no other modem control function can access the serial port This parameter must 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 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 The modemInitStatus function returns the status of the connection attempt initiated by modeminit The modemInitEnd function terminates initialization of the modem If a communication 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 amodemDial function or an incoming call is active on the port the modemlnit fu
302. nt 0 point lt 15 point t fprintf coml n r d point p if the point is on if dinData amp 1 lt lt point 0 p tcehar Ly putchar 0 Print analog input data fprintf com1 r nAin Point Value n r for point 0 point lt 4 point fprintf coml d Sf n r point ainDataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 la 238 ISaGRAF C Tools User and Reference Manual 239 May 8 2007 isaRead5506Inputs Read 5506 Inputs Syntax include lt ctools h gt unsigned isaRead5506Inputs UINT16 moduleAddress UCHAR dinData INT16 ainDataArray Description The isaRead5506Inputs function reads the digital and analog inputs from the specified 5506 I O module Data is read from all 8 digital inputs and copied to the variable pointed to by dinData Data is read from all 8 analog inputs and copied to the array pointed to by ainDataArray moduleAddress is the address of the 5506 module Valid values are 0 to 15 dinData must point to an 8 bit unsigned character Each of the 8 bits in the character represents one input point ainDataArray must point to an array of eight 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaWrite5506Outputs Example This program di
303. nue to operate until the controller power is cycled Changing the protocol type or Erasing the C Program from SaGRAF Initialize dialog will not remove the Modbus handler If the handler is located ina RAM based application and left enabled while a different C application is downloaded the original handler will be corrupted and the system will likely crash See Also Handler Function ISaGRAF C Tools User and Reference Manual 202 May 8 2007 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 unsigned handler unsigned char message unsigned messageLength unsigned char response unsigned responseLength di 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 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 functio
304. oBusReadLastByte ioBusReadMessage ioBusSelectForWrite ioBusWriteByte ioBusWriteMessage Example See example for ioBusReadByte ISaGRAF C Tools User and Reference Manual May 8 2007 ioBusSelectForWrite Select PC Slave Device for Writing Syntax include lt ctools h gt unsigned ioBusSelectForWrite unsigned char address Description The ioBusSelectForWrite function selects an C slave device for writing It writes the slave device address with the read write bit set to the write state The function handles the formatting of the address byte The function has one parameter the address of the device It returns TRUE if the write succeeded that is the byte was acknowledged by the slave It returns FALSE if the write failed that is the byte was not acknowledged by the slave Notes This function can only be used immediately after a START condition e g ioBusStart The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadByte ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusWriteByte ioBusWriteMessage Example See example for ioBusWriteByte ISaGRAF C Tools User and Reference Manual 220 May 8 2007 ioBusStart Issue an FC Bus START Condition Syntax include lt ctools h gt void ioBusStart void Description The ioBusStart function issues an C bus START condition Notes The IO_SYSTEM resource must be requested before calling this f
305. ogID amp dLogConfig else could not delete log else Could not read settings ISaGRAF C Tools User and Reference Manual May 8 2007 86 datalogPurge Purge Data Log Function Syntax include lt ctools h gt BOOLEAN datalogPurge UINT16 logID BOOLEAN purgeAll UINT32 sequenceNumber i 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 1ogID specifies the data log The valid range is 0 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 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 datalogReadStart datalogReadNext
306. ogram data to the end of memory see Start Up Function Structure section for more information The sections may be rearranged and new sections added according to the following rules e The far_appcode section must be first in the order listing e All code sections must follow the far_appcode section e The far_endcode section must be the last code section e All data sections must follow the code sections e The heap section must be last in the order listing F Specify location and order of memory sections sect far_appcode 00400000h order far_appcode far_code CODE const order strings literals __INITDATA far_endcode order far_zerovars far_initvars DATA heap The next section of the command file creates initialized data sections All variables in the specified section are initialized at start up of the program The linker creates a copy of the data in these sections and stores it in the __INITDATA section Create initialized variables section LA initdata far_initvars The next section of the command file lists the application program object modules files to be included in the program You may also include libraries of functions you create here The sample command file includes one object module app obj The next section of the command file lists the start up routines and standard libraries to be included There are three object modules and two libraries Module Description S
307. on The SCADASense series of programmable controllers do not have a Status output 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 Register Assignment uses bits 0 and 1 of the status code It is recommended that the setStatusBit function be used instead of setStatus to prevent modification of these bits See Also setStatusBit clearStatusBit getStatusBit ISaGRAF C Tools User and Reference Manual 363 May 8 2007 setStatusBit Set Bits in Controller Status Code Syntax include lt ctools h gt unsigned setStatusBit unsigned 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 SCADASense series of programmable controllers do not have a status output The binary sequence consists of short and long flashes of the error LED A short flas
308. on 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 must be enabled before calling this function in order to create the DNP ISaGRAF C Tools User and Reference Manual 129 May 8 2007 dnpSaveBlConfig Save DNP Binary Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveBIConfig UINT16 point dnpBinaryInput pBinaryInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetBIConfig Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpSaveBlConfigEx Write DNP Binary Input Extended Point Syntax BOOLEAN dnpSaveBIConfigEx UINT16 point dnpBinaryInputEx pBinaryInput Description This function writes the configuration of
309. on of com3 The IO_SYSTEM resource must be requested before calling this function See Also isaReadLPInputs Example This program turns on all 12 digital outputs and sets the analog outputs to full scale include lt ctools h gt void main void unsigned digitalData int analogData 2 turn on all digital outputs digitalData Ox0FFF set analog outputs to full scale analogData 0 32767 analogData 1 32767 Write output data to SCADAPack LP I O request_resource IO_SYSTEM isaWriteLPOutputs digitalData analogData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 277 May 8 2007 isaWriteSP100O0utputs Write to SCADAPack 100 Outputs Syntax include lt ctools h gt unsigned isaWriteSP1000utputs unsigned doutData Description The isaWriteSP1000utputs function writes data to the digital outputs of the SCADAPack 100 I O doutData is the digital output data The first 6 bits of the specified 16 bit data value are written to the 6 digital outputs The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function See Also isaReadSP100Inputs Example This program turns on all 6 digital outputs include lt ctools h gt void main void unsigned digitalData turn on all digital outputs digitalData Ox0FFF Write outpu
310. onfiguration tables e store and forward enable flags e LED power settings e make for wake up sources e execution period on power up for PID controllers e HART modem settings The IO_SYSTEM resource must be requested before calling this function See Also load Example This code fragment saves all parameters request_resource IO_SYSTEM save EEPROM_RUN release_resource IO_SYSTEM C Tools User and Reference Manual 340 May 8 2007 searchRoutingTable Search Routing Table Syntax include lt ctools h gt BOOLEAN searchRoutingTable 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 must be enabled before calling this function in order to create the DNP configuration ISaGRAF C Tools User and Reference Manual May 8 2007 341 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
311. onfigures the module moduleAddress is the address of the 5606 module Valid values are 0 to 7 doutData must point to an array of two 8 bit unsigned characters Each bit in the array represents one output point The 16 bits of the array are written to the 16 digital outputs aoutData must point to an array of two 16 bit integers Analog data from this array are written to the two analog outputs inputType must point to an array of 8 unsigned integers that select the type of analog inputs on the module Valid values for each integer are e 0 0to 5V e 1 0to10V e 2 0to20 mA e 3 4to0 20 mA inputFilter selects the analog input filter This is used for all inputs Valid values are e 0 3Hz e 1 6Hz e 2 11 Hz e 3 30 Hz scanFrequency is the scan frequency setting Valid values are e 0 60Hz e 1 50Hz outputType selects the type of analog outputs on the module Valid values are e 0 01t020mA e 1 4to 20 mA The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling this function ISaGRAF C Tools User and Reference Manual 273 May 8 2007 See Also isaRead5606Inputs Example This program turns on all 16 digital outputs and sets the analog outputs to full scale include lt ctools h gt void mai n void UCHAR digitalData INT16 analogData UINT16 inputType UINT16 inputFilte UINT16 scanFreque UINT16 outputType
312. ort coml amp portset enable Modbus protocol on serial port 2 settings type MODBUS_ASCITI settings station 2 settings priority 3 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 DISABLE portset flow_tx DISABLE portset typ RS485_2WIRE portset timeout 600 set_port com2 amp portset release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual May 8 2007 286 Main communication loop while TRUE Transfer slave inputs to outputs request_resource IO_SYSTEM master_message com2 2 1 10001 17 8 1 release_resource IO_SYSTEM wait_for_response com2 0 Transfer inputs to slave outputs e request_resource IO_SYSTEM master_message com2 15 1 1 10009 8 release_resource IO_SYS wait_for_response com2 10 T r Allow other tasks to execute release_processor Examples using DF1 Protocol Full Duplex Using the same example program above apply the following calling format for the master_message function This code fragment uses the protected write command function 0 to transmit 13 length 13 16 bit registers to slave station 10 sl
313. ortCharacteristics 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 portConfiguration Get pointer to port configuration table portindex Get array index for serial port portStream Get serial port corresponding to index queue_mode Set serial port transmitter mode ISaGRAF C Tools User and Reference Manual S a May 8 2007 route setDTR set_port Redirect standard I O streams Control RS232 port DTR signal Set serial port communication parameters Serial Communication Macros The ctools h file defines macros for specifying serial communication parameters Refer to the C Tools Macros section for details on each macro listed BAUD75 BAUD110 BAUD150 BAUD300 BAUD600 BAUD1200 BAUD2400 BAUD4800 BAUD9600 BAUD19200 BAUD38400 BAUD57600 BAUD115200 com1 com2 com3 com4 DATA7 DATA8 DISABLE ENABLE EVEN FULL FOPEN_MAX HALF NONE NOTYPE ODD PC_FLOW_RX_RECEIVE_STOP PC_FLOW_RX_XON_XOFF PC_FLOW_TX_IGNORE_CTS ISaGRAF C Tools User and Reference Manual May 8 2007 Specifies 75 baud port speed Specifies 110 baud port speed Specifies 150 baud port speed Specifies 300 baud port speed Specifies 600 baud port speed Specifies 1200 baud port speed Specifies 2400 baud port speed Specifies 4800 baud port speed Specifies 9600 baud port speed Specifies 19200 baud port speed Specifies
314. ot compatible with the standard UNIX style functions supplied by Microtec The IO_SYSTEM resource must be requested before calling this function See Also setclock getClockTime Example This program displays the current date and time include lt ctools h gt main void struct clock now request_resource IO_SYSTEM now getclock read the clock release_resource IO_SYSTEM printf 2d 2d 2d now day now month now year printf 2d 2d r n now hour now minute ISaGRAF C Tools User and Reference Manual 155 May 8 2007 getClockAlarm Read the Real Time Clock Alarm Settings Syntax include lt ctools h gt ALARM_S ETTING getClockAlarm void Description The getClockAlarm function returns the alarm setting in the real time clock The alarm is used to wake the controller from sleep mode Notes The IO_SYSTEM resource must be requested before calling this function See Also alarmin setClockAlarm ISaGRAF C Tools User and Reference Manual May 8 2007 156 getClockTime Read the Real Time Clock Syntax include lt ctools h gt void getClockTime long pDays long pHundredths Description The getClockTime function reads the read time clock and returns the value as the number of whole days since 01 01 97 and the number of hundredths of a second since the start of the current day The function works for 100 years from 01 01 97 to 12 31 9
315. otocol It supports access to the I O database serial port reconfiguration and program loading The application program can disable the TeleBUS protocol and use the serial ports for other purposes TeleBUS protocols are compatible with the widely supported Modbus ASCII and RTU protocols Clock Calendar The processor s hardware clock calendar is supported by the C Tools The time date and day of week can be read and set by the application software Timers The controller provides 32 software timers They are individually programmable for tick rates from ten per second to once every 25 5 seconds Timers may be linked to digital outputs to cause external devices to turn on off after a specified period All timers operate in the background from a hardware interrupt generated by the main system clock Duty Cycle and Pulse Outputs The digital I O driver provides duty cycle and pulse train outputs Duty cycle outputs generate continuous square waves Pulse train outputs generate finite sequences of pulses Outputs are generated independent of the application program Watchdog Timer The controller supports a hardware watchdog timer to detect and respond to hardware or software failures Watchdog timer trigger pulses may be generated by the user program or by the system clock Checksums To simplify the implementation of self checking communication algorithms the C Tools provide four types of checksums additive CRC 16 CRC CCITT an
316. ource 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 ISaGRAF C Tools User and Reference Manual 76 May 8 2007 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 b dbase MODBUS 30002 setdbase MODBUS 40020 a b release_resource IO_SYSTEM Allow other tasks to execute release_processor void task2 void while TRUE body of task 2 loop event handler wait_event TIME_TO_PRINT printf It s time for a coffee break r n The shutdown function stops the signalling of TIME _TO_PRINT events when application is stopped ay void shutdown void endTimedEvent TIME_TO_PRINT void main void TASKINFO taskStatus continuos processing task at priority 1 create_task taskl 1 APPLICATION 2 event handler needs larger stack for printf function create_task task2 3 APPLICATION 4 set up task exit handler to stop signalling of events when this task ends taskStatus getTas
317. 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 connected 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 controller the CTS line must 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 must 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 Additional serial communication functions are included in the Microtec run time library clear_errors Clear serial port error counters clear_tx Clear serial port transmit buffer get_port Read serial port communication parameters getP
318. p sequence for other components ISaGRAF C Tools User and Reference Manual 17 May 8 2007 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 RTOS supports up to 16 tasks There are 5 task priority levels to aid in scheduling of task execution Task Execution SCADAPack controllers can execute one task at a time The 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 Task execution is based upon the priority of tasks There are 5 priority levels Level 0 is reserved for the null task This task runs when there are no other tasks available for execution Application programs can use levels 1 to 4 The main task is created at
319. pecifies 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 set 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 See Also modemAbort modemAbortAll modemDial modemDialEnd modemlnit modemlnitEnd modemInitStatus modemNotification ISaGRAF C Tools User and Reference Manual 299 May 8 2007 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 a
320. peed Specifies 600 baud port speed D75 Specifies 75 baud port speed D9600 Specifies 9600 baud port speed EOR Byte wise exclusive OR checksum Variable name cascade setpoint source CLASSO_ specifies a flag for enabling DNP Class 0 data specifies a flag for enabling DNP Class 1 data specifies a flag for enabling DNP Class 2 data specifies a flag for enabling DNP Class 3 data Specifies switch is in closed position Cold boot switch depressed when CPU was reset Points to a file object for the com1 serial port 1_FRE System event com1 transmit buffer is no longer full This event is used internally by the serial I O driver 1_RCV System event indicates activity on com1 receiver The meaning depends on the character handler installed Points to a file object for the com2 serial port System event com2 transmit buffer is no longer full This event is used internally by the serial I O driver System event indicates activity on com2 receiver The meaning depends on the character handler installed eont a Points to a file object for the com3 serial port eot System event indicates activity on com3 receiver The meaning depends on the character handler installed Points to a file object for the com4serial port System event indicates activity on com4 receiver The meaning depends on the character handler installed TER_CHANNELS Specifies number of 5000 Series counte
321. point ainDataArray must point to an array of ten 16 bit integers The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function reads data from the 5604 I O module it also processes the receiver buffer for the com serial port The com3 serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of coms The IO_SYSTEM resource must be requested before calling this function See Also isaWrite56040utputs Example This program displays the values of the 35 digital inputs and 10 analog inputs read from the 5604 I O include lt ctools h gt void main void UINT16 point UCHAR dinData 5 INT16 ainDataArray 10 Read input data from 5604 I O request_resource IO_SYSTEM isaRead5604Inputs dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r ISaGRAF C Tools User and Reference Manual 246 May 8 2007 for point 0 point lt 35 point fprintf coml n r d point if the point is on if dinData point 8 amp 1 lt lt point putchar 1l putchar 0 Print analog input data fprintf coml r nAin Point Value n r for point 0 point lt 10 point t fprintf coml d Sd n r point ainDataArray point
322. priority level 1 Tasks that are not running are held in queues The Ready Queue holds all 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 prevent 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 Note that this does not prevent 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 Task Management Functions There are five RTOS functions for task management Refer to the Function Specification section for details on each function listed ISaGRAF C Tools User and Reference
323. r Note that 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 e priority is the task priority of the protocol task This field is not used if the protocol type is NO_PROTOCOL e SFMessaging is the enable Store and Forward messaging control flag e ADDRESS_MODE is 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 e type is the protocol type It may be one of NO_PROTOCOL MODBUS_RTU or MODBUS_ASCII e station is the station address of the controller Note that 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 e priority is the task priority of the protocol task This field is not used if the protocol type is NO_PROTOCOL e SFMessaging is the enable Store and Forward messaging control flag e ADDRESS_MODE is the addressing mode AM_standard or AM_extended e enronEnabled determines if the Enron Modbus station is enabled It may be TRUE or FAL
324. r STOP2 macro e flow_rx specifies flow control on the receiver It is either the DISABLE or ENABLE macro e Forcom1 and com2 setting this parameter selects XON XOFF flow control It may be enabled or disabled If any protocol other than Modbus ASCII is used on the port you must set flow_rx to DISABLE If Modbus ASCII or no protocol is used you can set flow_rx to ENABLE or DISABLE In most cases DISABLE is recommended e For com3 and com4 setting this parameter selects Receiver Disable after message reception This is used with the Modbus RTU protocol only If the Modbus RTU protocol is used set flow_rx to ENABLE Otherwise set flow_rx to DISABLE e flow_tx specifies flow control on the transmitter It is either the DISABLE or ENABLE macro e Forcom1 and com2 setting this parameter selects XON XOFF flow control It may be enabled or disabled If any protocol other than Modbus ASCII is used on the port you must set flow_tx to DISABLE If Modbus ASCII or no protocol is used you can set flow_tx to ENABLE or DISABLE In most cases DISABLE is recommended e For com3 and com setting this parameter indicates if the port should ignore the CTS signal Setting the parameter to ENABLE causes the port to ignore the CTS signal e type specifies the serial port type It is one of NOTYPE RS232 RS232_MODEM RS485 or RS232_COLLISION_AVOIDANCE macros ISaGRAF C Tools User and Reference Manual 420 May 8 2007 e timeout specifies the tim
325. r and security 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 reliable 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 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 most 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 most commonly a simple RS 232 or RS 485 interface Refer to the DNP User Manual for complete information on DNP protocol including the Device Profile Document DNP Communication Protocols Functions There are several library functions related to DNP communication protocol Refer to the Function Specification sec
326. r input channels COUNTER_END gt Number of last counter input channel COUN ERS TAR Number of first counter input channel If defined indicates counter I O hardware supported Frequency of the system clock in cycles per second Variable name control register CRC_ CRC 16 type CRC checksum reverse algorithm CCITT type CRC checksum reverse algorithm Maximum length of the HART command or response field ISaGRAF C Tools User and Reference Manual 392 May 8 2007 Specifies 7 bit world length D TAT ATA8 Specifies 8 bit word length Variable name deadband DB DB_BADSIZE Error code out of range address specified DB_OK Error code no error occurred DE_BusyLine The phone number called was busy D E_CallAborted A call in progress was aborted by the user DB_BADTYPE Error code bad database addressing type specified DE_BadConfig The modem configuration structure contains an error EB 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 DE_FailedToConnect The modem could not connect to the remote site the modem is too short oError No error has occurred 5 Zz to the controller serial port has answered an incoming call DIN_END Number of last regular dig
327. rce IO_SYSTEM Print digital input data fprintf coml Din Point Value n r fprintf coml n r d me Oy putchar dinData amp 0x0001 1 O Print analog input data fprintf coml r nAin Point Value n r fprintf com1 Sd d n r 0 ainData 0 fprintf com1 Sd d n r 1 ainData 1 fprintf comt Sd d n r 2 ainData 2 Print counter input data fprintf coml r nAin Point Value n r for point 0 point lt 2 point fprintf coml d d n r point counterData point ISaGRAF C Tools User and Reference Manual 236 May 8 2007 isaRead5505Inputs Read 5505 Inputs Syntax include lt ctools h gt unsigned isaRead5505Inputs UINT16 moduleAddress UINT16 dinData float ainDataArray Description The isaRead5505Inputs function reads the digital and analog inputs from the specified 5505 I O module Data is read from all 16 digital inputs and copied to the variable pointed by dinData Data is read from all 4 analog inputs and copied to the array pointed to by ainDataArray moduleAddress is the address of the 5505 module Valid values are 0 to 15 dinData must point to a 16 bit unsigned integer Each of the 16 bits in the integer represents one input point to There are 16 digital input points on the module The function of these inputs is described in the table below e e a E Offset E ON channel 0 RTD is open or PWR input
328. received character install_handler com6 signalCharacter while TRUE Wait for a character to be received wait_event CHARACTER_RECEIVED 49 Echo the character back character fgetc com6 fputc character com6 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 void auxiliary void while TRUE 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 Create serial communication task ISaGRAF C Tools User and Reference Manual 26 May 8 2007 create_task echoData 3 APPLICATION 3 Create a task same priority as main task create_task auxiliary 1 APPLICATION 2 while TRUE add application specific code here Allow other tasks of this priority to execute release_processor j Explanation of Task Execution SCADAPack 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 il
329. rees Celsius Specifies temperatures in degrees Fahrenheit Specifies temperatures in degrees Kelvin Specifies temperatures in degrees Rankine TeleSAFE 6000 16EX controller TeleSAFE Micro16 controller Specifies timer is has reached zero Specifies timer is generating timed output change Error code invalid digital I O address Error code invalid timer interval Error code invalid timer Error code invalid time value Number of last valid software timer Task status indicating task is executing Task status indicating task is ready to execute Task status indicating task is blocked waiting for a resource Task status indicating task is blocked waiting for an envelope Task status indicating task is blocked waiting for an event Task status indicating task is blocked waiting for a message ISaGRAF C Tools User and Reference Manual May 8 2007 398 Macro Definition VI_DATE_SIZE Number of characters in version information date field WRITESTATU enum WriteStatus WS_ALL All wake up sources enabled WS_COUNTER_0_OVE Bit mask to enable counter 0 overflow as wake up source Bit mask to enable counter 1 overflow as wake up source WS_CO ER_2_OVERF LOW Bit mask to enable counter 2 overflow as wake up source WS_INT PT_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 No wake up source enabled Bit mask to enable real t
330. rity 4 Com1 Protocol Task Executes when mes sage event occurs Processes e message Priority 3 Timer Interrupt 240 Hz Interrupt Processes Ladders timers e jiffy timer e watchdog timer e timed events Priority h w interrupt Com2 Protocol Task Executes when mes sage event occurs Processes e message Priority 3 Com3 Protocol Task Executes when mes sage event occurs Processes e message Priority 3 Optional User Tasks Created by user from the Main Task Priority 1 to 4 Com 4 Protocol Task Executes when mes sage event occurs Processes e message Priority 3 Ladders amp I O Scan Task Main Task typical Task loop runs continuously Task loop runs continuously while TRUE while TRUE request_resource IO_SYSTEM request_resource IO_SYSTEM read data from input modules to I O database Register Assignment functions requiring O_SYSTEM resource release_resource IO_SYSTEM if program is in RUN mode execute ladder logic program functions not requiring O_SYSTEM resource write data from I O database to output modules Register Assignment release_processor release_resource IO_SYSTEM release_processor Priority 1 Priority 1 The highest priority routines that execute are hardware interrupt handlers Most hardware interrupt handlers perform their functions transparently The Timer Interrupt handler is important to applicat
331. rned if any variable is non zero 0 returned if variable is 0 30001 to 39999 word 16 bits 1250 to 11248 40001 to 49999 word 16 bits 11249 to 21247 Modbus Database Functions There are several library functions related to the Modbus database Refer to the ISaGRAF C Tools Function Specifications section for details on each function listed dbase Reads a value from the database installDbaseHandler Allows an extension to be defined for the dbase function installSetdbaseHandler Allows an extension to be defined for the setdbase function Dbase Handler Function User defined function that handles reading of Modbus addresses not assigned in the ISaGRAF Dictionary setdbase Writes a value to the database Setdbase Handler Function User defined function that handles writing to Modbus addresses not assigned in the ISaGRAF Dictionary ISaGRAF C Tools User and Reference Manual 56 May 8 2007 Database Macros 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 coi
332. ros for use in the power management functions Refer to the C Tools Macros section for details on each macro listed 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 PM_LAN_ ENABLED The LAN is enabled PM_LAN_DISABLED The LAN is disabled PM_USB_PERIPHERAL_ENABLED The USB peripheral port is enabled PM_USB_PERIPHERAL_DISABLED The USB peripheral port is disabled PM_USB_HOST_ENABLED The USB host port is enabled PM_USB_HOST_DISABLED The USB host port is disabled PM_UNAVAILABLE The status of the device could not be read Configuration Data EEPROM Functions The EEPROM is nonvolatile memory used to store configuration parameters The application program cannot store application data into this memory It can cause the system configuration parameters to be written using the save function The contents of the EEPROM are copied to RAM under two conditions during a RUN boot of the controller and when the application program executes the load function The following data is loaded on a RUN boot otherwise default information is used e serial port configuration tables e protocol configuration tables e enable store and forward settings e LED power settings e mask for wake up sources e execution period on power up for each PID There are two library functions related to the configuration data EEPROM Refer to the Function Specification section for
333. rray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r for point 0 point lt 16 point fprintf coml n r d point putchar dinData amp 0x0001 1 O ISaGRAF C Tools User and Reference Manual 252 May 8 2007 dinData gt gt 1 Print analog input data fprintf coml r nAin Point Value n r for point 0 point lt 8 point t fprintf coml d d n r point ainDataArray point ISaGRAF C Tools User and Reference Manual 253 May 8 2007 isaReadSP100Inputs Read SCADAPack 100 Inputs Syntax include lt ctools h gt unsigned isaReadSP100Inputs unsigned dinData int ainDataArray unsigned long cinDataArray Description The isaReadSP100Inputs function reads the digital analog and counter inputs from SCADAPack 100 I O Data is read from all 6 digital inputs and copied to the 16 bit value pointed to by dinData Data is read from all 6 analog inputs and copied to the array pointed to by ainDataArray Data is read from the counter input and copied to the array pointed to by cinDataArray dinData must point to a 16 bit integer ainDataArray must point to an array of six 16 bit integers cinDataArray must point to an array of one 32 bit integer The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes The IO_SYSTEM resource must be requested before calling th
334. rs e rx_buffer_size is the size of the receive buffer in characters e xrx_buffer_used is the number of characters in the receive buffer e tx_buffer_size is the size of the transmit buffer in characters e tx_buffer_used is the number of characters in the transmit buffer e 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 ISaGRAF C Tools User and Reference Manual 421 May 8 2007 isolate the signals with the SIGNAL_CTS SIGNAL_DCD SIGNAL_OH SIGNAL_RING or SIGNAL_VOICE macros READSTATUS The READSTATUS enumerated type indicates the status of an I C bus message read and may have one of the following values enum ReadStatus RS_success RS_selectFailed typedef enum ReadStatus READSTATUS e RS_success returns read was successful e RS_selectFailed returns slave device could not be selected routingTable The routingTable type describes an entry in the DNP Routing Table Note that the DNP Routing Table is a list of routes which are maintained in ascending order of DNP addresses typedef struct RoutingTable_type UINT16 address a UINT16 comPort L UINT16 retries UINT16 timeout routingTable e address is the DNP address e comPort is the serial port interface station address com port interface number of retries timeout in milliseconds e
335. rt tasks Main Loop while TRUE Perform application functions Initialization actions typically consist of variable declarations variable initialization and one time actions that must be performed when the program starts running Supporting tasks see Real Time Operating System section are typically created before the main loop of the program Tasks can be created and ended dynamically during the execution of a program as well The main loop of a program is always an infinite loop that continually performs the actions required by the program The main function normally never returns Example The following is an example of a three module program Each function is stored in a separate file This program will be used in subsequent examples File funcl c include lt ctools h gt void funcl void fputs This is function 1 r n coml File func2 c include lt ctools h gt ISaGRAF C Tools User and Reference Manual 10 May 8 2007 void func2 void fputs This is function 2 r n coml File main c include lt ctools h gt extern void funcl void extern void func2 void void main void funcl while TRUE func2 Start Up Function Structure The user s main function is called from the appstart function of the C Tools It is not necessary to understand the appstart function to write programs However it performs a number of usef
336. rtchandler IME now IME new i 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 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 ISaGRAF C Tools User and Reference Manual 209 May 8 2007 interruptCounter Read Interrupt Input Counter Syntax include lt ctools h gt unsigned long interruptCounter unsigned clear Description The interruptCounter routine reads the interrupt input as a counter If clearis TRUE the counter is cleared after reading otherwise if it is FALSE the counter continues to accumulate Notes Th
337. s release_resource IO_SYSTEM Install clock handler function installClockHandler alarmHandler Create task for processing alarm events create_task processAlarms 3 APPLICATION 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 body of main task loop other processing code Allow other tasks to execute release_processor ISaGRAF C Tools User and Reference Manual May 8 2007 193 installDbaseHandler Install User Defined Dbase Handler Syntax include lt ctools h gt void installDbaseHandler BOOLEAN handler unsigned address int 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 ISaGRAF application downloaded or e There is no ISaGRAF 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
338. s 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 inputs Refer to the SCADAPack 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 readCounter Read a controller counter with or without automatic clearing of the counter register interruptCounter Read the controller interrupt input as a counter with or without automatic clearing of the counter value ioRead4Counter Read any 4 point Counter input module Counter Input Macros The ctools h file defines the following macro for use with counter inputs Refer to the C Tools Macros section for details LOCAL_COUNTERS Number of controller counter inputs ISaGRAF C Tools User and Reference Manual 39 May 8 2007 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 all 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 second The sequence then repeats The sequence may be read as the Controller Status Code Refer to the SCADAPack Syst
339. s required or just occurred switch event case DNP_CONNECTION_REQUIRED indicate connection is needed and clear other bits request_resource IO_SYSTEM setdbase MODBUS CONNECTION_REQUIRED 1 setdbase MODBUS MESSAGE_COMPLETE 0 setdbase MODBUS MESSAGE_FAILED 0 release_resource IO_SYSTEM break case DNP_MESSAGE_COMPLETE indicate message sent and clear other bits 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 ISaGRAF C Tools User and Reference Manual 99 May 8 2007 Go sews e naan N N ee ou ae Seo eo aee ee oa Soe eee Seo ewe ae 7 E ne Se main 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 eae Gate a eat ga aap ei eet gg eg cg a ale a a le i ay void main void int lastConnectionState last state of connection register int currentConn
340. se returns response received e HR_NoResponse returns no response after all attempts e HR_WaitTransmit returns modem is not ready to transmit HART_SETTINGS The HART_SETTINGS type is a structure containing the configuration for the HART modem module The useAutoPreamb1e 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 unsigned attempts unsigned preambles BOOLEA useAutoPreamble unsigned deviceType HART_SETTINGS e 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 HART_VARIABLE 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 Note that not all fields will be used by all commands Refer to the command specific documentation typedef struct hartVariable_t float value unsigned units unsigned variableCode HART_VARIABLE e value is the value of the variable e units are the units of measurement e variableCode is the transmitter sp
341. set function resets the target controller to default settings Configuration parameters are reset to default values All other registers are set to zero All forcing is removed Locked variables are unlocked Set all database locations to zero Clear real time clock alarm settings Clear serial port event counters Clear store and forward configuration Enable LED power by default and return to default state after 5 minutes Set Outputs on Stop settings to Hold Set 5904 HART modem configuration for all modems Set Modbus TCP default configuration 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 ISaGRAF program The IO_SYSTEM resource must be requested before calling this function Example include lt ctools h gt void main void Power Up Initialization request_resource IO_SYSTEM ioDatabaseReset release_resource IO_SYSTEM the rest of the program ISaGRAF C Tools User and Reference Manual 226 May 8 2007 ioRefresh Update Outputs with Internal Data Syntax include lt ctools h gt void ioRefresh void Description The ioRefresh function resets devices on the 5000 series I O bus Input channels are scanned to update their values from the I O hardware Output channels are scanned to write
342. sor Display Status of Pulse Train tinfo read_timer_info 10 printf Pulses Remaining d r n tinfo time 2 printf Output Channel Sd r n tinfo channel printf Output Bit Sd r n tinfo bit ISaGRAF C Tools User and Reference Manual 330 May 8 2007 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 messages See Also send_message poll_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 printf Message data ld r n msg gt data deallocate_envelope msg ISaGRAF C Tools User and Reference Manual 331 May 8 2007 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 priorit
343. source 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 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 Care must be taken 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 access 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 ISaGRAF C Tools User and Reference Manual 19 May 8 2007 release_resource Free a resource for use by other tasks lO SYSTEM Resource The lO_SYSTEM resource regulates access to all 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 prevent a conflict as protocols and background operations are interrupt driven Do not retain control of the resource for more that 0 1 seconds or background operations will not execute properly DYNAMIC_MEM
344. splays the values of the 8 digital inputs and 8 analog inputs read from 5506 I O module 3 include lt ctools h gt void main void UINT16 point UCHAR dinData INT16 ainDataArray 8 Read input data from 5506 I O module request_resource IO_SYSTEM isaRead5506Inputs 3 dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r for point 0 point lt 7 point ISaGRAF C Tools User and Reference Manual 240 May 8 2007 fprintf coml n r d if the point is on point if dinData amp 1 lt lt point 0 putchar 1l putchar 0 Print analog input data fprintf coml r nAin Point for point 0 point lt 8 fprintf coml Value n r point d n r point ainDataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 241 isaRead5601Inputs Read SCADAPack Lower I O Module Inputs Syntax include lt ctools h gt unsigned isaRead5601Inputs unsigned dinData int ainDataArray Description The isaRead5601Inputs function reads the digital and analog inputs from a 5601 I O Module SCADAPack lower I O module Data is read from all 16 digital inputs and copied to the 16 bit value pointed to by dinData Data is read from all 8 analog inputs and copied to the array pointed to by ainDataArray dinData must point to a 16 b
345. sponse 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 ee Ss oases eats void wait_for_response FILE stream unsigned time struct prot_status status static unsigned long good bad interval 0 1 settimer 0 time do Allow other tasks to execute release_processor status get_protocol_status stream while timer 0 amp amp status command MM_SENT ISaGRAF C Tools User and Reference Manual 285 May 8 2007 if status command MM_RECEIVED good else bad fprintf com1 Good 8lu Bad 8lu r good bad main The main function sets up serial ports then sends commands to a Modbus slave E7 void 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 3 settings SFMessaging 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 DISABLE portset flow_tx DISABLE portset typ RS232 portset timeout 600 set_p
346. sting the O_SYSTEM resource ensures 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 Example dbaseHandler c This is a sample program for the installDbaseHandler and installSetdbaseHandler functions This sample program demonstrates database handlers for the Modbus registers 1001 to 1100 and 31001 to 31100 When the handlers are installed calls to the functions dbase or setdbase for these Modbus registers will call these handlers This ISaGRAF C Tools User and Reference Manual 197 May 8 2007 is true as long as the register is not already assigned to an ISaGRAF variable Note that the dbase and setdbase functions are used by C applications and by all protocols E include ctools h See section on Data Storage in this manual if coilDbase and inputDbase need to be saved when controller is off static unsigned charcoilDbase 100 static unsigned inputDbase 100 static BOOLEAN dbaseHandler unsigned address Modbus register address int value pointer to value at address if address gt 1000 amp amp address lt 1100 value coilDbase address 1001 return TRUE else if address gt 31000
347. t 0 fprintf coml It s COLD r n lse if temperature gt 90 fprintf coml It s HOT r n ISaGRAF C Tools User and Reference Manual May 8 2007 IT 328 readTimerVariable Read ISaGRAF Timer Variable Syntax include lt ctools h gt BOOLEAN readTimerVariable unsigned char varName unsigned long 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 ISaGRAF 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 SaGRAF Symbols Status is invalid FALSE is returned and the current value is left unchanged The ISaGRAF Symbols Status is invalid if the Application TIC code download and Application Symbols download do not share the same symbols CRC checksum Notes This function requires the ISaGRAF Application Symbols to be downloaded to the controller in addition to the Application TIC code This function provides a convenient method to access ISaGRAF variables by name however because the variable name must be looked up in the ISaGRAF variable list each call the performan
348. t Occurrence Syntax include lt ctools h gt int poll_event int 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 See Also signal_event startTimedEvent Example This program implements a somewhat inefficient transfer of data between com1 and com2 It would be more efficient to test for EOF from getc include lt ctools h gt void main void while TRUE if poll_event COM1_RCVR fputc getc coml com2 if poll_event COM2_RCVR fputc getc com2 coml Allow other tasks to execute release_processor ISaGRAF C Tools User and Reference Manual 307 May 8 2007 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 message has been received The current task always continues to execute Notes Refer
349. t be set to RS232_MODEM Normally this function should be called once the modemInitStatus 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 modemlnitEnd 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 See Also modemAbort modemAbortAll modemDial modemDialEnd modemDialStatus modemlnit modemlnitStatus modemNotification ISaGRAF C Tools User and Reference Manual 302 May 8 2007 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 modemInitStatus function returns the status a modem initialization started by the modemlnit function port specifies the serial port where the modem is installed id is the port reservation identifier returned by the modemlnit 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 di
350. t ctools h gt This function processes Enron Modbus commands UINT16 commandHandler UINT16 length HAR pCommand NT16 responseSize NT16 pResponseLength HAR pResponse QHHA UCHAR command UINT16 result if a command byte was received if length gt 1 get the command byte command pCommand 0 switch command read unit status command case 7 if the response buffer is large enough if responseSize gt 2 build the respons pResponse 1 17 pResponseLength 2 indicate the command worked ISaGRAF C Tools User and Reference Manual May 8 2007 header pResponse 0 pCommand 0 set the unit status set response length 150 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 handler when the main task ends 7 void mainExitHandler void unhook the handler function enroniInstallCommandHandler NULL void main void TASKINFO thisTask install handler to execute when this task ends thisTask getTaskInfo 0
351. t data to SCADAPack 100 I O request_resource IO_SYSTEM isaWriteSP1000utputs digitalData release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 278 May 8 2007 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 series 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 ISaGRAF C Tools User and Reference Manual 279 May 8 2007 ledPower Set LED Power State Syntax include lt ctools h gt unsigned ledPower unsigned 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 must 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 ledSetDefault ISaG
352. t 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 255 occurrences of an event will be recorded The current task is blocked of there is a higher priority task waiting for the event Notes Refer to the Real Time Operating System section for more information on events This function must only be used within an interrupt handler Valid events are numbered 0 to RTOS_EVENTS 1 Any events defined in ctools h are not valid events for use in an application program See Also signal_event startTimedEvent installClockHandler ISaGRAF C Tools User and Reference Manual 214 May 8 2007 interval Set Timer Tick Interval Syntax include lt ctools h gt void interval unsigned timer unsigned value Description The interval function sets the tick interval for timer to value Tick intervals are measured in multiples of 0 1 second If the timer number is invalid the task s error code is set to TIMER_BADTIMER Notes The default timer tick interval is 1 10 second See Also settimer Example Set timer 5 to count 12 seconds using 1 0 s ticks interval 5 10 1 0 s ticks settimer 5 12 time 12 seconds Set timer 5 to count 12 seconds using 0 1 s ticks interval 5 1 0 1 s ticks settimer 5 120 time 12 seconds ISaGRAF C Tools User and Reference Manual 215 May 8 20
353. tBOConfig Get DNP Binary Output Configuration Syntax include lt ctools h gt BOOLEAN dnpGetBOConfig UINT16 point dnpBinaryOutput pBinaryOutput 3 Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveBOConfig Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetCl16Config Get DNP 16 bit Counter Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetCI1l6Config UINT16 point dnpCounterInput pCounterInput i Description This 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 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 must be enabled before calling this function in order to create the DNP configuration See Also
354. tCI32 is number of 32 bit counter events ISaGRAF C Tools User and Reference Manual May 8 2007 ntAI16 is number of 16 bit analog input events ntAI32 is number of 32 bit analog input events input events counter events counter events analog input events analog input events UINT16 eventCountAISF number of short floating point analog input events INT16 eventCountClassl number of class 1 events UINT16 eventCountClass2 number of class INT16 eventCountClass3 number of class 2 events 3 events 413 e eventCountAISF is number of short floating point analog input events e eventCountClass1 isthe class 1 event counter e eventCountClass2 is the class 2 event counter e eventCountClass3 is the class 3 event counter envelope The envelope type is a structure containing a message envelope Envelopes are used for inter task communication typedef struct env struct env xlink unsigned source unsigned destination unsigned type unsigned long data unsigned owner 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 the 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 messa
355. tDevice_t unsigned char manufacturerID unsigned char manufacturerDeviceType unsigned char preamblesRequested unsigned char commandRevision unsigned char transmitterRevision unsigned char softwareRevision unsigned char hardwareRevision unsigned char flags unsigned long devicelID HART_DEVICE HART_RESPONSE 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 unsigned responseCode unsigned length char data DATA_SIZE HART_RESPONSE e response is the response code from the device e length is the length of response data e data DATA_SIZ Gl is the data field for the response HART RESULT 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 ISaGRAF C Tools User and Reference Manual 415 May 8 2007 e HR_CommandSent returns command sent e HR_Respon
356. taArray EM release_resource IO_SYS Print module data fprintf coml Point for point 0 point lt fprintf coml Sd EM Value n r 8 point t Sd n r point dataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 250 isaRead8sDin Read 8 Digital Inputs Syntax include lt ctools h gt unsigned isaRead8Din unsigned moduleAddress unsigned char data Description The isaRead8Din function reads any 8 point Digital Input Module at the specified moduleAddress Data is read from all 8 digital inputs and copied to the 8 bit value pointed to by data The function returns FALSE if the moduleAddress is invalid or if an I O error occurs otherwise TRUE is returned The valid range for moduleAddress is 0 to 15 The IO_SYSTEM resource must be requested before calling this function See Also isaRead16Din Example This program displays the values of the 8 digital inputs read from an 8 point Digital Input Module at module address 0 include lt ctools h gt void main void unsigned point unsigned char dinData Read data from digital input module request_resource IO_SYSTEM isaRead8Din 0 amp dinData release_resource IO_SYSTEM Print module data fprintf coml Point Value for point 0 point lt 8 pointt t fprintf coml n r d point putchar dinData amp 0x01 1 0 d
357. 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 Start Up Task Info Structure The ctools h file defines the structure Start Up Information Structure 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 five library functions related to controller program status information Refer to the Function Specification section for details on each function listed applicationChecksum Returns the application program checksum getBootType Returns the controller boot up status getProgramStatus Returns the application program execution status setBootType Sets the controller boot up status setProgramStatus Sets the application program execution status ISaGRAF C Tools User and Reference Manual 32 May 8 2007 Program Status Information Macros The ctools h file defines the following macros for use with controller program information Refer to the C Tools Macros section for details on each macro listed NEW_PROGRAM Application program is newly loaded PROGRAM_EXECUTED Application program has been executed COLD_BOOT Controller started in COLD BOOT mode RUN Controller started in RUN mode SERVICE Controller started in SERVICE mode REENTRY_BOOT Controller
358. tate DS_Calling Terminate the initialization modemInitEnd coml portID amp status 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 The shutdown function aborts any active modem connections when the task is ended void shutdown void modemAbort com1 void 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 ISaGRAF C Tools User and Reference Manual May 8 2007 51 portSettings stop_bits STOP1 portSettings flow_rx DISABLE portSettings flow_tx DISABLE portSettings type RS232_MODEM portSettings timeout 600 request_resource IO_SYSTEM set_port coml amp portSettings 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 F1l amp A0 amp KO amp MO amp B1 strcpy dialSettings phoneNumber 555 1212
359. tes The IO_SYSTEM resource must be requested before calling this function See Also getclock Example This function switches the clock to daylight savings time include lt ctools h gt include lt primitiv h gt void daylight void struct clock now request_resource IO_SYSTEM now getclock now hour now hour 1 24 setclock amp now request_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 346 May 8 2007 setClockAlarm Set the Real Time Clock Alarm Syntax include lt ctools h gt unsigned setClockAlarm ALARM_SETTING alarm Description The setClockAlarm function configures the real time clock to alarm at the specified alarm setting The ALARM_SETTING structure a arm specifies the time of the alarm Refer to the rtc 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 lO_SYSTEM resource must be requested before calling this function See Also alarmi
360. the C Tools Macros section for details on each macro listed The ctools h file defines the following macros READSTATUS enumeration type ReadStatus WRITESTATUS enumeration type WriteStatus I O Bus Communication Types The ctools h file defines the enumeration types ReadStatus and WriteStatus Refer to the C Tools Structures and Types section for complete information on structures and enumeration types System Functions 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 applicationChecksum Returns the application program checksum ioClear Clears all I O points ioDatabaseReset Resets the controller to default settings ioRefresh Refresh outputs with internal data ISaGRAF C Tools User and Reference Manual 36 May 8 2007 ioReset Reset all I O modules Controller I O Hardware This section of the manual provides an overview of the ISaGRAF C Tools functions relating to controller signal input and output I O These functions are provided in addition to the run time library supplied with the Microtec C compiler Analog Input Functions The controller supports internal analog inputs and external analog input modules Refer to the SCADAPack System Hardware Manual for further
361. the program is loaded in ROM it cannot modify the variable a If the program is loaded in RAM it can be run once after being written to a controller memory All subsequent attempts to run the program will fail void main void static int a 1 arty other code here Working Around the Problem There are two ways to work around the problem 1 Use global variable instead of a local variable For example static int a 1 void main void att other code here ISaGRAF C Tools User and Reference Manual 426 May 8 2007 2 Ifthe local variable is to be initialized to zero then a non initialized static local variable can be used For example void main void static int a att other code here In this example the declaration static int a is the same as the following static int a 0 The operating systems sets non initialized variables stored in the zerovars section to zero before running the program Correction to the Problem This problem exists with the C Compiler supplied by Microtec It will not be corrected Users must work around the problem as described above Use of pow Function The compiler sometimes incorrectly evaluates expressions involving the pow function with other arithmetic Also a task calling the pow function requires at least 5 stack blocks The need for more stack space by the pow function is not a compiler problem it is simply a requirement of po
362. then the user s application program runs An error is likely only if the program in RAM has been damaged or improperly linked if _initcopy 0 main If the main function returns the task is ended First any modem control sessions started by the application are terminated abortAllDialupApps Then the task is ended This will cause all other APPLICATION tasks created by main to be stopped as well taskStatus getTaskInfo 0 end_task taskStatus taskID 1 Stack space is required to create additional tasks Refer to the create_task function for more information coms is used only in the SCADAPack and SCADAPack PLUS controllers 3 com4 is used only in the SCADAPack LIGHT and SCADAPack PLUS controllers ISaGRAF C Tools User and Reference Manual 12 May 8 2007 Data Storage All non initialized variables local and global are initialized to zero on program startup by the Microtec C Compiler The I O database is the only se ction of memory that is not initialized to zero on startup Data stored in the I O database is maintained when power to the controller is lost and remains until the controller is initialized from the ISaGRAF program In most cases the I O database provides adequate space for data storage However if additional non initialized memory is required for example for an array of custom data structures an non initialized section of memory can be created as shown in the example
363. ther 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 function 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 Macros The ctools h file defines the following macros for use with LED power control Refer to the C Tools Macros section for details on each macro listed LED_OFF Specifies LED is to be turned off LED_ON Specifies LED is to be turned on 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 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 ISaGRAF C Tools User and Reference Manual 41 May 8 2007 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
364. this function Example include lt ctools h gt void main void request_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 349 May 8 2007 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 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 ISaGRAF C Tools User and Reference Manual 350 May 8 2007 setDTR Control RS232 Port DTR Signal Syntax include lt ctools h gt void setDTR FILE stream unsigned state Description The setDTR function sets the status of the DTR signal line for the communication port specified by stream 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 ISaGRAF C Tools User and Reference Manual 351 May 8 2007 setlOErrorindication Set I O Module Error Indication Syntax include lt ctools h gt void setIOErrorIndication unsigned state Description The setlOErrorIndication function
365. this product you agree to these terms Modifications Control Microsystems reserves the right to make modifications to the ISaGRAF C Tools and to change its specifications without notice Non Disclosure SCADAPack TeleSAFE and TelePACE are registered trademarks of Control Microsystems The ISaGRAF C Tools is a copyrighted product of Control Microsystems Users are specifically prohibited from copying the ISaGRAF C Tools in whole or in part by any means whatsoever except for purposes of a backup copy and from disclosing proprietary information belonging to Control Microsystems ISaGRAF C Tools User and Reference Manual 429 May 8 2007
366. timeoutRequest Example See the example for the timeoutRequest function ISaGRAF C Tools User and Reference Manual 376 May 8 2007 timeoutRequest Request Timeout Notification Function Syntax include lt ctools h gt unsigned timeoutRequest unsigned delay envelope pEnvelope Description This function requests a timeout notification A message is sent to the task specified in the envelope after the specified delay A task receives the message using the receive_message or poll_message function The envelope received by the receiving task has the following characteristics e The source field is set to the task ID of the task that called t imeoutRequest e The message type field is set to MSG_TIMEOUT e The message data is set to the timeout ID The function has two parameters the length of time in tenths of a second before the timeout occurs and a pointer to an envelope The resolution of the delay is 0 1 0 seconds The notification message is sent delay 1 to delay tenths of a second after the function call The function returns the ID of the timeout request This can be used to identify and cancel the timeout The timeout ID changes with each call to the function Although the ID will eventually repeat it is sufficiently unique to allow the timeout notification to be identified This can be useful in identifying notifications received by a task and matching them with requests Notes Do not de alloc
367. tion for details on each function listed dnplinstallConnectionHandler Configures the connection handler for DNP dnpClearEventLog Deletes all change events from the DNP change event buffers dnpConnectionEvent Report a DNP connection event dnpCreateRoutingTable Allocates memory for a new routing table ISaGRAF C Tools User and Reference Manual 59 May 8 2007 dnpGenerateEventLog dnpGetConfiguration dnpGetConfigurationEx dnpSaveConfiguration dnpSaveConfigurationEx dnpGetBIConfig dnpSaveBlConfig dnpSaveBlConfigEx dnpGetBOConfig dnpGetBIConfigEx dnpSaveBOConfig dnpGetAl16Config dnpSaveAl16Config dnpGetAl32Config dnpSaveAlSFConfig dnpGetAlSFConfig dnpSaveAl32Config dnpGetA0O16Config dnpSaveAO16Config dnpGetAO32Config dnpSaveAO32Config dnpSaveAOSFConfig dnpGetAOSFConfig dnpGetCl16Config dnpSaveCl16Config dnpGetCl32Config dnpSaveCl32Config dnpGetRuntimeStatus dnpSendUnsolicited dnpSendUnsolicitedResponse Generates a change event for the DNP point Reads the DNP protocol configuration Reads the extended DNP configuration parameters Writes the DNP protocol configuration parameters Writes the extended DNP configuration parameters Reads the configuration of a DNP binary input point Writes the configuration of a DNP binary input point Writes the configuration of an extended DNP Binary Input point Reads the configuration of a DNP binary output point Reads the configuration of an extended DNP Binary I
368. tion 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 See Also signal_event startTimedEvent Example See the example for the signal_event function ISaGRAF C Tools User and Reference Manual 380 May 8 2007 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 See Also wd_manual wd_pulse Example See the example for the wd_manual function ISaGRAF C Tools User and Reference Manual May 8 2007 381 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 must retrigger the watchdog timer at least every 0 5 seconds using the wd_pulse function to prevent an controller reset Refer to the Functions Overview section for more information See Also wd_auto wd_pulse 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 void main void wd_manual wd_pulse code executing in less than
369. tion response ISaGRAF C Tools User and Reference Manual 203 May 8 2007 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 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 66 _ TeleBUS extension Used by TelePACE _ _ _ 68__ TeleBUS extension Used by TelePACE _ __ o 69 TeleBUS extension Used by TelePACE __ Z 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 release the appropriate resources to ensure proper operation 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
370. tionTable Clear all store and forward translation table entries enroninstallCommandHandler Installs handler for Enron Modbus commands getABConfiguration Reads DF1 protocol configuration parameters get_protocol Reads protocol parameters ISaGRAF C Tools User and Reference Manual 53 May 8 2007 getProtocolSettings getProtocolSettingsEx get_protocol_status getSFMapping getSFTranslation installModbusHandler master_message modbusExceptionStatus modbusSlavelD pollABSlave resetAlIABSlaves setABConfiguration set_protocol setProtocolSettings setProtocolSettingsEx setSFMapping setSFTranslation start_protocol Reads extended addressing protocol parameters for a serial port Reads extended addressing and Enron Modbus protocol parameters for a serial port Reads protocol message and error counters This function is a stub and no longer performs a necessary operation Read store and forward translation table entry This function allows user defined extensions to standard Modbus protocol Sends a protocol message to another device Sets response for the read exception status function Sets response for the read slave ID function Requests a response from a slave controller using the half duplex version of the protocol Clears responses from the response buffers of half duplex slave controllers Defines DF1 protocol configuration parameters Sets protocol parameters and starts protocol Sets exten
371. to the Real Time Operating System section for more information on messages See Also send_message receive_message 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 ISaGRAF C Tools User and Reference Manual 308 May 8 2007 poll_ resource Test Resource Availability Syntax include lt ctools h gt int poll_resource int 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 request_resou rce re lease_resou rce ISaGRAF C Tools User and Reference Manual 309 May 8 2007 portConfiguration Get Pointer to Port Configuration Structure Syntax include lt ctools h gt struct pconfig portConfiguration FILE stream Description The portConfiguration function returns a pointer to the configuration structure for stream A NULL pointer is returned if stream is not valid
372. ts Example This program displays the values of the 5 inputs read from a 5602 I O Module as both digital and analog inputs include lt ctools h gt void main void unsigned point unsigned char dinData int ainDataArray 5 Read input data from 5601 module request_resource IO_SYSTEM isaRead5602Inputs amp dinData ainDataArray release_resource IO_SYSTEM Print digital input data fprintf coml Din Point Value n r for point 0 point lt 5 point t ISaGRAF C Tools User and Reference Manual 244 May 8 2007 fprintf coml n r d We POENE putchar dinData amp 0x01 1 0 dinData gt gt 1 Print analog input data fprintf coml r nAin Point Value n r for point 0 point lt 5 point t fprintf coml d Sd n r point ainDataArray point ISaGRAF C Tools User and Reference Manual May 8 2007 r 245 isaRead5604Inputs Read 5604 Inputs Syntax include lt ctools h gt unsigned isaRead5604Inputs UCHAR dinData INT16 ainDataArray Description The isaRead5604Inputs function reads the digital and analog inputs from 5604 I O module Data is read from all 35 digital inputs and copied to the array pointed to by dinData Data is read from all 10 analog inputs and copied to the array pointed to by ainDataArray dinData must point to an array of five 8 bit unsigned characters Each bit in the array represents one input
373. ture 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 lO_SYSTEM resource must be requested before calling this function See Also getClockAlarm setClockAlarm Example include lt ctools h gt Ne a ee a NE ey E E a a conservePower The conservePower function places the controller into sleep mode for 10 minutes E a er eee ee void conservePower void ALARM_SETTING alarm request_resource IO_SYSTEM Alarm in 10 minutes alarm alarmIn 0 10 0 setClockAlarm alarm Put controller in low power mode sleep release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 64 May 8 2007 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 A
374. ual references only those features of the ISaGRAF Workbench pertaining to the C Program Loader dialog Please refer to the chapter Controller Commands and Options of the 1EC1131 Reference and User Manual for a complete description of the following ISaGRAF Workbench menus which will be useful during C Program development Additional Documentation Additional documentation on ISaGRAF IEC 61131 3 and the TeleSAFE Micro16 and SCADAPack controllers is found in the following documents The on line help for the ISaGRAF C program loader contains a complete reference to the operation of the loader To display on line help select Contents from the Help menu The SCADAPack amp Micro16 System Manual is a complete reference to controller and I O modules used with SCADAPack and Micro16 controllers It contains the SCADAPack Controller Hardware Manuals the TeleSAFE Micro16 System Manual and hardware manuals for all 5000 Series I O modules The TeleBUS Protocols User Manual describes communication using Modbus compatible protocols ISaGRAF C Tools User and Reference Manual 5 May 8 2007 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 System Requirements ISaGRAF C Tools requires the following minimum system configurat
375. uccessful WS selectFailed slave could not be selected WS_noAcknowledge slave failed to acknowledge data Notes The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadByte ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusSelectForWrite ioBusWriteByte Example include lt ctools h gt void main void unsigned char message 10 unsigned char ioBusAddress 114 WRITESTATUS status request_resource IO_SYSTEM Write a 10 byte message to I2C device status i1oBusWriteMessage ioBusAddress 10 message release_resource IO_SYSTEM if status WS_success fprintf coml I O error d n r status ISaGRAF C Tools User and Reference Manual 224 May 8 2007 ioClear Turn Off all Outputs Syntax include lt ctools h gt void io_clear void Description The ioClear function turns off all outputs as follows e analog outputs are set to 0 e digital outputs are turned set to 0 turned off Also all delayed digital I O actions started by the pulse pulse_train and timeout functions are always canceled Notes The IO_SYSTEM resource must be requested before calling this function ISaGRAF C Tools User and Reference Manual 225 May 8 2007 ioDatabaseReset Initialize O Database with Default Values Syntax include lt ctools h gt void ioDatabaseReset void Description The ioDatabaseRe
376. ul functions that can be modified by the user The start up code has five major functions e create and initialize the application program heap for dynamic memory allocation e specify the number of stack blocks allocated to the main task e initialize application program variables e control execution of the protocol ladder logic and background I O tasks e execute the main function Source code for the function is supplied with the C Tools The following discussion refers to statements found in the file appstart c The heap is a section of memory used by dynamic memory allocation functions such as malloc The heap starts at the end of RAM used by the program and continues to the end of physical RAM The limit is set by the statement end_of_heap EQU 41ffffh The limit is set by default to the smallest memory option available for the controller If your controller has more memory change the value of the constant according to the following table RAM Installed C Application Program RAM Addresses 128 Kbytes none ladder logic only 256 Kbytes 640 Kbytes 400000h 47FFFFh 640 Kbytes 1024 Kbytes 388000h 3E7FFFN 400000h 47FFFFh ISaGRAF C Tools User and Reference Manual 11 May 8 2007 The application program signature section of the file contains a constant that determines the size of the stack allocated to the main task The stack size is sufficient for most applications It can be changed by mod
377. ule number is invalid Notes The HART_DEVICE structure must be initialized using hartCommandoO or hartCommand1 1 The function returns immediately after the command is sent The calling program must 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 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 hartCommand33 hartStatus hartSetConfiguration ISaGRAF C Tools User and Reference Manual 181 May 8 2007 hartCommand11 Read Unique Identifier Associated with Tag Syntax include lt ctools h gt BOOLEAN hartCommandll unsigned 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 devic
378. unction See Also ioBusStop ioBusReadByte ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusSelectForWrite ioBusWriteByte ioBusWriteMessage Example See example for ioBusReadByte ISaGRAF C Tools User and Reference Manual May 8 2007 221 ioBusStop Issue an FC Bus STOP Condition Syntax include lt ctools h gt void ioBusStop void Description The ioBusStop function issues an 1 C bus STOP condition Notes The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusReadByte ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusSeleciForWrite ioBusWriteByte ioBusWriteMessage Example See example for ioBusReadByte ISaGRAF C Tools User and Reference Manual May 8 2007 222 ioBusWriteByte Write One Byte to PC Slave Device Syntax include lt ctools h gt unsigned ioBusWriteByte unsigned char byte Description The ioBusWriteByte function writes one byte to an I C slave device and returns the acknowledge signal from the slave It returns TRUE if the write succeeded that is the byte was acknowledged by the slave It returns FALSE if the write failed that is the byte was not acknowledged by the slave This function can be used multiple times in sequence to write data to a device Notes ioBusWriteByte can be used to write the address selection byte at the start of an I C message however the ioBusSelectForRead and ioBusSelectForWrite f
379. unction See Also ioBusWriteMessage ioBusStart ioBusStop ioBusReadByte ioBusReadLastByte ioBusSelectForRead ioBusSelectForWrite ioBusWriteByte ioBusWriteMessage Example include lt ctools h gt void main void unsigned charmessage 10 unsigned char ioBusAddress 114 READSTATUS status request_resource IO_SYSTEM Read a 10 byte message from I2C device status i1oBusReadMessage ioBusAddress 10 message release_resource IO_SYSTEM if status RS_success fprintf com1 I O error d n r status ISaGRAF C Tools User and Reference Manual 218 May 8 2007 ioBusSelectForRead Select PC Slave Device for Reading Syntax include lt ctools h gt unsigned ioBusSelectForRead unsigned char address Description The ioBusSelectForRead function selects an C slave device for reading It writes the slave device address with the read write bit set to the read state The function handles the formatting of the address byte The function has one parameter the address of the device It returns TRUE if the write succeeded that is the byte was acknowledged by the slave It returns FALSE if the write failed that is the byte was not acknowledged by the slave Notes This function can only be used immediately after a START condition e g ioBusStart The IO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadByte i
380. unction See Also isaWrite2Aout isaWrite4Aout isaWrite5303Aout Example This program sets all 4 analog outputs to half scale on a 5304 Analog Output Module at module at address 0 include lt ctools h gt void 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 5304 analog output module request_resource IO_SYSTEM isaWriteAout 0 105304 dataArray release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 276 May 8 2007 isaWriteLPOutputs Write to SCADAPack LP Outputs Syntax include lt ctools h gt unsigned isaWriteLPOutputs unsigned doutData int aoutData 2 Description The isaWriteLPOutputs function writes data to the digital and analog outputs of the SCADAPack LP I O doutData is the digital output data The first 12 bits of the specified 16 bit data value are written to the 12 digital outputs aoutData is an array of two analog output values The function returns FALSE if an I O error occurs otherwise TRUE is returned Notes When this function writes data to the SCADAPack LP I O it also processes the transmit buffer for the com3 serial port The com serial port is also continuously processed automatically The additional service to the com3 receiver caused by this function does not affect the normal automatic operati
381. unctions provide a more convenient interface for doing this The lO_SYSTEM resource must be requested before calling this function See Also ioBusStart ioBusStop ioBusReadByte ioBusReadLastByte ioBusReadMessage ioBusSelectForRead ioBusSelectForWrite ioBusWriteMessage Example include lt ctools h gt void main void unsigned char data 2 unsigned char ioBusAddress 114 request_resource IO_SYSTEM ioBusStart if ioBusSelectForWrite ioBusAddress ioBusWriteByte data 0 ioBusWriteByte data 1 ioBusStop release_resource IO_SYSTEM ISaGRAF C Tools User and Reference Manual 223 May 8 2007 ioBusWriteMessage Write Message to FC Slave Device Syntax include lt ctools h gt WRITESTATUS ioBusWriteMessage unsigned address unsigned numberBytes unsigned char message Description The ioBusWriteMessage function writes a specified number of bytes to an I C slave device The function issues the START condition selects the device for writing writes the specified number of bytes and issues a STOP condition If the slave fails to acknowledge the selection or any data written to it the write is aborted immediately The function has three parameters the address of the device the number of bytes to write numberBytes and a pointer to the buffer message containing the data The function returns the status of the write Value Description WS _ success write was s
382. uration ABConfig getABConfiguration coml amp ABConfig printf Min protected address Su r n ABConfig min_protected_address printf Max protected address Su r n ABConfig max_protected_address ISaGRAF C Tools User and Reference Manual May 8 2007 153 getBootType Get Controller Boot Up State Syntax include lt ctools h gt unsigned getBootType void Description The getBootType function returns the boot up state of the controller The possible return values are SERVICE controller started in SERVICE mode RUN controller started in RUN mode Example include lt ctools h gt void main void struct prot_settings settings Disable the protocol on serial port 1 settings type NO_PROTOCOL settings station 1 settings priority 3 settings SFMessaging FALSE request_resource IO_SYSTEM set_protocol coml amp settings release_resource IO_SYSTEM Display the boot status information printf Boot type d r n getBootType ISaGRAF C Tools User and Reference Manual May 8 2007 154 getclock Read the Real Time Clock Syntax include lt rtc h gt struct clock getclock void Description The getclock function reads the time and date from the real time clock hardware The getclock function returns a struct clock containing the time and date information Notes The time format returned by the getclock function is n
383. urce unsigned 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 OR ed together e WS NONE e WS _ALL e WS _REAL_TIME CLOCK e WS_INTERRUPT_INPUT e WS_LED POWER_SWITCH e WS _COUNTER_0_OVERFLOW e WS _COUNTER_1_OVERFLOW e WS _COUNTER_2_ OVERFLOW Notes Specifying WS_NONE as the wake up source will prevent the controller from waking except by a power on reset See Also getWakeSource sleep Example The code fragments below show how to enable and disable wake up sources Wake up on all sources setWakeSource WS_ALL Enable wake up on real time clock only setWakeSource WS_REAL_ TINE _CLOCK ISaGRAF C Tools User and Reference Manual 366 May 8 2007 signal_event Signal Occurrence of Event Syntax include lt ctools h gt void signal_event int 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 255 occurrences of an event will be recorded The current task is blocked of there is a higher priority task waiting for the event Notes Refer to the Real Time Operating System section for mor
384. ure 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetAl32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetAl32Config Get DNP 32 bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAI32Config UINT32 point dnpAnalogInput pAnalogInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpSaveAl32Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpGetAlISFConfig Get Short Floating Point Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpGetAISFConfig UINT16 point dnpAnalogInput pAnalogInput Description This function
385. veAl16Config Save DNP 16 Bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAI16Config UINT16 point dnpAnalogInput pAnalogInput i Description This 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 must be enabled before calling this function in order to create the DNP configuration See Also dnpGetAl16Config Example See example in the dnpGetConfiguration function section ISaGRAF C Tools User and Reference Manual May 8 2007 dnpSaveAl32Config Save DNP 32 Bit Analog Input Configuration Syntax include lt ctools h gt BOOLEAN dnpSaveAI32Config UINT32 point dnpAnalogInput pAnalogInput i Description This 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 must be enabled before calling this function in order to
386. vents e BI_bufferSize 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 CI16_number is the number of 16 bit counter input points Valid values are 0 to 9999 e CI16_startAddress is the DNP address of the first C116 point e CI16_reportingMethod determines how Cl16 inputs are reported either Change Of State or Log All Events e CI16_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 CI32_startAddress is the DNP address of the first C132 point e CI32_reportingMethod determines how Cl32 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 C132 points O LSW first 1 MSW first e AI16_number is the number of 16 bit analog input points Valid values are O to 9999 e AI16_startAddress is the DNP address of the first Al16 point e AI16_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 AI16_bufferSize is the number of e
387. vents 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 O 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 ISaGRAF C Tools User and Reference Manual 407 May 8 2007 e Set this to CURRENT_VALUE to report the value of the latest change event measured A1I32_bufferSize is the number of events in the 32 bit analog input change buffer Valid values are 0 to 9999 A132_wordOrder is the Word Order of Al32 points O LSW first 1 MSW first AO16_number is the number of 16 bit analog output points Valid values are 0 to 9999 AO16_startAddress is the DNP address of the first AO16 point AO32_number is the number of 32 bit analog output points Valid values are 0 to 9999 AOQ32_startAddress is the DNP address of the first AO32 point AO32_wordOrder is the Word Order of AO32 points O LSW first 1 MSW first AOSF_number is the number of short float Analog Outputs AOSF_startAddress is the DNP address of first AOSF point 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 isthe maximum period to hold Class 1 events befor reporting hold
388. w Problems Caused Some arithmetic expressions involving the pow function may result in incorrect results When testing expressions that call pow if the result is found to be incorrect it will be consistently incorrect for all values used by variables in the expression The pow function requires at least 5 stack blocks If 4 or less stack blocks are used by the task calling pow the controller will overflow its stack space When the stack space overflows the behavior is unpredictable and will most likely cause the controller to reset Example The compiler generates incorrect code for the following example The result of this expression is incorrect for all values used for its variables void main void double a b c d 6 a pow b c d e other code here ISaGRAF C Tools User and Reference Manual 427 May 8 2007 Working Around the Problem There are two ways to work around the problem 1 To work around the problem compute the pow result on a separate line and use the result in the arithmetic expression afterwards For example void main void double a b c d e result result pow b c a result d e other code here Note that when a task calls the pow function it requires at least 5 stack blocks The default stack space allocated to the main task is only 4 blocks To modify the number of stack blocks allocated to the main task refer to the section Start Up Function Stru
389. watch time rolls over to 0 when it reaches the maximum value for an unsigned long integer 4 294 967 295 ms or about 497 days There is one library function to access the stopwatch time Refer to the readStopwatch section for details readStopwatch reads the stopwatch timer ISaGRAF C Tools User and Reference Manual 44 May 8 2007 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 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 prevent 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 all 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
390. wn J D R R Du lgo U Dp wn J O U n J O U N 4 n qG tg LICA TUP_SYSTI INPUT TATUS TION SYSTEM M ED E ep TES D nN A GI H Specifies a signal is asserted I O line bit mask ring signal Not supported forced low 0 I O line bit mask voice data switch signal Defined if sleep function is supported SmartWIRE 5201 and 5202 controllers STA K_SIZE START_COIL _HOLDING Size of the machine stack Start of the coils section in the linear database Start of the holding register section in the linear database Start of the input register section in the linear database Start of the status section in the linear database Specifies the application start up task Specifies the system start up task Specifies 1 stop bit Specifies 2 stop bits Specifies a system type task System tasks are not terminated by the end_application function T_K _R ELVIN ANKINE HI H H T Tj T T Ay T T SA MI H H H H H H z eal Hi H S Ss Ss El Gl O GJI H R_BADADD ER_BADINTE RO_16 E TI TI zal zg H n EX R_BADTIME R_BADVALUE R_MAX ECUTING TS_READY TS_WAIT RESOU TS_WAIT_ T_CELSIUS T_FAHRENHEIT TS_WAITT_EVENT TS_WAIT_MESSAGE Specifies temperatures in deg
391. y 8 2007 Load the Configuration Parameters DEFAU DEFAU TRUE DEFAU DEFAU DEFAU TRUE DEFAU DEFAU DEFAU 8 8 24 48 Izy LT_DNP_MASTER LT_DNP_RTU LT_DLINK_RETRIES LT_DLINK_TIMEOUT LT_OPERATE_TIMEOUT LT_MAX_RESP_LENGTH LT_APPL_RETRIES LT_APPL_TIMEOUT TIME_SYNC r DEFAULT_COS_BUFF DEFAULT_SOE_BUFF 116 configuration CI32_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 A032_number 8 configuration unsolicited TRUE configuration holdTime DEFAULT_HOLD_TIME configuration holdCount DEFAULT_HOLD_COUNT dnpSaveConfiguration 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 binaryOutput modbusAddress1l 1 index binaryOutput modbusAddress2 1 index binaryOutput controlType NOT_PAIRED dnpSaveBOConfig index amp binaryOutput Configure Bi
392. y Reads an entry from the routing table dnpReadRoutingTableSize Reads the total number of entries in the routing table dnpSearchRoutingTable Searches the routing table for a specific DNP address dnpWriteRoutingTableDialStrings Writes a primary and secondary dial string into an entry in the DNP routing table dnpReadRoutingTableDialStrings Reads a primary and secondary dial string from an entry in the DNP routing table 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 ISaGRAF Variable Access Functions Variables declared in an ISaGRAF application are accessed from a C application using the ISaGRAF variable access functions listed below Refer to the ISaGRAF C Tools Function Specifications 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
393. y run in a round robin fashion as each releases the processor to the next Notes The release_processor function must be called in all idle loops of a program to allow other tasks to execute 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 release_resou rce ISaGRAF C Tools User and Reference Manual 332 May 8 2007 release_resource Release Control of a Resource Syntax include lt ctools h gt void release_resource int 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 tasks 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 poll_resource Example See the example for the request_resource function ISaGRAF C Tools User and Reference Manual May 8 2007 report_error Set Task Error Code Syntax include lt ctools h gt void report_error int 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
Download Pdf Manuals
Related Search
Related Contents
Professional JUMP-sTarTer Professional BaTTerie D - CAT ABB i-bus® KNX Module 4/8 entrées BE/S Manuel d`utilisation produit Brochure - D3E Electronique Guide de sécurité pour les travaux de couverture 1 衛生管理の基準 [PDFファイル/494KB] Philips 77071/27/66 User Manual - Psn Copyright © All rights reserved.
Failed to retrieve file