Compare commits

...

21 Commits

Author SHA1 Message Date
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
ca7bede4b7 Actually added the files for msgPrintControl 2025-03-04 09:23:34 +01:00
d3307db987 Added msgPrintControl feature to control the maximum number of IOC shell
message repetitions.
2025-03-04 09:12:11 +01:00
591509bd43 Forgot to save the changes to sinqController.cpp beforehand 2025-02-25 08:59:21 +01:00
5854d2c9d0 Added motor target position record which allows to read out the motor
target position from within a driver.
2025-02-25 08:51:44 +01:00
f134a61649 Added an explanation how to build the patched motorBase library from GFA 2025-02-20 18:01:51 +01:00
49be84068f Merge branch 'main' of https://git.psi.ch/sinq-epics-modules/sinqmotor 2025-02-14 16:20:41 +01:00
e92a867189 Bugfix for movTimeoutWatchdog
Update of README.md
2025-02-14 16:19:17 +01:00
8bc6109e2a Bugfix for movTimeoutWatchdog 2025-02-14 16:17:11 +01:00
c06cf8e76c Fixed small typo in an error message 2025-01-22 11:01:08 +01:00
f14ac66971 Missing controller name in PV name 2025-01-08 16:01:04 +01:00
b6e0f03a17 Moved the initialization of some parameters into sinqMotor 2024-12-23 09:30:24 +01:00
5946563372 Merge branch 'main' of https://git.psi.ch/sinq-epics-modules/sinqmotor 2024-12-11 09:59:36 +01:00
da96b4b973 Adjusted the encoder type naming to that of the new NICOS class
(https://forge.frm2.tum.de/review/c/frm2/nicos/nicos/+/35285)
2024-12-11 09:57:59 +01:00
61087d2e44 Adjusted the encoder type naming to that of the new NICOS class
(https://forge.frm2.tum.de/review/c/frm2/nicos/nicos/+/35285)
2024-12-11 09:49:17 +01:00
11 changed files with 1662 additions and 619 deletions

View File

@ -24,16 +24,6 @@ formatting:
tags: tags:
- sinq - sinq
# clangtidy:
# stage: lint
# script:
# - curl https://docker.psi.ch:5000/v2/_catalog
# # - dnf update -y
# # - dnf install -y clang-tools-extra
# # - clang-tidy sinqEPICSApp/src/*.cpp sinqEPICSApp/src/*.c sinqEPICSApp/src/*.h -checks=cppcoreguidelines-*,cert-*
# # tags:
# # - sinq
build_module: build_module:
stage: build stage: build
script: script:

View File

@ -6,14 +6,16 @@ BUILDCLASSES=Linux
EPICS_VERSIONS=7.0.7 EPICS_VERSIONS=7.0.7
ARCH_FILTER=RHEL% ARCH_FILTER=RHEL%
# additional module dependencies # Specify the version of asynMotor we want to build against
REQUIRED+=asynMotor asynMotor_VERSION=7.2.2
# Source files to build # Source files to build
SOURCES += src/msgPrintControl.cpp
SOURCES += src/sinqAxis.cpp SOURCES += src/sinqAxis.cpp
SOURCES += src/sinqController.cpp SOURCES += src/sinqController.cpp
# Headers which allow using this library in concrete driver implementations # Headers which allow using this library in concrete driver implementations
HEADERS += src/msgPrintControl.h
HEADERS += src/sinqAxis.h HEADERS += src/sinqAxis.h
HEADERS += src/sinqController.h HEADERS += src/sinqController.h
@ -21,6 +23,9 @@ HEADERS += src/sinqController.h
TEMPLATES += db/asynRecord.db TEMPLATES += db/asynRecord.db
TEMPLATES += db/sinqMotor.db TEMPLATES += db/sinqMotor.db
# This file registers the motor-specific functions in the IOC shell.
DBDS += src/sinqMotor.dbd
USR_CFLAGS += -Wall -Wextra -Weffc++ -Wunused-result # -Werror USR_CFLAGS += -Wall -Wextra -Weffc++ -Wunused-result # -Werror
# MISCS would be the place to keep the stream device template files # MISCS would be the place to keep the stream device template files

118
README.md
View File

@ -2,23 +2,22 @@
## Overview ## Overview
This library offers base classes for EPICS motor drivers (`sinqAxis` and `sinqController`) of PSI SINQ. These classes are extensions of the classes `asynMotorAxis` and `asynMotorController` from the `asynMotor` framework (https://github.com/epics-modules/motor/tree/master/motorApp/MotorSrc) and bundle some common functionalities. This library offers base classes for EPICS motor drivers (`sinqAxis` and `sinqController`) of PSI SINQ. These classes are extensions of the classes `asynMotorAxis` and `asynMotorController` from the `asynMotor` framework (https://github.com/epics-modules/motor/tree/master/motorApp/MotorSrc) and bundle some common functionality.
## User guide ## User guide
### Architecture of EPICS motor drivers at SINQ ### Architecture of EPICS motor drivers at SINQ
As mentioned before, the asyn-framework offers two base classes `asynMotorAxis` and `asynMotorController`. At SINQ, we extend those classes by two children classes `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 pmacv3-driver: https://git.psi.ch/sinq-epics-modules/pmacv3 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 for a like this: The full inheritance chain for two different motor drivers "a" and "b" looks like this:
`asynController -> sinqController -> aController` `asynController -> sinqController -> aController`
`asynAxis -> sinqAxis -> aAxis` `asynAxis -> sinqAxis -> aAxis`
`asynController -> sinqController -> bController` `asynController -> sinqController -> bController`
`asynAxis -> sinqAxis -> bAxis` `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 version management is SemVer-compatible (https://semver.org/lang/de/) in order to ensure compatibility. 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.
For example, if driver "a" depends on version 2.1.0 of "sinqMotor", then it is safe to use version 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.
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). 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).
@ -30,52 +29,60 @@ An EPICS IOC for motor control at SINQ is started by executing a script with the
# Load libraries needed for the IOC # Load libraries needed for the IOC
require sinqMotor, 1.0.0 require sinqMotor, 1.0.0
require pmacv3, 1.2.0 require turboPmac, 1.2.0
# Define environment variables used later to parametrize the individual controllers # Define environment variables used later to parametrize the individual controllers
epicsEnvSet("TOP","/ioc/sinq-ioc/sinqtest-ioc/") epicsEnvSet("TOP","/ioc/sinq-ioc/sinqtest-ioc/")
epicsEnvSet("INSTR","SQ:SINQTEST:") epicsEnvSet("INSTR","SQ:SINQTEST:")
# Include other scripts for the controllers 1 and 2 # Include other scripts for the controllers 1 and 2
< mcu1.cmd < turboPmac1.cmd
< mcu2.cmd < turboPmac2.cmd
iocInit() 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 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 ("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 some needed parameters (they can be safely overwritten in e.g. mcu2.cmd) # Define the name of the controller and the corresponding port
epicsEnvSet("NAME","mcu1") epicsEnvSet("NAME","turboPmac1")
epicsEnvSet("ASYN_PORT","p$(NAME)") epicsEnvSet("ASYN_PORT","p$(NAME)")
# Define the IP adress of the controller # 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("$(ASYN_PORT)","172.28.101.24:1025")
# Create the controller object in EPICS. The function "pmacv3Controller" is # Create the controller object with the defined name and connect it to the socket via the port name.
# provided by loading the shared library pmacv3 earlier. # The other parameters are as follows:
pmacv3Controller("$(NAME)","$(ASYN_PORT)",8,0.05,1,0.05); # 8: Maximum number of axes
# 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);
# Create four axes objects on slots 1, 2, 3 and 5 of the controller. # Define some axes for the specified motor controller at the given slot (1, 2 and 5). No slot may be used twice!
pmacv3Axis("$(NAME)",1); turboPmacAxis("$(NAME)",1);
pmacv3Axis("$(NAME)",2); turboPmacAxis("$(NAME)",2);
pmacv3Axis("$(NAME)",3); turboPmacAxis("$(NAME)",5);
pmacv3Axis("$(NAME)",5);
# Create some general PVs of an asynRecord, substituting the macro P by concatenating INSTR and NAME and PORT by ASYN_PORT. # Set the number of subsequent timeouts
dbLoadRecords("$(sinqMotor_DB)/asynRecord.db","P=$(INSTR)$(NAME),PORT=$(ASYN_PORT)") setMaxSubsequentTimeouts("$(NAME)", 20);
# Create PVs provided by the sinqMotor database template. This template is parametrized by the substitution file "mcu1.substitutions" (see below) # Configure the timeout frequency watchdog: A maximum of 10 timeouts are allowed in 300 seconds before an alarm message is sent.
setThresholdComTimeout("$(NAME)", 300, 10);
# Parametrize the EPICS record database with the substitution file named after the motor controller.
epicsEnvSet("SINQDBPATH","$(sinqMotor_DB)/sinqMotor.db") epicsEnvSet("SINQDBPATH","$(sinqMotor_DB)/sinqMotor.db")
dbLoadTemplate("$(TOP)/mcu1.substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)") dbLoadTemplate("$(TOP)/$(NAME).substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)")
epicsEnvSet("SINQDBPATH","$(turboPmac_DB)/turboPmac.db")
# Create PVs specific for pmacv3. Again, we load a database template and parametrize it with the substitution file "mcu1.substitutions" dbLoadTemplate("$(TOP)/$(NAME).substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)")
epicsEnvSet("SINQDBPATH","$(pmacv3_DB)/pmacv3.db") dbLoadRecords("$(sinqMotor_DB)/asynRecord.db","P=$(INSTR)$(NAME),PORT=$(ASYN_PORT)")
dbLoadTemplate("$(TOP)/mcu1.substitutions", "INSTR=$(INSTR)$(NAME):,CONTROLLER=$(NAME)")
``` ```
### Substitution file ### Substitution file
The substitution file is a table containing axis-specific information which is used to create the axis-specific PVs. To work with sinqMotor, "mcu1.substitutions" needs to look like this: The substitution file is a table containing axis-specific information which is used to create the axis-specific PVs.
To work with sinqMotor, "mcu1.substitutions" needs to look like this (the order of columns does not matter):
``` ```
file "$(SINQDBPATH)" file "$(SINQDBPATH)"
{ {
@ -93,20 +100,20 @@ The variable `SINQDBPATH` has been set in "mcu1.cmd" before calling `dbLoadTempl
- `AXIS`: Index of the axis, corresponds to the physical connection of the axis to the MCU. - `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, NAME and M. For example, the PV of the first axis would be "SQ:SINQTEST:mcu1:lin1".
- `DESC`: Description of the motor. This field is just for documentation and is not needed for operating a motor.
- `EGU`: Engineering units. For a linear motor, this is mm, for a rotaty motor, this is degree. - `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. - `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). - `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 #### Optional parameters
The default values for those parameters are given for the individual records in db/sinqMotor.db The default values for those parameters are given for the individual records in db/sinqMotor.db
- `MSGTEXTSIZE`: Buffer size for the motor message record in characters - `DESC`: Description of the motor. This field is just for documentation and is not needed for operating a motor. Defaults to the motor name.
- `ENABLEMOVWATCHDOG`: Sets `setWatchdogEnabled` during IOC startup to the given value. - `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 - `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 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 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). 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. - `CANSETSPEED`: If set to 1, the motor speed can be modified by the user. Defaults to 0.
### Motor record resolution MRES ### Motor record resolution MRES
@ -154,27 +161,29 @@ 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. 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 #### 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. - `paramLibAccessFailed`: Write a standardized message if accessing the parameter library failed.
- `stringifyAsynStatus`: Convert the enum `asynStatus` into a human-readable string. - `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.
- `setThresholdComTimeout`: Set the maximum number of timeouts and the time window size for the timeout frequency limit.
- `checkMaxSubsequentTimeouts`: Check if the number of subsequent timeouts exceeds a specified limit.
- `setMaxSubsequentTimeouts`: Set the limit for the number of subsequent timeouts before the user is informed.
#### sinqAxis #### sinqAxis.h
- `atFirstPoll`: This function is executed once before the first poll. If it returns anything but `asynSuccess`, it retries. - `enable`: This function is called if the `$(INSTR)$(M):Enable` PV from db/sinqMotor.db is set.
- `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. This is an empty function which should be overwritten by concrete driver implementations.
- `checkMovTimeoutWatchdog`: Check if the watchdog timed out. - `reset`: This function is called when the `$(INSTR)$(M):Reset` PV from db/sinqMotor.db is set.
- `setWatchdogEnabled`: Enables / disables the watchdog. This function is also available in the IOC shell. It calls `doReset` and performs some fast polls after `doReset` returns.
- `setOffsetMovTimeout`: Set a linear offset for the expected movement time. This function is also available in the IOC shell. - `doReset`: This is an empty function which should be overwritten by concrete driver implementations.
- `setScaleMovTimeout`: Set a scaling factor for the expected movement time. This function is also available in the IOC shell.
- `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.
- `move`: This function sets the absolute target position in the parameter library and then calls `doMove`. - `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. - `doMove`: This is an empty function which should be overwritten by concrete driver implementations.
- `home`: This function sets the absolute target position in the parameter library and then calls `doHome`. The target position is assumed to be the high limit, if the distance of the current position to it is larger than that to the low limit, and the low limit otherwise. - `home`: This function sets the internal status flags for the homing process and then calls doHome.
- `doHome`: This is an empty function which should be overwritten by concrete driver implementations. - `doHome`: This is an empty function which should be overwritten by concrete driver implementations.
- `poll`: This is a wrapper around `doPoll` which performs some bookkeeping tasks before and after calling `doPoll`: - `poll`: This is a wrapper around `doPoll` which performs some bookkeeping tasks before and after calling `doPoll`:
Before calling `doPoll`: Before calling `doPoll`:
- Try to execute `atFirstPoll` once during the lifetime of the IOC (and retry, if that failed) - Reset the status problem flag, the communication error flag and the error message.
After calling `doPoll`: After calling `doPoll`:
- Call `checkMovTimeoutWatchdog`. If the movement timed out, create an error message for the user - Call `checkMovTimeoutWatchdog`. If the movement timed out, create an error message for the user
@ -182,9 +191,18 @@ sinqMotor offers a variety of additional methods for children classes to standar
- Reset `motorStatusProblem_`, `motorStatusCommsError_` and `motorMessageText_` if `doPoll` returned `asynSuccess` - Reset `motorStatusProblem_`, `motorStatusCommsError_` and `motorMessageText_` if `doPoll` returned `asynSuccess`
- Run `callParamCallbacks` - Run `callParamCallbacks`
- Return the status of `doPoll` - 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. - `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. - `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.
- `checkMovTimeoutWatchdog`: Check if the watchdog timed out.
- `setWatchdogEnabled`: Enables / disables the watchdog. This function is also available in the IOC shell.
- `setOffsetMovTimeout`: Set a linear offset for the expected movement time. This function is also available in the IOC shell.
- `setScaleMovTimeout`: Set a scaling factor for the expected movement time. This function is also available in the IOC shell.
#### msgPrintControl.h
In addition to the two extension classes this library also includes a mechanism which prevents excessive repetitions of the same error message to the IOC shell via the classes `msgPrintControl` and `msgPrintControlKey`. A detailed description of the mechanism can be found in the docstring of `msgPrintControl`. The implementation of the `poll` function of `sinqAxis` also contains an example how to use it. Using this feature in derived drivers is entirely optional.
### Versioning ### Versioning
@ -194,6 +212,12 @@ All existing tags can be listed with `git tag` in the sinqMotor directory. Detai
### How to build it ### How to build it
The makefile in the top directory includes all necessary steps for compiling a shared library together with the header files into `/ioc/modules` (using the PSI EPICS build system).Therefore it is sufficient to run `make install` from the terminal. This library is based on the PSI version of the EPICS motor record, which can be found here: `https://git.psi.ch/epics_driver_modules/motorBase`. We use a branch with a bugfix which is currently not merged into master due to resistance of the PSI userbase: `https://git.psi.ch/epics_driver_modules/motorBase/-/tree/pick_fix-lockup-VAL-HOMF-VAL`. This library can be build with the following steps, assuming GCC and make are available:
- `git clone https://git.psi.ch/epics_driver_modules/motorBase/-/tree/pick_fix-lockup-VAL-HOMF-VAL`
- `cd motorBase`
- `git tag 7.2.2`. The latest version on master is currently 7.2.1, hence we increment the bugfix version counter by one
- `make install`
To build sinqMotor itself, the makefile in the top directory includes all necessary steps for compiling a shared library together with the header files into `/ioc/modules` (using the PSI EPICS build system). Therefore it is sufficient to clone this repository to a suitable location (`git clone https://git.psi.ch/sinq-epics-modules/sinqmotor/-/tree/main`). Afterwards, switch to the directory (`cd sinqmotor`) and run `make install`.
To use the library when writing a concrete motor driver, include it in the makefile of your application / library the same way as other libraries such as e.g. `asynMotor` by adding `REQUIRED+=sinqMotor` to your Makefile. The version can be specified with `sinqMotor_VERSION=x.x.x.` To use the library when writing a concrete motor driver, include it in the makefile of your application / library the same way as other libraries such as e.g. `asynMotor` by adding `REQUIRED+=sinqMotor` to your Makefile. The version can be specified with `sinqMotor_VERSION=x.x.x.`

View File

@ -1,27 +1,77 @@
# The main asyn motor record. Some fields are populated from the substitution # The main asyn motor record. Some fields are populated from the substitution
# files via macros: # files via macros:
# - $(INSTR): Name of the instrument, e.g. "SQ:SINQTEST:" # - INSTR: Name of the instrument, e.g. "SQ:SINQTEST:"
# - $(M): Name of the motor in EPICS, e.g. "lin1" # - M: Name of the motor in EPICS, e.g. "lin1"
# - $(DESC): Short description of the motor # - DESC: Short description of the motor. If not given, this is equal to M
# - $(DIR): This value is usually set to "Pos". If the motor axis direction # - DIR: This value is usually set to "Pos". If the motor axis direction
# should be inverted, this value can be set to "Neg" # should be inverted, this value can be set to "Neg"
# - $(CONTROLLER): Name of the motor controller, e.g. "mcu1" # - CONTROLLER: Name of the motor controller, e.g. "mcu1"
# - $(AXIS): Number of the axis, e.g. "1" # - AXIS: Number of the axis, e.g. "1"
# - $(MRES): Motor record resolution. See the README.md for a detailed discussion # - MRES: Motor record resolution. See the README.md for a detailed discussion
# - $(EGU): Engineering units. In case of a rotary axis, this is "degree", in # - EGU: Engineering units. In case of a rotary axis, this is "degree", in
# case of a linear axis this is "mm". # case of a linear axis this is "mm".
# - RTRY: The maximum number of times the motor record will try again to move to
# the desired position. When the retry limit is reached, the motor record will
# declare the motion finished. If the desired position was not reached, the
# field MISS will be set to 1 and NICOS will emit a warning "Did not reach
# target position". If this value is set to 0, the retry deadband is never
# applied and therefore MISS will always be 0. The error message "Did not reach
# target position" will therefore never appear.
# - RDBD: Retry deadband: When the motor has finished a complete motion,
# possibly including backlash takeout, the motor record will compare its current
# position with the desired position. If the magnitude of the difference is
# 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.
record(motor,"$(INSTR)$(M)") record(motor,"$(INSTR)$(M)")
{ {
field(DESC,"$(DESC)") field(DESC,"$(DESC=$(M))")
field(DTYP,"asynMotor") field(DTYP,"asynMotor")
field(DIR,"$(DIR=Pos)") field(DIR,"$(DIR=Pos)")
field(OUT,"@asyn($(CONTROLLER),$(AXIS))") field(OUT,"@asyn($(CONTROLLER),$(AXIS))")
field(MRES,"$(MRES)") field(MRES,"$(MRES)")
field(EGU,"$(EGU)") field(EGU,"$(EGU)")
field(INIT,"") field(INIT,"")
field(PINI, "NO") field(PINI,"NO")
field(TWV,"1") field(TWV,"1")
field(RTRY, "0") field(RTRY,"0")
field(RDBD,"0")
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")
}
# 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):StopRBV")
{
field(DTYP, "asynInt32")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_FORCE_STOP")
field(SCAN, "I/O Intr")
field(FLNK, "$(INSTR)$(M):Stop2Field")
}
record(longout, "$(INSTR)$(M):Stop2Field") {
field(DOL, "$(INSTR)$(M):StopRBV NPP")
field(OUT, "$(INSTR)$(M).STOP")
field(OMSL, "closed_loop")
} }
# This record forwards the motor record resolution MRES to the parameter library # This record forwards the motor record resolution MRES to the parameter library
@ -30,7 +80,7 @@ record(motor,"$(INSTR)$(M)")
# for calculating the estimated time of arrival inside the watchdog). # for calculating the estimated time of arrival inside the watchdog).
record(ao,"$(INSTR)$(M):RecResolution") { record(ao,"$(INSTR)$(M):RecResolution") {
field(DESC, "$(M) resolution") field(DESC, "$(M) resolution")
field(DOL, "$(INSTR)$(M).MRES CP MS") field(DOL, "$(INSTR)$(M).MRES CP")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
field(DTYP, "asynFloat64") field(DTYP, "asynFloat64")
field(OUT, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_REC_RESOLUTION") field(OUT, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_REC_RESOLUTION")
@ -123,12 +173,13 @@ record(ao, "$(INSTR)$(M):LimitsOffset") {
record(ai, "$(INSTR)$(M):DHLM_RBV") record(ai, "$(INSTR)$(M):DHLM_RBV")
{ {
field(DTYP, "asynFloat64") field(DTYP, "asynFloat64")
field(VAL, "$(DHLM=0)")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_HIGH_LIMIT_FROM_DRIVER") field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_HIGH_LIMIT_FROM_DRIVER")
field(SCAN, "I/O Intr") field(SCAN, "I/O Intr")
field(FLNK, "$(INSTR)$(M):PushDHLM2Field") field(FLNK, "$(INSTR)$(M):PushDHLM2Field")
} }
record(ao, "$(INSTR)$(M):PushDHLM2Field") { 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(OUT, "$(INSTR)$(M).DHLM")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }
@ -141,12 +192,13 @@ record(ao, "$(INSTR)$(M):PushDHLM2Field") {
record(ai, "$(INSTR)$(M):DLLM_RBV") record(ai, "$(INSTR)$(M):DLLM_RBV")
{ {
field(DTYP, "asynFloat64") field(DTYP, "asynFloat64")
field(VAL, "$(DLLM=0)")
field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_LOW_LIMIT_FROM_DRIVER") field(INP, "@asyn($(CONTROLLER),$(AXIS)) MOTOR_LOW_LIMIT_FROM_DRIVER")
field(SCAN, "I/O Intr") field(SCAN, "I/O Intr")
field(FLNK, "$(INSTR)$(M):PushDLLM2Field") field(FLNK, "$(INSTR)$(M):PushDLLM2Field")
} }
record(ao, "$(INSTR)$(M):PushDLLM2Field") { 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(OUT, "$(INSTR)$(M).DLLM")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }
@ -164,7 +216,7 @@ record(ai, "$(INSTR)$(M):VELO_RBV")
field(FLNK, "$(INSTR)$(M):PushVELO2Field") field(FLNK, "$(INSTR)$(M):PushVELO2Field")
} }
record(ao, "$(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(OUT, "$(INSTR)$(M).VELO")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }
@ -182,7 +234,7 @@ record(ai, "$(INSTR)$(M):VBAS_RBV")
field(FLNK, "$(INSTR)$(M):PushVBAS2Field") field(FLNK, "$(INSTR)$(M):PushVBAS2Field")
} }
record(ao, "$(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(OUT, "$(INSTR)$(M).VBAS")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }
@ -200,7 +252,7 @@ record(ai, "$(INSTR)$(M):VMAX_RBV")
field(FLNK, "$(INSTR)$(M):PushVMAX2Field") field(FLNK, "$(INSTR)$(M):PushVMAX2Field")
} }
record(ao, "$(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(OUT, "$(INSTR)$(M).VMAX")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }
@ -218,7 +270,7 @@ record(ai, "$(INSTR)$(M):ACCL_RBV")
field(FLNK, "$(INSTR)$(M):PushACCL2Field") field(FLNK, "$(INSTR)$(M):PushACCL2Field")
} }
record(ao, "$(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(OUT, "$(INSTR)$(M).ACCL")
field(OMSL, "closed_loop") field(OMSL, "closed_loop")
} }

114
src/msgPrintControl.cpp Normal file
View File

@ -0,0 +1,114 @@
#include "msgPrintControl.h"
#include <unordered_map>
msgPrintControlKey::msgPrintControlKey(char *controller, int axisNo,
const char *functionName, int line) {
controller_ = controller;
axisNo_ = axisNo;
line_ = line;
functionName_ = functionName;
}
void msgPrintControlKey::format(char *buffer, size_t bufferSize) {
snprintf(buffer, bufferSize, "controller %s, axis %d, function %s, line %d",
controller_.c_str(), axisNo_, functionName_, line_);
}
// =============================================================================
msgPrintControl::msgPrintControl(size_t maxRepetitions) {
maxRepetitions_ = maxRepetitions;
}
bool msgPrintControl::shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
asynUser *pasynUser) {
// Reset the suffix
suffix_[0] = 0;
if (wantToPrint) {
/*
We want to print the message associated with key -> Check if the number
of allowed repetitions is exceeded. If true, inform the user that
further output is suppressed.
*/
if (map_.find(key) != map_.end()) {
size_t repetitions = map_[key];
if (repetitions < maxRepetitions_) {
// Number of allowed repetitions not exceeded -> Printing the
// message is ok.
map_[key] = repetitions + 1;
return true;
} else if (repetitions == maxRepetitions_) {
// Reached number of allowed repetitions -> Printing the message
// is ok, but further trys are rejected.
char formattedKey[100] = {0};
key.format(formattedKey, sizeof(formattedKey));
snprintf(suffix_, sizeof(suffix_),
" Further repetition of this error message (key "
"\"%s\") is suppressed.",
formattedKey);
map_[key] = repetitions + 1;
return true;
} else {
// Exceeded number of allowed repetitions -> Do not print the
// message
return false;
}
} else {
// Message is not yet in map -> create an entry so it is watched in
// the future.
map_[key] = 1;
return true;
}
} else {
/*
We do not want to print the message associated with key -> If the key is
part of the map, set the counter back to zero.
*/
if (map_.find(key) != map_.end()) {
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;
}
}
return false;
}
}
bool msgPrintControl::shouldBePrinted(char *portName, int axisNo,
const char *functionName, int line,
bool wantToPrint, asynUser *pasynUser) {
msgPrintControlKey key =
msgPrintControlKey(portName, axisNo, functionName, __LINE__);
return shouldBePrinted(key, wantToPrint, pasynUser);
}
void msgPrintControl::resetCount(msgPrintControlKey &key, asynUser *pasynUser) {
if (map_.find(key) != map_.end()) {
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;
}
}
}
char *msgPrintControl::getSuffix() { return suffix_; }

