Compare commits

...

16 Commits

Author SHA1 Message Date
2a7934b8d6 Fixed bug where arguments were given in the wrong order. 2025-05-05 08:51:34 +02:00
3071e402b2 Fixed bug in sinqMotor.db (bad field name) 2025-04-29 14:43:32 +02:00
dd0610fd99 Added connection assertion and moved msgPrintControl to key 2025-04-25 15:54:41 +02:00
c7936191d9 Added Connected PV 2025-04-25 13:17:41 +02:00
3ec83b115e Added further info on versioning to README.md 2025-04-24 09:17:05 +02:00
bfda809257 Added high default value for RDBD
See docstring: This is to prevent overshoot stop commands.
2025-04-23 13:46:02 +02:00
76a91d4a2f Added message print control for movement timout watchdog 2025-04-22 11:43:47 +02:00
228bcf7fd7 Renamed some member fields 2025-04-17 16:28:52 +02:00
db03ffea0e Added adaptive polling
See documentation in README.md for parameter ADAPTPOLL
2025-04-16 13:05:48 +02:00
4c3254687d Renamed "ipPortUser_" to "ipPortAsynOctetSyncIO_"
I learned that there might be multiple asynUsers connected to the same
port for different types (asynInt32, asynOctet, ...). Therefore I
renamed "ipPortUser_" to better reflect this.
2025-04-15 17:15:34 +02:00
eb94379efe Small detail improvements from code review
In a code review with Edward and Alex, some optimization potential in
the sinqMotor.db file was discovered. This patch implements those
improvements.
2025-04-09 16:39:36 +02:00
1dd132c709 Added the ability to set the limits from the substitution file 2025-04-04 13:29:49 +02:00
7729eceb28 Added doReset wrapper around reset and added two functions to set and
retrieve the motor position which handle the conversion via
motorRecResolution.
2025-03-31 10:42:07 +02:00
828e9bc59c Fixed a bug in msgPrintControl 2025-03-19 15:01:20 +01:00
f26d1bb612 Added public accessors for all status library indices and some other
properties. This also enabled the removal of "friend classes".
2025-03-10 16:53:45 +01:00
bed245b010 Added PVs for error reset and status problem reporting and fixed a bug
in msgPrintControl
2025-03-10 14:28:24 +01:00
8 changed files with 797 additions and 267 deletions

123
README.md
View File

@ -8,7 +8,7 @@ This library offers base classes for EPICS motor drivers (`sinqAxis` and `sinqCo
### Architecture of EPICS motor drivers at SINQ
The asyn-framework offers two base classes `asynMotorAxis` and `asynMotorController`. At SINQ, we extend those classes by two children `sinqAxis` and `sinqController` which are not complete drivers on their own, but serve as an additional framework for writing drivers. The concrete drivers are then created as separated libraries, an example is the TurboPMAC-driver: https://git.psi.ch/sinq-epics-modules/turboPmac.
The asyn-framework offers two base classes `asynMotorAxis` and `asynMotorController`. At SINQ, we extend those classes by two children `sinqAxis` and `sinqController` which are not complete drivers on their own, but serve as a framework extension for writing drivers. The concrete drivers are then created as separated libraries, an example is the TurboPMAC-driver: https://git.psi.ch/sinq-epics-modules/turboPmac.
The full inheritance chain for two different motor drivers "a" and "b" looks like this:
`asynController -> sinqController -> aController`
@ -17,9 +17,48 @@ The full inheritance chain for two different motor drivers "a" and "b" looks lik
`asynController -> sinqController -> bController`
`asynAxis -> sinqAxis -> bAxis`
Those inheritance chains are created at runtime by loading shared libraries. Therefore, it is important to load compatible versions. At SINQ, the versioning numbers follow the SemVer standard (https://semver.org/lang/de/). For example, if driver "a" depends on version 2.1.0 of "sinqMotor", then it is safe to use "sinqMotor" 2.5.3 since 2.5.3 is backwards compatible to 2.1.0. However, it is not allowed to use e.g. version 1.9.0 or 2.0.0 or 3.0.1 instead. For more details on SemVer, please refer to the official documentation.
Those inheritance chains are created at runtime by loading shared libraries. These libraries must be compatible to each other (see next section).
To find out which version of sinqMotor is needed by driver "a", refer to its Makefile (line `sinqMotor_VERSION=x.x.x`, where x.x.x is the minimum required version).
### Versioning
In order to make sure the shared libraries are compatible to each other, we use the "require" framework extension for EPICS (https://github.com/paulscherrerinstitute/require). If a shared library has another library as a dependency, it is checked whether the latter is already loaded. If yes, the loaded version is considered compatible if:
1) no specific version was required by the former library
2) the already loaded version matches the required version exactly
3) major and minor numbers are the same and already loaded patch number is equal to the required one or higher
4) major numbers are the same and already loaded minor number is higher than the required one
5) the already loaded version is a test version and the required version is not a test version
These rules are in complicance with the SemVer standard (https://semver.org/lang/de/)
If the dependency hasn't been loaded yet, it is loaded now. In case no specific version is required, the latest numbered version is used.
Because these rules are checked sequentially for each required dependency and no unloading is performed, it is important to consider the order of required libraries. Consider the following example:
```
require "libDriverA" # sinqMotor 1.2 is specified as a dependency
require "libDriverB" # sinqMotor 1.0 is specified as a dependency
```
`require` first checks the dependencies of `libDriverA` and sees that `sinqMotor 1.2` is required. It therefore load `sinqMotor 1.2` and then `libDriverA`. Now the next `require` starts analyzing the dependencies of `libDriverB` and sees that `sinqMotor 1.0` is required. Since `sinqMotor 1.2` is already loaded, rule 4) is applied and `libDriverB` is assumed to be compatible with `sinqMotor 1.2` as well (which it should be according to SemVer).
When the order is inverted, the following happens:
```
require "libDriverB" # sinqMotor 1.0 is specified as a dependency
require "libDriverA" # sinqMotor 1.2 is specified as a dependency
```
`require` first checks the dependencies of `libDriverB` and sees that `sinqMotor 1.0` is required. It therefore load `sinqMotor 1.0` and then `libDriverB`. Now the next `require` starts analyzing the dependencies of `libDriverA` and sees that `sinqMotor 1.2` is required. Since `sinqMotor 1.0` is already loaded, `require` cannot load `sinqMotor 1.2`. Therefore the IOC startup is aborted with an error message.
In order to make the setup script more robust, it is therefore recommended to explicitly add a dependency version which is compatible to all required libraries:
```
require "sinqMotor", "1.2"
require "libDriverB" # sinqMotor 1.0 is specified as a dependency
require "libDriverA" # sinqMotor 1.2 is specified as a dependency
```
The IOC startup now succeeds because we made sure the higher version is loaded first.
Please see the README.md of https://github.com/paulscherrerinstitute/require for more details.
To find out which version of sinqMotor is needed by a driver, refer to its Makefile (line `sinqMotor_VERSION=x.x.x`, where x.x.x is the minimum required version).
### IOC startup script
@ -29,28 +68,28 @@ An EPICS IOC for motor control at SINQ is started by executing a script with the
# Load libraries needed for the IOC
require sinqMotor, 1.0.0
require turboPmac, 1.2.0
require actualDriver, 1.2.0
# Define environment variables used later to parametrize the individual controllers
epicsEnvSet("TOP","/ioc/sinq-ioc/sinqtest-ioc/")
epicsEnvSet("INSTR","SQ:SINQTEST:")
# Include other scripts for the controllers 1 and 2
< mcu1.cmd
< mcu2.cmd
< actualDriver.cmd
< actualDriver.cmd
iocInit()
```
The first line is a so-called shebang which instructs Linux to execute the file with the executable located at the given path - the IOC shell in this case. The controller script "mcu1.cmd" looks like this:
The script for controller 1 ("mcu1.cmd") for a Turbo PMAC (see https://git.psi.ch/sinq-epics-modules/turboPmac) has the following structure. The scripts for other controller types can be found in the README.md of their respective repositories.
The script for controller 1 ("turboPmac1.cmd") for a Turbo PMAC (see https://git.psi.ch/sinq-epics-modules/turboPmac) has the following structure. The scripts for other controller types can be found in the README.md of their respective repositories.
```
# Define the name of the controller and the corresponding port
epicsEnvSet("NAME","mcu1")
epicsEnvSet("ASYN_PORT","p$(NAME)")
epicsEnvSet("DRIVER_PORT","actualDriver1")
epicsEnvSet("IP_PORT","p$(DRIVER_PORT)")
# Create the TCP/IP socket used to talk with the controller. The socket can be adressed from within the IOC shell via the port name
drvAsynIPPortConfigure("$(ASYN_PORT)","172.28.101.24:1025")
drvAsynIPPortConfigure("$(IP_PORT)","172.28.101.24:1025")
# Create the controller object with the defined name and connect it to the socket via the port name.
# The other parameters are as follows:
@ -58,25 +97,25 @@ drvAsynIPPortConfigure("$(ASYN_PORT)","172.28.101.24:1025")
# 0.05: Busy poll period in seconds
# 1: Idle poll period in seconds
# 1: Socket communication timeout in seconds
turboPmacController("$(NAME)", "$(ASYN_PORT)", 8, 0.05, 1, 1);
actualDriverController("$(DRIVER_PORT)", "$(IP_PORT)", 8, 0.05, 1, 1);
# Define some axes for the specified MCU at the given slot (1, 2 and 5). No slot may be used twice!
turboPmacAxis("$(NAME)",1);
turboPmacAxis("$(NAME)",2);
turboPmacAxis("$(NAME)",5);
# Define some axes for the specified motor controller at the given slot (1, 2 and 5). No slot may be used twice!
actualDriverAxis("$(DRIVER_PORT)",1);
actualDriverAxis("$(DRIVER_PORT)",2);
actualDriverAxis("$(DRIVER_PORT)",5);
# Set the number of subsequent timeouts
setMaxSubsequentTimeouts("$(NAME)", 20);
setMaxSubsequentTimeouts("$(DRIVER_PORT)", 20);
# Configure the timeout frequency watchdog:
setThresholdComTimeout("$(NAME)", 100, 1);
# Configure the timeout frequency watchdog: A maximum of 10 timeouts are allowed in 300 seconds before an alarm message is sent.
setThresholdComTimeout("$(DRIVER_PORT)", 300, 10);
# Parametrize the EPICS record database with the substitution file named after the MCU.
# Parametrize the EPICS record database with the substitution file named after the motor controller.
epicsEnvSet("SINQDBPATH","$(sinqMotor_DB)/sinqMotor.db")
dbLoadTemplate("$(TOP)/$(NAME).substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)")
epicsEnvSet("SINQDBPATH","$(turboPmac_DB)/turboPmac.db")
dbLoadTemplate("$(TOP)/$(NAME).substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)")
dbLoadRecords("$(sinqMotor_DB)/asynRecord.db","P=$(INSTR)$(NAME),PORT=$(ASYN_PORT)")
dbLoadTemplate("$(TOP)/$(DRIVER_PORT).substitutions", "INSTR=$(INSTR)$(DRIVER_PORT):,CONTROLLER=$(DRIVER_PORT)")
epicsEnvSet("SINQDBPATH","$(actualDriver_DB)/turboPmac.db")
dbLoadTemplate("$(TOP)/$(DRIVER_PORT).substitutions", "INSTR=$(INSTR)$(DRIVER_PORT):,CONTROLLER=$(DRIVER_PORT)")
dbLoadRecords("$(sinqMotor_DB)/asynRecord.db","P=$(INSTR)$(DRIVER_PORT),PORT=$(IP_PORT)")
```
### Substitution file
@ -87,11 +126,11 @@ To work with sinqMotor, "mcu1.substitutions" needs to look like this (the order
file "$(SINQDBPATH)"
{
pattern
{ AXIS, M, DESC, EGU, DIR, MRES, MSGTEXTSIZE, ENABLEMOVWATCHDOG, LIMITSOFFSET, CANSETSPEED }
{ 1, "lin1", "Linear motor doing whatever", mm, Pos, 0.001, 200, 1, 1.0, 1 }
{ 2, "rot1", "First rotary motor", degree, Neg, 0.001, 200, 0, 1.0, 0 }
{ 3, "rot2", "Second rotary motor", degree, Pos, 0.001, 200, 0, 0.0, 1 }
{ 5, "rot3", "Surprise: Third rotary motor", degree, Pos, 0.001, 200, 1, 2.0, 0 }
{ AXIS, M, DESC, EGU, DIR, MRES, MSGTEXTSIZE, ENABLEMOVWATCHDOG, LIMITSOFFSET, CANSETSPEED, ADAPTPOLL }
{ 1, "lin1", "Linear motor doing whatever", mm, Pos, 0.001, 200, 1, 1.0, 1, 1 }
{ 2, "rot1", "First rotary motor", degree, Neg, 0.001, 200, 0, 1.0, 0, 1 }
{ 3, "rot2", "Second rotary motor", degree, Pos, 0.001, 200, 0, 0.0, 1, 0 }
{ 5, "rot3", "Surprise: Third rotary motor", degree, Pos, 0.001, 200, 1, 2.0, 0, 0 }
}
```
The variable `SINQDBPATH` has been set in "mcu1.cmd" before calling `dbLoadTemplate`.
@ -99,21 +138,22 @@ The variable `SINQDBPATH` has been set in "mcu1.cmd" before calling `dbLoadTempl
#### Mandatory parameters
- `AXIS`: Index of the axis, corresponds to the physical connection of the axis to the MCU.
- `M`: The full PV name is created by concatenating the variables INSTR, NAME and M. For example, the PV of the first axis would be "SQ:SINQTEST:mcu1:lin1".
- `M`: The full PV name is created by concatenating the variables INSTR, DRIVER_PORT and M. For example, the PV of the first axis would be "SQ:SINQTEST:mcu1:lin1".
- `EGU`: Engineering units. For a linear motor, this is mm, for a rotaty motor, this is degree.
- `DIR`: If set to "Neg", the axis direction is inverted.
- `MRES`: This is a scaling factor determining the resolution of the position readback value. For example, 0.001 means a precision of 1 um. A detailed description can be found in section [Motor record resolution MRES](#motor-record-resolution-mres).
#### Optional parameters
The default values for those parameters are given for the individual records in db/sinqMotor.db
- `DESC`: Description of the motor. This field is just for documentation and is not needed for operating a motor.
- `MSGTEXTSIZE`: Buffer size for the motor message record in characters
- `ENABLEMOVWATCHDOG`: Sets `setWatchdogEnabled` during IOC startup to the given value.
- `DESC`: Description of the motor. This field is just for documentation and is not needed for operating a motor. Defaults to the motor name.
- `MSGTEXTSIZE`: Buffer size for the motor message record in characters. Defaults to 200 characters
- `ENABLEMOVWATCHDOG`: Sets `setWatchdogEnabled` during IOC startup to the given value. Defaults to 0.
- `LIMITSOFFSET`: If the motor limits are read out from the controller, they can
be further reduced by this offset in order to avoid errors due to slight overshoot
on the motor controller. For example, if this value is 1.0 and the read-out limits
are [-10.0 10.0], the EPICS limits are set to [-9.0 9.0]. This parameter uses engineering units (EGU).
- `CANSETSPEED`: If set to 1, the motor speed can be modified by the user.
are [-10.0 10.0], the EPICS limits are set to [-9.0 9.0]. This parameter uses engineering units (EGU). Defaults to 0.0.
- `CANSETSPEED`: If set to 1, the motor speed can be modified by the user. Defaults to 0.
- `ADAPTPOLL`: If set to any value other than 0, adaptive polling is enabled for this particular axis. Adaptive polling is designed to reduce the communication load in case some axis is moving. By default, if at least one axis is moving, all axes are polled using the busy / moving poll period (see [IOC startup script](#ioc-startup-script)). Adaptive polling modifies this behaviour so that the affected axis is only polled with the busy / moving poll period if it itself is moving. Defaults to 1.
### Motor record resolution MRES
@ -155,6 +195,10 @@ coupling, changes to the parameter library via setDoubleParam are NOT
transferred to (motor_record_pv_name).MRES or to
(motor_record_pv_name):Resolution.
### Additional records
`sinqMotor` provides a variety of additional records. See `db/sinqMotor.db` for the complete list and the documentation.
## Developer guide
### Base classes
@ -162,7 +206,7 @@ transferred to (motor_record_pv_name).MRES or to
sinqMotor offers a variety of additional methods for children classes to standardize certain patterns (e.g. writing messages to the IOC shell and the motor message PV). For a detailed description, please see the respective function documentation in the .h-files. All of these functions can be overwritten manually if e.g. a completely different implementation of `poll` is required. Some functions are marked as virtual, because they are called from other functions of sinqMotor and therefore need runtime polymorphism. Functions without that marker are not called anywhere in sinqMotor.
#### sinqController.h
- `errMsgCouldNotParseResponse`: Write a standardized message if parsing a device response failed.
- `couldNotParseResponse`: Write a standardized message if parsing a device response failed.
- `paramLibAccessFailed`: Write a standardized message if accessing the parameter library failed.
- `stringifyAsynStatus`: Convert the enum `asynStatus` into a human-readable string.
- `checkComTimeoutWatchdog`: Calculates the timeout frequency (number of timeouts in a given time) and informs the user if a specified limit has been exceeded.
@ -171,7 +215,11 @@ sinqMotor offers a variety of additional methods for children classes to standar
- `setMaxSubsequentTimeouts`: Set the limit for the number of subsequent timeouts before the user is informed.
#### sinqAxis.h
- `enable`: This function is called if the "Enable" PV from db/sinqMotor.db is set. This is an empty function which should be overwritten by concrete driver implementations.
- `enable`: This function is called if the `$(INSTR)$(M):Enable` PV from db/sinqMotor.db is set.
This is an empty function which should be overwritten by concrete driver implementations.
- `reset`: This function is called when the `$(INSTR)$(M):Reset` PV from db/sinqMotor.db is set.
It calls `doReset` and performs some fast polls after `doReset` returns.
- `doReset`: This is an empty function which should be overwritten by concrete driver implementations.
- `move`: This function sets the absolute target position in the parameter library and then calls `doMove`.
- `doMove`: This is an empty function which should be overwritten by concrete driver implementations.
- `home`: This function sets the internal status flags for the homing process and then calls doHome.
@ -187,7 +235,8 @@ sinqMotor offers a variety of additional methods for children classes to standar
- Reset `motorStatusProblem_`, `motorStatusCommsError_` and `motorMessageText_` if `doPoll` returned `asynSuccess`
- Run `callParamCallbacks`
- Return the status of `doPoll`
- `doPoll`: This is an empty function which should be overwritten by concrete driver implementations.
- `motorPosition`: Returns the parameter library value of the motor position, accounted for the motor record resolution (see section "Motor record resolution MRES")
- `setMotorPosition`: Writes the given value into the parameter library, accounted for the motor record resolution (see section "Motor record resolution MRES")
- `setVeloFields`: Populates the motor record fields VELO (actual velocity), VBAS (minimum allowed velocity) and VMAX (maximum allowed velocity) from the driver.
- `setAcclField`: Populates the motor record field ACCL from the driver.
- `startMovTimeoutWatchdog`: Starts a watchdog for the movement time. This watchdog compares the actual time spent in a movement operation with an expected time, which is calculated based on the distance of the current and the target position.

View File

@ -23,7 +23,10 @@
# greater than RDBD, the motor will try again, as if the user had requested a
# move from the now current position to the desired position. Only a limited
# number of retries will be performed (see RTRY). If the given value is smaller
# than MRES, it is set to MRES.
# than MRES, it is set to MRES. In this version of the record, we set RDBD to a
# very high value in order to suppress both retries and the NTM (new target
# monitor) logic from issuing stop commands during overshoots (see
# https://epics.anl.gov/bcda/synApps/motor/motorRecord.html#Fields_misc).
record(motor,"$(INSTR)$(M)")
{
field(DESC,"$(DESC=$(M))")
@ -34,18 +37,48 @@ record(motor,"$(INSTR)$(M)")
field(EGU,"$(EGU)")
field(INIT,"")
field(PINI,"NO")
field(DHLM, "$(DHLM=0)")
field(DLLM, "$(DLLM=0)")
field(TWV,"1")
field(RTRY,"0")
field(RDBD,"0")
field(BDST,"0")
field(RDBD, "$(RDBD=10e300)") # Suppress retries and overshoot stop commands
field(BDST, "0")
field(RMOD,"3") # Retry mode 3 ("In-Position"): This suppresses any retries from the motor record.
}
# This PV reads out the 10th bit of the MSTA field of the motor record, which
# is the "motorStatusProblem_" bit.
record(calc, "$(INSTR)$(M):StatusProblem")
{
field(INPA, "$(INSTR)$(M).MSTA CP")
field(CALC, "A >> 9")
}
# If the value of this PV is 0, the according axis is currently disconnected from the controller.
# Trying to give commands to a disconnected axis will result in an error message in the IOC shell
# This record is coupled to the parameter library via motorConnected_ -> MOTOR_CONNECTED.
record(longin, "$(INSTR)$(M):Connected")
{
field(DTYP, "asynInt32")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_CONNECTED")
field(SCAN, "I/O Intr")
field(PINI, "NO")
field(VAL, "1")
}
# Call the reset function of the corresponding sinqAxis
# This record is coupled to the parameter library via motorReset_ -> MOTOR_RESET.
record(longout, "$(INSTR)$(M):Reset") {
field(DTYP, "asynInt32")
field(OUT, "@asyn($(CONTROLLER),$(AXIS),1) MOTOR_RESET")
field(PINI, "NO")
}
# This PV allows force-stopping the motor record from within the driver by setting
# the motorForceStop_ value in the parameter library to 1. It should be reset to 0 by the driver afterwards.
# The implementation strategy is taken from https://epics.anl.gov/tech-talk/2022/msg00464.php.
# This record is coupled to the parameter library via motorForceStop_ -> MOTOR_FORCE_STOP.
record(longin, "$(INSTR)$(M):STOP_RBV")
record(longin, "$(INSTR)$(M):StopRBV")
{
field(DTYP, "asynInt32")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_FORCE_STOP")
@ -53,7 +86,7 @@ record(longin, "$(INSTR)$(M):STOP_RBV")
field(FLNK, "$(INSTR)$(M):Stop2Field")
}
record(longout, "$(INSTR)$(M):Stop2Field") {
field(DOL, "$(INSTR)$(M):STOP_RBV CP")
field(DOL, "$(INSTR)$(M):StopRBV NPP")
field(OUT, "$(INSTR)$(M).STOP")
field(OMSL, "closed_loop")
}
@ -64,7 +97,7 @@ record(longout, "$(INSTR)$(M):Stop2Field") {
# for calculating the estimated time of arrival inside the watchdog).
record(ao,"$(INSTR)$(M):RecResolution") {
field(DESC, "$(M) resolution")
field(DOL, "$(INSTR)$(M).MRES CP MS")
field(DOL, "$(INSTR)$(M).MRES CP")
field(OMSL, "closed_loop")
field(DTYP, "asynFloat64")
field(OUT, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_REC_RESOLUTION")
@ -124,6 +157,18 @@ record(longout, "$(INSTR)$(M):CanSetSpeed") {
field(VAL, "$(CANSETSPEED=0)")
}
# If this PV has a value other than 0, adaptive polling for this axis is enabled.
# The standard motor record behaviour is to poll all axis with the busy / move poll
# period if at least one of the axes is moving. Adaptive polling changes this so
# that only axes which were moving in the last poll are polled with the busy / move poll
# period and all other axes are polled with the idle poll period.
record(longout, "$(INSTR)$(M):AdaptivePolling") {
field(DTYP, "asynInt32")
field(OUT, "@asyn($(CONTROLLER),$(AXIS),1) ADAPTIVE_POLLING")
field(PINI, "YES")
field(VAL, "$(ADAPTPOLL=1)")
}
# The timeout mechanism for movements can be enabled / disabled by setting
# this PV to 1 / 0.
# This record is coupled to the parameter library via motorEnableMovWatchdog -> MOTOR_ENABLE_MOV_WATCHDOG.
@ -157,14 +202,17 @@ record(ao, "$(INSTR)$(M):LimitsOffset") {
record(ai, "$(INSTR)$(M):DHLM_RBV")
{
field(DTYP, "asynFloat64")
field(VAL, "$(DHLM=0)")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_HIGH_LIMIT_FROM_DRIVER")
field(SCAN, "I/O Intr")
field(FLNK, "$(INSTR)$(M):PushDHLM2Field")
field(PINI, "NO")
}
record(ao, "$(INSTR)$(M):PushDHLM2Field") {
field(DOL, "$(INSTR)$(M):DHLM_RBV CP")
field(DOL, "$(INSTR)$(M):DHLM_RBV NPP")
field(OUT, "$(INSTR)$(M).DHLM")
field(OMSL, "closed_loop")
field(PINI, "NO")
}
# This record pair reads the parameter library value for "motorLowLimitFromDriver_"
@ -175,14 +223,17 @@ record(ao, "$(INSTR)$(M):PushDHLM2Field") {
record(ai, "$(INSTR)$(M):DLLM_RBV")
{
field(DTYP, "asynFloat64")
field(VAL, "$(DLLM=0)")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_LOW_LIMIT_FROM_DRIVER")
field(SCAN, "I/O Intr")
field(FLNK, "$(INSTR)$(M):PushDLLM2Field")
field(PINI, "NO")
}
record(ao, "$(INSTR)$(M):PushDLLM2Field") {
field(DOL, "$(INSTR)$(M):DLLM_RBV CP")
field(DOL, "$(INSTR)$(M):DLLM_RBV NPP")
field(OUT, "$(INSTR)$(M).DLLM")
field(OMSL, "closed_loop")
field(PINI, "NO")
}
# This record pair reads the parameter library value for "motorVeloFromDriver_"
@ -198,7 +249,7 @@ record(ai, "$(INSTR)$(M):VELO_RBV")
field(FLNK, "$(INSTR)$(M):PushVELO2Field")
}
record(ao, "$(INSTR)$(M):PushVELO2Field") {
field(DOL, "$(INSTR)$(M):VELO_RBV CP")
field(DOL, "$(INSTR)$(M):VELO_RBV NPP")
field(OUT, "$(INSTR)$(M).VELO")
field(OMSL, "closed_loop")
}
@ -216,7 +267,7 @@ record(ai, "$(INSTR)$(M):VBAS_RBV")
field(FLNK, "$(INSTR)$(M):PushVBAS2Field")
}
record(ao, "$(INSTR)$(M):PushVBAS2Field") {
field(DOL, "$(INSTR)$(M):VBAS_RBV CP")
field(DOL, "$(INSTR)$(M):VBAS_RBV NPP")
field(OUT, "$(INSTR)$(M).VBAS")
field(OMSL, "closed_loop")
}
@ -234,7 +285,7 @@ record(ai, "$(INSTR)$(M):VMAX_RBV")
field(FLNK, "$(INSTR)$(M):PushVMAX2Field")
}
record(ao, "$(INSTR)$(M):PushVMAX2Field") {
field(DOL, "$(INSTR)$(M):VMAX_RBV CP")
field(DOL, "$(INSTR)$(M):VMAX_RBV NPP")
field(OUT, "$(INSTR)$(M).VMAX")
field(OMSL, "closed_loop")
}
@ -252,7 +303,7 @@ record(ai, "$(INSTR)$(M):ACCL_RBV")
field(FLNK, "$(INSTR)$(M):PushACCL2Field")
}
record(ao, "$(INSTR)$(M):PushACCL2Field") {
field(DOL, "$(INSTR)$(M):ACCL_RBV CP")
field(DOL, "$(INSTR)$(M):ACCL_RBV NPP")
field(OUT, "$(INSTR)$(M).ACCL")
field(OMSL, "closed_loop")
}
@ -270,4 +321,4 @@ record(waveform, "$(INSTR)$(M):EncoderType") {
field(FTVL, "CHAR")
field(NELM, "80")
field(SCAN, "I/O Intr")
}
}

View File

@ -2,11 +2,13 @@
#include <unordered_map>
msgPrintControlKey::msgPrintControlKey(char *controller, int axisNo,
const char *functionName, int line) {
const char *functionName, int line,
size_t maxRepetitions) {
controller_ = controller;
axisNo_ = axisNo;
line_ = line;
functionName_ = functionName;
maxRepetitions_ = maxRepetitions;
}
void msgPrintControlKey::format(char *buffer, size_t bufferSize) {
@ -16,10 +18,6 @@ void msgPrintControlKey::format(char *buffer, size_t bufferSize) {
// =============================================================================
msgPrintControl::msgPrintControl(size_t maxRepetitions) {
maxRepetitions_ = maxRepetitions;
}
bool msgPrintControl::shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
asynUser *pasynUser) {
@ -34,12 +32,12 @@ bool msgPrintControl::shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
*/
if (map_.find(key) != map_.end()) {
size_t repetitions = map_[key];
if (repetitions < maxRepetitions_) {
if (repetitions < key.maxRepetitions_) {
// Number of allowed repetitions not exceeded -> Printing the
// message is ok.
map_[key] = repetitions + 1;
return true;
} else if (repetitions == maxRepetitions_) {
} else if (repetitions == key.maxRepetitions_) {
// Reached number of allowed repetitions -> Printing the message
// is ok, but further trys are rejected.
char formattedKey[100] = {0};
@ -69,13 +67,16 @@ bool msgPrintControl::shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
*/
if (map_.find(key) != map_.end()) {
if (map_[key] != 0) {
char formattedKey[100] = {0};
key.format(formattedKey, sizeof(formattedKey));
asynPrint(pasynUser, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d\nError "
"associated with key \"%s\" has been resolved.\n",
key.controller_.c_str(), key.axisNo_,
key.functionName_, key.line_, formattedKey);
if (pasynUser != nullptr) {
char formattedKey[100] = {0};
key.format(formattedKey, sizeof(formattedKey));
asynPrint(
pasynUser, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d\nError "
"associated with key \"%s\" has been resolved.\n",
key.controller_.c_str(), key.axisNo_, key.functionName_,
key.line_, formattedKey);
}
map_[key] = 0;
}
}
@ -85,15 +86,27 @@ bool msgPrintControl::shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
bool msgPrintControl::shouldBePrinted(char *portName, int axisNo,
const char *functionName, int line,
bool wantToPrint, asynUser *pasynUser) {
bool wantToPrint, asynUser *pasynUser,
size_t maxRepetitions) {
msgPrintControlKey key =
msgPrintControlKey(portName, axisNo, functionName, __LINE__);
return shouldBePrinted(key, wantToPrint, pasynUser);
}
void msgPrintControl::resetCount(msgPrintControlKey &key) {
void msgPrintControl::resetCount(msgPrintControlKey &key, asynUser *pasynUser) {
if (map_.find(key) != map_.end()) {
map_[key] = 0;
if (map_[key] != 0) {
if (pasynUser != nullptr) {
char formattedKey[100] = {0};
key.format(formattedKey, sizeof(formattedKey));
asynPrint(pasynUser, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d\nError "
"associated with key \"%s\" has been resolved.\n",
key.controller_.c_str(), key.axisNo_,
key.functionName_, key.line_, formattedKey);
}
map_[key] = 0;
}
}
}

View File

@ -1,6 +1,8 @@
#ifndef msgPrintControl_H
#define msgPrintControl_H
#define DefaultMaxRepetitions 4
#include <asynDriver.h>
#include <string.h>
#include <string>
@ -14,13 +16,22 @@
class msgPrintControlKey {
public:
std::string controller_;
// -1 is a non-axis specific message
// -1 indicates a non-axis specific message
int axisNo_;
const char *functionName_;
int line_;
/**
* @brief Maximum number of times a message is printed before it is
* suppressed. This number is not used as part of the hash.
*
*/
size_t maxRepetitions_;
msgPrintControlKey(char *controller_, int axisNo, const char *fileName,
int line);
int line, size_t maxRepetitions = DefaultMaxRepetitions);
bool operator==(const msgPrintControlKey &other) const {
return axisNo_ == other.axisNo_ && line_ == other.line_ &&
@ -32,7 +43,7 @@ class msgPrintControlKey {
};
/**
* @brief Implementation of the hash functionality for msgPrintControlKey
* @brief Implementation of the hash functionality for `msgPrintControlKey`
*
*/
namespace std {
@ -57,7 +68,7 @@ template <> struct hash<msgPrintControlKey> {
* axis fails, a corresponding error message is created in each poll. This
* could "flood" the IOC shell with noise. To prevent this, this class keeps
* track of the number of subsequent error message repetition. Each message is
* uniquely identified by "msgPrintControlKey". The function shouldBePrinted
* uniquely identified by `msgPrintControlKey`. The function `shouldBePrinted`
* can be used in order to see if a message should be printed or not:
*
* ```
@ -67,32 +78,32 @@ template <> struct hash<msgPrintControlKey> {
* if (msgPrintControl.shouldBePrinted(controller, axisNo, __PRETTY_FUNCTION__,
* __LINE__, wantToPrint)) { asynPrint(...)
* }
*
* ```
*/
class msgPrintControl {
public:
msgPrintControl(size_t maxRepetitions);
/**
* @brief Checks if the error message associated with "key" has been printed
* more than "maxRepetitions_" times in a row. If yes, returns false,
* otherwise true. Counter is reset if wantToPrint is false.
* more than `this->maxRepetitions_` times in a row. If yes, returns false,
* otherwise true. Counter is reset if `wantToPrint` is false.
*
* If the conditions for printing a message are met, "wantToPrint" must be
* set to true. The function then checks if "maxRepetitions_" has been
* If the conditions for printing a message are met, `wantToPrint` must be
* set to true. The function then checks if `maxRepetitions_` has been
* exceeded. If yes, the function returns no, indicating that the message
* should not be printed. If no, the number of repetitions stored in the map
* is incremented and the function returns true, indicating that the message
* should be printed.
*
* If the conditions for printing a message are not met, "wantToPrint" must
* If the conditions for printing a message are not met, `wantToPrint` must
* be set to false. This resets the map entry.
*
* @param key Key associated with the message, used to
* identify individual messages
* @param wantToPrint If the message associated with key should be
* printed, this value should be true, otherwise false.
* @param pasynUser If the problem has been resolved (wantToPrint =
* false), a corresponding status message is printed using the given
* asynUser. If this pointer is a nullptr, no message is printed.
* @return bool If true, the message should be printed, if
* false, it should not.
*/
@ -108,26 +119,29 @@ class msgPrintControl {
* @param fileName
* @param line
* @param wantToPrint
* @return true
* @return false
* @param pasynUser
*/
bool shouldBePrinted(char *controller, int axisNo, const char *functionName,
int line, bool wantToPrint, asynUser *pasynUser);
void resetCount(msgPrintControlKey &key);
int line, bool wantToPrint, asynUser *pasynUser,
size_t maxRepetitions = DefaultMaxRepetitions);
/**
* @brief Maximum number of times a message is printed before it is
* suppressed.
* @brief Reset the error message count incremented in `shouldBePrinted` for
* the given key
*
* @param key Key associated with the message, used to
* identify individual messages
* @param pasynUser If the problem has been resolved (`wantToPrint =
* false`), a corresponding status message is printed using the given
* asynUser. If this pointer is a nullptr, no message is printed.
*/
size_t maxRepetitions_;
void resetCount(msgPrintControlKey &key, asynUser *pasynUser);
char *getSuffix();
private:
std::unordered_map<msgPrintControlKey, size_t> map_;
char suffix_[200] = {0};
char suffix_[300] = {0};
};
#endif

View File

@ -14,11 +14,27 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
scaleMovTimeout_ = 2.0;
offsetMovTimeout_ = 30;
targetPosition_ = 0.0;
wasMoving_ = false;
epicsTimeGetCurrent(&lastPollTime_);
// This check is also done in asynMotorAxis, but there the IOC continues
// running even though the configuration is incorrect. When failing this
// check, the IOC is stopped, since this is definitely a configuration
// problem.
if ((axisNo < 0) || (axisNo >= pC->numAxes())) {
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(axis index %d is not in range 0 to %d)\n. Terminating IOC",
pC->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__, axisNo,
pC->numAxes() - 1);
exit(-1);
}
// Motor is assumed to be enabled
status = setIntegerParam(pC_->motorEnableRBV_, 1);
status = setIntegerParam(pC_->motorEnableRBV(), 1);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -28,9 +44,9 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
}
// By default, motors cannot be disabled
status = setIntegerParam(pC_->motorCanDisable_, 0);
status = setIntegerParam(pC_->motorCanDisable(), 0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -40,9 +56,21 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
}
// Provide a default value for the motor position.
status = setDoubleParam(pC_->motorPosition_, 0.0);
status = setDoubleParam(pC_->motorPosition(), 0.0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
pC->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
pC_->stringifyAsynStatus(status));
exit(-1);
}
// Assume that the motor is connected initially
status = setIntegerParam(pC_->motorConnected(), 1);
if (status != asynSuccess) {
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -52,9 +80,9 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
}
// We assume that the motor has no status problems initially
status = setIntegerParam(pC_->motorStatusProblem_, 0);
status = setIntegerParam(pC_->motorStatusProblem(), 0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -64,9 +92,9 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
}
// Set the homing-related flags
status = setIntegerParam(pC_->motorStatusHome_, 0);
status = setIntegerParam(pC_->motorStatusHome(), 0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -74,9 +102,9 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
pC_->stringifyAsynStatus(status));
exit(-1);
}
status = setIntegerParam(pC_->motorStatusHomed_, 0);
status = setIntegerParam(pC_->motorStatusHomed(), 0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -84,9 +112,9 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
pC_->stringifyAsynStatus(status));
exit(-1);
}
status = setIntegerParam(pC_->motorStatusAtHome_, 0);
status = setIntegerParam(pC_->motorStatusAtHome(), 0);
if (status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
"(setting a parameter value failed "
"with %s)\n. Terminating IOC",
@ -97,11 +125,53 @@ sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
}
asynStatus sinqAxis::poll(bool *moving) {
// Local variable declaration
asynStatus pl_status = asynSuccess;
asynStatus poll_status = asynSuccess;
int homing = 0;
int homed = 0;
int adaptivePolling = 0;
/*
If adaptive polling is enabled:
- Check if the motor was moving during the last poll
- If yes, perform the poll
- If no, check if the last poll was at least an idlePollPeriod ago
- If yes, perform the poll
- If no, skip it
*/
pl_status =
pC_->getIntegerParam(axisNo_, pC_->adaptivePolling(), &adaptivePolling);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "adaptivePolling", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
};
// Using the EPICS timestamp here, see
// https://docs.epics-controls.org/projects/base/en/latest/epicsTime_h.html#_CPPv414epicsTimeStamp
// Get the current time
epicsTimeStamp ts;
epicsTimeGetCurrent(&ts);
if (adaptivePolling != 0) {
// Motor wasn't moving during the last poll
if (!wasMoving_) {
// Add the idle poll period
epicsTimeStamp earliestTimeNextPoll = lastPollTime_;
epicsTimeAddSeconds(&earliestTimeNextPoll, pC_->idlePollPeriod());
if (epicsTimeLessThanEqual(&earliestTimeNextPoll, &ts) == 0) {
*moving = false;
return asynSuccess;
}
}
}
// Update the start time of the last poll
lastPollTime_ = ts;
/*
At the beginning of the poll, it is assumed that the axis has no status
@ -110,17 +180,17 @@ asynStatus sinqAxis::poll(bool *moving) {
The motorStatusProblem_ field changes the motor record fields SEVR and STAT.
*/
pl_status = setIntegerParam(pC_->motorStatusProblem_, false);
pl_status = setIntegerParam(pC_->motorStatusProblem(), false);
if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusCommsError_, false);
pl_status = setIntegerParam(pC_->motorStatusCommsError(), false);
if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusCommsError_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
pl_status = setStringParam(pC_->motorMessageText_, "");
pl_status = setStringParam(pC_->motorMessageText(), "");
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorMessageText_",
axisNo_, __PRETTY_FUNCTION__,
@ -133,23 +203,26 @@ asynStatus sinqAxis::poll(bool *moving) {
// return.
poll_status = doPoll(moving);
// Motor was moving during this poll
wasMoving_ = *moving;
// The poll did not succeed: Something went wrong and the motor has a status
// problem.
if (poll_status != asynSuccess) {
pl_status = setIntegerParam(pC_->motorStatusProblem_, true);
pl_status = setIntegerParam(pC_->motorStatusProblem(), true);
if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
}
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorStatusHomed_, &homed);
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorStatusHomed(), &homed);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHomed_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorStatusHome_, &homing);
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorStatusHome(), &homing);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHome_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
@ -158,19 +231,19 @@ asynStatus sinqAxis::poll(bool *moving) {
if (homing == 1 && !(*moving)) {
// Set the homing-related flags
pl_status = setIntegerParam(pC_->motorStatusHome_, 0);
pl_status = setIntegerParam(pC_->motorStatusHome(), 0);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusHomed_, 1);
pl_status = setIntegerParam(pC_->motorStatusHomed(), 1);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHomed_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusAtHome_, 1);
pl_status = setIntegerParam(pC_->motorStatusAtHome(), 1);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusAtHome_",
axisNo_, __PRETTY_FUNCTION__,
@ -187,15 +260,15 @@ asynStatus sinqAxis::poll(bool *moving) {
// function should be called at the end of a poll implementation.
pl_status = callParamCallbacks();
bool wantToPrint = pl_status != asynSuccess;
if (pC_->msgPrintControl_.shouldBePrinted(
if (pC_->getMsgPrintControl().shouldBePrinted(
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__, wantToPrint,
pC_->pasynUserSelf)) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
pC_->pasynUser())) {
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line "
"%d:\ncallParamCallbacks failed with %s.%s\n",
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
pC_->stringifyAsynStatus(poll_status),
pC_->msgPrintControl_.getSuffix());
pC_->getMsgPrintControl().getSuffix());
}
if (wantToPrint) {
poll_status = pl_status;
@ -210,36 +283,47 @@ asynStatus sinqAxis::move(double position, int relative, double minVelocity,
double maxVelocity, double acceleration) {
// Status of parameter library operations
asynStatus pl_status = asynSuccess;
asynStatus status = asynSuccess;
double motorRecResolution = 0.0;
// =========================================================================
// When a new move is done, the motor is not homed anymore
pl_status = setIntegerParam(pC_->motorStatusHomed_, 0);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHomed_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusAtHome_, 0);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusAtHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorRecResolution_,
&motorRecResolution);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorRecResolution_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
// Store the target position internally
targetPosition_ = position * motorRecResolution;
return doMove(position, relative, minVelocity, maxVelocity, acceleration);
status = doMove(position, relative, minVelocity, maxVelocity, acceleration);
if (status != asynSuccess) {
return status;
}
status = assertConnected();
if (status != asynSuccess) {
return status;
}
// Since the move command was successfull, we assume that the motor has
// started its movement.
status = setIntegerParam(pC_->motorStatusHomed(), 0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusHomed_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
status = setIntegerParam(pC_->motorStatusAtHome(), 0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusAtHome_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
status = pC_->getDoubleParam(axisNo_, pC_->motorRecResolution(),
&motorRecResolution);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorRecResolution_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
// Needed for adaptive polling
wasMoving_ = true;
return pC_->callParamCallbacks();
}
asynStatus sinqAxis::doMove(double position, int relative, double minVelocity,
@ -256,7 +340,7 @@ asynStatus sinqAxis::home(double minVelocity, double maxVelocity,
if (status == asynSuccess) {
status = setStringParam(pC_->motorMessageText_, "Homing");
status = setStringParam(pC_->motorMessageText(), "Homing");
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_",
axisNo_, __PRETTY_FUNCTION__,
@ -264,31 +348,37 @@ asynStatus sinqAxis::home(double minVelocity, double maxVelocity,
}
// Set the homing-related flags
status = setIntegerParam(pC_->motorStatusHome_, 1);
status = setIntegerParam(pC_->motorStatusHome(), 1);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = setIntegerParam(pC_->motorStatusHomed_, 0);
// Set field ATHM to zero
status = setIntegerParam(pC_->motorStatusHomed(), 0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusHomed_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = setIntegerParam(pC_->motorStatusAtHome_, 0);
status = setIntegerParam(pC_->motorStatusAtHome(), 0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusAtHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = assertConnected();
if (status != asynSuccess) {
return status;
}
// Update the motor record
return callParamCallbacks();
} else if (status == asynError) {
// asynError means that we tried to home an absolute encoder
status = setStringParam(pC_->motorMessageText_,
status = setStringParam(pC_->motorMessageText(),
"Can't home a motor with absolute encoder");
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_",
@ -296,11 +386,16 @@ asynStatus sinqAxis::home(double minVelocity, double maxVelocity,
__LINE__);
}
status = assertConnected();
if (status != asynSuccess) {
return status;
}
// Update the motor record
return callParamCallbacks();
} else {
// Bubble up all other problems
return status;
return assertConnected();
}
}
@ -309,15 +404,106 @@ asynStatus sinqAxis::doHome(double minVelocity, double maxVelocity,
return asynSuccess;
}
asynStatus sinqAxis::reset() {
asynStatus status = doReset();
if (status == asynSuccess) {
// Perform some fast polls
pC_->lock();
bool moving = false;
for (int i = 0; i < 5; i++) {
epicsThreadSleep(pC_->movingPollPeriod());
if (poll(&moving) == asynSuccess) {
break;
}
}
pC_->unlock();
}
asynStatus pl_status = assertConnected();
if (pl_status != asynSuccess) {
return pl_status;
}
return status;
}
asynStatus sinqAxis::doReset() { return asynError; }
asynStatus sinqAxis::enable(bool on) { return asynSuccess; }
asynStatus sinqAxis::motorPosition(double *motorPosition) {
asynStatus status = asynSuccess;
double motorRecResolution = 0.0;
status = pC_->getDoubleParam(axisNo(), pC_->motorRecResolution(),
&motorRecResolution);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorRecResolution_",
axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
status = pC_->getDoubleParam(axisNo(), pC_->motorPosition(), motorPosition);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorPosition_", axisNo(),
__PRETTY_FUNCTION__,
__LINE__);
}
*motorPosition = *motorPosition * motorRecResolution;
return status;
}
asynStatus sinqAxis::setMotorPosition(double motorPosition) {
asynStatus status = asynSuccess;
double motorRecResolution = 0.0;
status = pC_->getDoubleParam(axisNo(), pC_->motorRecResolution(),
&motorRecResolution);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorRecResolution_",
axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
status = setDoubleParam(pC_->motorPosition(),
motorPosition / motorRecResolution);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorPosition_", axisNo(),
__PRETTY_FUNCTION__,
__LINE__);
}
return status;
}
asynStatus sinqAxis::assertConnected() {
asynStatus status = asynSuccess;
int connected = 0;
status = pC_->getIntegerParam(axisNo(), pC_->motorConnected(), &connected);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorConnected", axisNo(),
__PRETTY_FUNCTION__, __LINE__);
}
if (connected == 0) {
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line "
"%d:\nAxis is not connected, all commands are ignored.\n",
pC_->portName, axisNo(), __PRETTY_FUNCTION__, __LINE__);
}
return asynSuccess;
}
asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
asynStatus status = asynSuccess;
int variableSpeed = 0;
// Can the speed of the motor be varied?
status =
pC_->getIntegerParam(axisNo_, pC_->motorCanSetSpeed_, &variableSpeed);
pC_->getIntegerParam(axisNo_, pC_->motorCanSetSpeed(), &variableSpeed);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorCanSetSpeed_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
@ -326,7 +512,7 @@ asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
// Check the inputs and create corresponding error messages
if (vbas > vmax) {
asynPrint(pC_->lowLevelPortUser_, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nLower speed "
"limit vbas=%lf must not be smaller than upper limit "
"vmax=%lf.\n",
@ -334,7 +520,7 @@ asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
vbas, vmax);
status = setStringParam(
pC_->motorMessageText_,
pC_->motorMessageText(),
"Lower speed limit must not be smaller than upper speed limit");
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_",
@ -344,14 +530,14 @@ asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
return asynError;
}
if (velo < vbas || velo > vmax) {
asynPrint(pC_->lowLevelPortUser_, ASYN_TRACE_ERROR,
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nActual "
"speed velo=%lf must be between lower limit vbas=%lf and "
"upper limit vmax=%lf.\n",
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
velo, vbas, vmax);
status = setStringParam(pC_->motorMessageText_,
status = setStringParam(pC_->motorMessageText(),
"Speed is not inside limits");
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_",
@ -361,21 +547,21 @@ asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
return asynError;
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver_, vbas);
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver(), vbas);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver_, velo);
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver(), velo);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, vmax);
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver(), vmax);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
@ -383,21 +569,21 @@ asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
}
} else {
// Set minimum and maximum speed equal to the set speed
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver_, velo);
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver(), velo);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver_, velo);
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver(), velo);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, velo);
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver(), velo);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
@ -413,7 +599,7 @@ asynStatus sinqAxis::setAcclField(double accl) {
return asynError;
}
asynStatus status = setDoubleParam(pC_->motorAcclFromDriver_, accl);
asynStatus status = setDoubleParam(pC_->motorAcclFromDriver(), accl);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorAcclFromDriver_",
axisNo_, __PRETTY_FUNCTION__,
@ -423,14 +609,14 @@ asynStatus sinqAxis::setAcclField(double accl) {
}
asynStatus sinqAxis::setWatchdogEnabled(bool enable) {
return setIntegerParam(pC_->motorEnableMovWatchdog_, enable);
return setIntegerParam(pC_->motorEnableMovWatchdog(), enable);
}
asynStatus sinqAxis::startMovTimeoutWatchdog() {
asynStatus pl_status;
int enableMovWatchdog = 0;
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog_,
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog(),
&enableMovWatchdog);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_",
@ -440,8 +626,7 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
if (enableMovWatchdog == 1) {
// These parameters are only needed in this branch
double motorPosition = 0.0;
double motorPositionRec = 0.0;
double motorPos = 0.0;
double motorVelocity = 0.0;
double motorVelocityRec = 0.0;
double motorAccel = 0.0;
@ -458,24 +643,11 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
to save the read result to the member variable earlier), since the
parameter library is updated at a later stage!
*/
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorRecResolution_,
&motorRecResolution);
pl_status = motorPosition(&motorPos);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorRecResolution_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
return pl_status;
}
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorPosition_,
&motorPositionRec);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorPosition",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
motorPosition = motorPositionRec * motorRecResolution;
/*
We use motorVelocity, which corresponds to the record field VELO.
From https://epics.anl.gov/docs/APS2015/14-Motor-Record.pdf:
@ -488,9 +660,16 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
= VELO / MRES motorAccel = (motorVelocity - motorVelBase) / ACCL
Therefore, we need to correct the values from the parameter library.
*/
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorRecResolution(),
&motorRecResolution);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorRecResolution_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
// Read the velocity
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorVelocity_,
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorVelocity(),
&motorVelocityRec);
// Only calculate timeContSpeed if the motorVelocity has been populated
@ -501,12 +680,12 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
if (pl_status == asynSuccess) {
timeContSpeed = std::ceil(
std::fabs(targetPosition_ - motorPosition) / motorVelocity);
std::fabs(targetPosition_ - motorPos) / motorVelocity);
}
}
pl_status =
pC_->getDoubleParam(axisNo_, pC_->motorAccel_, &motorAccelRec);
pC_->getDoubleParam(axisNo_, pC_->motorAccel(), &motorAccelRec);
if (pl_status == asynSuccess && motorVelocityRec > 0.0 &&
motorAccelRec > 0.0) {
@ -531,7 +710,7 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
asynStatus pl_status;
int enableMovWatchdog = 0;
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog_,
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog(),
&enableMovWatchdog);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_",
@ -545,17 +724,25 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
return asynSuccess;
}
// Create the unique callsite identifier manually so it can be used later in
// the shouldBePrinted calls.
msgPrintControlKey key = msgPrintControlKey(pC_->portName, axisNo_,
__PRETTY_FUNCTION__, __LINE__);
// Check if the expected time of arrival has been exceeded.
if (expectedArrivalTime_ < time(NULL)) {
// Check the watchdog
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nExceeded "
"expected arrival time %ld (current time is %ld).\n",
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
expectedArrivalTime_, time(NULL));
if (pC_->getMsgPrintControl().shouldBePrinted(key, true,
pC_->pasynUser())) {
asynPrint(pC_->pasynUser(), ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nExceeded "
"expected arrival time %ld (current time is %ld).\n",
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
expectedArrivalTime_, time(NULL));
}
pl_status = setStringParam(
pC_->motorMessageText_,
pC_->motorMessageText(),
"Exceeded expected arrival time. Check if the axis is blocked.");
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorMessageText_",
@ -563,15 +750,16 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
__LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusProblem_, true);
pl_status = setIntegerParam(pC_->motorStatusProblem(), true);
if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
// Even if the movement timed out, the rest of the poll should continue.
return asynSuccess;
} else {
pC_->getMsgPrintControl().resetCount(key, pC_->pasynUser());
}
// Even if the movement timed out, the rest of the poll should continue.
return asynSuccess;
}
@ -590,8 +778,7 @@ extern "C" {
*/
asynStatus setWatchdogEnabled(const char *portName, int axisNo, int enable) {
sinqController *pC;
pC = (sinqController *)findAsynPortDriver(portName);
sinqController *pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
@ -649,8 +836,7 @@ asynStatus setOffsetMovTimeout(const char *portName, int axisNo,
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nAxis %d does not "
"exist or is not an "
"instance of sinqAxis.",
"exist or is not an instance of sinqAxis.",
portName, __PRETTY_FUNCTION__, __LINE__, axisNo);
}
@ -697,9 +883,9 @@ asynStatus setScaleMovTimeout(const char *portName, int axisNo,
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nAxis %d does not "
"exist or is not an "
"instance of sinqAxis.",
"exist or is not an instance of sinqAxis.",
portName, __PRETTY_FUNCTION__, __LINE__, axisNo);
return asynError;
}
return axis->setScaleMovTimeout(scaleMovTimeout);