146
src/msgPrintControl.h Normal file
View File

@ -0,0 +1,146 @@
#ifndef msgPrintControl_H
#define msgPrintControl_H
#include <asynDriver.h>
#include <string.h>
#include <string>
#include <unordered_map>
/**
* @brief Class to identify a message print location. See the docstring of
* `msgPrintControl` on how to use this key.
*
*/
class msgPrintControlKey {
public:
std::string controller_;
// -1 indicates a non-axis specific message
int axisNo_;
const char *functionName_;
int line_;
msgPrintControlKey(char *controller_, int axisNo, const char *fileName,
int line);
bool operator==(const msgPrintControlKey &other) const {
return axisNo_ == other.axisNo_ && line_ == other.line_ &&
strcmp(functionName_, other.functionName_) == 0 &&
controller_ == other.controller_;
}
void format(char *buffer, size_t bufferSize);
};
/**
* @brief Implementation of the hash functionality for `msgPrintControlKey`
*
*/
namespace std {
template <> struct hash<msgPrintControlKey> {
size_t operator()(const msgPrintControlKey &obj) const {
// Combine the hashes of the members (x and y)
size_t h1 = std::hash<std::string>{}(obj.controller_);
size_t h2 = hash<int>{}(obj.axisNo_);
size_t h3 = std::hash<const char *>{}(obj.functionName_);
size_t h4 = hash<int>{}(obj.line_);
// Combine the hashes (simple XOR and shifting technique)
return h1 ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3);
}
};
} // namespace std
/**
* @brief Class to control the number of repetitions of error messages
*
* This class is used to prevent excessive repetitions of identical error
* messages. For example, if the communication between a controller and an
* 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`
* can be used in order to see if a message should be printed or not:
*
* ```
* const char* controller = "MCU" // Name of the controller
* int axisNo = 0; // Number of the axis
* bool wantToPrint = evaluateConditions(...); *
* 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 `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
* 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
* 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.
*/
bool shouldBePrinted(msgPrintControlKey &key, bool wantToPrint,
asynUser *pasynUser);
/**
* @brief Like `shouldBePrinted(msgPrintControlKey key, bool wantToPrint)`,
* but constructs the key from the first four arguments.
*
* @param controller_
* @param axisNo
* @param fileName
* @param line
* @param wantToPrint
* @param pasynUser
*/
bool shouldBePrinted(char *controller, int axisNo, const char *functionName,
int line, bool wantToPrint, asynUser *pasynUser);
/**
* @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.
*/
void resetCount(msgPrintControlKey &key, asynUser *pasynUser);
/**
* @brief Maximum number of times a message is printed before it is
* suppressed.
*
*/
size_t maxRepetitions_;
char *getSuffix();
private:
std::unordered_map<msgPrintControlKey, size_t> map_;
char suffix_[300] = {0};
};
#endif