View File

@ -7,6 +7,7 @@ Stefan Mathis, November 2024
#ifndef sinqAxis_H
#define sinqAxis_H
#include "asynMotorAxis.h"
#include <epicsTime.h>
class epicsShareClass sinqAxis : public asynMotorAxis {
public:
@ -19,15 +20,12 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
sinqAxis(class sinqController *pC_, int axisNo);
/**
* @brief Perform some standardized operation before and after the concrete
* @brief Perform some standardized operations before and after the concrete
`doPoll` implementation.
*
* Wrapper around doPoll which performs the following operations:
Before calling doPoll:
* Wrapper around `doPoll` which performs the following operations:
- Try to execute atFirstPoll once (and retry, if that failed)
After calling doPoll:
- Call the `doPoll` method
- Reset motorStatusProblem_, motorStatusCommsError_ and motorMessageText_ if
doPoll returned asynSuccess
@ -45,8 +43,8 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
*
* @param moving Forwarded to `doPoll`.
* @return asynStatus Forward the status of `doPoll`, unless one of
the parameter library operation fails (in that case, returns the failed
operation status).
the parameter library operation fails (in that case, returns the status of
the failed operation.
*/
asynStatus poll(bool *moving);
@ -61,11 +59,12 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
virtual asynStatus doPoll(bool *moving);
/**
* @brief Perform some standardized operation before and after the concrete
* @brief Perform some standardized operations before and after the concrete
`doMove` implementation.
* Wrapper around `doMove` which calculates the (absolute) target position
and stores it in the parameter library. After that, it calls and returns
and stores it in the member variable `targetPosition_`. This member variable
is e.g. used for the movement watchdog. Afterwards, it calls and returns
`doMove`.
*
* @param position Forwarded to `doMove`.
@ -160,10 +159,33 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
virtual asynStatus doHome(double minVelocity, double maxVelocity,
double acceleration, int forwards);
/**
* @brief This function is called when the PV "$(INSTR)$(M):Reset" is set to
* any value. It calls `doReset` (which ought to be implemented by a child
* class) and then performs da defined number of consecutive fast polls. If
* one of the polls returns asynSuccess, it returns immediately.
*
* @return asynStatus
*/
asynStatus reset();
/**
* @brief Implementation of the "proper", device-specific `reset` method.
This method should be implemented by a child class of sinqAxis. If the
motor cannot be reset, this function should return asynError.
*
* @return asynStatus
*/
virtual asynStatus doReset();
/**
* @brief This function enables / disables an axis. It should be implemented
* by a child class of sinqAxis.
*
* The concrete implementation should (but doesn't need to) follow the
* convention that a value of 0 disables the axis and any other value
* enables it.
*
* @param on
* @return asynStatus
*/
@ -175,7 +197,7 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
* Populates the speed fields of the motor record. If the param lib
* entry motorCanSetSpeed_ (connected to the PV x:VariableSpeed) is set to
* 1, VBAS and VMAX are set to min and max respectively. Otherwise, they are
* set to val. Additionally, the speed itself is set to velo.
* set to val. Additionally, the speed itself is set to VELO.
*
* The units of the inputs are engineering units (EGU) per second (e.g. mm/s
* if the EGU is mm).
@ -230,15 +252,15 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
with
timeContSpeed = abs(motorTargetPosition - motorPosition) / motorVelBase
timeContSpeed = abs(targetPosition - motorPosition) / motorVelBase
timeAcc = motorVelBase / motorAccel
The values motorTargetPosition, motorVelBase, motorAccel and
positionAtMovementStart are taken from the parameter library. Therefore it
is necessary to populate them before using this function. If they are not
given, both speed and velocity are assumed to be infinite. This means that
timeContSpeed and/or timeAcc are set to zero. motorTargetPosition is
populated automatically when using the doMove function.
The values motorVelBase, motorAccel and positionAtMovementStart are taken
from the parameter library. Therefore it is necessary to populate them
before using this function. If they are not given, both speed and velocity
are assumed to be infinite. This means that timeContSpeed and/or timeAcc are
set to zero. targetPosition is populated automatically when using the doMove
function.
The values offsetMovTimeout_ and scaleMovTimeout_ can be set directly from
the IOC shell with the functions setScaleMovTimeout and setOffsetMovTimeout,
@ -267,7 +289,7 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
* @brief Set the offsetMovTimeout. Also available in the IOC shell
* (see "extern C" section in sinqController.cpp).
*
See documentation of `checkMovTimeoutWatchdog` for details.
* See documentation of `checkMovTimeoutWatchdog` for details.
*
* @param offsetMovTimeout Offset (in seconds)
* @return asynStatus
@ -291,17 +313,68 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
return asynSuccess;
}
friend class sinqController;
/**
* @brief Return the axis number of this axis
*
* @return int
*/
int axisNo() { return axisNo_; }
/**
* @brief Read the motor position from the paramLib, adjusted for the
* motorRecResolution
*
* The motorPosition value in the paramLib is the encoder position
* divided by the motorRecResolution (see README.md). This function
* fetches the paramLib value and multiplies it with motorRecResolution
* (also fetched from the paramLib).
*
* @param motorPositon
* @return asynStatus
*/
asynStatus motorPosition(double *motorPositon);
/**
* @brief Write the motor position in the paramLib, adjusted for the
* motorRecResolution
*
* The motorPosition value in the paramLib is the encoder position
* divided by the motorRecResolution (see README.md). This function takes
* the input value and divides it with motorRecResolution (fetched from
* the paramLib).
*
* @param motorPosition
* @return asynStatus
*/
asynStatus setMotorPosition(double motorPosition);
/**
* @brief Check if the axis is not connected and print a corresponding error
* message
*
* This method is meant to be used at the end of "interactive" function
* calls such as move, home, stop etc which can be manually triggered from
* the IOC shell or from the channel access protocol.
*/
asynStatus assertConnected();
protected:
// Internal variables used in the movement timeout watchdog
time_t expectedArrivalTime_;
time_t offsetMovTimeout_;
double scaleMovTimeout_;
bool watchdogMovActive_;
// Store the motor target position for the movement time calculation
double targetPosition_;
bool wasMoving_;
/*
Store the time since the last poll
*/
epicsTimeStamp lastPollTime_;
private:
sinqController *pC_;
};