View File

@ -1,104 +1,120 @@
#include "sinqAxis.h" #include "sinqAxis.h"
#include "epicsExport.h"
#include "iocsh.h"
#include "sinqController.h" #include "sinqController.h"
#include <errlog.h>
#include <math.h> #include <math.h>
#include <unistd.h> #include <unistd.h>
sinqAxis::sinqAxis(class sinqController *pC, int axisNo) sinqAxis::sinqAxis(class sinqController *pC, int axisNo)
: asynMotorAxis((asynMotorController *)pC, axisNo), pC_(pC) { : asynMotorAxis((asynMotorController *)pC, axisNo), pC_(pC) {
asynStatus status = asynSuccess;
initial_poll_ = true;
watchdogMovActive_ = false; watchdogMovActive_ = false;
init_poll_counter_ = 0;
scaleMovTimeout_ = 2.0; scaleMovTimeout_ = 2.0;
offsetMovTimeout_ = 30; offsetMovTimeout_ = 30;
} targetPosition_ = 0.0;
asynStatus sinqAxis::atFirstPoll() { // This check is also done in asynMotorAxis, but there the IOC continues
asynStatus status = asynSuccess; // running even though the configuration is incorrect. When failing this
int variableSpeed = 0; // check, the IOC is stopped, since this is definitely a configuration
// problem.
if ((axisNo < 0) || (axisNo >= pC->numAxes())) {
asynPrint(pC_->asynUserSelf(), 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 // Motor is assumed to be enabled
status = pC_->setIntegerParam(axisNo_, pC_->motorEnableRBV_, 1); status = setIntegerParam(pC_->motorEnableRBV(), 1);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorEnableRBV_", asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
__PRETTY_FUNCTION__, __LINE__); "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);
} }
// By default, motors cannot be disabled // By default, motors cannot be disabled
status = pC_->setIntegerParam(axisNo_, pC_->motorCanDisable_, 0); status = setIntegerParam(pC_->motorCanDisable(), 0);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorCanDisable_", asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
__PRETTY_FUNCTION__, __LINE__); "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);
} }
status = // Provide a default value for the motor position.
pC_->getIntegerParam(axisNo_, pC_->motorCanSetSpeed_, &variableSpeed); status = setDoubleParam(pC_->motorPosition(), 0.0);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorCanSetSpeed_", asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
__PRETTY_FUNCTION__, __LINE__); "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);
} }
if (variableSpeed == 1) { // We assume that the motor has no status problems initially
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver_, 0.0); status = setIntegerParam(pC_->motorStatusProblem(), 0);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_", asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
__PRETTY_FUNCTION__, __LINE__); "Controller \"%s\", axis %d => %s, line %d:\nFATAL ERROR "
} "(setting a parameter value failed "
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, "with %s)\n. Terminating IOC",
1000000000.0); pC->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
if (status != asynSuccess) { pC_->stringifyAsynStatus(status));
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_", exit(-1);
__PRETTY_FUNCTION__, __LINE__);
}
} else {
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver_, 0.0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_",
__PRETTY_FUNCTION__, __LINE__);
}
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, 0.0);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_",
__PRETTY_FUNCTION__, __LINE__);
}
} }
return status; // Set the homing-related flags
status = setIntegerParam(pC_->motorStatusHome(), 0);
if (status != asynSuccess) {
asynPrint(pC_->asynUserSelf(), 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);
}
status = setIntegerParam(pC_->motorStatusHomed(), 0);
if (status != asynSuccess) {
asynPrint(pC_->asynUserSelf(), 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);
}
status = setIntegerParam(pC_->motorStatusAtHome(), 0);
if (status != asynSuccess) {
asynPrint(pC_->asynUserSelf(), 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);
}
} }
asynStatus sinqAxis::poll(bool *moving) { asynStatus sinqAxis::poll(bool *moving) {
// Local variable declaration // Local variable declaration
asynStatus pl_status = asynSuccess; asynStatus pl_status = asynSuccess;
asynStatus poll_status = asynSuccess; asynStatus poll_status = asynSuccess;
int homing = 0;
// ========================================================================= int homed = 0;
// If this poll is the initial poll, check if the parameter library has
// already been initialized. If not, force EPICS to repeat the poll until
// the initialization is complete (or until a timeout is reached). Once the
// parameter library has been initialized, read configuration data from the
// motor controller into it.
if (initial_poll_) {
poll_status = atFirstPoll();
if (poll_status == asynSuccess) {
initial_poll_ = false;
} else {
// Send a message to the IOC shell every 10 trials.
init_poll_counter_ += 1;
if (init_poll_counter_ % 10 == 0) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nRunning function 'atFirstPoll' "
"failed %d times with error %s.\n",
__PRETTY_FUNCTION__, __LINE__, init_poll_counter_,
pC_->stringifyAsynStatus(poll_status));
}
// Wait for 100 ms until trying the entire poll again
usleep(100000);
return poll_status;
}
}
/* /*
At the beginning of the poll, it is assumed that the axis has no status At the beginning of the poll, it is assumed that the axis has no status
@ -107,20 +123,21 @@ asynStatus sinqAxis::poll(bool *moving) {
The motorStatusProblem_ field changes the motor record fields SEVR and STAT. 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) { if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
pl_status = setIntegerParam(pC_->motorStatusCommsError_, false); pl_status = setIntegerParam(pC_->motorStatusCommsError(), false);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusCommsError_", pC_->paramLibAccessFailed(pl_status, "motorStatusCommsError_", axisNo_,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
pl_status = setStringParam(pC_->motorMessageText_, ""); pl_status = setStringParam(pC_->motorMessageText(), "");
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorMessageText_", return pC_->paramLibAccessFailed(pl_status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
// The poll function is just a wrapper around doPoll and // The poll function is just a wrapper around doPoll and
@ -132,43 +149,68 @@ asynStatus sinqAxis::poll(bool *moving) {
// The poll did not succeed: Something went wrong and the motor has a status // The poll did not succeed: Something went wrong and the motor has a status
// problem. // problem.
if (poll_status != asynSuccess) { if (poll_status != asynSuccess) {
pl_status = setIntegerParam(pC_->motorStatusProblem_, true); pl_status = setIntegerParam(pC_->motorStatusProblem(), true);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
} }
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);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHome_", axisNo_,
__PRETTY_FUNCTION__, __LINE__);
}
if (homing == 1 && !(*moving)) {
// Set the homing-related flags
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);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusHomed_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = setIntegerParam(pC_->motorStatusAtHome(), 1);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorStatusAtHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
}
// Check and update the watchdog // Check and update the watchdog
if (checkMovTimeoutWatchdog(*moving) != asynSuccess) { if (checkMovTimeoutWatchdog(*moving) != asynSuccess) {
return asynError; return asynError;
} }
if (pl_status != asynSuccess) {
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFunction isEnabled failed with %s.\n",
__PRETTY_FUNCTION__, __LINE__,
pC_->stringifyAsynStatus(poll_status));
pl_status = setStringParam(pC_->motorMessageText_,
"Could not check whether the motor is "
"enabled or not. Please call the support");
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__);
}
}
// According to the function documentation of asynMotorAxis::poll, this // According to the function documentation of asynMotorAxis::poll, this
// function should be called at the end of a poll implementation. // function should be called at the end of a poll implementation.
pl_status = callParamCallbacks(); pl_status = callParamCallbacks();
if (pl_status != asynSuccess) { bool wantToPrint = pl_status != asynSuccess;
// If we can't communicate with the parameter library, it doesn't make if (pC_->getMsgPrintControl().shouldBePrinted(
// sense to try and upstream this to the user -> Just log the error pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__, wantToPrint,
asynPrint( pC_->asynUserSelf())) {
pC_->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
"%s => line %d:\ncallParamCallbacks failed with %s for axis %d", "Controller \"%s\", axis %d => %s, line "
__PRETTY_FUNCTION__, __LINE__, "%d:\ncallParamCallbacks failed with %s.%s\n",
pC_->stringifyAsynStatus(poll_status), axisNo_); pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
pC_->stringifyAsynStatus(poll_status),
pC_->getMsgPrintControl().getSuffix());
}
if (wantToPrint) {
poll_status = pl_status; poll_status = pl_status;
} }
@ -180,35 +222,35 @@ asynStatus sinqAxis::doPoll(bool *moving) { return asynSuccess; }
asynStatus sinqAxis::move(double position, int relative, double minVelocity, asynStatus sinqAxis::move(double position, int relative, double minVelocity,
double maxVelocity, double acceleration) { double maxVelocity, double acceleration) {
double targetPosition = 0.0;
// Status of parameter library operations // Status of parameter library operations
asynStatus pl_status = asynSuccess; asynStatus pl_status = asynSuccess;
double motorRecResolution = 0.0;
// ========================================================================= // =========================================================================
// Calculate the (absolute) target position // When a new move is done, the motor is not homed anymore
if (relative) { pl_status = setIntegerParam(pC_->motorStatusHomed(), 0);
double motorPosition = 0.0;
pl_status =
pC_->getDoubleParam(axisNo_, pC_->motorPosition_, &motorPosition);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorPosition_",
__PRETTY_FUNCTION__, __LINE__);
}
targetPosition = position + motorPosition;
} else {
targetPosition = position;
}
// Set the target position
pl_status = setDoubleParam(pC_->motorTargetPosition_, targetPosition);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorTargetPosition_", return pC_->paramLibAccessFailed(pl_status, "motorStatusHomed_",
__PRETTY_FUNCTION__, __LINE__); 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); return doMove(position, relative, minVelocity, maxVelocity, acceleration);
} }
@ -221,48 +263,59 @@ asynStatus sinqAxis::doMove(double position, int relative, double minVelocity,
asynStatus sinqAxis::home(double minVelocity, double maxVelocity, asynStatus sinqAxis::home(double minVelocity, double maxVelocity,
double acceleration, int forwards) { double acceleration, int forwards) {
double targetPosition = 0.0; asynStatus status = asynSuccess;
double position = 0.0;
double highLimit = 0.0;
double lowLimit = 0.0;
// Status of parameter library operations status = doHome(minVelocity, maxVelocity, acceleration, forwards);
asynStatus pl_status = asynSuccess;
// ========================================================================= if (status == asynSuccess) {
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorPosition_, &position); status = setStringParam(pC_->motorMessageText(), "Homing");
if (pl_status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorPosition_", return pC_->paramLibAccessFailed(status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
} __LINE__);
}
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorHighLimit_, &highLimit); // Set the homing-related flags
if (pl_status != asynSuccess) { status = setIntegerParam(pC_->motorStatusHome(), 1);
return pC_->paramLibAccessFailed(pl_status, "motorHighLimit_", if (status != asynSuccess) {
__PRETTY_FUNCTION__, __LINE__); return pC_->paramLibAccessFailed(status, "motorStatusHome_",
} axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
// 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);
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorStatusAtHome_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorLowLimit_, &lowLimit); // Update the motor record
if (pl_status != asynSuccess) { return callParamCallbacks();
return pC_->paramLibAccessFailed(pl_status, "motorLowLimit_",
__PRETTY_FUNCTION__, __LINE__);
}
if (std::fabs(position - highLimit) > std::fabs(position - lowLimit)) { } else if (status == asynError) {
targetPosition = highLimit; // asynError means that we tried to home an absolute encoder
status = setStringParam(pC_->motorMessageText(),
"Can't home a motor with absolute encoder");
if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_",
axisNo_, __PRETTY_FUNCTION__,
__LINE__);
}
// Update the motor record
return callParamCallbacks();
} else { } else {
targetPosition = lowLimit; // Bubble up all other problems
return status;
} }
// Set the target position
pl_status = setDoubleParam(pC_->motorTargetPosition_, targetPosition);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorTargetPosition_",
__PRETTY_FUNCTION__, __LINE__);
}
return doHome(minVelocity, maxVelocity, acceleration, forwards);
} }
asynStatus sinqAxis::doHome(double minVelocity, double maxVelocity, asynStatus sinqAxis::doHome(double minVelocity, double maxVelocity,
@ -270,87 +323,164 @@ asynStatus sinqAxis::doHome(double minVelocity, double maxVelocity,
return asynSuccess; 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();
}
return status;
}
asynStatus sinqAxis::doReset() { return asynError; }
asynStatus sinqAxis::enable(bool on) { return asynSuccess; } 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::setVeloFields(double velo, double vbas, double vmax) { asynStatus sinqAxis::setVeloFields(double velo, double vbas, double vmax) {
asynStatus status = asynSuccess; asynStatus status = asynSuccess;
int variableSpeed = 0; int variableSpeed = 0;
// Can the speed of the motor be varied? // Can the speed of the motor be varied?
status = status =
pC_->getIntegerParam(axisNo_, pC_->motorCanSetSpeed_, &variableSpeed); pC_->getIntegerParam(axisNo_, pC_->motorCanSetSpeed(), &variableSpeed);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorCanSetSpeed_", return pC_->paramLibAccessFailed(status, "motorCanSetSpeed_", axisNo_,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
if (variableSpeed == 1) { if (variableSpeed == 1) {
// Check the inputs and create corresponding error messages // Check the inputs and create corresponding error messages
if (vbas > vmax) { if (vbas > vmax) {
asynPrint(pC_->lowLevelPortUser_, ASYN_TRACE_ERROR, asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
"%s => line %d:\nLower speed limit vbas=%lf must not be " "Controller \"%s\", axis %d => %s, line %d:\nLower speed "
"smaller than upper limit vmax=%lf.\n", "limit vbas=%lf must not be smaller than upper limit "
__PRETTY_FUNCTION__, __LINE__, vbas, vmax); "vmax=%lf.\n",
pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
vbas, vmax);
status = setStringParam( status = setStringParam(
pC_->motorMessageText_, pC_->motorMessageText(),
"Lower speed limit must not be smaller than upper speed limit"); "Lower speed limit must not be smaller than upper speed limit");
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_", return pC_->paramLibAccessFailed(status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
return asynError; return asynError;
} }
if (velo < vbas || velo > vmax) { if (velo < vbas || velo > vmax) {
asynPrint(pC_->lowLevelPortUser_, ASYN_TRACE_ERROR, asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
"%s => line %d:\nActual speed velo=%lf must be between " "Controller \"%s\", axis %d => %s, line %d:\nActual "
"lower limit vbas=%lf and upper limit vmx=%lf.\n", "speed velo=%lf must be between lower limit vbas=%lf and "
__PRETTY_FUNCTION__, __LINE__, velo, vbas, vmax); "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"); "Speed is not inside limits");
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorMessageText_", return pC_->paramLibAccessFailed(status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
return asynError; return asynError;
} }
status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver_, vbas); status = pC_->setDoubleParam(axisNo_, pC_->motorVbasFromDriver(), vbas);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_", return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver_, velo); status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver(), velo);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_", return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, vmax); status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver(), vmax);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_", return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
} else { } else {
// Set minimum and maximum speed equal to the set speed // 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) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_", return pC_->paramLibAccessFailed(status, "motorVbasFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver_, velo); status = pC_->setDoubleParam(axisNo_, pC_->motorVeloFromDriver(), velo);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_", return pC_->paramLibAccessFailed(status, "motorVeloFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver_, velo); status = pC_->setDoubleParam(axisNo_, pC_->motorVmaxFromDriver(), velo);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_", return pC_->paramLibAccessFailed(status, "motorVmaxFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
} }
return status; return status;
@ -362,36 +492,34 @@ asynStatus sinqAxis::setAcclField(double accl) {
return asynError; return asynError;
} }
asynStatus status = asynStatus status = setDoubleParam(pC_->motorAcclFromDriver(), accl);
pC_->setDoubleParam(axisNo_, pC_->motorAcclFromDriver_, accl);
if (status != asynSuccess) { if (status != asynSuccess) {
return pC_->paramLibAccessFailed(status, "motorAcclFromDriver_", return pC_->paramLibAccessFailed(status, "motorAcclFromDriver_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
return status; return status;
} }
asynStatus sinqAxis::setWatchdogEnabled(bool enable) { asynStatus sinqAxis::setWatchdogEnabled(bool enable) {
return pC_->setIntegerParam(axisNo_, pC_->motorEnableMovWatchdog_, enable); return setIntegerParam(pC_->motorEnableMovWatchdog(), enable);
} }
asynStatus sinqAxis::startMovTimeoutWatchdog() { asynStatus sinqAxis::startMovTimeoutWatchdog() {
asynStatus pl_status; asynStatus pl_status;
int enableMovWatchdog = 0; int enableMovWatchdog = 0;
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog_, pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog(),
&enableMovWatchdog); &enableMovWatchdog);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_", return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
if (enableMovWatchdog == 1) { if (enableMovWatchdog == 1) {
// These parameters are only needed in this branch // These parameters are only needed in this branch
double motorPosition = 0.0; double motorPos = 0.0;
double motorPositionRec = 0.0;
double motorTargetPositionRec = 0.0;
double motorTargetPosition = 0.0;
double motorVelocity = 0.0; double motorVelocity = 0.0;
double motorVelocityRec = 0.0; double motorVelocityRec = 0.0;
double motorAccel = 0.0; double motorAccel = 0.0;
@ -408,22 +536,11 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
to save the read result to the member variable earlier), since the to save the read result to the member variable earlier), since the
parameter library is updated at a later stage! parameter library is updated at a later stage!
*/ */
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorRecResolution_, pl_status = motorPosition(&motorPos);
&motorRecResolution);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorRecResolution_", return pl_status;
__PRETTY_FUNCTION__, __LINE__);
} }
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorPosition_,
&motorPositionRec);
if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorPosition",
__PRETTY_FUNCTION__, __LINE__);
}
motorPosition = motorPositionRec * motorRecResolution;
/* /*
We use motorVelocity, which corresponds to the record field VELO. We use motorVelocity, which corresponds to the record field VELO.
From https://epics.anl.gov/docs/APS2015/14-Motor-Record.pdf: From https://epics.anl.gov/docs/APS2015/14-Motor-Record.pdf:
@ -436,9 +553,16 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
= VELO / MRES motorAccel = (motorVelocity - motorVelBase) / ACCL = VELO / MRES motorAccel = (motorVelocity - motorVelBase) / ACCL
Therefore, we need to correct the values from the parameter library. 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 // Read the velocity
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorVelocity_, pl_status = pC_->getDoubleParam(axisNo_, pC_->motorVelocity(),
&motorVelocityRec); &motorVelocityRec);
// Only calculate timeContSpeed if the motorVelocity has been populated // Only calculate timeContSpeed if the motorVelocity has been populated
@ -446,20 +570,15 @@ asynStatus sinqAxis::startMovTimeoutWatchdog() {
if (pl_status == asynSuccess && motorVelocityRec > 0.0) { if (pl_status == asynSuccess && motorVelocityRec > 0.0) {
// Convert back to the value in the VELO field // Convert back to the value in the VELO field
motorVelocity = motorVelocityRec * motorRecResolution; motorVelocity = motorVelocityRec * motorRecResolution;
pl_status = pC_->getDoubleParam(axisNo_, pC_->motorTargetPosition_,
&motorTargetPositionRec);
motorTargetPosition = motorTargetPositionRec * motorRecResolution;
if (pl_status == asynSuccess) { if (pl_status == asynSuccess) {
timeContSpeed = timeContSpeed = std::ceil(
std::ceil(std::fabs(motorTargetPosition - motorPosition) / std::fabs(targetPosition_ - motorPos) / motorVelocity);
motorVelocity);
} }
} }
pl_status = pl_status =
pC_->getDoubleParam(axisNo_, pC_->motorAccel_, &motorAccelRec); pC_->getDoubleParam(axisNo_, pC_->motorAccel(), &motorAccelRec);
if (pl_status == asynSuccess && motorVelocityRec > 0.0 && if (pl_status == asynSuccess && motorVelocityRec > 0.0 &&
motorAccelRec > 0.0) { motorAccelRec > 0.0) {
@ -484,11 +603,12 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
asynStatus pl_status; asynStatus pl_status;
int enableMovWatchdog = 0; int enableMovWatchdog = 0;
pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog_, pl_status = pC_->getIntegerParam(axisNo_, pC_->motorEnableMovWatchdog(),
&enableMovWatchdog); &enableMovWatchdog);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_", return pC_->paramLibAccessFailed(pl_status, "motorEnableMovWatchdog_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
// Not moving or watchdog not active / enabled // Not moving or watchdog not active / enabled
@ -500,23 +620,24 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
// Check if the expected time of arrival has been exceeded. // Check if the expected time of arrival has been exceeded.
if (expectedArrivalTime_ < time(NULL)) { if (expectedArrivalTime_ < time(NULL)) {
// Check the watchdog // Check the watchdog
asynPrint(pC_->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(pC_->asynUserSelf(), ASYN_TRACE_ERROR,
"%s => line %d:\nAxis %d exceeded the expected arrival time " "Controller \"%s\", axis %d => %s, line %d:\nExceeded "
"%ld (current time is %ld).\n", "expected arrival time %ld (current time is %ld).\n",
__PRETTY_FUNCTION__, __LINE__, axisNo_, expectedArrivalTime_, pC_->portName, axisNo_, __PRETTY_FUNCTION__, __LINE__,
time(NULL)); expectedArrivalTime_, time(NULL));
pl_status = setStringParam( pl_status = setStringParam(
pC_->motorMessageText_, pC_->motorMessageText(),
"Exceeded expected arrival time. Check if the axis is blocked."); "Exceeded expected arrival time. Check if the axis is blocked.");
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return pC_->paramLibAccessFailed(pl_status, "motorMessageText_", return pC_->paramLibAccessFailed(pl_status, "motorMessageText_",
__PRETTY_FUNCTION__, __LINE__); axisNo_, __PRETTY_FUNCTION__,
__LINE__);
} }
pl_status = setIntegerParam(pC_->motorStatusProblem_, true); pl_status = setIntegerParam(pC_->motorStatusProblem(), true);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", pC_->paramLibAccessFailed(pl_status, "motorStatusProblem_", axisNo_,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
@ -525,3 +646,159 @@ asynStatus sinqAxis::checkMovTimeoutWatchdog(bool moving) {
} }
return asynSuccess; return asynSuccess;
} }
// =============================================================================
// IOC shell functions
extern "C" {
/**
* @brief Enable / disable the watchdog (FFI implementation)
*
* @param portName Name of the controller
* @param axisNo Axis number
* @param enable If 0, disable the watchdog, otherwise enable
* it
* @return asynStatus
*/
asynStatus setWatchdogEnabled(const char *portName, int axisNo, int enable) {
sinqController *pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError;
}
asynMotorAxis *asynAxis = pC->getAxis(axisNo);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
errlogPrintf(
"Controller \"%s\", axis %d => %s, line %d:\nAxis does not "
"exist or is not an instance of sinqAxis.",
portName, axisNo, __PRETTY_FUNCTION__, __LINE__);
}
return axis->setWatchdogEnabled(enable != 0);
}
static const iocshArg setWatchdogEnabledArg0 = {"Controller port name",
iocshArgString};
static const iocshArg setWatchdogEnabledArg1 = {"Axis number", iocshArgInt};
static const iocshArg setWatchdogEnabledArg2 = {
"Enabling / disabling the watchdog", iocshArgInt};
static const iocshArg *const setWatchdogEnabledArgs[] = {
&setWatchdogEnabledArg0, &setWatchdogEnabledArg1, &setWatchdogEnabledArg2};
static const iocshFuncDef setWatchdogEnabledDef = {"setWatchdogEnabled", 3,
setWatchdogEnabledArgs};
static void setWatchdogEnabledCallFunc(const iocshArgBuf *args) {
setWatchdogEnabled(args[0].sval, args[1].ival, args[2].ival);
}
// =============================================================================
/**
* @brief Set the offsetMovTimeout (FFI implementation)
*
* @param portName Name of the controller
* @param axisNo Axis number
* @param offsetMovTimeout Offset (in seconds)
* @return asynStatus
*/
asynStatus setOffsetMovTimeout(const char *portName, int axisNo,
double offsetMovTimeout) {
sinqController *pC;
pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError;
}
asynMotorAxis *asynAxis = pC->getAxis(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.",
portName, __PRETTY_FUNCTION__, __LINE__, axisNo);
}
return axis->setOffsetMovTimeout(offsetMovTimeout);
}
static const iocshArg setOffsetMovTimeoutArg0 = {"Controller port name",
iocshArgString};
static const iocshArg setOffsetMovTimeoutArg1 = {"Axis number", iocshArgInt};
static const iocshArg setOffsetMovTimeoutArg2 = {"Offset timeout for movement",
iocshArgDouble};
static const iocshArg *const setOffsetMovTimeoutArgs[] = {
&setOffsetMovTimeoutArg0, &setOffsetMovTimeoutArg1,
&setOffsetMovTimeoutArg2};
static const iocshFuncDef setOffsetMovTimeoutDef = {"setOffsetMovTimeout", 3,
setOffsetMovTimeoutArgs};
static void setOffsetMovTimeoutCallFunc(const iocshArgBuf *args) {
setOffsetMovTimeout(args[0].sval, args[1].ival, args[2].dval);
}
// =============================================================================
/**
* @brief Set the setScaleMovTimeout (FFI implementation)
*
* @param portName Name of the controller
* @param axisNo Axis number
* @param scaleMovTimeout Scaling factor (in seconds)
* @return asynStatus
*/
asynStatus setScaleMovTimeout(const char *portName, int axisNo,
double scaleMovTimeout) {
sinqController *pC;
pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) {
errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError;
}
asynMotorAxis *asynAxis = pC->getAxis(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.",
portName, __PRETTY_FUNCTION__, __LINE__, axisNo);
return asynError;
}
return axis->setScaleMovTimeout(scaleMovTimeout);
}
static const iocshArg setScaleMovTimeoutArg0 = {"Controller port name",
iocshArgString};
static const iocshArg setScaleMovTimeoutArg1 = {"Axis number", iocshArgInt};
static const iocshArg setScaleMovTimeoutArg2 = {
"Multiplier for calculated move time", iocshArgDouble};
static const iocshArg *const setScaleMovTimeoutArgs[] = {
&setScaleMovTimeoutArg0, &setScaleMovTimeoutArg1, &setScaleMovTimeoutArg2};
static const iocshFuncDef setScaleMovTimeoutDef = {"setScaleMovTimeout", 3,
setScaleMovTimeoutArgs};
static void setScaleMovTimeoutCallFunc(const iocshArgBuf *args) {
setScaleMovTimeout(args[0].sval, args[1].ival, args[2].dval);
}
// =============================================================================
// This function is made known to EPICS in sinqMotor.dbd and is called by EPICS
// in order to register all functions in the IOC shell
static void sinqAxisRegister(void) {
iocshRegister(&setOffsetMovTimeoutDef, setOffsetMovTimeoutCallFunc);
iocshRegister(&setScaleMovTimeoutDef, setScaleMovTimeoutCallFunc);
iocshRegister(&setWatchdogEnabledDef, setWatchdogEnabledCallFunc);
}
epicsExportRegistrar(sinqAxisRegister);
} // extern C

View File

@ -4,8 +4,8 @@ This class extends asynMotorAxis by some features used in SINQ.
Stefan Mathis, November 2024 Stefan Mathis, November 2024
*/ */
#ifndef __SINQDRIVER #ifndef sinqAxis_H
#define __SINQDRIVER #define sinqAxis_H
#include "asynMotorAxis.h" #include "asynMotorAxis.h"
class epicsShareClass sinqAxis : public asynMotorAxis { class epicsShareClass sinqAxis : public asynMotorAxis {
@ -19,38 +19,31 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
sinqAxis(class sinqController *pC_, int axisNo); sinqAxis(class sinqController *pC_, int axisNo);
/** /**
* @brief This function is executed once during the very first poll. * @brief Perform some standardized operations before and after the concrete
*
* This function is executed at the very first poll after the IOC startup.
If it returns anything else than 'asynSuccess', the function is evaluated
again after 100 ms until it succeeds. Every 10 trials a warning is emitted.
The default implementation just returns asynSuccess and is meant to be
overwritten by concrete driver implementations.
*
* @return asynStatus
*/
virtual asynStatus atFirstPoll();
/**
* @brief Perform some standardized operation before and after the concrete
`doPoll` implementation. `doPoll` implementation.
* *
* Wrapper around doPoll which performs the following operations: * Wrapper around `doPoll` which performs the following operations:
Before calling doPoll:
- Try to execute atFirstPoll once (and retry, if that failed) - Call the `doPoll` method
After calling doPoll:
- Reset motorStatusProblem_, motorStatusCommsError_ and motorMessageText_ if - Reset motorStatusProblem_, motorStatusCommsError_ and motorMessageText_ if
doPoll returned asynSuccess doPoll returned asynSuccess
- If the movement timeout watchdog has been started, check it. - If the movement timeout watchdog has been started, check it.
- Update the parameter library entry motorEnableRBV_ by calling isEnabled.
- Run `callParamCallbacks` - The flags `motorStatusHome_`, `motorStatusHomed_` and
`motorStatusAtHome_` are set to their idle values (0, 1 and 1 respectively)
in the `poll()` method once the homing procedure is finished. See the
documentation of the `home()` method for more details.
- Run `callParamCallbacks()`
- Return the status of `doPoll` - Return the status of `doPoll`
* *
* @param moving Forwarded to `doPoll`. * @param moving Forwarded to `doPoll`.
* @return asynStatus Forward the status of `doPoll`, unless one of * @return asynStatus Forward the status of `doPoll`, unless one of
the parameter library operation fails (in that case, returns the failed the parameter library operation fails (in that case, returns the status of
operation status). the failed operation.
*/ */
asynStatus poll(bool *moving); asynStatus poll(bool *moving);
@ -65,11 +58,12 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
virtual asynStatus doPoll(bool *moving); 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. `doMove` implementation.
* Wrapper around `doMove` which calculates the (absolute) target position * 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`. `doMove`.
* *
* @param position Forwarded to `doMove`. * @param position Forwarded to `doMove`.
@ -100,23 +94,42 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
double maxVelocity, double acceleration); double maxVelocity, double acceleration);
/** /**
* @brief Perform some standardized operation before and after the concrete * @brief Wrapper around doHome which handles the homing-related flags
`doHome` implementation. *
* * The homing procedure of the motor record is controlled by the following
* Wrapper around move which calculates the (absolute) target position and * parameter library flags:
stores it in the parameter library. The target position in a homing maneuver *
is calculated as follows: * - `motorMoveToHome_`: Setting this flag to `1` indicates to EPICS that a
homing procedure should start and can therefore be used to start homing from
within the driver.
if abs(current position - high limit) > abs(current position - low limit) * - `motorStatusHome_`: This flag should be set to `1` while the motor is
{ actively moving toward its home position and to `0` when the home position
high limit is reached.
} *
else * - `motorStatusHomed_`: This flag should be set to `0` at the start of a
{ homing command and to 1 once the home position is reached.
low limit *
} * - `motorStatusAtHome_`: This flag is similar to `motorStatusHomed_`, but
in addition it should also be `1` when the motor is at its home position,
but wasn't actively homed in order to get there.
*
* This function performs the following operations in the given order:
*
* - Call `doHome()` and forward the parameters
*
* - If `doHome()` returned asynSuccess: Set `motorStatusHome_` to `1`,
`motorStatusHomed_` to `0` and `motorStatusAtHome_` to `0`.
*
* - If `doHome()` returned asynError: This means that the motor cannot be
homed because the encoder is absolute. Set a corresponding error message,
but return asynSuccess in order to avoid any automatic retries by asyn.
After that, it calls and returns doHome. * - If `doHome()` returned anything else: Forward the status.
*
* The flags `motorStatusHome_`, `motorStatusHomed_` and
`motorStatusAtHome_` are set to their idle values (0, 1 and 1 respectively)
in the `poll()` method once the homing procedure is finished.
* *
* @param minVelocity Forwarded to `doHome`. * @param minVelocity Forwarded to `doHome`.
* @param maxVelocity Forwarded to `doHome`. * @param maxVelocity Forwarded to `doHome`.
@ -131,7 +144,9 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
/** /**
* @brief Implementation of the "proper", device-specific home method. This * @brief Implementation of the "proper", device-specific home method. This
method should be implemented by a child class of sinqAxis. method should be implemented by a child class of sinqAxis. If the motor
cannot be homed because it has an absolute encoder, this function should
return asynError.
* *
* @param minVelocity Minimum velocity VMIN from the motor record * @param minVelocity Minimum velocity VMIN from the motor record
* @param maxVelocity Maximum velocity VMAX from the motor record * @param maxVelocity Maximum velocity VMAX from the motor record
@ -143,10 +158,33 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
virtual asynStatus doHome(double minVelocity, double maxVelocity, virtual asynStatus doHome(double minVelocity, double maxVelocity,
double acceleration, int forwards); 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 * @brief This function enables / disables an axis. It should be implemented
* by a child class of sinqAxis. * 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 * @param on
* @return asynStatus * @return asynStatus
*/ */
@ -158,7 +196,7 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
* Populates the speed fields of the motor record. If the param lib * Populates the speed fields of the motor record. If the param lib
* entry motorCanSetSpeed_ (connected to the PV x:VariableSpeed) is set to * 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 * 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 * The units of the inputs are engineering units (EGU) per second (e.g. mm/s
* if the EGU is mm). * if the EGU is mm).
@ -213,15 +251,15 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
with with
timeContSpeed = abs(motorTargetPosition - motorPosition) / motorVelBase timeContSpeed = abs(targetPosition - motorPosition) / motorVelBase
timeAcc = motorVelBase / motorAccel timeAcc = motorVelBase / motorAccel
The values motorTargetPosition, motorVelBase, motorAccel and The values motorVelBase, motorAccel and positionAtMovementStart are taken
positionAtMovementStart are taken from the parameter library. Therefore it from the parameter library. Therefore it is necessary to populate them
is necessary to populate them before using this function. If they are not before using this function. If they are not given, both speed and velocity
given, both speed and velocity are assumed to be infinite. This means that are assumed to be infinite. This means that timeContSpeed and/or timeAcc are
timeContSpeed and/or timeAcc are set to zero. motorTargetPosition is set to zero. targetPosition is populated automatically when using the doMove
populated automatically when using the doMove function. function.
The values offsetMovTimeout_ and scaleMovTimeout_ can be set directly from The values offsetMovTimeout_ and scaleMovTimeout_ can be set directly from
the IOC shell with the functions setScaleMovTimeout and setOffsetMovTimeout, the IOC shell with the functions setScaleMovTimeout and setOffsetMovTimeout,
@ -250,7 +288,7 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
* @brief Set the offsetMovTimeout. Also available in the IOC shell * @brief Set the offsetMovTimeout. Also available in the IOC shell
* (see "extern C" section in sinqController.cpp). * (see "extern C" section in sinqController.cpp).
* *
See documentation of `checkMovTimeoutWatchdog` for details. * See documentation of `checkMovTimeoutWatchdog` for details.
* *
* @param offsetMovTimeout Offset (in seconds) * @param offsetMovTimeout Offset (in seconds)
* @return asynStatus * @return asynStatus
@ -274,17 +312,49 @@ class epicsShareClass sinqAxis : public asynMotorAxis {
return asynSuccess; 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);
protected: protected:
bool initial_poll_; // Internal variables used in the movement timeout watchdog
int init_poll_counter_;
// Helper variables for movementTimeoutWatchdog
time_t expectedArrivalTime_; time_t expectedArrivalTime_;
time_t offsetMovTimeout_; time_t offsetMovTimeout_;
double scaleMovTimeout_; double scaleMovTimeout_;
bool watchdogMovActive_; bool watchdogMovActive_;
// Store the motor target position for the movement time calculation
double targetPosition_;
private: private:
sinqController *pC_; sinqController *pC_;

View File

@ -5,6 +5,32 @@
#include "iocsh.h" #include "iocsh.h"
#include "sinqAxis.h" #include "sinqAxis.h"
#include <errlog.h> #include <errlog.h>
#include <vector>
/*
Contains all instances of turboPmacAxis which have been created and is used in
the initialization hook function.
*/
static std::vector<sinqController *> controller;
/**
* @brief Hook function to perform certain actions during the IOC initialization
*
* @param iState
*/
void sinqController::epicsInithookFunction(initHookState iState) {
if (iState == initHookAfterIocRunning) {
// Iterate through all axes of each and call the initialization method
// on each one of them.
for (std::vector<sinqController *>::iterator itC = controller.begin();
itC != controller.end(); ++itC) {
sinqController *controller = *itC;
controller->startPoller(controller->movingPollPeriod_,
controller->idlePollPeriod_, 1);
}
}
}
sinqController::sinqController(const char *portName, sinqController::sinqController(const char *portName,
const char *ipPortConfigName, int numAxes, const char *ipPortConfigName, int numAxes,
@ -15,30 +41,39 @@ sinqController::sinqController(const char *portName,
// As described in the function documentation, an offset of 1 is // As described in the function documentation, an offset of 1 is
// added for better readability of the configuration. // added for better readability of the configuration.
numAxes + 1, numAxes + 1,
/*
4 Parameters are added in sinqController:
- MOTOR_MESSAGE_TEXT
- MOTOR_TARGET_POSITION
- ENABLE_AXIS
- ENABLE_AXIS_RBV
- ENABLE_MOV_WATCHDOG
- LIMITS_OFFSET
*/
NUM_MOTOR_DRIVER_PARAMS + NUM_SINQMOTOR_DRIVER_PARAMS + NUM_MOTOR_DRIVER_PARAMS + NUM_SINQMOTOR_DRIVER_PARAMS +
numExtraParams, numExtraParams,
0, // No additional interfaces beyond those in base class 0, // No additional interfaces beyond those in base class
0, // No additional callback interfaces beyond those in base class 0, // No additional callback interfaces beyond those in base class
ASYN_CANBLOCK | ASYN_MULTIDEVICE, ASYN_CANBLOCK | ASYN_MULTIDEVICE,
1, // autoconnect 1, // autoconnect
0, 0, 0), // Default priority and stack size
0) // Default priority and stack size msgPrintControl_(4) {
{
// Initialization of local variables
asynStatus status = asynSuccess; asynStatus status = asynSuccess;
// Initialization of all member variables // Handle to the asynUser of the IP port asyn driver
lowLevelPortUser_ = nullptr; ipPortAsynOctetSyncIO_ = nullptr;
// Initial values for the average timeout mechanism, can be overwritten
// later by a FFI function
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)
maxSubsequentTimeouts_ = 10;
maxSubsequentTimeoutsExceeded_ = false;
// Store the poll period information. The poller itself will be started
// later (after the IOC is running in epicsInithookFunction)
movingPollPeriod_ = movingPollPeriod;
idlePollPeriod_ = idlePollPeriod;
// =========================================================================; // =========================================================================;
@ -46,12 +81,13 @@ sinqController::sinqController(const char *portName,
We try to connect to the port via the port name provided by the constructor. We try to connect to the port via the port name provided by the constructor.
If this fails, the function is terminated via exit. If this fails, the function is terminated via exit.
*/ */
pasynOctetSyncIO->connect(ipPortConfigName, 0, &lowLevelPortUser_, NULL); pasynOctetSyncIO->connect(ipPortConfigName, 0, &ipPortAsynOctetSyncIO_,
if (status != asynSuccess || lowLevelPortUser_ == nullptr) { NULL);
errlogPrintf( if (status != asynSuccess || ipPortAsynOctetSyncIO_ == nullptr) {
"%s => line %d:\nFATAL ERROR (cannot connect to MCU controller).\n" errlogPrintf("Controller \"%s\" => %s, line %d:\nFATAL ERROR (cannot "
"Terminating IOC", "connect to MCU controller).\n"
__PRETTY_FUNCTION__, __LINE__); "Terminating IOC",
portName, __PRETTY_FUNCTION__, __LINE__);
exit(-1); exit(-1);
} }
@ -64,38 +100,40 @@ sinqController::sinqController(const char *portName,
createParam("MOTOR_MESSAGE_TEXT", asynParamOctet, &motorMessageText_); createParam("MOTOR_MESSAGE_TEXT", asynParamOctet, &motorMessageText_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
exit(-1); stringifyAsynStatus(status));
}
// Internal parameter library entry which stores the movement target
status = createParam("MOTOR_TARGET_POSITION", asynParamFloat64,
&motorTargetPosition_);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed "
"with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
status = createParam("MOTOR_ENABLE", asynParamInt32, &motorEnable_); status = createParam("MOTOR_ENABLE", asynParamInt32, &motorEnable_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
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); exit(-1);
} }
status = createParam("MOTOR_ENABLE_RBV", asynParamInt32, &motorEnableRBV_); status = createParam("MOTOR_ENABLE_RBV", asynParamInt32, &motorEnableRBV_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -103,9 +141,10 @@ sinqController::sinqController(const char *portName,
createParam("MOTOR_CAN_DISABLE", asynParamInt32, &motorCanDisable_); createParam("MOTOR_CAN_DISABLE", asynParamInt32, &motorCanDisable_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -113,9 +152,10 @@ sinqController::sinqController(const char *portName,
createParam("MOTOR_CAN_SET_SPEED", asynParamInt32, &motorCanSetSpeed_); createParam("MOTOR_CAN_SET_SPEED", asynParamInt32, &motorCanSetSpeed_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -123,9 +163,10 @@ sinqController::sinqController(const char *portName,
&motorLimitsOffset_); &motorLimitsOffset_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -138,9 +179,10 @@ sinqController::sinqController(const char *portName,
&motorHighLimitFromDriver_); &motorHighLimitFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -148,9 +190,10 @@ sinqController::sinqController(const char *portName,
&motorLowLimitFromDriver_); &motorLowLimitFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -158,9 +201,10 @@ sinqController::sinqController(const char *portName,
&motorEnableMovWatchdog_); &motorEnableMovWatchdog_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -168,9 +212,10 @@ sinqController::sinqController(const char *portName,
&motorVeloFromDriver_); &motorVeloFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -178,9 +223,10 @@ sinqController::sinqController(const char *portName,
&motorVbasFromDriver_); &motorVbasFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -188,9 +234,10 @@ sinqController::sinqController(const char *portName,
&motorVmaxFromDriver_); &motorVmaxFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
@ -198,40 +245,59 @@ sinqController::sinqController(const char *portName,
&motorAcclFromDriver_); &motorAcclFromDriver_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
status = createParam("ENCODER_TYPE", asynParamOctet, &encoderType_); status = createParam("ENCODER_TYPE", asynParamOctet, &encoderType_);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (creating a parameter failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
// Poller configuration status = createParam("MOTOR_FORCE_STOP", asynParamInt32, &motorForceStop_);
status = startPoller(movingPollPeriod, idlePollPeriod, 1);
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nFATAL ERROR (starting the poller failed " "Controller \"%s\" => %s, line %d:\nFATAL ERROR (creating a "
"with %s).\nTerminating IOC", "parameter failed with %s).\nTerminating IOC",
__PRETTY_FUNCTION__, __LINE__, stringifyAsynStatus(status)); portName, __PRETTY_FUNCTION__, __LINE__,
pasynOctetSyncIO->disconnect(lowLevelPortUser_); stringifyAsynStatus(status));
exit(-1); exit(-1);
} }
// Register the hook function during construction of the first axis object
if (controller.empty()) {
initHookRegister(&epicsInithookFunction);
}
// Collect all axes into this list which will be used in the hook function
controller.push_back(this);
} }
sinqController::~sinqController(void) { 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_); free(this->pAxes_);
} }
msgPrintControl &sinqController::getMsgPrintControl() {
return msgPrintControl_;
}
asynStatus sinqController::writeInt32(asynUser *pasynUser, epicsInt32 value) { asynStatus sinqController::writeInt32(asynUser *pasynUser, epicsInt32 value) {
int function = pasynUser->reason; int function = pasynUser->reason;
@ -239,72 +305,73 @@ asynStatus sinqController::writeInt32(asynUser *pasynUser, epicsInt32 value) {
asynMotorAxis *asynAxis = getAxis(pasynUser); asynMotorAxis *asynAxis = getAxis(pasynUser);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis); sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) { if (axis == nullptr) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nAxis %d is not an instance of sinqAxis", "Controller \"%s\", axis %d => %s, line %d:\nAxis is not an "
__PRETTY_FUNCTION__, __LINE__, axis->axisNo_); "instance of sinqAxis",
portName, axis->axisNo(), __PRETTY_FUNCTION__, __LINE__);
return asynError; return asynError;
} }
// Handle custom PVs // Handle custom PVs
if (function == motorEnable_) { if (function == motorEnable_) {
return axis->enable(value != 0); return axis->enable(value != 0);
} else if (function == motorReset_) {
return axis->reset();
} else if (function == motorForceStop_) {
return axis->stop(0.0);
} else { } else {
return asynMotorController::writeInt32(pasynUser, value); return asynMotorController::writeInt32(pasynUser, value);
} }
} }
asynStatus sinqController::readInt32(asynUser *pasynUser, epicsInt32 *value) { asynStatus sinqController::readInt32(asynUser *pasynUser, epicsInt32 *value) {
// Casting into a sinqAxis is necessary to get access to the field axisNo()
asynMotorAxis *asynAxis = getAxis(pasynUser);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
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__);
return asynError;
}
if (pasynUser->reason == motorEnableRBV_) { if (pasynUser->reason == motorEnableRBV_) {
// Read out the parameter library return getIntegerParam(axis->axisNo(), motorEnableRBV_, value);
asynMotorAxis *asynAxis = getAxis(pasynUser);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nAxis %d is not an instance of sinqAxis",
__PRETTY_FUNCTION__, __LINE__, axis->axisNo_);
return asynError;
}
return getIntegerParam(axis->axisNo_, motorEnableRBV_, value);
} else if (pasynUser->reason == motorCanDisable_) { } else if (pasynUser->reason == motorCanDisable_) {
// Check if the motor can be disabled return getIntegerParam(axis->axisNo(), motorCanDisable_, value);
asynMotorAxis *asynAxis = getAxis(pasynUser);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s => line %d:\nAxis %d is not an instance of sinqAxis",
__PRETTY_FUNCTION__, __LINE__, axis->axisNo_);
return asynError;
}
return getIntegerParam(axis->axisNo_, motorCanDisable_, value);
} else { } else {
return asynMotorController::readInt32(pasynUser, value); return asynMotorController::readInt32(pasynUser, value);
} }
} }
asynStatus sinqController::errMsgCouldNotParseResponse(const char *command, asynStatus sinqController::couldNotParseResponse(const char *command,
const char *response, const char *response,
int axisNo, int axisNo,
const char *functionName, const char *functionName,
int lineNumber) { int line) {
asynStatus pl_status = asynSuccess; asynStatus pl_status = asynSuccess;
asynPrint(lowLevelPortUser_, ASYN_TRACE_ERROR, asynPrint(ipPortAsynOctetSyncIO_, ASYN_TRACE_ERROR,
"%s => line %d:\nCould not interpret response %s for " "Controller \"%s\", axis %d => %s, line %d:\nCould not interpret "
"command %s.\n", "response \"%s\" for command \"%s\".\n",
functionName, lineNumber, response, command); portName, axisNo, functionName, line, response, command);
pl_status = setStringParam( pl_status = setStringParam(
motorMessageText_, motorMessageText_,
"Could not interpret MCU response. Please call the support"); "Could not interpret controller response. Please call the support");
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return paramLibAccessFailed(pl_status, "motorMessageText_", return paramLibAccessFailed(pl_status, "motorMessageText_", axisNo,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
pl_status = setIntegerParam(motorStatusCommsError_, 1); pl_status = setIntegerParam(motorStatusCommsError_, 1);
if (pl_status != asynSuccess) { if (pl_status != asynSuccess) {
return paramLibAccessFailed(pl_status, "motorStatusCommsError_", return paramLibAccessFailed(pl_status, "motorStatusCommsError_", axisNo,
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
} }
@ -313,17 +380,19 @@ asynStatus sinqController::errMsgCouldNotParseResponse(const char *command,
asynStatus sinqController::paramLibAccessFailed(asynStatus status, asynStatus sinqController::paramLibAccessFailed(asynStatus status,
const char *parameter, const char *parameter,
int axisNo,
const char *functionName, const char *functionName,
int lineNumber) { int line) {
if (status != asynSuccess) { if (status != asynSuccess) {
asynPrint(ipPortAsynOctetSyncIO_, 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,
stringifyAsynStatus(status));
// Log the error message and try to propagate it. If propagating fails, // Log the error message and try to propagate it. If propagating fails,
// there is nothing we can do here anyway. // there is nothing we can do here anyway.
asynPrint(lowLevelPortUser_, ASYN_TRACE_ERROR,
"%s => line %d:\n Accessing the parameter library failed for "
"parameter %s with error %s.\n",
functionName, lineNumber, parameter,
stringifyAsynStatus(status));
setStringParam(motorMessageText_, setStringParam(motorMessageText_,
"Accessing paramLib failed. Please call the support."); "Accessing paramLib failed. Please call the support.");
} }
@ -331,6 +400,131 @@ asynStatus sinqController::paramLibAccessFailed(asynStatus status,
return status; return status;
} }
asynStatus sinqController::checkComTimeoutWatchdog(int axisNo,
char *motorMessage,
size_t motorMessageSize) {
asynStatus paramLibStatus = asynSuccess;
// Add a new timeout event to the queue
timeoutEvents_.push_back(time(NULL));
// Remove every event which is older than the time window from the deque
while (1) {
if (timeoutEvents_.empty()) {
break;
}
if (timeoutEvents_[0] + comTimeoutWindow_ <= time(NULL)) {
timeoutEvents_.pop_front();
} else {
break;
}
}
// Check if the maximum allowed number of events has been exceeded
bool wantToPrint = timeoutEvents_.size() > maxNumberTimeouts_;
if (msgPrintControl_.shouldBePrinted(portName, axisNo, __PRETTY_FUNCTION__,
__LINE__, wantToPrint,
pasynUserSelf)) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nMore than %ld "
"communication timeouts in %ld "
"seconds.%s\n",
portName, axisNo, __PRETTY_FUNCTION__, __LINE__,
maxNumberTimeouts_, comTimeoutWindow_,
msgPrintControl_.getSuffix());
}
if (wantToPrint) {
snprintf(motorMessage, motorMessageSize,
"More than %ld communication timeouts in %ld seconds. Please "
"call the support.",
maxNumberTimeouts_, comTimeoutWindow_);
paramLibStatus = setIntegerParam(motorStatusCommsError_, 1);
if (paramLibStatus != asynSuccess) {
return paramLibAccessFailed(paramLibStatus,
"motorStatusCommsError_", axisNo,
__PRETTY_FUNCTION__, __LINE__);
}
return asynError;
} else {
return asynSuccess;
}
}
asynStatus sinqController::checkComTimeoutWatchdog(sinqAxis *axis) {
char motorMessage[200] = {0};
asynStatus status =
checkComTimeoutWatchdog(axis->axisNo(), motorMessage, 200);
if (status == asynError) {
status = axis->setStringParam(motorMessageText_, motorMessage);
if (status != asynSuccess) {
return paramLibAccessFailed(status, "motorMessageText_",
axis->axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
}
return status;
}
asynStatus sinqController::checkMaxSubsequentTimeouts(int timeoutNo, int axisNo,
char *motorMessage,
size_t motorMessageSize) {
asynStatus paramLibStatus = asynSuccess;
if (timeoutNo >= maxSubsequentTimeouts_) {
if (!maxSubsequentTimeoutsExceeded_) {
snprintf(motorMessage, motorMessageSize,
"Communication timeout between IOC and motor controller. "
"Trying to reconnect ...");
asynPrint(
this->pasynUserSelf, ASYN_TRACE_ERROR,
"Controller \"%s\", axis %d => %s, line %d:\nMore than %d "
"subsequent communication "
"timeouts\n",
this->portName, axisNo, __PRETTY_FUNCTION__, __LINE__,
maxSubsequentTimeouts_);
paramLibStatus = setIntegerParam(motorStatusCommsError_, 1);
if (paramLibStatus != asynSuccess) {
return paramLibAccessFailed(paramLibStatus,
"motorStatusCommsError_", axisNo,
__PRETTY_FUNCTION__, __LINE__);
}
maxSubsequentTimeoutsExceeded_ = true;
}
return asynError;
} else {
maxSubsequentTimeoutsExceeded_ = false;
motorMessage[0] = '\0';
return asynSuccess;
}
}
asynStatus sinqController::checkMaxSubsequentTimeouts(int timeoutNo,
sinqAxis *axis) {
char motorMessage[200] = {0};
asynStatus status = checkMaxSubsequentTimeouts(axis->axisNo(), timeoutNo,
motorMessage, 200);
if (status == asynError) {
status = axis->setStringParam(motorMessageText_, motorMessage);
if (status != asynSuccess) {
return paramLibAccessFailed(status, "motorMessageText_",
axis->axisNo(), __PRETTY_FUNCTION__,
__LINE__);
}
}
return status;
}
// Static pointers (valid for the entire lifetime of the IOC). The number behind // Static pointers (valid for the entire lifetime of the IOC). The number behind
// the strings gives the integer number of each variant (see also method // the strings gives the integer number of each variant (see also method
// stringifyAsynStatus) // stringifyAsynStatus)
@ -386,161 +580,131 @@ const char *sinqController::stringifyAsynStatus(asynStatus status) {
return asynParamInvalidListStringified; return asynParamInvalidListStringified;
} }
asynPrint( asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
pasynUserSelf, ASYN_TRACE_ERROR, "%s, line %d:\nInput did not match any "
"%s => line %d:\nInput did not match any variant of asynStatus.\n", "variant of asynStatus.\n",
__PRETTY_FUNCTION__, __LINE__); __PRETTY_FUNCTION__, __LINE__);
return inputDidNotMatchAsynStatus; return inputDidNotMatchAsynStatus;
} }
// ============================================================================= // =============================================================================
// Provide the setters to IOC shell // IOC shell functions
extern "C" { extern "C" {
// =============================================================================
/** /**
* @brief Enable / disable the watchdog (FFI implementation) * @brief Set the threshold for the communication timeout frequency (FFI
* implementation)
* *
* @param portName Name of the controller * @param comTimeoutWindow Size of the time window used to calculate
* @param axisNo Axis number * the moving average of timeout events in seconds. Set this value to 0 to
* @param enable If 0, disable the watchdog, otherwise enable * deactivate the watchdog.
* it * @param maxNumberTimeouts Maximum number of timeouts which may occur
* within the time window before the watchdog is triggered.
* @return asynStatus * @return asynStatus
*/ */
asynStatus setWatchdogEnabled(const char *portName, int axisNo, int enable) { asynStatus setThresholdComTimeout(const char *portName, int comTimeoutWindow,
int maxNumberTimeouts) {
sinqController *pC; sinqController *pC;
pC = (sinqController *)findAsynPortDriver(portName); pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) { if (pC == nullptr) {
errlogPrintf("%s => line %d:\nPort %s not found.", __PRETTY_FUNCTION__, errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
__LINE__, portName); portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError; return asynError;
} }
asynMotorAxis *asynAxis = pC->getAxis(axisNo); return pC->setThresholdComTimeout(comTimeoutWindow, maxNumberTimeouts);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
errlogPrintf("%s => line %d:\nAxis %d does not exist or is not an "
"instance of sinqAxis.",
__PRETTY_FUNCTION__, __LINE__, axisNo);
}
return axis->setWatchdogEnabled(enable != 0);
} }
static const iocshArg setWatchdogEnabledArg0 = {"Controller port name", static const iocshArg setThresholdComTimeoutArg0 = {"Controller port name",
iocshArgString}; iocshArgString};
static const iocshArg setWatchdogEnabledArg1 = {"Axis number", iocshArgInt}; static const iocshArg setThresholdComTimeoutArg1 = {
static const iocshArg setWatchdogEnabledArg2 = { "Time window communication timeout frequency", iocshArgInt};
"Enabling / disabling the watchdog", iocshArgInt}; static const iocshArg setThresholdComTimeoutArg2 = {
static const iocshArg *const setWatchdogEnabledArgs[] = { "Maximum allowed number of communication timeouts within the window",
&setWatchdogEnabledArg0, &setWatchdogEnabledArg1, &setWatchdogEnabledArg2}; iocshArgInt};
static const iocshFuncDef setWatchdogEnabledDef = {"setWatchdogEnabled", 3, static const iocshArg *const setThresholdComTimeoutArgs[] = {
setWatchdogEnabledArgs}; &setThresholdComTimeoutArg0, &setThresholdComTimeoutArg1,
&setThresholdComTimeoutArg2};
static const iocshFuncDef setThresholdComTimeoutDef = {
"setThresholdComTimeout", 3, setThresholdComTimeoutArgs};
static void setWatchdogEnabledCallFunc(const iocshArgBuf *args) { static void setThresholdComTimeoutCallFunc(const iocshArgBuf *args) {
setWatchdogEnabled(args[0].sval, args[1].ival, args[2].ival); setThresholdComTimeout(args[0].sval, args[1].ival, args[2].ival);
} }
// ============================================================================= // =============================================================================
/** /**
* @brief Set the offsetMovTimeout (FFI implementation) * @brief Set the maximum number of subsequent timeouts (FFI implementation)
* *
* @param portName Name of the controller * @param comTimeoutWindow Size of the time window used to calculate
* @param axisNo Axis number * the moving average of timeout events. Set this value to 0 to deactivate
* @param offsetMovTimeout Offset (in seconds) * the watchdog.
* @param maxNumberTimeouts Maximum number of timeouts which may occur
* within the time window before the watchdog is triggered.
* @return asynStatus * @return asynStatus
*/ */
asynStatus setOffsetMovTimeout(const char *portName, int axisNo, asynStatus setMaxSubsequentTimeouts(const char *portName,
double offsetMovTimeout) { int maxSubsequentTimeouts) {
void *ptr = findAsynPortDriver(portName);
if (ptr == nullptr) {
/*
We can't use asynPrint here since this macro would require us
to get a ipPortAsynOctetSyncIO_ from a pointer to an asynPortDriver.
However, the given pointer is a nullptr and therefore doesn't
have a ipPortAsynOctetSyncIO_! printf is an EPICS alternative which
works w/o that, but doesn't offer the comfort provided
by the asynTrace-facility
*/
errlogPrintf("Controller \"%s\" => %s, line %d:\nPort %s not found.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError;
}
// Unsafe cast of the pointer to an asynPortDriver
asynPortDriver *apd = (asynPortDriver *)(ptr);
sinqController *pC; // Safe downcast
pC = (sinqController *)findAsynPortDriver(portName); sinqController *pC = dynamic_cast<sinqController *>(apd);
if (pC == nullptr) { if (pC == nullptr) {
errlogPrintf("%s => line %d:\nPort %s not found.", __PRETTY_FUNCTION__, errlogPrintf(
__LINE__, portName); "Controller \"%s\" => %s, line %d:\ncontroller on port %s is not a "
"turboPmacController.",
portName, __PRETTY_FUNCTION__, __LINE__, portName);
return asynError; return asynError;
} }
asynMotorAxis *asynAxis = pC->getAxis(axisNo); // Set the new value
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis); pC->setMaxSubsequentTimeouts(maxSubsequentTimeouts);
if (axis == nullptr) {
errlogPrintf("%s => line %d:\nAxis %d does not exist or is not an "
"instance of sinqAxis.",
__PRETTY_FUNCTION__, __LINE__, axisNo);
}
return axis->setOffsetMovTimeout(offsetMovTimeout); return asynSuccess;
} }
static const iocshArg setOffsetMovTimeoutArg0 = {"Controller port name", static const iocshArg SetMaxSubsequentTimeoutsArg0 = {
iocshArgString}; "Controller name (e.g. mcu1)", iocshArgString};
static const iocshArg setOffsetMovTimeoutArg1 = {"Axis number", iocshArgInt}; static const iocshArg SetMaxSubsequentTimeoutsArg1 = {
static const iocshArg setOffsetMovTimeoutArg2 = {"Offset timeout for movement", "Maximum number of subsequent timeouts before the user receives an error "
iocshArgDouble}; "message",
static const iocshArg *const setOffsetMovTimeoutArgs[] = { iocshArgInt};
&setOffsetMovTimeoutArg0, &setOffsetMovTimeoutArg1, static const iocshArg *const SetMaxSubsequentTimeoutsArgs[] = {
&setOffsetMovTimeoutArg2}; &SetMaxSubsequentTimeoutsArg0, &SetMaxSubsequentTimeoutsArg1};
static const iocshFuncDef setOffsetMovTimeoutDef = {"setOffsetMovTimeout", 3, static const iocshFuncDef setMaxSubsequentTimeoutsDef = {
setOffsetMovTimeoutArgs}; "setMaxSubsequentTimeouts", 2, SetMaxSubsequentTimeoutsArgs};
static void setMaxSubsequentTimeoutsCallFunc(const iocshArgBuf *args) {
static void setOffsetMovTimeoutCallFunc(const iocshArgBuf *args) { setMaxSubsequentTimeouts(args[0].sval, args[1].ival);
setOffsetMovTimeout(args[0].sval, args[1].ival, args[2].dval);
}
// =============================================================================
/**
* @brief Set the setScaleMovTimeout (FFI implementation)
*
* @param portName Name of the controller
* @param axisNo Axis number
* @param scaleMovTimeout Scaling factor (in seconds)
* @return asynStatus
*/
asynStatus setScaleMovTimeout(const char *portName, int axisNo,
double scaleMovTimeout) {
sinqController *pC;
pC = (sinqController *)findAsynPortDriver(portName);
if (pC == nullptr) {
errlogPrintf("%s => line %d:\nPort %s not found.", __PRETTY_FUNCTION__,
__LINE__, portName);
return asynError;
}
asynMotorAxis *asynAxis = pC->getAxis(axisNo);
sinqAxis *axis = dynamic_cast<sinqAxis *>(asynAxis);
if (axis == nullptr) {
errlogPrintf("%s => line %d:\nAxis %d does not exist or is not an "
"instance of sinqAxis.",
__PRETTY_FUNCTION__, __LINE__, axisNo);
}
return axis->setScaleMovTimeout(scaleMovTimeout);
}
static const iocshArg setScaleMovTimeoutArg0 = {"Controller port name",
iocshArgString};
static const iocshArg setScaleMovTimeoutArg1 = {"Axis number", iocshArgInt};
static const iocshArg setScaleMovTimeoutArg2 = {
"Multiplier for calculated move time", iocshArgDouble};
static const iocshArg *const setScaleMovTimeoutArgs[] = {
&setScaleMovTimeoutArg0, &setScaleMovTimeoutArg1, &setScaleMovTimeoutArg2};
static const iocshFuncDef setScaleMovTimeoutDef = {"setScaleMovTimeout", 3,
setScaleMovTimeoutArgs};
static void setScaleMovTimeoutCallFunc(const iocshArgBuf *args) {
setScaleMovTimeout(args[0].sval, args[1].ival, args[2].dval);
} }
// ============================================================================= // =============================================================================
// This function is made known to EPICS in sinqMotor.dbd and is called by EPICS
// in order to register all functions in the IOC shell
static void sinqControllerRegister(void) { static void sinqControllerRegister(void) {
iocshRegister(&setOffsetMovTimeoutDef, setOffsetMovTimeoutCallFunc); iocshRegister(&setThresholdComTimeoutDef, setThresholdComTimeoutCallFunc);
iocshRegister(&setScaleMovTimeoutDef, setScaleMovTimeoutCallFunc); iocshRegister(&setMaxSubsequentTimeoutsDef,
iocshRegister(&setWatchdogEnabledDef, setWatchdogEnabledCallFunc); setMaxSubsequentTimeoutsCallFunc);
} }
epicsExportRegistrar(sinqControllerRegister); epicsExportRegistrar(sinqControllerRegister);

View File

@ -1,17 +1,23 @@
/* /*
This class extends asynMotorController by some features used in SINQ. This class extends asynMotorController by some features used in SINQ. See the
README.md for details.
Stefan Mathis, November 2024 Stefan Mathis, November 2024
*/ */
#ifndef __sinqController #ifndef sinqController_H
#define __sinqController #define sinqController_H
#include "asynMotorController.h" #include "asynMotorController.h"
#include "msgPrintControl.h"
#include <deque>
#include <initHooks.h>
#include <unordered_map>
#define motorMessageIsFromDriverString "MOTOR_MESSAGE_DRIVER" #define motorMessageIsFromDriverString "MOTOR_MESSAGE_DRIVER"
#define motorMessageTextString "MOTOR_MESSAGE_TEXT" #define motorMessageTextString "MOTOR_MESSAGE_TEXT"
#define IncrementalEncoder "Incremental encoder" #define IncrementalEncoder "incremental"
#define AbsoluteEncoder "Absolute encoder" #define AbsoluteEncoder "absolute"
#define NoEncoder "none"
class epicsShareClass sinqController : public asynMotorController { class epicsShareClass sinqController : public asynMotorController {
public: public:
@ -26,17 +32,17 @@ class epicsShareClass sinqController : public asynMotorController {
pAxes_ which has the length specified here. When getting an axis, the pAxes_ which has the length specified here. When getting an axis, the
`getAxis` function indexes into this array. A length of 8 would therefore `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 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 axis enumeration identical to that of the hardware, we start counting the
counting the axes with 1 and end at 8. Therefore, an offset of 1 is added axes with 1 and end at 8. Therefore, an offset of 1 is added when forwarding
when forwarding this number to asynMotorController. this number to asynMotorController.
* @param movingPollPeriod Time between polls when moving (in seconds) * @param movingPollPeriod Time between polls when moving (in seconds)
* @param idlePollPeriod Time between polls when not moving (in * @param idlePollPeriod Time between polls when not moving (in
seconds) seconds)
* @param extraParams Number of extra parameter library entries * @param extraParams Number of extra parameter library entries
* created in a concrete driver implementation * created in a concrete driver implementation
*/ */
sinqController(const char *portName, const char *SINQPortName, int numAxes, sinqController(const char *portName, const char *ipPortConfigName,
double movingPollPeriod, double idlePollPeriod, int numAxes, double movingPollPeriod, double idlePollPeriod,
int numExtraParams); int numExtraParams);
/** /**
@ -76,7 +82,7 @@ class epicsShareClass sinqController : public asynMotorController {
* *
* If accessing the parameter library failed (return status != * If accessing the parameter library failed (return status !=
asynSuccess), calling this function writes a standardized message to both 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. status.
* *
* @param status Status of the failed parameter library access * @param status Status of the failed parameter library access
@ -84,12 +90,13 @@ class epicsShareClass sinqController : public asynMotorController {
error messages. error messages.
* @param functionName Name of the caller function. It is recommended * @param functionName Name of the caller function. It is recommended
to use a macro, e.g. __func__ or __PRETTY_FUNCTION__. to use a macro, e.g. __func__ or __PRETTY_FUNCTION__.
* @param lineNumber 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__. called. It is recommended to use a macro, e.g. __LINE__.
* @return asynStatus Returns input status. * @return asynStatus Returns input status.
*/ */
asynStatus paramLibAccessFailed(asynStatus status, const char *parameter, asynStatus paramLibAccessFailed(asynStatus status, const char *parameter,
const char *functionName, int lineNumber); int axisNo, const char *functionName,
int line);
/** /**
* @brief Error handling in case parsing a command response failed. * @brief Error handling in case parsing a command response failed.
@ -104,14 +111,13 @@ class epicsShareClass sinqController : public asynMotorController {
* @param axisNo_ Axis where the problem occurred * @param axisNo_ Axis where the problem occurred
* @param functionName Name of the caller function. It is recommended * @param functionName Name of the caller function. It is recommended
to use a macro, e.g. __func__ or __PRETTY_FUNCTION__. to use a macro, e.g. __func__ or __PRETTY_FUNCTION__.
* @param lineNumber 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__. called. It is recommended to use a macro, e.g. __LINE__.
* @return asynStatus Returns asynError. * @return asynStatus Returns asynError.
*/ */
asynStatus errMsgCouldNotParseResponse(const char *command, asynStatus couldNotParseResponse(const char *command, const char *response,
const char *response, int axisNo, int axisNo, const char *functionName,
const char *functionName, int line);
int lineNumber);
/** /**
* @brief Convert an asynStatus into a descriptive string. * @brief Convert an asynStatus into a descriptive string.
@ -121,20 +127,211 @@ class epicsShareClass sinqController : public asynMotorController {
*/ */
const char *stringifyAsynStatus(asynStatus status); const char *stringifyAsynStatus(asynStatus status);
friend class sinqAxis; /**
* @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
happens very often, this may indicate a network problem and must therefore
be forwarded to the user. This is checked by calculating the moving average
of events and comparing it to a threshhold. Both the threshold and the time
window for the moving average can be configured in the IOC via the function
setThresholdCom.
This function exists in two variants: Either the error message can be
written into a buffer provided by the caller or it written directly into the
parameter library of the provided axis.
* @param axis Axis to which the error message is sent
*
* @return asynStatus asynError, if the threshold has been
exceeded, asynSuccess otherwise
*/
virtual asynStatus checkComTimeoutWatchdog(class sinqAxis *axis);
/**
* @brief See documentation of checkComTimeoutWatchdog(sinqAxis * axis)
*
* @param userMessage Buffer for the user message
* @param userMessageSize Buffer size in chars
* @return asynStatus
*/
virtual asynStatus checkComTimeoutWatchdog(int axisNo, char *motorMessage,
size_t motorMessageSize);
/**
* @brief Set the threshold for the communication timeout mechanism
*
* @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.
* @param maxNumberTimeouts Maximum number of timeouts which may occur
* within the time window before the watchdog is triggered.
* @return asynStatus
*/
virtual asynStatus setThresholdComTimeout(time_t comTimeoutWindow,
size_t maxNumberTimeouts) {
comTimeoutWindow_ = comTimeoutWindow;
maxNumberTimeouts_ = maxNumberTimeouts;
return asynSuccess;
}
/**
* @brief Inform the user, if the number of timeouts exceeds the threshold
* specified with `setMaxSubsequentTimeouts`.
*
* @param timeoutNo Number of subsequent timeouts which already
* happened.
* @param axis
* @return asynStatus
*/
virtual asynStatus checkMaxSubsequentTimeouts(int timeoutNo,
class sinqAxis *axis);
/**
* @brief See documentation of `checkMaxSubsequentTimeouts(sinqAxis * axis)`
*
* @param userMessage Buffer for the user message
* @param userMessageSize Buffer size in chars
* @return asynStatus
*/
virtual asynStatus checkMaxSubsequentTimeouts(int timeoutNo, int axisNo,
char *motorMessage,
size_t motorMessageSize);
/**
* @brief Set the maximum number of subsequent timeouts before the user is
* informed.
*
* @param maxSubsequentTimeouts
* @return asynStatus
*/
asynStatus setMaxSubsequentTimeouts(int maxSubsequentTimeouts) {
maxSubsequentTimeouts_ = maxSubsequentTimeouts;
return asynSuccess;
}
/**
* @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.
*/
msgPrintControl &getMsgPrintControl();
// =========================================================================
// 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 motorVeloFromDriver() { return motorVeloFromDriver_; }
int motorVbasFromDriver() { return motorVbasFromDriver_; }
int motorVmaxFromDriver() { return motorVmaxFromDriver_; }
int motorAcclFromDriver() { return motorAcclFromDriver_; }
int motorHighLimitFromDriver() { return motorHighLimitFromDriver_; }
int motorLowLimitFromDriver() { return motorLowLimitFromDriver_; }
int encoderType() { return encoderType_; }
// Additional members
int numAxes() { return numAxes_; }
double idlePollPeriod() { return idlePollPeriod_; }
double movingPollPeriod() { return movingPollPeriod_; }
asynUser *asynUserSelf() { return pasynUserSelf; }
asynUser *ipPortAsynOctetSyncIO() { return ipPortAsynOctetSyncIO_; }
// =========================================================================
protected: protected:
asynUser *lowLevelPortUser_; // Pointer to the port user which is specified by the char array
// `ipPortConfigName` in the constructor
asynUser *ipPortAsynOctetSyncIO_;
double movingPollPeriod_;
double idlePollPeriod_;
msgPrintControl msgPrintControl_;
// Internal variables used in the communication timeout frequency watchdog
time_t comTimeoutWindow_; // Size of the time window
size_t maxNumberTimeouts_; // Maximum acceptable number of events within the
// time window
std::deque<time_t>
timeoutEvents_; // Deque holding the timestamps of the individual events
// Communicate a timeout to the user after it has happened this many times
// in a row
int maxSubsequentTimeouts_;
bool maxSubsequentTimeoutsExceeded_;
#define FIRST_SINQMOTOR_PARAM motorMessageText_ #define FIRST_SINQMOTOR_PARAM motorMessageText_
int motorMessageText_; int motorMessageText_;
int motorTargetPosition_; int motorReset_;
int motorEnable_; int motorEnable_;
int motorEnableRBV_; int motorEnableRBV_;
int motorCanDisable_; int motorCanDisable_;
int motorEnableMovWatchdog_; int motorEnableMovWatchdog_;
int motorCanSetSpeed_; int motorCanSetSpeed_;
int motorLimitsOffset_; int motorLimitsOffset_;
int motorForceStop_;
/* /*
These parameters are here to write values from the hardware to the EPICS These parameters are here to write values from the hardware to the EPICS
motor record. Using motorHighLimit_ / motorLowLimit_ does not work: motor record. Using motorHighLimit_ / motorLowLimit_ does not work:
@ -150,6 +347,9 @@ class epicsShareClass sinqController : public asynMotorController {
int motorLowLimitFromDriver_; int motorLowLimitFromDriver_;
int encoderType_; int encoderType_;
#define LAST_SINQMOTOR_PARAM encoderType_ #define LAST_SINQMOTOR_PARAM encoderType_
private:
static void epicsInithookFunction(initHookState iState);
}; };
#define NUM_SINQMOTOR_DRIVER_PARAMS \ #define NUM_SINQMOTOR_DRIVER_PARAMS \
(&LAST_SINQMOTOR_PARAM - &FIRST_SINQMOTOR_PARAM + 1) (&LAST_SINQMOTOR_PARAM - &FIRST_SINQMOTOR_PARAM + 1)

View File

@ -2,3 +2,4 @@
# SINQ specific DB definitions # SINQ specific DB definitions
#--------------------------------------------- #---------------------------------------------
registrar(sinqControllerRegister) registrar(sinqControllerRegister)
registrar(sinqAxisRegister)