View File

@ -48,15 +48,22 @@ sinqController::sinqController(const char *portName,
ASYN_CANBLOCK | ASYN_MULTIDEVICE,
1, // autoconnect
0, 0), // Default priority and stack size
msgPrintControl_(4) {
msgPrintControl_() {
asynStatus status = asynSuccess;
lowLevelPortUser_ = nullptr;
// Handle to the asynUser of the IP port asyn driver
pasynOctetSyncIOipPort_ = nullptr;
// Initial values for the average timeout mechanism, can be overwritten
// later by a FFI function
comTimeoutWindow_ = 3600;
comTimeoutWindow_ = 3600; // seconds
// Number of timeouts which may occur before an error is forwarded to the
// user
maxNumberTimeouts_ = 60;
// Queue holding the timeout event timestamps
timeoutEvents_ = {};
// Inform the user after 10 timeouts in a row (default value)
@ -74,8 +81,9 @@ sinqController::sinqController(const char *portName,
We try to connect to the port via the port name provided by the constructor.
If this fails, the function is terminated via exit.
*/
pasynOctetSyncIO->connect(ipPortConfigName, 0, &lowLevelPortUser_, NULL);
if (status != asynSuccess || lowLevelPortUser_ == nullptr) {
pasynOctetSyncIO->connect(ipPortConfigName, 0, &pasynOctetSyncIOipPort_,
NULL);
if (status != asynSuccess || pasynOctetSyncIOipPort_ == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nFATAL ERROR (cannot "
"connect to MCU controller).\n"
"Terminating IOC",
@ -109,6 +117,16 @@ sinqController::sinqController(const char *portName,
exit(-1);
}
status = createParam("MOTOR_RESET", asynParamInt32, &motorReset_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"parameter failed with %s).\nTerminating IOC",
portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1);
}
status = createParam("MOTOR_ENABLE_RBV", asynParamInt32, &motorEnableRBV_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
@ -152,6 +170,16 @@ sinqController::sinqController(const char *portName,
exit(-1);
}
status = createParam("MOTOR_CONNECTED", asynParamInt32, &motorConnected_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"parameter failed with %s).\nTerminating IOC",
portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1);
}
/*
We need to introduce 2 new parameters in order to write the limits from the
driver to the EPICS record. See the comment in sinqController.h next to
@ -234,6 +262,16 @@ sinqController::sinqController(const char *portName,
exit(-1);
}
status = createParam("ADAPTIVE_POLLING", asynParamInt32, &adaptivePolling_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"parameter failed with %s).\nTerminating IOC",
portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1);
}
status = createParam("ENCODER_TYPE", asynParamOctet, &encoderType_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
@ -264,9 +302,15 @@ sinqController::sinqController(const char *portName,
}
sinqController::~sinqController(void) {
/*
Cleanup of the memory allocated in the asynMotorController constructor
*/
// Free all axes
for (int axisNo = 0; axisNo < numAxes_; axisNo++) {
if (pAxes_[axisNo] != nullptr) {
delete pAxes_[axisNo];
}
}
// Cleanup of the array allocated in the asynMotorController constructor
free(this->pAxes_);
}
@ -286,13 +330,15 @@ asynStatus sinqController::writeInt32(asynUser *pasynUser, epicsInt32 value) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nAxis is not an "
"instance of sinqAxis",
portName, axis->axisNo_, __PRETTY_FUNCTION__, __LINE__);
portName, axis->axisNo(), __PRETTY_FUNCTION__, __LINE__);
return asynError;
}
// Handle custom PVs
if (function == motorEnable_) {
return axis->enable(value != 0);
} else if (function == motorReset_) {
return axis->reset();
} else if (function == motorForceStop_) {
return axis->stop(0.0);
} else {
@ -302,7 +348,7 @@ asynStatus sinqController::writeInt32(asynUser *pasynUser, epicsInt32 value) {
asynStatus sinqController::readInt32(asynUser *pasynUser, epicsInt32 *value) {
// Casting into a sinqAxis is necessary to get access to the field axisNo_
// Casting into a sinqAxis is necessary to get access to the field axisNo()
asynMotorAxis *asynAxis = getAxis(pasynUser);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
@ -310,27 +356,27 @@ asynStatus sinqController::readInt32(asynUser *pasynUser, epicsInt32 *value) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nAxis is not an "
"instance of sinqAxis.\n",
portName, axis->axisNo_, __PRETTY_FUNCTION__, __LINE__);
portName, axis->axisNo(), __PRETTY_FUNCTION__, __LINE__);
return asynError;
}
if (pasynUser->reason == motorEnableRBV_) {
return getIntegerParam(axis->axisNo_, motorEnableRBV_, value);
return getIntegerParam(axis->axisNo(), motorEnableRBV_, value);
} else if (pasynUser->reason == motorCanDisable_) {
return getIntegerParam(axis->axisNo_, motorCanDisable_, value);
return getIntegerParam(axis->axisNo(), motorCanDisable_, value);
} else {
return asynMotorController::readInt32(pasynUser, value);
}
}
asynStatus sinqController::errMsgCouldNotParseResponse(const char *command,
const char *response,
int axisNo,
const char *functionName,
int line) {
asynStatus sinqController::couldNotParseResponse(const char *command,
const char *response,
int axisNo,
const char *functionName,
int line) {
asynStatus pl_status = asynSuccess;
asynPrint(lowLevelPortUser_, ASYN_TRACE_ERROR,
asynPrint(pasynOctetSyncIOipPort_, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nCould not interpret "
"response \"%s\" for command \"%s\".\n",
portName, axisNo, functionName, line, response, command);
@ -359,7 +405,7 @@ asynStatus sinqController::paramLibAccessFailed(asynStatus status,
int line) {
if (status != asynSuccess) {
asynPrint(lowLevelPortUser_, ASYN_TRACE_ERROR,
asynPrint(pasynOctetSyncIOipPort_, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\n Accessing the "
"parameter library failed for parameter %s with error %s.\n",
portName, axisNo, functionName, line, parameter,
@ -434,12 +480,12 @@ asynStatus sinqController::checkComTimeoutWatchdog(sinqAxis *axis) {
char motorMessage[200] = {0};
asynStatus status =
checkComTimeoutWatchdog(axis->axisNo_, motorMessage, 200);
checkComTimeoutWatchdog(axis->axisNo(), motorMessage, 200);
if (status == asynError) {
status = axis->setStringParam(motorMessageText_, motorMessage);
if (status != asynSuccess) {
return paramLibAccessFailed(status, "motorMessageText_",
axis->axisNo_, __PRETTY_FUNCTION__,
axis->axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
}
@ -459,8 +505,7 @@ asynStatus sinqController::checkMaxSubsequentTimeouts(int timeoutNo, int axisNo,
asynPrint(
this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nMore than %d "
"subsequent communication "
"timeouts\n",
"subsequent communication timeouts.\n",
this->portName, axisNo, __PRETTY_FUNCTION__, __LINE__,
maxSubsequentTimeouts_);
@ -486,13 +531,13 @@ asynStatus sinqController::checkMaxSubsequentTimeouts(int timeoutNo,
char motorMessage[200] = {0};
asynStatus status =
checkMaxSubsequentTimeouts(axis->axisNo_, timeoutNo, motorMessage, 200);
asynStatus status = checkMaxSubsequentTimeouts(timeoutNo, axis->axisNo(),
motorMessage, 200);
if (status == asynError) {
status = axis->setStringParam(motorMessageText_, motorMessage);
if (status != asynSuccess) {
return paramLibAccessFailed(status, "motorMessageText_",
axis->axisNo_, __PRETTY_FUNCTION__,
axis->axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
}
@ -573,8 +618,8 @@ extern "C" {
* implementation)
*
* @param comTimeoutWindow Size of the time window used to calculate
* the moving average of timeout events. Set this value to 0 to deactivate
* the watchdog.
* the moving average of timeout events in seconds. Set this value to 0 to
* deactivate the watchdog.
* @param maxNumberTimeouts Maximum number of timeouts which may occur
* within the time window before the watchdog is triggered.
* @return asynStatus
@ -628,9 +673,9 @@ asynStatus setMaxSubsequentTimeouts(const char *portName,
if (ptr == nullptr) {
/*
We can't use asynPrint here since this macro would require us
to get a lowLevelPortUser_ from a pointer to an asynPortDriver.
to get a pasynOctetSyncIOipPort_ from a pointer to an asynPortDriver.
However, the given pointer is a nullptr and therefore doesn't
have a lowLevelPortUser_! printf is an EPICS alternative which
have a pasynOctetSyncIOipPort_! printf is an EPICS alternative which
works w/o that, but doesn't offer the comfort provided
by the asynTrace-facility
*/

View File

@ -32,17 +32,17 @@ class epicsShareClass sinqController : public asynMotorController {
pAxes_ which has the length specified here. When getting an axis, the
`getAxis` function indexes into this array. A length of 8 would therefore
mean that the axis slots 0 to 7 are available. However, in order to keep the
axis enumeration in sync with the electronics counting logic, we start
counting the axes with 1 and end at 8. Therefore, an offset of 1 is added
when forwarding this number to asynMotorController.
axis enumeration identical to that of the hardware, we start counting the
axes with 1 and end at 8. Therefore, an offset of 1 is added when forwarding
this number to asynMotorController.
* @param movingPollPeriod Time between polls when moving (in seconds)
* @param idlePollPeriod Time between polls when not moving (in
seconds)
* @param extraParams Number of extra parameter library entries
* created in a concrete driver implementation
*/
sinqController(const char *portName, const char *SINQPortName, int numAxes,
double movingPollPeriod, double idlePollPeriod,
sinqController(const char *portName, const char *ipPortConfigName,
int numAxes, double movingPollPeriod, double idlePollPeriod,
int numExtraParams);
/**
@ -82,7 +82,7 @@ class epicsShareClass sinqController : public asynMotorController {
*
* If accessing the parameter library failed (return status !=
asynSuccess), calling this function writes a standardized message to both
the IOC shell and the motor message text PV. It then returns the input
the IOC shell and the motorMessageText PV. It then returns the input
status.
*
* @param status Status of the failed parameter library access
@ -90,7 +90,7 @@ class epicsShareClass sinqController : public asynMotorController {
error messages.
* @param functionName Name of the caller function. It is recommended
to use a macro, e.g. __func__ or __PRETTY_FUNCTION__.
* @param line Source code line where this function is
* @param line Source code line where this function is
called. It is recommended to use a macro, e.g. __LINE__.
* @return asynStatus Returns input status.
*/
@ -115,9 +115,9 @@ class epicsShareClass sinqController : public asynMotorController {
called. It is recommended to use a macro, e.g. __LINE__.
* @return asynStatus Returns asynError.
*/
asynStatus errMsgCouldNotParseResponse(const char *command,
const char *response, int axisNo,
const char *functionName, int line);
asynStatus couldNotParseResponse(const char *command, const char *response,
int axisNo, const char *functionName,
int line);
/**
* @brief Convert an asynStatus into a descriptive string.
@ -131,7 +131,7 @@ class epicsShareClass sinqController : public asynMotorController {
* @brief This function should be called when a communication timeout
occured. It calculates the frequency of communication timeout events and
creates an error message, if an threshold has been exceeded.
*
Occasionally, communication timeouts between the IOC and the motor
controller may happen, usually because the controller takes too long to
respond. If this happens infrequently, this is not a problem. However, if it
@ -181,7 +181,7 @@ class epicsShareClass sinqController : public asynMotorController {
/**
* @brief Inform the user, if the number of timeouts exceeds the threshold
* specified with setMaxSubsequentTimeouts
* specified with `setMaxSubsequentTimeouts`.
*
* @param timeoutNo Number of subsequent timeouts which already
* happened.
@ -192,10 +192,10 @@ class epicsShareClass sinqController : public asynMotorController {
class sinqAxis *axis);
/**
* @brief See documentation of checkMaxSubsequentTimeouts(sinqAxis * axis)
* @brief See documentation of `checkMaxSubsequentTimeouts(sinqAxis * axis)`
*
* @param userMessage Buffer for the user message
* @param userMessageSize Buffer size in chars
* @param userMessage Buffer for the user message
* @param userMessageSize Buffer size in chars
* @return asynStatus
*/
virtual asynStatus checkMaxSubsequentTimeouts(int timeoutNo, int axisNo,
@ -216,17 +216,110 @@ class epicsShareClass sinqController : public asynMotorController {
/**
* @brief Get a reference to the map used to control the maximum number of
* message repetitions. See the documentation of printRepetitionWatchdog in
* msgPrintControl.h for details.
*
* @return std::unordered_map<msgPrintControlKey, size_t>&
* message repetitions. See the documentation of `printRepetitionWatchdog`
* in msgPrintControl.h for details.
*/
msgPrintControl &getMsgPrintControl();
friend class sinqAxis;
// =========================================================================
// Public getters for protected members
// Accessors for double parameters
int motorMoveRel() { return motorMoveRel_; }
int motorMoveAbs() { return motorMoveAbs_; }
int motorMoveVel() { return motorMoveVel_; }
int motorHome() { return motorHome_; }
int motorStop() { return motorStop_; }
int motorVelocity() { return motorVelocity_; }
int motorVelBase() { return motorVelBase_; }
int motorAccel() { return motorAccel_; }
int motorPosition() { return motorPosition_; }
int motorEncoderPosition() { return motorEncoderPosition_; }
int motorDeferMoves() { return motorDeferMoves_; }
int motorMoveToHome() { return motorMoveToHome_; }
int motorResolution() { return motorResolution_; }
int motorEncoderRatio() { return motorEncoderRatio_; }
int motorPGain() { return motorPGain_; }
int motorIGain() { return motorIGain_; }
int motorDGain() { return motorDGain_; }
int motorHighLimit() { return motorHighLimit_; }
int motorLowLimit() { return motorLowLimit_; }
int motorClosedLoop() { return motorClosedLoop_; }
int motorPowerAutoOnOff() { return motorPowerAutoOnOff_; }
int motorPowerOnDelay() { return motorPowerOnDelay_; }
int motorPowerOffDelay() { return motorPowerOffDelay_; }
int motorPowerOffFraction() { return motorPowerOffFraction_; }
int motorPostMoveDelay() { return motorPostMoveDelay_; }
int motorStatus() { return motorStatus_; }
int motorUpdateStatus() { return motorUpdateStatus_; }
// Accessors for status bits (integers)
int motorStatusDirection() { return motorStatusDirection_; }
int motorStatusDone() { return motorStatusDone_; }
int motorStatusHighLimit() { return motorStatusHighLimit_; }
int motorStatusAtHome() { return motorStatusAtHome_; }
int motorStatusSlip() { return motorStatusSlip_; }
int motorStatusPowerOn() { return motorStatusPowerOn_; }
int motorStatusFollowingError() { return motorStatusFollowingError_; }
int motorStatusHome() { return motorStatusHome_; }
int motorStatusHasEncoder() { return motorStatusHasEncoder_; }
int motorStatusProblem() { return motorStatusProblem_; }
int motorStatusMoving() { return motorStatusMoving_; }
int motorStatusGainSupport() { return motorStatusGainSupport_; }
int motorStatusCommsError() { return motorStatusCommsError_; }
int motorStatusLowLimit() { return motorStatusLowLimit_; }
int motorStatusHomed() { return motorStatusHomed_; }
// Parameters for passing additional motor record information to the driver
int motorRecResolution() { return motorRecResolution_; }
int motorRecDirection() { return motorRecDirection_; }
int motorRecOffset() { return motorRecOffset_; }
// Accessors for additional PVs defined in sinqController
int motorMessageText() { return motorMessageText_; }
int motorReset() { return motorReset_; }
int motorEnable() { return motorEnable_; }
int motorEnableRBV() { return motorEnableRBV_; }
int motorCanDisable() { return motorCanDisable_; }
int motorEnableMovWatchdog() { return motorEnableMovWatchdog_; }
int motorCanSetSpeed() { return motorCanSetSpeed_; }
int motorLimitsOffset() { return motorLimitsOffset_; }
int motorForceStop() { return motorForceStop_; }
int motorConnected() { return motorConnected_; }
int motorVeloFromDriver() { return motorVeloFromDriver_; }
int motorVbasFromDriver() { return motorVbasFromDriver_; }
int motorVmaxFromDriver() { return motorVmaxFromDriver_; }
int motorAcclFromDriver() { return motorAcclFromDriver_; }
int motorHighLimitFromDriver() { return motorHighLimitFromDriver_; }
int motorLowLimitFromDriver() { return motorLowLimitFromDriver_; }
int adaptivePolling() { return adaptivePolling_; }
int encoderType() { return encoderType_; }
// Additional members
int numAxes() { return numAxes_; }
double idlePollPeriod() { return idlePollPeriod_; }
double movingPollPeriod() { return movingPollPeriod_; }
/**
* @brief Return a pointer to the asynUser of the controller
*
* @return asynUser*
*/
asynUser *pasynUser() { return pasynUserSelf; }
/**
* @brief Return a pointer to the low-level octet (string) IP Port
*
* @return asynUser*
*/
asynUser *pasynOctetSyncIOipPort() { return pasynOctetSyncIOipPort_; }
// =========================================================================
protected:
asynUser *lowLevelPortUser_;
// Pointer to the port user which is specified by the char array
// `ipPortConfigName` in the constructor
asynUser *pasynOctetSyncIOipPort_;
double movingPollPeriod_;
double idlePollPeriod_;
msgPrintControl msgPrintControl_;
@ -243,8 +336,12 @@ class epicsShareClass sinqController : public asynMotorController {
int maxSubsequentTimeouts_;
bool maxSubsequentTimeoutsExceeded_;
/*
See the documentation in db/sinqMotor.db for the following integers
*/
#define FIRST_SINQMOTOR_PARAM motorMessageText_
int motorMessageText_;
int motorReset_;
int motorEnable_;
int motorEnableRBV_;
int motorCanDisable_;
@ -252,6 +349,7 @@ class epicsShareClass sinqController : public asynMotorController {
int motorCanSetSpeed_;
int motorLimitsOffset_;
int motorForceStop_;
int motorConnected_;
/*
These parameters are here to write values from the hardware to the EPICS
motor record. Using motorHighLimit_ / motorLowLimit_ does not work:
@ -265,6 +363,7 @@ class epicsShareClass sinqController : public asynMotorController {
int motorAcclFromDriver_;
int motorHighLimitFromDriver_;
int motorLowLimitFromDriver_;
int adaptivePolling_;
int encoderType_;
#define LAST_SINQMOTOR_PARAM encoderType_