diff --git a/docs/src/config/python-hal-interface.adoc b/docs/src/config/python-hal-interface.adoc index 384ddcb8a4d..1fe98f654f2 100644 --- a/docs/src/config/python-hal-interface.adoc +++ b/docs/src/config/python-hal-interface.adoc @@ -206,6 +206,23 @@ In that case, the call uses the _value_ to set the port's queue size and it must See below xref:_hal_port_pipes[on configuring a port]. + Throws a `RuntimeError` exception if HAL is not initialized. +hal.get_p(_name_:string):: +Returns the value of the pin or param with _name_. +If _name_ refers to a pin and that pin is connected, then the connected signal's value is returned. +Boolean types return `True` or `False`. +Integer scalar types return an integer. +Floating point types return a float. +A `RuntimeError` exception is thrown if no pin or param is found by that name. + +Throws a `RuntimeError` exception if HAL is not initialized. + +hal.get_s(_name_:string):: +Returns the value of the signal with _name_. +Boolean types return `True` or `False`. +Integer scalar types return an integer. +Floating point types return a float. +A `RuntimeError` exception is thrown if no signal is found by that name. + +Throws a `RuntimeError` exception if HAL is not initialized. + hal.get_value(_name_:string):: Returns the value of the pin, param or signal with _name_, searched in that order. Boolean types return `True` or `False`. diff --git a/docs/src/man/man1/halrmt.1.adoc b/docs/src/man/man1/halrmt.1.adoc index 9086723abe6..65dd59824bc 100644 --- a/docs/src/man/man1/halrmt.1.adoc +++ b/docs/src/man/man1/halrmt.1.adoc @@ -2,221 +2,303 @@ == NAME -halrmt - remote-control interface for LinuxCNC +halrmt - remote-control interface for LinuxCNC/HAL == SYNOPSIS -*halrmt* [*--port* __] [*--name* __] [*--connectpw* __] [*--enablepw* __] [*--sessions* __] [*-ini* __] +*halrmt* [*--port* __] [*--name* __] [*--connectpw* __] [*--enablepw* __] [*--sessions* __] [*--ini* __] == OPTIONS ---port _port_:: Waits for socket connections (telnet) on specified -socket, without port specification it uses default port 5006. -(Note: linuxcncrsh uses 5007 as default.) ---name _server_name_:: Sets the server name to specified name for Hello. ---connectpw _password_:: Sets the connection password to 'password'. Default: EMC. ---enablepw _password_:: Sets the enable password to _password_. Default EMCTOO. ---sessions :: Sets the maximum number of simultaneous connextions to max sessions. Default is no limit (-1). --ini __:: Uses the specified _INI file_ instead of the default emc.ini. +-h,--help:: + Print a brief usage help message. -== DESCRIPTION - -The application *halrmt* supports six commands that are meant to be sent -to an instance of HAL that is running on another machine. Of these, the commands _set_ and _get_ contain HAL specific sub-commands that are based -on the commands supported by _halcmd_. - -Commands and most parameters are not case sensitive. -The exceptions are passwords, file paths and text strings. -The supported commands are as follows: - -Hello :: -If a valid password was entered the server will respond with "HELLO ACK -__ __" where server name and server version are -looked up from the implementation. If an invalid password or any other -syntax error occurs then the server responds with "HELLO NAK". - -Get:: The get command includes one of the HAL sub-commands, -described below and zero or more additional parameters. -Set:: The set command inclides one of the HAL sub-commands, -described below and one or more additional parameters. -Quit:: The quit command disconnects the associated socket connection. -Shutdown:: The shutdown command tells LinuxCNC to shut down -before quitting the connection. This command may only be issued if the -Hello has been successfully negotiated and the connection has control of -the CNC (see enable sub-command below). This command has no parameters. -Help:: The help command will return help information in text format over the -telnet connection. If no parameters are specified, it will itemize the -available commands. If a command is specified, it will provide usage -information for the specified command. Help will respond regardless of -whether a "Hello" has been successfully negotiated. - -*HAL sub-commands:* - -echo on | off:: With get will return the current echo -state, with set, sets the echo state. When echo is on, all commands will -be echoed upon receipt. This state is local to each connection. - -verbose on | off:: With get will return the current verbose state, with set, sets -the verbose state. When in verbose mode is on, all set commands return -positive acknowledgement in the form SET ACK. In addition, -text error messages will be issued when in verbose mode. This state is -local to each connection. - -enable | off:: With get will return On or -Off to indicate whether the current connection is enabled to perform -control functions. With set and a valid password, the current connection -is enabled for control functions. "OFF" may not be used as a password -and disables control functions for this connection. - -config [TBD] comm_mode ascii | binary:: With get, will return the current -communications mode. With set, will set the communications mode to the -specified mode. The binary protocol is TBD. - -comm_prot :: With get, returns the current protocol version used by the server, -with set, sets the server to use the specified protocol version, provided it is -lower than or equal to the highest version number supported by the server implementation. - -Comps []:: -Get only, returns all components beginning with the specified substring. -If no substring is specified then it returns all components. - -Pins []:: -Get only, returns all information about all pins beginning with the -specified substring. If no substring is specified then it returns all -pins. - -PinVals []:: -Get only, returns only value information about all pins beginning with -the specified substring. If no substring is specified then it returns -all pins. - -Signals []:: -Get only, returns all information about all signals beginning with the -specified substring. If no substring is specified then it returns all -signals. - -SigVals []:: -Get only, returns only value information about all signals beginning -with the specified substring. If no substring is specified then it -returns all pins. - -Params []:: -Get only, returns all information about all parameters beginning with -the specified substring. If no substring is specified then it returns -all parameters. - -ParamVals []:: -Get only, returns only value information about all parameters beginning -with the specified substring. If no substring is specified then it -returns all pins parameters. - -Functs []:: -Get only, returns all information about all functions beginning with the -specified substring. If no substring is specified then it returns all -functions. - -Threads:: -Get only, returns all information about all functions. +-n,--name _server_name_:: + Sets the server name to specified name for in reply to `HELLO` command. + Default: EMCNETSVR. -Comp :: -Get only, returns the component matching the specified name. +-p,--port _port_:: + Listen on TCP port _port_ for connection. + Both IPv4 and IPv6 connections are accepted. + Default port is 5006. + (Note: linuxcncrsh uses 5007 as default) -Pin :: -Get only, returns all information about the pin matching the specified name. +-w,--connectpw _password_:: + Sets the `HELLO` command password to _password_. + Default: EMC. -PinVal :: -Get only, returns the value of the pin matching the specified name. +-e,--enablepw _password_:: + Sets the `SET ENABLE` command password to _password_. + Default: EMCTOO. -Sig :: -Get only, returns all information about the pin matching the specified name. +-s,--sessions _max_sessions_:: + Sets the maximum number of simultaneous connextions to _max_sessions_. + Default is no limit (0). -SigVal :: -Get only, returns just the value of the signal matching the specified name. +-i,--ini _INI_file_:: + Uses the specified _INI_file_. + The default is to get the _INI_file_ name from the environment variable `INI_FILE_NAME`. -Param :: -Get only, returns all information about the parameter matching the specified name. +-q,--quiet:: + Don't print informational messages to the console. -ParamVal :: -Get only, returns just the value of the parameter matching the specified name. - -Funct :: -Get only, returns all information about the parameter matching the -specified name. - -Thread :: -Get only, returns all information about the thread matching the -specified name. - -LoadRt :: -Set only, loads the real time executable specified by name. - -Unload :: -Set only, unloads the executable specified by name. - -LoadUsr :: -Set only, loads the user executable specified by name. - -Linkps :: -Set only, links the specified pin to the specified signal. - -Linksp :: -Set only, links the specified signal to the specified pin. - -Linkpp :: -Set only, links the pin specified by pin 1 with the pin specified by pin 2. - -Net :: -Set only, nets the specified net list. - -Unlinkp :: -Set only, unlinks the specified pins. - -Lock +== DESCRIPTION -Unlock +The application *halrmt* supports six primary commands to manipulate the HAL of a remote LinuxCNC instance. +Of these, the commands `SET` and `GET` contain HAL specific sub-commands. +The sub-commands are based on the commands supported by *halcmd*(1). -NewSig :: -Set only, creates the signal specified by name and of type specified by -type. +=== COMMANDS -DelSig :: -Set only, deletes the signal specified by name. +Commands, sub-commands and most parameters are not case sensitive. +The exceptions are passwords, file paths and text strings. -SetP :: -Set only, sets the parameter specified by name to the value specified by -value. +The supported commands are as follows: -SetS :: -Set only, sets the signal specified by name to the value specified by -value. +hello []:: + If a valid _password_ was entered the server will respond with + + `HELLO ACK __ __` + + where server name and server version are looked up from the implementation. + If an invalid _password_ or any other syntax error occurs then the server responds with `HELLO NAK`. + +get [args...]:: + The get command includes one of the HAL sub-commands, + described below and zero or more additional parameters. + +set [args...]:: + The set command includes one of the HAL sub-commands, + described below and one or more additional parameters. + +quit:: + The quit command disconnects the associated socket connection. + +shutdown:: + The shutdown command disconnects all clients and tells *halrmt* to shut down. + This command may only be issued if the `HELLO` has been successfully negotiated. + The connection must be enabled. + +help [sub-command]:: + The help command will return information in text over the network connection. + If no parameters are specified, it will itemize the available commands. + If a command is specified, it will provide usage information for the specified command. + Command `HELP` will respond regardless of whether a `HELLO` has been successfully negotiated. + +=== SUBCOMMANDS + +A 'pattern' is a glob pattern as the shell implements it. +Backslash characters in a 'pattern' are not special (don't escape) and are case insensitive. + +set addf [arg [arg...]]:: + Adds the function specified by _name_, to the thread specified by _thread_. + Optional parameters may be specified by _arg_. + +get comp :: + Returns the component matching the specified _name_. + +get comps [pattern]:: + Returns information about all components matching _pattern_. + If no _pattern_ is specified then all components are returned. + +set delf :: + Deletes the function specified by _name_. + +set delsig |all:: + Deletes the signal specified by _signalname_. + Specifying 'all' will remove all signals in the system. + +get echo:: +set echo {on|off}:: + With get will return the current echo state. + With set, sets the echo state to the supplied argument. + When echo is on, all commands will be echoed upon receipt. + The _echo_ state is local to each connection. + + The echoed line is INI-variable expanded if `SET EXPAND` is set to 'On'. + This allows you to see the actual command being executed. + +get enable:: +set enable |off:: + With get will return 'On' or 'Off' to indicate whether the current connection is enabled to perform control functions. + With set and a valid password, the current connection is enabled for control functions. + The argument 'OFF' may not be used as a password and disables control functions for this connection. + +get expand:: +set expand {on|off}:: + Get or set INI-file variable expansion. + Setting the INI-file expansion to _on_ will pre-process every input line and substitute variables. + An INI-file variable is specified by `[SECTION]VAR` or `[SECTION](VAR)`. + Not using parentheses requires you to have trailing white-space or be at the end of the line. + INI-file expansion defaults to off and requires a valid INI-file. + Enabling expansion with no or an invalid INI-file will expand to an empty string. + Expansion is applied to the input line _before_ it is tokenized. + That means that all commands and sub-commands are subject to expansion. + Everything typed as input is first expanded before processed. + The _expand_ state is local to each connection. + +get funct :: + Returns all information about the parameter matching the specified _name_. + +get functs [pattern]:: + Returns information about functions matching _pattern_. + If no _pattern_ is specified then all functions are returned. + +get ini
:: + Return the variable \[__section__]_var_ from the current INI-file. + +get inifile:: +set inifile :: + Gets the current active INI-file's name or sets the active INI-file to _filename_. + A test is performed to validate the new INI-file when set. + Setting the INI-file is local to the connection. + +set linkps []:: + Add _pinname_ to signal with _signalname_. + Will act as `SET UNLINKP _pinname_` if no _signalname_ is provided. + +set linksp :: + Add _pinname_ to signal with _signalname_. + +set loadrt [arg [arg...]]:: + Load the real-time component _compname_ with optional arguments. + The real-time environment must have been started or an error will be returned. + +set loadusr [flags] [arg [arg...]]:: + Loads the user component _program_ and passes any optional arguments. + The _flags_ are on or more of: + * *-W* - to wait for the component to become ready. + The component is assumed to have the same name as the first argument of the command. + Use *-n* to override the component name to look for. + * *-n* _name_ - to wait for the component, which will have the given _name_. + * *-w* - to wait for the program to exit + * *-i* - to ignore the program return value (with *-w*) + +get lock:: +set lock {all|load|config|params|run|tune|none}:: + Gets the current HAL lock value or sets the HAL lock of the argument's value. + The _tune_ value is a combination of _load_ and _config_. + The values _all_, _none_ and _tune_ override any other values in the lock that may be present. + Doing `SET LOCK none` is equivalent to `SET UNLOCK all`. + +get net :: +set net [pinname [pinname...]]:: + Get shows all the pins connected to _signalname_. + Set creates a signal _signalname_ and adds all the _pinname_ pins to the signal. + +set newsig :: + Creates the signal specified by _signalname_ and of type specified by _type_. + +get param :: + Returns all information about the parameter matching the specified _paramname_. + +get params [pattern]:: + Returns information about parameters matching _pattern_. + If no _pattern_ is specified then all parameters are returned. + +get paramval :: + Returns just the value of the parameter matching the specified _paramname_. + +get paramvals [pattern]:: + Returns only value information about all parameters matching _pattern_. + If no _pattern_ is specified then all parameters are returned. + +get pin :: + Returns all information about the pin matching the specified _pinname_. + +get pins [pattern]:: + Returns all information about all pins matching _pattern_. + If no _pattern_ is specified then all pins are returned. + +get pinval :: + Returns the value of the pin matching the specified _pinname_. + +get pinvals [pattern]:: + Returns only value information about all pins matching _pattern_. + If no _pattern_ is specified then all pins are returned. + +set save {all|comp|sig|link|linka|net|neta|param|thread} []:: + Will return the saved content on the connection if no filename is provided. + Saves the specified set of data to file _filename_ instead if provided. + +set setp :: + Sets the pin or parameter specified by _pinname_/_paramname_ to the value specified by _value_. + +set sets :: + Sets the signal specified by _signalname_ to the value specified by _value_. + +get signal :: + Returns all information about the pin matching the specified _signalname_. + +get signals [pattern]:: + Returns all information about all signals matching _pattern_. + If no _pattern_ is specified then all signals are returned. + +get sigval :: + Returns just the value of the signal matching the specified _signalname_. -AddF []:: -Set only, adds the function specified by name, to the thread specified -by thread, with the optional parameters specified by parameters. +get sigvals [pattern]:: + Returns only value information about all signals matching _pattern_. + If no _pattern_ is specified then all signals are returned. + +set start:: + Start the real-time threads. + The real-time environment must have been started or an error will be returned. + +set stop:: + Stop the real-time threads. + The real-time environment must have been started or an error will be returned. + +get time:: + Returns the time, in seconds, from the start of the epoch. + The starting time depends on the platform. -DelF :: -Set only, deletes the function specified by name. +get timestamp:: +set timestamp {on|off} [{on|off}]:: + Enable or disable printing of a timestamp on messages sent back from the server to the user. + The optional format argument selects human readable date/time format and seconds since the epoch. + The format prints seconds when off and human readable when on. + +get thread :: + Returns all information about the thread matching the specified _name_. + +get threads [pattern]:: + Returns all information about all threads matching _pattern_. + If no _pattern_ is specified then all threads are returned. + +set unlinkp :: + Unlinks the specified _pinname_ from any signal it may be attached to. -Save +set unload :: + Unloads the real-time component _compname_. + The real-time environment must have been started or an error will be returned. -Start +set unlock {all|load|config|params|run|tune|none}:: + Removes the HAL lock of the argument's value. + The _tune_ value is a combination of _load_ and _config_. + Removing _none_ has no effect but may be useful in scripting. -Stop +get verbose:: +set verbose on | off:: + With get will return the current verbose state. + With set, sets the verbose state to the supplied argument. + When verbose mode is on, all `SET` commands return positive acknowledgement in the form `SET ACK`. + In addition, text error messages will be issued when in verbose mode. + The _verbose_ state is local to each connection. == SEE ALSO -linuxcnc(1) +*linuxcnc*(1), +*halcmd*(1). Much more information about LinuxCNC and HAL is available in the LinuxCNC and HAL User Manuals, found at /usr/share/doc/LinuxCNC/. == BUGS -It is not known if this interface currently works. +Probably, but it has been mostly rewritten after the last incarnation incurred som bit-rot and was deemed non-functional. == AUTHOR This man page written by Andy Pugh, as part of the LinuxCNC project. +Manual page updated by B.Stultiens after the rewrite. == REPORTING BUGS @@ -224,7 +306,8 @@ Report bugs at https://github.com/LinuxCNC/linuxcnc/issues. == COPYRIGHT -Copyright © 2020 Andy Pugh. +Copyright © 2020 Andy Pugh. + +Copyright © 2026 B.Stultiens. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR diff --git a/docs/src/man/man3/hal.3.adoc b/docs/src/man/man3/hal.3.adoc index 8a19c80a94f..839f8035dca 100644 --- a/docs/src/man/man3/hal.3.adoc +++ b/docs/src/man/man3/hal.3.adoc @@ -1,3 +1,5 @@ +:manvolnum: 3 + = hal(3) == NAME @@ -67,13 +69,103 @@ so that realtime components and non-realtime programs can access the data. == REALTIME CONSIDERATIONS -For an explanation of realtime considerations, see *rtapi(3)*. +For an explanation of realtime considerations, see rtapi(3). == HAL STATUS CODES Except as noted in specific manual pages, HAL returns negative errno values for errors, and non-negative values for success. +== EXAMPLE + +A simple component with two pins that copies data from one to the other: + +[source,c] +---- +#include +#include +#include + +static const char cname[] = "mycomp"; +static int comp_id; + +// Container structure type for our pins +typedef struct { + hal_real_t pino; + hal_sint_t pini; + hal_sint_t offs; + hal_real_t mult; +} mycomp_hal_t; + +static mycomp_hal_t *pins; + +// Macro to make error checking easier +#define CHKP(x,p) do { \ + int _rv = (x); \ + if(_rv < 0) { \ + rtapi_print_msg(RTAPI_MSG_ERR, "%s: Failed to create '%s.%s', err=%d\n", \ + cname, cname, (p), _rv); \ + return _rv; \ + } \ + } while(0) + +static void process(void *arg, long period) +{ + (void)arg; // Unused + (void)period; // Unused + + // pino = (pini - offs) * mult + // Also converts from signed integer input to floating point output + rtapi_sint sint = hal_get_sint(pins->pini) - hal_get_sint(pins->offs); + hal_set_real(pins->pino, sint * hal_get_real(pins->mult)); +} + +int rtapi_app_main(void) +{ + // Get memory for the pins + pins = (mycomp_hal_t *)hal_malloc(sizeof(*pins)); + if(!pins) { + rtapi_print_msg(RTAPI_MSG_ERR, "%s: Failed to allocate HAL memory\n", cname); + return -ENOMEM; + } + + // Initialize HAL for this component + if((comp_id = hal_init(cname)) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "%s: hal_init() failed err=%d\n", cname, comp_id); + return comp_id; + } + + // Create some pins + CHKP(hal_pin_new_real(comp_id, HAL_OUT, &pins->pino, 3.14, "%s.pino", cname), "pino"); + CHKP(hal_pin_new_sint(comp_id, HAL_IN, &pins->pini, 3, "%s.pini", cname), "pini"); + + // Create some parameters + CHKP(hal_param_new_real(comp_id, HAL_RW, &pins->mult, 0, "%s.scale", cname), "scale"); + CHKP(hal_param_new_sint(comp_id, HAL_RW, &pins->offs, 0, "%s.offset", cname), "offset"); + + // Export our function + int rv = hal_export_functf(process, NULL, 1, 0, comp_id, "%s.process", cname); + if(rv < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "%s: Failed export of 'process' err=%d\n", cname, rv); + return rv; + } + + // Mark us ready + if((rv = hal_ready(comp_id)) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "%s: hal_ready() failed err=%d\n", cname, rv); + return rv; + } + + return 0; +} + +void rtapi_app_exit(void) +{ + if(comp_id > 0) + hal_exit(comp_id); +} +---- + == SEE ALSO rtapi(3) diff --git a/docs/src/man/man3/hal_add_funct_to_thread.3.adoc b/docs/src/man/man3/hal_add_funct_to_thread.3.adoc index 5b973e035a7..5e86dde1db6 100644 --- a/docs/src/man/man3/hal_add_funct_to_thread.3.adoc +++ b/docs/src/man/man3/hal_add_funct_to_thread.3.adoc @@ -6,12 +6,14 @@ hal_add_funct_to_thread, hal_del_funct_from_thread - cause a function to be executed at regular intervals -== SYNTAX +== SYNOPSIS [source,c] ---- -int hal_add_funct_to_thread(const char* funct_name, const char* thread_name, int position) -int hal_del_funct_from_thread(const char* funct_name, const char* thread_name) +#include + +int hal_add_funct_to_thread(const char* funct_name, const char* thread_name, int position); +int hal_del_funct_from_thread(const char* funct_name, const char* thread_name); ---- == ARGUMENTS @@ -31,10 +33,10 @@ position:: == DESCRIPTION -The function *hal_add_funct_to_thread* adds another function that is exported by a realtime HAL component to a realtime thread. +The function *hal_add_funct_to_thread()* adds another function that is exported by a realtime HAL component to a realtime thread. This determines how often and in what order functions are executed. -The function *hal_del_funct_from_thread* removes a function from a thread. +The function *hal_del_funct_from_thread()* removes a function from a thread. == RETURN VALUE diff --git a/docs/src/man/man3/hal_comp_by_name.3.adoc b/docs/src/man/man3/hal_comp_by_name.3.adoc new file mode 100644 index 00000000000..f86fbbd2df4 --- /dev/null +++ b/docs/src/man/man3/hal_comp_by_name.3.adoc @@ -0,0 +1,47 @@ +:manvolnum: 3 + += hal_comp_by_name(3) + +== NAME + +hal_comp_by_name, hal_comp_by_id - Retrieve information about a named component + +== SYNOPSIS + +[source,c] +---- +#include + +int hal_comp_by_name(const char *comp, hal_query_t *query); +int hal_comp_by_id(int comp_id, hal_query_t *query); +---- + +== ARGUMENTS + +comp:: + A HAL component name. +comp_id:: + A HAL component identifier. +query:: + A query structure that will receive the component's information. + May be NULL if no information is required, besides determining whether the component exists. + +== DESCRIPTION + +The *hal_comp_by_name()* and *hal_comp_by_id()* functions retrieve component information by name or ID. + +If no component was found, then *-ENOENT* is returned. +If the _query_ argument is not NULL, then the query structure will contain all available information about the component. + +== RETURN VALUE + +Returns zero (0) on success or a negative errno code: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The component does not exist. + +== SEE ALSO + +hal_query_t(3) diff --git a/docs/src/man/man3/hal_create_thread.3.adoc b/docs/src/man/man3/hal_create_thread.3.adoc index dad537b4ac1..9289803f210 100644 --- a/docs/src/man/man3/hal_create_thread.3.adoc +++ b/docs/src/man/man3/hal_create_thread.3.adoc @@ -1,14 +1,20 @@ +:manvolnum: 3 + = hal_create_thread(3) == NAME hal_create_thread - Create a HAL thread -== SYNTAX +== SYNOPSIS -int hal_create_thread(const char* _name_, unsigned long _period_, int _uses_fp_) +[source,c] +---- +#include -int hal_thread_delete(const char* _name_) +int hal_create_thread(const char *name, unsigned long period, int uses_fp); +int hal_thread_delete(const char *name); +---- == ARGUMENTS @@ -42,6 +48,14 @@ Call only from realtime init code, not from other realtime or non-realtime code. Returns a HAL status code. +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-EPERM:: HAL is config locked. +-EEXIST:: The thread name already exists (hal_create_thread). +-ENOMEM:: Failed to allocate memory for thread registration. +-ENOENT:: The thread does not exist (hal_thread_delete). + == SEE ALSO hal_export_funct(3) diff --git a/docs/src/man/man3/hal_exit.3.adoc b/docs/src/man/man3/hal_exit.3.adoc index 3396d1c7ec9..3bbd2336dd1 100644 --- a/docs/src/man/man3/hal_exit.3.adoc +++ b/docs/src/man/man3/hal_exit.3.adoc @@ -1,12 +1,19 @@ +:manvolnum: 3 + = hal_exit(3) == NAME hal_exit - Shut down HAL -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include -int hal_exit(int _comp_id_) +int hal_exit(int comp_id); +---- == ARGUMENTS @@ -15,8 +22,12 @@ comp_id:: == DESCRIPTION -The function *hal_exit* shuts down and cleans up HAL and RTAPI. -It must be called prior to exit by any module that called *hal_init*. +The function *hal_exit()* shuts down and cleans up HAL and RTAPI. +It must be called prior to exit by any module that called hal_init(3). + +Each hal_init(3) call must be matched with a *hal_exit()* call. +Failing to do so will leak resources in HAL memory and may hamper proper shutdown. +Usually you'd call *hal_exit()* in rtapi_app_exit(3). == REALTIME CONSIDERATIONS @@ -24,4 +35,13 @@ Call only from within non-realtime or init/cleanup code, not from realtime tasks == RETURN VALUE -Returns a HAL status code. +Returns zero (0) on success or a HAL status code: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-ENOENT:: The component does not exist. + +== SEE ALSO + +hal_init(3), +rtapi_app_exit(3) diff --git a/docs/src/man/man3/hal_export_funct.3.adoc b/docs/src/man/man3/hal_export_funct.3.adoc index b33574f0ef6..3ff00485fab 100644 --- a/docs/src/man/man3/hal_export_funct.3.adoc +++ b/docs/src/man/man3/hal_export_funct.3.adoc @@ -6,11 +6,17 @@ hal_export_funct, hal_export_functf - create a realtime function callable from a thread -== SYNTAX +== SYNOPSIS -typedef void(*hal_funct_t)(void* _arg_, long _period_) +[source,c] +---- +#include -int hal_export_funct(const char* _name_, hal_funct_t _funct_, void* _arg_, int _uses_fp_, int _reentrant_, int _comp_id_) +typedef void(*hal_funct_t)(void *arg, long period); + +int hal_export_funct(const char *name, hal_funct_t funct, void *arg, int uses_fp, int reentrant, int comp_id); +int hal_export_functf(hal_funct_t funct, void *arg, int uses_fp, int reentrant, int comp_id, const char *fmt, ...); +---- == ARGUMENTS @@ -27,18 +33,21 @@ reentrant:: If reentrant is non-zero, the function may be preempted and called again before the first call completes. Otherwise, it may only be added to one thread. comp_id:: - A HAL component identifier returned by an earlier call to *hal_init*. + A HAL component identifier returned by an earlier call to hal_init(3). +fmt, ...:: + A printf-style format string and arguments == DESCRIPTION -*hal_export_funct* makes a realtime function provided by a component available to the system. -A subsequent call to *hal_add_funct_to_thread* can be used to schedule the +The *hal_export_funct()* function makes a realtime function provided by a component available to the system. +A subsequent call to hal_add_funct_to_thread(3) can be used to schedule the execution of the function as needed by the system. When this function is placed on a HAL thread, and HAL threads are started, _funct_ is called repeatedly with two arguments: -_void *arg_ is the same value that was given to *hal_export_funct*, -and _long period_ is the interval between calls in nanoseconds. +[horizontal] +_void *arg_:: is the same value that was given to *hal_export_funct()*, +_long period_:: is the interval between calls in nanoseconds. Each call to the function should do a small amount of work and return. diff --git a/docs/src/man/man3/hal_get_p.3.adoc b/docs/src/man/man3/hal_get_p.3.adoc new file mode 100644 index 00000000000..6ed6a765994 --- /dev/null +++ b/docs/src/man/man3/hal_get_p.3.adoc @@ -0,0 +1,133 @@ +:manvolnum: 3 + += hal_get_p(3) + +== NAME + +hal_get_p, hal_getref_p - Get HAL pin or param value and information + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_get_p(hal_query_t *query, hal_query_cb callback, void *arg); +int hal_getref_p(hal_query_t *query); +---- + +== ARGUMENTS + +query:: + The query structure containing the data to search for and returns all data found. + +callback:: + The callback function to invoke when the data has been found or NULL if no callback is required. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_get_p()* function will retrieve the value of a pin or param, including its data reference. +The value of a pin, if connected, is the signal's value. +The _query_ structure should be set to zero before the call, except for the fields noted here. + +The _query.name_ must be set to the name of the pin or parameter you want to get. +Optionally, you can enforce to look exclusively for a pin or param by setting _query.qtype_ before the call to: + +* `0` - look for either pin or param +* `HAL_QTYPE_PIN` - only look for a pin +* `HAL_QTYPE_PARAM` - only look for a param + +Note that both pins and params share one namespace and cannot overlap. + +You can further limit the search by setting _query.pp.type_ to the HAL type you want to find. +If the pin or param is found, but has a different type, then *-EEXIST* is returned. + +The _callback_ is called with all fields set appropriately, including value and data reference. +You must to demultiplex the _query.pp.value_ according to the _query.pp.type_ field. + +The *hal_getref_p()* function will only retrieve the data reference of the pin or param. +No callback is used and no value is retrieved. +The reference of a pin, if connected, is the signal's value. +All query fields, expect _query.pp.value_ are set upon return. +The *hal_getref_p()* function is preferable if you do not need the actual pin or param value, like testing for existence. + +If found, both *hal_get_p()* and *hal_getref_p()* set the _query.name_ field to the actual live pin or param name. +Also, both functions set _query.qtype_ to the actual query type found. + +== RETURN VALUE + +Both functions return zero (0) on success. +The return value of the _callback_ is returned if it got called. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The pin or param does not exist. +-EEXIST:: The pin or param exists but is of different type (*hal_get_p()* only). +-EIO:: The internal data pointer is missing. +-EBADF:: An invalid type was detected. + +== EXAMPLES + +[source,c] +---- +int have_p(const char *ppname) +{ + hal_query_t query = {}; + query.name = ppname; + + int rv = hal_getref_p(&query); + + if(-ENOENT == rv) + return 0; // Does not exist + + if(0 == rv) + return 1; // Does exist + + return rv; // An error occured +} +---- + +[source,c] +---- +int print_p_val(const char *ppname) +{ + hal_query_t query = {}; + query.name = ppname; + + int rv = hal_get_p(&query, NULL, NULL); + + if(-ENOENT == rv) { + printf("%s: not found\n", ppname); + } else if(0 != rv) { + return rv; // Let upstream handle any errors + } + + if(HAL_QTYPE_PIN == query.qtype) { + printf("%s (%s): ", ppname, query.pp.signal ? query.pp.signal : "no signal"); + } else { + printf("%s (param): ", ppname); + } + + switch(query.pp.type) { + case HAL_BOOL: printf("%s\n", query.pp.value.b ? "true" : "false"); break; + case HAL_REAL: printf("%f\n", query.pp.value.r); break; + case HAL_SINT: printf("%ld\n", query.pp.value.s); break; + case HAL_UINT: printf("%lu\n", query.pp.value.u); break; + default: printf("unsupported value type %d\n", (int)query.pp.type); break; + } + + return 0; +} +---- + +== SEE ALSO + +hal_query_t(3), hal_set_p(3) diff --git a/docs/src/man/man3/hal_get_realtime_type.3.adoc b/docs/src/man/man3/hal_get_realtime_type.3.adoc index b72114a1f92..9babdd5690f 100644 --- a/docs/src/man/man3/hal_get_realtime_type.3.adoc +++ b/docs/src/man/man3/hal_get_realtime_type.3.adoc @@ -6,16 +6,29 @@ hal_get_realtime_type - Get the type of the running realtime -== SYNTAX +== SYNOPSIS -hal_realtime_type_t hal_get_realtime_type() +[source,c] +---- +#include -== RETURN VALUE +hal_realtime_type_t hal_get_realtime_type(); +---- + +== DESCRIPTION -*hal_get_realtime_type* returns the type of the running realtime system or a HAL status code on failure. +Retrieve the realtype type of the LinuxCNC instance currently running. -For uspace, this returns *REALTIME_TYPE_UNINITIALIZED* if *rtapi_app* is not running. It is safe to assume -this never happens in realtime components. But userspace components can be loaded without *rtapi_app* being -started. +For uspace, this returns *REALTIME_TYPE_UNINITIALIZED* if *rtapi_app* is not running. +It is safe to assume this never happens in realtime components. +But userspace components can be loaded without *rtapi_app* being started. For rtai, this always returns *REALTIME_TYPE_RTAI*. + +== RETURN VALUE + +Returns the type of the running realtime system. Returns *-EFAULT* if HAL is not initialized. + +== SEE ALSO + +rtapi(3) diff --git a/docs/src/man/man3/hal_get_s.3.adoc b/docs/src/man/man3/hal_get_s.3.adoc new file mode 100644 index 00000000000..16deac60165 --- /dev/null +++ b/docs/src/man/man3/hal_get_s.3.adoc @@ -0,0 +1,119 @@ +:manvolnum: 3 + += hal_get_s(3) + +== NAME + +hal_get_s, hal_getref_s - Get HAL signal value and information + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_get_s(hal_query_t *query, hal_query_cb callback, void *arg); +int hal_getref_s(hal_query_t *query); +---- + +== ARGUMENTS + +query:: + The query structure containing the data to search for and returns all data found. + +callback:: + The callback function to invoke when the data has been found or NULL if no callback is required. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_get_s()* function will retrieve the value of a signal, including its data reference. +The _query_ structure should be set to zero before the call, except for the fields noted here. + +The _query.name_ must be set to the name of the signal you want to get. + +You can further limit the search by setting _query.sig.type_ to the HAL type you want to find. +If the signal is found, but has a different type, then *-EEXIST* is returned. + +The _callback_ is called with all fields set appropriately, including value and data reference. +You must to demultiplex the _query.sig.value_ according to the _query.sig.type_ field. + +The *hal_getref_s()* function will only retrieve the data reference of the signal. +No callback is used and no value is retrieved. +All query fields, expect _query.sig.value_ are set upon return. +The *hal_getref_s()* function is preferable if you do not need the actual signal, like testing for existence. + +If found, both *hal_get_s()* and *hal_getref_s()* set the _query.name_ field to the actual live signal name. +Also, both functions set _query.qtype_ to `HAL_QTYPE_SIGNAL`. + +== RETURN VALUE + +Both functions return zero (0) on success. +The return value of the _callback_ is returned if it got called. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The signal does not exist. +-EEXIST:: The signal exists but is of different type (*hal_get_s()* only). +-EIO:: The internal data pointer is missing. +-EBADF:: An invalid type was detected. + +== EXAMPLES + +[source,c] +---- +int have_s(const char *signame) +{ + hal_query_t query = {}; + query.name = signame; + int rv = hal_getref_s(&query); + + if(-ENOENT == rv) + return 0; // Does not exist + + if(0 == rv) + return 1; // Does exist + + return rv; // An error occured +} +---- + +[source,c] +---- +int print_s_val(const char *signame) +{ + hal_query_t query = {}; + query.name = signame; + + int rv = hal_get_s(&query, NULL, NULL); + + if(-ENOENT == rv) { + printf("%s: not found\n", signame); + } else if(0 != rv) { + return rv; // Let upstream handle any errors + } + + printf("%s (%s): ", signame, query.sig.writers ? "driven" : "not driven"); + + switch(query.sig.type) { + case HAL_BOOL: printf("%s\n", query.sig.value.b ? "true" : "false"); break; + case HAL_REAL: printf("%f\n", query.sig.value.r); break; + case HAL_SINT: printf("%ld\n", query.sig.value.s); break; + case HAL_UINT: printf("%lu\n", query.sig.value.u); break; + default: printf("unsupported value type %d\n", (int)query.sig.type); break; + } + + return 0; +} +---- + +== SEE ALSO + +hal_query_t(3), hal_set_s(3) diff --git a/docs/src/man/man3/hal_getter.3.adoc b/docs/src/man/man3/hal_getter.3.adoc new file mode 100644 index 00000000000..b949ef5cf95 --- /dev/null +++ b/docs/src/man/man3/hal_getter.3.adoc @@ -0,0 +1,42 @@ +:manvolnum: 3 + += hal_getter(3) + +== NAME + +hal_getter, hal_get_bool, hal_get_real, hal_get_sint, hal_get_uint, +hal_get_si32, hal_get_ui32, hal_get_si32_clamped, hal_get_ui32_clamped - HAL pin and param data reader + +== SYNOPSIS + +[source,c] +---- +#include + +rtapi_bool hal_get_bool(hal_bool_t refp); +rtapi_real hal_get_real(hal_real_t refp); +rtapi_sint hal_get_sint(hal_sint_t refp); +rtapi_uint hal_get_uint(hal_uint_t refp); + +rtapi_s32 hal_get_si32(hal_sint_t refp); +rtapi_u32 hal_get_ui32(hal_uint_t refp); +rtapi_s32 hal_get_si32_clamped(hal_sint_t refp); +rtapi_u32 hal_get_ui32_clamped(hal_uint_t refp); +---- + +== ARGUMENTS + +refp:: + Pin, param or signal data reference. + +== DESCRIPTION + +The **hal_get_*()** family of functions will get the value of a pin, param or signal from its data reference. + +Reading 32-bit values normally truncates the value from the underlying storage. +The *hal_get_si32_clamped()* and *hal_get_ui32_clamped()* functions will clamp the read value based on type. +The ranges are `RTAPI_INT32_MIN`...`RTAPI_INT32_MAX` for signed and `0`...`RTAPI_UINT32_MAX` for unsigned values. + +== SEE ALSO + +hal_setter(3), hal_type_t(3), hal_pin_new(3), hal_param_new(3) diff --git a/docs/src/man/man3/hal_init.3.adoc b/docs/src/man/man3/hal_init.3.adoc index 83d5602a816..f6d7a95e525 100644 --- a/docs/src/man/man3/hal_init.3.adoc +++ b/docs/src/man/man3/hal_init.3.adoc @@ -1,24 +1,32 @@ +:manvolnum: 3 + = hal_init(3) == NAME hal_init - Sets up HAL and RTAPI -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include -int hal_init(const char* _modname_) +int hal_init(const char *modname); +---- == ARGUMENTS +[horizontal] modname:: The name of this HAL module. == DESCRIPTION -*hal_init* sets up HAL and RTAPI. It must be called by any module -that intends to use the API, before any other RTAPI calls. +The *hal_init()* function sets up HAL and RTAPI. +It must be called by any module that intends to use the API, before any other RTAPI calls. -_modname_ must point to a string that identifies the module. +The _modname_ argument must point to a string that identifies the module. The string may be no longer than *HAL_NAME_LEN* characters. == REALTIME CONSIDERATIONS @@ -27,6 +35,17 @@ Call only from within non-realtime or init/cleanup code, not from realtime tasks == RETURN VALUE -On success, returns a positive integer module ID, which is used for -subsequent calls to HAL and rtapi APIs. On failure, returns a HAL error -code. +Returns a positive non-zero integer component ID on success. +The component ID is used for subsequent calls to HAL and rtapi APIs. +On failure, returns a negative errno value: + +[horizontal] +-EINVAL:: The name argument was too long. +-EEXIST:: The component name already exists. +-EMFILE:: Too many modules (rtapi error). +-ENOMEM:: Failed to allocate memory for component registration. +-EPROTO:: HAL data version mismatch. + +== SEE ALSO + +hal_exit(3) diff --git a/docs/src/man/man3/hal_init_funct_to_thread.3.adoc b/docs/src/man/man3/hal_init_funct_to_thread.3.adoc new file mode 100644 index 00000000000..9e44a77bb4b --- /dev/null +++ b/docs/src/man/man3/hal_init_funct_to_thread.3.adoc @@ -0,0 +1,65 @@ +:manvolnum: 3 + += hal_init_funct_to_thread(3) + +== NAME + +hal_init_funct_to_thread - cause an initialization function to be executed at the start of the thread + +== SYNOPSIS + +[source,c] +---- +#include + +int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, int position); +---- + +== ARGUMENTS + +funct_name:: + The name of the function. +thread_name:: + The name of the thread. +position:: + The desired location within the thread. + This determines the init order of the running the functions in the thread at startup. + A positive number indicates the desired location as measured from the beginning of the thread. + A negative number indicated the desired location as measured from the end. + A value of +1 means this function will become the first one to run, +5 means it will be the fifth one to run. + A value of -2 means it will be next to last, and -1 means it will be last. + Zero (0) is an illegal position value. + +== DESCRIPTION + +The *hal_init_funct_to_thread()* function registers _funcname_ to run exactly once in the realtime context of _thread_name_. +Init functions run before the thread executes any cyclic (addf-registered) function. +The init list is invoked in a dedicated "special cycle" the first time the thread observes `threads_running == 1`. +The cyclic function list is skipped during that cycle. +After the init list returns, the thread's period is re-anchored. +The next cyclic cycle wakes one full period later. +This avoids both spurious "unexpected realtime delay" and assures a clean starting boundary for long/slow init functions. + +Calls made to *hal_init_funct_to_thread()* after the init cycle has already run fail with -EALREADY. + +== RETURN VALUE + +Returns zero (0) on success. +Returns a negative errno code on failure: + +[horizontal] +-EPERM:: HAL is config locked. +-EINVAL:: An invalid argument was passed. +-EFAULT:: The shared memory was not mapped. +-ENOENT:: The function or thread does not exist. +-EALREADY:: if the thread is already running. +-ENOMEM:: Failed to allocate memory for function registration. + + +== REALTIME CONSIDERATIONS + +Call only from realtime init code, not from other realtime or non-realtime code. + +== SEE ALSO + +hal_add_funct_to_thread(3), hal_thread_new(3), hal_export_funct(3) diff --git a/docs/src/man/man3/hal_list_comp.3.adoc b/docs/src/man/man3/hal_list_comp.3.adoc new file mode 100644 index 00000000000..9a1b9231af1 --- /dev/null +++ b/docs/src/man/man3/hal_list_comp.3.adoc @@ -0,0 +1,89 @@ +:manvolnum: 3 + += hal_list_comp(3) + +== NAME + +hal_list_comp - Iterate HAL components + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_comp(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure that returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_comp()* function will iterate all registered components and call the _callback_ for each. +The _query_ structure should be set to zero before the call. + +The _callback_ is called with all fields set appropriately. +The _query.qtype_ is set to `HAL_QTYPE_COMP`. + +The iteration continues until no more components are available or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_comp()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. + +== EXAMPLES + +[source,c] +---- +static int print_comps_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + printf("%s(%d) %s %d %s (%s)\n", + query->name, + query->comp.comp_id, + query->comp.type == HAL_COMP_TYPE_REALTIME ? "RT" : "User", + query->comp.pid, + query->comp.ready ? "ready" : "notready", + query->comp.insmod ? query->comp.insmod : ""); + } + return 0; // Keep on going +} + +// Print components that match a pattern +int print_comps(const char *pattern) +{ + hal_query_t query = {}; + + int rv = hal_list_comp(&query, print_comps_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3) diff --git a/docs/src/man/man3/hal_list_funct.3.adoc b/docs/src/man/man3/hal_list_funct.3.adoc new file mode 100644 index 00000000000..7803e28208c --- /dev/null +++ b/docs/src/man/man3/hal_list_funct.3.adoc @@ -0,0 +1,88 @@ +:manvolnum: 3 + += hal_list_funct(3) + +== NAME + +hal_list_funct - Iterate HAL functions + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_funct(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure that returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_funct()* function will iterate all registered components and call the _callback_ for each. +The _query_ structure should be set to zero before the call. + +The _callback_ is called with all fields set appropriately. +The _query.qtype_ is set to `HAL_QTYPE_FUNCT`. + +The iteration continues until no more components are available or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_comp()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. + +== EXAMPLES + +[source,c] +---- +static int print_functs_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + printf("%s %s(%d) %d %s\n", + query->name, + query->funct.comp, + query->funct.comp_id, + query->funct.users, + query->funct.reentrant ? "reentrant" : "non-reentrant"); + } + return 0; // Keep on going +} + +// Print functions that match a pattern +int print_functs(const char *pattern) +{ + hal_query_t query = {}; + + int rv = hal_list_funct(&query, print_functs_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3) diff --git a/docs/src/man/man3/hal_list_p.3.adoc b/docs/src/man/man3/hal_list_p.3.adoc new file mode 100644 index 00000000000..c387310ddad --- /dev/null +++ b/docs/src/man/man3/hal_list_p.3.adoc @@ -0,0 +1,104 @@ +:manvolnum: 3 + += hal_list_p(3) + +== NAME + +hal_list_p - Iterate HAL pins and params + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_p(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure containing the data to search for and returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_p()* function will iterate all registered pins and param and call the _callback_ for each. +The _query_ structure should be set to zero before the call, except for the fields noted here. + +You can enforce to look exclusively for a pin or param by setting _query.qtype_ before the call to: + +* `0` - look for either pin or param +* `HAL_QTYPE_PIN` - only look for a pin +* `HAL_QTYPE_PARAM` - only look for a param + +Note that both pins and params share one namespace and cannot overlap. + +The _callback_ is called with all fields set appropriately, including value and data reference. +The _query.qtype_ is set to `HAL_QTYPE_PIN` or `HAL_QTYPE_PARAM` according to the item found. +You must demultiplex the _query.pp.value_ and _query.pp.ref_ according to the _query.pp.type_ field in the callback function. + +The iteration continues until no more pins or params are available or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_p()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-EBADF:: An invalid type was detected. + +== EXAMPLES + +[source,c] +---- +static int print_pins_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + printf("%s: ", query->name); + switch(query->pp.type) { + case HAL_BOOL: printf("%s\n", query->pp.value.b ? "true" : "false"); break; + case HAL_REAL: printf("%f\n", query->pp.value.r); break; + case HAL_SINT: printf("%ld\n", query->pp.value.s); break; + case HAL_PORT: + case HAL_UINT: printf("%lu\n", query->pp.value.u); break; + default: printf("unsupported value type %d\n", (int)query->pp.type); break; + } + } + return 0; // Keep on going +} + +// Print only pins that match a pattern +int print_pins(const char *pattern) +{ + hal_query_t query = {}; + query.qtype = HAL_QTYPE_PIN; + + int rv = hal_list_p(&query, print_pins_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3), +hal_list_s(3), hal_list_p_s(3), +hal_get_p(3) diff --git a/docs/src/man/man3/hal_list_p_s.3.adoc b/docs/src/man/man3/hal_list_p_s.3.adoc new file mode 100644 index 00000000000..e45def69578 --- /dev/null +++ b/docs/src/man/man3/hal_list_p_s.3.adoc @@ -0,0 +1,104 @@ +:manvolnum: 3 + += hal_list_p_s(3) + +== NAME + +hal_list_p_s - Iterate HAL pins connected to a specific signal + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_p_s(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure containing the data to search for and returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_p_s()* function will iterate all pins connected to a specific signal and call the _callback_ for each. +The _query_ structure should be set to zero before the call, except the _query.name_ field. +The _query.name_ must be set to the signal to search for. + +The _callback_ is called with all fields set appropriately, including value and data reference. +The _query.qtype_ is set to `HAL_QTYPE_PIN` for each pin found. +You must demultiplex the _query.pp.value_ and _query.pp.ref_ according to the _query.pp.type_ field in the callback function. +However, the pin type is always the same as the signal type or they could not be connected. +If you know the signal type, then you could use that for the pins too. + +The iteration continues until no more connected pins are found or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_p_s()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The signal is not found. +-EBADF:: An invalid type was detected. + +== EXAMPLES + +[source,c] +---- +static int print_sigpins_cb(hal_query_t *query, void *arg) +{ + (void)arg; // Not used in this example + + printf("%s: %s: ", query->pp.signal, query->name); + if(HAL_OUT == query->pp.dir) + printf("out: "); + else if(HAL_IN == query->pp.dir) + printf("in : "); + else + printf("io : "); + switch(query->pp.type) { + case HAL_BOOL: printf("%s\n", query->pp.value.b ? "true" : "false"); break; + case HAL_REAL: printf("%f\n", query->pp.value.r); break; + case HAL_SINT: printf("%ld\n", query->pp.value.s); break; + case HAL_PORT: + case HAL_UINT: printf("%lu\n", query->pp.value.u); break; + default: printf("unsupported value type %d\n", (int)query->pp.type); break; + } + return 0; // Keep on going +} + +// Print only pins that match a pattern +int print_sigpins(const char *signame) +{ + hal_query_t query = {}; + query.name = signame; + + int rv = hal_list_p_s(&query, print_sigpins_cb, NULL); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3), +hal_list_p(3), hal_list_s(3), +hal_get_p(3), hal_get_s(3) diff --git a/docs/src/man/man3/hal_list_s.3.adoc b/docs/src/man/man3/hal_list_s.3.adoc new file mode 100644 index 00000000000..960c49bf811 --- /dev/null +++ b/docs/src/man/man3/hal_list_s.3.adoc @@ -0,0 +1,95 @@ +:manvolnum: 3 + += hal_list_s(3) + +== NAME + +hal_list_s - Iterate HAL signals + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_s(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure that returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_s()* function will iterate all registered signals and call the _callback_ for each. +The _query_ structure should be set to zero before the call. + +The _callback_ is called with all fields set appropriately, including value and data reference. +The _query.qtype_ is set to `HAL_QTYPE_SIGNAL`. +You must demultiplex the _query.sig.value_ and _query.sig.ref_ according to the _query.sig.type_ field in the callback function. + +The iteration continues until no more signals are available or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_s()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-EBADF:: An invalid type was detected. + +== EXAMPLES + +[source,c] +---- +static int print_sigs_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + printf("%s (%s): ", query->name, query->sig.writers ? "driven" : "not driven"); + switch(query->sig.type) { + case HAL_BOOL: printf("%s\n", query->sig.value.b ? "true" : "false"); break; + case HAL_REAL: printf("%f\n", query->sig.value.r); break; + case HAL_SINT: printf("%ld\n", query->sig.value.s); break; + case HAL_UINT: printf("%lu\n", query->sig.value.u); break; + /* case HAL_PORT: could also happen, but that is left to the reader */ + default: printf("unsupported value type %d\n", (int)query->sig.type); break; + } + } + return 0; // Keep on going +} + +// Print signals that match a pattern +int print_sigs(const char *pattern) +{ + hal_query_t query = {}; + + int rv = hal_list_s(&query, print_sigs_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3), +hal_list_p(3), hal_list_p_s(3), +hal_get_s(3) diff --git a/docs/src/man/man3/hal_list_thread.3.adoc b/docs/src/man/man3/hal_list_thread.3.adoc new file mode 100644 index 00000000000..60885ce5ec3 --- /dev/null +++ b/docs/src/man/man3/hal_list_thread.3.adoc @@ -0,0 +1,129 @@ +:manvolnum: 3 + += hal_list_thread(3) + +== NAME + +hal_list_thread - Iterate HAL threads and their functions + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_list_thread(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure that returns all data found. + +callback:: + The callback function to invoke for each signal found. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_list_thread()* function will iterate all registered components and call the _callback_ for each. +The _query_ structure should be set to zero before the call, except for the _query.qtype_ field. + +The _query_qtype_ field can be set to: + +* `0` or `HAL_QTYPE_THREAD` - to iterate only threads +* `HAL_QTYPE_THREAD_FUNCT` - to iterate threads and the functions of each thread + +The _callback_ is called with all fields set appropriately. +The _query.qtype_ is set to `HAL_QTYPE_THREAD` when the callback is regarding a thread's information. +The _query.qtype_ is set to `HAL_QTYPE_THREAD_FUNCT` when the callback is regarding a thread's function information. +For functions, fields _query.thread.functidx_, _query.thread.funct_ and _query.thread.is_init_ are set. + +Iteration using `HAL_QTYPE_THREAD_FUNCT` will first invoke the _callback_ with _query.qtype_ set to `HAL_QTYPE_THREAD` to indicate the start of a new thread. +Then, if the thread contains functions, subsequent invocations will have _query.qtype_ set to `HAL_QTYPE_THREAD_FUNCT` until no more functions are in that thread. + +The iteration continues until no more components are available or the _callback_ returns non-zero. +You can return a positive value from the _callback_ to signal termination of iteration without triggering an error. +The return value from the _callback_ is returned from the *hal_list_comp()* function as is. + +== RETURN VALUE + +Returns zero (0) on success. +The return value of the _callback_ is returned if it was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. + +== EXAMPLES + +[source,c] +---- +static int print_threadfuncts_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + if(HAL_QTYPE_THREAD == query->qtype) { + // Thread callback + printf("%s %s(%d) %ld\n", query->name, + query->thread.comp, query->thread.comp_id, query->thread.period); + } else { + // Thread function callback + printf("--> %d %s%s\n", query->thread.functidx, + query->thread.funct, query->thread.is_init ? " (init)" : ""); + } + } + return 0; // Keep on going +} + +// Print threads and functions that match a pattern +int print_threadfuncts(const char *pattern) +{ + hal_query_t query = {}; + query.qtype = HAL_QTYPE_THREAD_FUNCT; + + int rv = hal_list_thread(&query, print_threadfuncts_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +[source,c] +---- +static int print_threads_cb(hal_query_t *query, void *arg) +{ + const char *pattern = (const char *)arg; + + if(!fnmatch(pattern, query->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + printf("%s %s(%d) %ld\n", query->name, + query->thread.comp, query->thread.comp_id, query->thread.period); + } + return 0; // Keep on going +} + +// Print threads that match a pattern +int print_threads(const char *pattern) +{ + hal_query_t query = {}; + query.qtype = HAL_QTYPE_THREAD; + + int rv = hal_list_thread(&query, print_threads_cb, (void *)pattern); + + if(0 != rv) + printf("Iteration failure: %s", hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3) diff --git a/docs/src/man/man3/hal_malloc.3.adoc b/docs/src/man/man3/hal_malloc.3.adoc index 7d0e8b82a39..ef3c4d4ff0d 100644 --- a/docs/src/man/man3/hal_malloc.3.adoc +++ b/docs/src/man/man3/hal_malloc.3.adoc @@ -1,12 +1,19 @@ +:manvolnum: 3 + = hal_malloc(3) == NAME hal_malloc - Allocate space in the HAL shared memory area -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include -void *hal_malloc(long int _size_) +void *hal_malloc(long int size); +---- == ARGUMENTS @@ -15,19 +22,18 @@ size:: == DESCRIPTION -*hal_malloc* allocates a block of memory from the main HAL shared memory -area. It should be used by all components to allocate memory for HAL -pins and parameters. It allocates `size' bytes, and returns a pointer to -the allocated space, or NULL (0) on error. The returned pointer will be -properly aligned for any type HAL supports. A component should allocate -during initialization all the memory it needs. +The *hal_malloc()* function allocates a block of memory from the main HAL shared memory area. +It should be used by all components to allocate memory for HAL pins and parameters. +It allocates _size_ bytes, and returns a pointer to the allocated space, or NULL (0) on error. +The returned pointer will be properly aligned for any type HAL supports. +A component should allocate during initialization all the memory it needs. -The allocator is very simple, and there is no `free'. The entire HAL -shared memory area is freed when the last component calls *hal_exit*. +The allocator is very simple, and there is no `free'. +The entire HAL shared memory area is freed when the last component calls hal_exit(3). This means that if you continuously install and remove one component while other components are present, you eventually will fill up the -shared memory and an install will fail. Removing all components -completely clears memory and you start fresh. +shared memory and an install will fail. +Removing all components and shared memory mappings completely clears memory and you start fresh. == RETURN VALUE diff --git a/docs/src/man/man3/hal_param_alias.3.adoc b/docs/src/man/man3/hal_param_alias.3.adoc index ef112ca0728..b870dfa828e 100644 --- a/docs/src/man/man3/hal_param_alias.3.adoc +++ b/docs/src/man/man3/hal_param_alias.3.adoc @@ -1,12 +1,19 @@ +:manvolnum: 3 + = hal_param_alias(3) == NAME hal_param_alias - create an alternate name for a param -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include -int *hal_param_alias*(const char **original_name*, const char **alias*); +int hal_param_alias(const char original_name, const char alias); +---- == ARGUMENTS @@ -18,7 +25,7 @@ alias:: == DESCRIPTION A param may have two names: the original name -(the one that was passed to a *hal_param_new* function) and an alias. +(the one that was passed to a hal_param_new(3) function) and an alias. Usually, aliases are for the convenience of users and should be created and destroyed via halcmd. However, in some cases it is sensible to create aliases directly in a component. diff --git a/docs/src/man/man3/hal_param_new-legacy.3.adoc b/docs/src/man/man3/hal_param_new-legacy.3.adoc new file mode 100644 index 00000000000..7f9e4bcae64 --- /dev/null +++ b/docs/src/man/man3/hal_param_new-legacy.3.adoc @@ -0,0 +1,62 @@ +:manvolnum: 3 + += hal_param_new-legacy(3) + +== NAME + +hal_param_new-legacy, hal_param_bit_new-legacy, hal_param_float_new-legacy, hal_param_u32_new-legacy, +hal_param_s32_new-legacy, hal_param_bit_newf-legacy, hal_param_float_newf-legacy, hal_param_u32_newf-legacy, +hal_param_s32_newf-legacy - creates a HAL parameter + +== SYNTAX + +int hal_param_bit_new(const char* _name_, hal_param_dir_t _dir_, hal_bit_t* _data_addr_, int _comp_id_) + +int hal_param_float_new(const char* _name_, hal_param_dir_t _dir_, hal_float_t* _data_addr_, int _comp_id_) + +int hal_param_u32_new(const char* _name_, hal_param_dir_t _dir_, hal_u32_t* _data_addr_, int _comp_id_) + +int hal_param_s32_new(const char* _name_, hal_param_dir_t _dir_, hal_s32_t* _data_addr_, int _comp_id_) + +int hal_param_bit_newf(hal_param_dir_t _dir_, hal_bit_t* _data_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_param_float_newf(hal_param_dir_t _dir_, hal_float_t* _data_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_param_u32_newf(hal_param_dir_t _dir_, hal_u32_t * _data_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_param_s32_newf(hal_param_dir_t _dir_, hal_s32_t * _data_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_param_new(const char* _name_, hal_type_t _type_, hal_param_dir_t _dir_, void* _data_addr_, int _comp_id_) + +== ARGUMENTS + +_name_:: + The name to give to the created parameter. +_dir_:: + The direction of the parameter, from the viewpoint of the component. + It may be one of *HAL_RO*, or *HAL_RW*. + A component may assign a value to any parameter, + but other programs (such as halcmd) may only assign a value to a parameter that is *HAL_RW*. +_data_addr_:: + The address of the data, which must lie within memory allocated by *hal_malloc*. +_comp_id_:: + A HAL component identifier returned by an earlier call to *hal_init*. +_fmt, ..._:: + A printf-style format string and arguments. +_type_:: + The type of the parameter, as specified in *hal_type_t(3)*. + +== DESCRIPTION + +The *hal_param_new* family of functions create a new _param_ object. + +There are functions for each of the data types that the HAL supports. +Pins may only be linked to signals of the same type. + +== RETURN VALUE + +Returns a HAL status code. + +== SEE ALSO + +hal_type_t(3) diff --git a/docs/src/man/man3/hal_param_new.3.adoc b/docs/src/man/man3/hal_param_new.3.adoc index 621b28a6da2..436ed032c59 100644 --- a/docs/src/man/man3/hal_param_new.3.adoc +++ b/docs/src/man/man3/hal_param_new.3.adoc @@ -4,57 +4,50 @@ == NAME -hal_param_new, hal_param_bit_new, hal_param_float_new, hal_param_u32_new, hal_param_s32_new, hal_param_bit_newf, hal_param_float_newf, hal_param_u32_newf, hal_param_s32_newf - creates a HAL parameter +hal_param_new, hal_param_new_bool, hal_param_new_real, hal_param_new_sint, hal_param_new_uint - creates a HAL parameter -== SYNTAX +== SYNOPSIS -int hal_param_bit_new(const char* _name_, hal_param_dir_t _dir_, hal_bit_t* _data_addr_, int _comp_id_) +[source,c] +---- +#include -int hal_param_float_new(const char* _name_, hal_param_dir_t _dir_, hal_float_t* _data_addr_, int _comp_id_) - -int hal_param_u32_new(const char* _name_, hal_param_dir_t _dir_, hal_u32_t* _data_addr_, int _comp_id_) - -int hal_param_s32_new(const char* _name_, hal_param_dir_t _dir_, hal_s32_t* _data_addr_, int _comp_id_) - -int hal_param_bit_newf(hal_param_dir_t _dir_, hal_bit_t* _data_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_param_float_newf(hal_param_dir_t _dir_, hal_float_t* _data_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_param_u32_newf(hal_param_dir_t _dir_, hal_u32_t * _data_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_param_s32_newf(hal_param_dir_t _dir_, hal_s32_t * _data_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_param_new(const char* _name_, hal_type_t _type_, hal_param_dir_t _dir_, void* _data_addr_, int _comp_id_) +int hal_param_new_bool(int comp_id, hal_pdir_t dir, hal_bool_t *param_ptr, rtapi_bool dflt, const char *fmt, ...); +int hal_param_new_real(int comp_id, hal_pdir_t dir, hal_real_t *param_ptr, rtapi_real dflt, const char *fmt, ...); +int hal_param_new_sint(int comp_id, hal_pdir_t dir, hal_sint_t *param_ptr, rtapi_sint dflt, const char *fmt, ...); +int hal_param_new_uint(int comp_id, hal_pdir_t dir, hal_uint_t *param_ptr, rtapi_uint dflt, const char *fmt, ...); +---- == ARGUMENTS -_name_:: - The name to give to the created parameter. -_dir_:: +comp_id:: + A HAL component identifier returned by an earlier call to hal_init(3). +dir:: The direction of the parameter, from the viewpoint of the component. - It may be one of *HAL_RO*, or *HAL_RW*. + It may be one of `HAL_RO`, or `HAL_RW`. A component may assign a value to any parameter, - but other programs (such as halcmd) may only assign a value to a parameter that is *HAL_RW*. -_data_addr_:: - The address of the data, which must lie within memory allocated by *hal_malloc*. -_comp_id_:: - A HAL component identifier returned by an earlier call to *hal_init*. -_fmt, ..._:: + but other programs (such as halcmd) may only assign a value to a parameter that is `HAL_RW`. +param_ptr:: + The address of the opaque param data storage reference, which must lie within memory allocated by hal_malloc(3). +dflt:: + The default assigned parameter value when the param is created. +fmt, ...:: A printf-style format string and arguments. -_type_:: - The type of the parameter, as specified in *hal_type_t(3)*. == DESCRIPTION -The *hal_param_new* family of functions create a new _param_ object. +The **hal_param_new_*()** family of functions create a new _param_ object. There are functions for each of the data types that the HAL supports. -Pins may only be linked to signals of the same type. +Parameters cannot be linked to signals. +They serve as static configuration and informational status for LinuxCNC. == RETURN VALUE -Returns a HAL status code. +Returns zero (0) on success, or a negative errno value on failure. == SEE ALSO -hal_type_t(3) +hal_pin_new(3), +hal_type_t(3), hal_pdir_t(3), +hal_getter(3), hal_setter(3) diff --git a/docs/src/man/man3/hal_parport.3.adoc b/docs/src/man/man3/hal_parport.3.adoc index ba31d09d640..6b0466b408d 100644 --- a/docs/src/man/man3/hal_parport.3.adoc +++ b/docs/src/man/man3/hal_parport.3.adoc @@ -1,21 +1,27 @@ +:manvolnum: 3 + = hal_parport(3) == NAME hal_parport - portable access to PC-style parallel ports -== SYNTAX +== SYNOPSIS + +Obsolete: Please use the rtapi_parport(3) interface instead. -.... +[source,c] +---- #include "hal_parport.h" -int hal_parport_get(int _comp_id_, hal_parport_t* _port_, unsigned short _base_, unsigned short _base_hi_, unsigned int _modes_) -void hal_parport_release(hal_parport_t* _port_) -.... + +int hal_parport_get(int comp_id, hal_parport_t *port, unsigned short base, unsigned short base_hi, unsigned int modes); +void hal_parport_release(hal_parport_t *port); +---- == ARGUMENTS comp_id:: - A HAL component identifier returned by an earlier call to *hal_init*. + A HAL component identifier returned by an earlier call to hal_init(3). port:: A pointer to a hal_parport_t structure. base:: @@ -33,7 +39,7 @@ modes:: == DESCRIPTION *hal_parport_get* allocates a parallel port for exclusive use of the named HAL component. -The port must be released with *hal_parport_release* before the component exits with *hal_exit*. +The port must be released with *hal_parport_release()* before the component exits with hal_exit(3). == HIGH ADDRESS PROBING @@ -44,14 +50,15 @@ If no high address is detected, port->base_hi is 0. == PARPORT STRUCTURE -.... +[source,c] +---- typedef struct { unsigned short base; unsigned short base_hi; .... // and further unspecified fields } hal_parport_t; -.... +---- == RETURN VALUE diff --git a/docs/src/man/man3/hal_pdir_t.3.adoc b/docs/src/man/man3/hal_pdir_t.3.adoc new file mode 100644 index 00000000000..26002849eed --- /dev/null +++ b/docs/src/man/man3/hal_pdir_t.3.adoc @@ -0,0 +1,38 @@ +:manvolnum: 3 + += hal_pdir_t(3) + +== NAME + +hal_pdir_t - HAL data direction enumeration + +== DESCRIPTION + +typedef enum *hal_pdir_t*;:: + HAL_IN;; + An input pin. + The owning component can only read the pin. + Multiple input pins can be connected to the same signal. + HAL_OUT;; + An output pin. + The owning component can read and write the pin. + Only one (1) output pin can be connected to a signal. + HAL_IO;; + A bidirectional pin. + The owning component can read and write the pin. + Multiple bidirectional pins can be connected to the same signal. + It must be ensured that _at least_ one component will be writing data onto the signal. + HAL_RW;; + A bidirectional parameter. + User-space programs can read and write the parameter. + The owning component can read and write the parameter. + Parameters cannot be connected to signals. + HAL_RO;; + An output parameter. + User-space programs can only read the parameter. + The component can read and write the parameter. + Parameters cannot be connected to signals. + +== SEE ALSO + +hal_pin_new(3), hal_param_new(3) diff --git a/docs/src/man/man3/hal_pin_alias.3.adoc b/docs/src/man/man3/hal_pin_alias.3.adoc index fbebffa0c01..382a457d041 100644 --- a/docs/src/man/man3/hal_pin_alias.3.adoc +++ b/docs/src/man/man3/hal_pin_alias.3.adoc @@ -1,12 +1,19 @@ +:manvolnum: 3 + = hal_pin_alias(3) == NAME hal_pin_alias - creates an alternate name for a pin -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include -int *hal_pin_alias*(const char* _original_name_, const char* _alias_); +int hal_pin_alias(const char *original_name, const char *alias); +---- == ARGUMENTS @@ -19,7 +26,7 @@ alias:: == DESCRIPTION A pin may have two names: the original name (the one that was passed to -a *hal_pin_new* function) and an alias. +a hal_pin_new(3) function) and an alias. Usually, aliases are for the convenience of users and should be created and destroyed via halcmd. However, in some cases it is sensible to create aliases directly in a component. diff --git a/docs/src/man/man3/hal_pin_new-legacy.3.adoc b/docs/src/man/man3/hal_pin_new-legacy.3.adoc new file mode 100644 index 00000000000..82a4cbce2a2 --- /dev/null +++ b/docs/src/man/man3/hal_pin_new-legacy.3.adoc @@ -0,0 +1,74 @@ +:manvolnum: 3 + += hal_pin_new-legacy(3) + +== NAME + +hal_pin_new-legacy, hal_pin_bit_new-legacy, hal_pin_float_new-legacy, hal_pin_u32_new-legacy, +hal_pin_s32_new-legacy, hal_pin_port_new-legacy, hal_pin_bit_newf-legacy, +hal_pin_float_newf-legacy, hal_pin_u32_newf-legacy, hal_pin_s32_newf-legacy, +hal_pin_port_newf-legacy - creates a HAL pin + +== SYNTAX + +int hal_pin_bit_new(const char* _name_, hal_pin_dir_t _dir_, hal_bit_t** _data_ptr_addr_, int _comp_id_) + +int hal_pin_float_new(const char* _name_, hal_pin_dir_t _dir_, hal_float_t** _data_ptr_addr_, int _comp_id_) + +int hal_pin_u32_new(const char* _name_, hal_pin_dir_t _dir_, hal_u32_t** _data_ptr_addr_, int _comp_id_) + +int hal_pin_s32_new(const char* _name_, hal_pin_dir_t _dir_, hal_s32_t** _data_ptr_addr_, int _comp_id_) + +int hal_pin_port_new(const char* _name_, hal_pin_dir_t _dir_, hal_port_t** _data_ptr_addr_, int _comp_id_) + +int hal_pin_bit_newf(hal_pin_dir_t _dir_, hal_bit_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_pin_float_newf(hal_pin_dir_t _dir_, hal_float_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_pin_u32_newf(hal_pin_dir_t _dir_, hal_u32_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_pin_s32_newf(hal_pin_dir_t _dir_, hal_s32_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_pin_port_newf(hal_pin_dir_t _dir_, hal_port_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) + +int hal_pin_new(const char* _name_, hal_type_t _type_, hal_pin_dir_t _dir_, void** _data_ptr_addr_, int _comp_id_) + +== ARGUMENTS + +name:: + Name of the pin. +dir:: + The direction of the pin, from the viewpoint of the component. + It may be one of *HAL_IN*, *HAL_OUT*, or *HAL_IO*. + Any number of *HAL_IN* or *HAL_IO* pins may be connected to the same signal, + but at most one *HAL_OUT* pin is permitted. + A component may assign a value to a pin that is *HAL_OUT* or *HAL_IO*, + but may not assign a value to a pin that is *HAL_IN*. +data_ptr_addr:: + The address of the pointer-to-data, which must lie within memory + allocated by *hal_malloc*. +comp_id:: + HAL component identifier returned by an earlier call to *hal_init*. +fmt,:: + printf-style format string and arguments +type:: + The type of the param, as specified in *hal_type_t(3)*. + +== DESCRIPTION + +The *hal_pin_new* family of functions create a new _pin_ object. +Once a pin has been created, it can be linked to a signal object using *hal_link*. +A pin contains a pointer, and the component that owns the pin +can dereference the pointer to access whatever signal is linked to the pin. +(If no signal is linked, it points to a dummy signal.) + +There are functions for each of the data types that the HAL supports. +Pins may only be linked to signals of the same type. + +== RETURN VALUE + +Returns 0 on success, or a negative errno value on failure. + +== SEE ALSO + +hal_type_t(3), hal_link(3) diff --git a/docs/src/man/man3/hal_pin_new.3.adoc b/docs/src/man/man3/hal_pin_new.3.adoc index 3907bffd099..30c3d40437d 100644 --- a/docs/src/man/man3/hal_pin_new.3.adoc +++ b/docs/src/man/man3/hal_pin_new.3.adoc @@ -4,71 +4,65 @@ == NAME -hal_pin_new, hal_pin_bit_new, hal_pin_float_new, hal_pin_u32_new, -hal_pin_s32_new, hal_pin_port_new, hal_pin_bit_newf, -hal_pin_float_newf, hal_pin_u32_newf, hal_pin_s32_newf, -hal_pin_port_newf - creates a HAL pin +hal_pin_new, hal_pin_new_bool, hal_pin_new_real, hal_pin_new_sint, hal_pin_new_uint, hal_pin_new_port - creates a HAL pin -== SYNTAX +== SYNOPSIS -int hal_pin_bit_new(const char* _name_, hal_pin_dir_t _dir_, hal_bit_t** _data_ptr_addr_, int _comp_id_) +[source,c] +---- +#include -int hal_pin_float_new(const char* _name_, hal_pin_dir_t _dir_, hal_float_t** _data_ptr_addr_, int _comp_id_) - -int hal_pin_u32_new(const char* _name_, hal_pin_dir_t _dir_, hal_u32_t** _data_ptr_addr_, int _comp_id_) - -int hal_pin_s32_new(const char* _name_, hal_pin_dir_t _dir_, hal_s32_t** _data_ptr_addr_, int _comp_id_) - -int hal_pin_port_new(const char* _name_, hal_pin_dir_t _dir_, hal_port_t** _data_ptr_addr_, int _comp_id_) - -int hal_pin_bit_newf(hal_pin_dir_t _dir_, hal_bit_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_pin_float_newf(hal_pin_dir_t _dir_, hal_float_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_pin_u32_newf(hal_pin_dir_t _dir_, hal_u32_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_pin_s32_newf(hal_pin_dir_t _dir_, hal_s32_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_pin_port_newf(hal_pin_dir_t _dir_, hal_port_t** _data_ptr_addr_, int _comp_id_, const char* _fmt_, _..._) - -int hal_pin_new(const char* _name_, hal_type_t _type_, hal_pin_dir_t _dir_, void** _data_ptr_addr_, int _comp_id_) +int hal_pin_new_bool(int comp_id, hal_pdir_t dir, hal_bool_t *pin_ptr, rtapi_bool dflt, const char *fmt, ...); +int hal_pin_new_real(int comp_id, hal_pdir_t dir, hal_real_t *pin_ptr, rtapi_real dflt, const char *fmt, ...); +int hal_pin_new_sint(int comp_id, hal_pdir_t dir, hal_sint_t *pin_ptr, rtapi_sint dflt, const char *fmt, ...); +int hal_pin_new_uint(int comp_id, hal_pdir_t dir, hal_uint_t *pin_ptr, rtapi_uint dflt, const char *fmt, ...); +int hal_pin_new_port(int comp_id, hal_pdir_t dir, hal_port_t *pin_ptr, const char *fmt, ...); +---- == ARGUMENTS -name:: - Name of the pin. +comp_id:: + HAL component identifier returned by an earlier call to hal_init(3). dir:: The direction of the pin, from the viewpoint of the component. - It may be one of *HAL_IN*, *HAL_OUT*, or *HAL_IO*. - Any number of *HAL_IN* or *HAL_IO* pins may be connected to the same signal, - but at most one *HAL_OUT* pin is permitted. - A component may assign a value to a pin that is *HAL_OUT* or *HAL_IO*, - but may not assign a value to a pin that is *HAL_IN*. -data_ptr_addr:: - The address of the pointer-to-data, which must lie within memory - allocated by *hal_malloc*. -comp_id:: - HAL component identifier returned by an earlier call to *hal_init*. -fmt,:: - printf-style format string and arguments -type:: - The type of the param, as specified in *hal_type_t(3)*. + It may be one of `HAL_IN`, `HAL_OUT`, or `HAL_IO`. + Any number of `HAL_IN` or `HAL_IO` pins may be connected to the same signal, + but at most one `HAL_OUT` pin is permitted. + A component may assign a value to a pin that is `HAL_OUT` or `HAL_IO`. + Components may not assign a value to a pin that is `HAL_IN`. +pin_ptr:: + The address of the opaque pin data storage reference, which must lie within memory allocated by hal_malloc(3). +dflt:: + The default assigned pin value when the pin is created. +fmt, ...:: + A printf-style format string and arguments == DESCRIPTION -The *hal_pin_new* family of functions create a new _pin_ object. -Once a pin has been created, it can be linked to a signal object using *hal_link*. -A pin contains a pointer, and the component that owns the pin -can dereference the pointer to access whatever signal is linked to the pin. -(If no signal is linked, it points to a dummy signal.) +The **hal_pin_new_*()** family of functions create a new _pin_ object. +The type of the pin corresponds to one of the hal_type_t(3) types. +Once a pin has been created, it can be linked to a signal object using hal_link(3). +A pin contains an opaque reference, which can be dereferenced the appropriate getter/setter. +Pins of type `HAL_IN` only can use the appropriate getter **hal_get_*()**. +Pins of type `HAL_OUT` and `HAL_IO` and use the getter and the setter **hal_set_*()**. +Getting and settin a pin's value will address the value of the signal if the pin is connected. +If no signal is linked, it gets/sets a dummy signal. There are functions for each of the data types that the HAL supports. Pins may only be linked to signals of the same type. +The *hal_pin_new_port()* functions is special in that it does not have a default. +Exact two `HAL_PORT` port pins, one `HAL_IN` and one `HAL_OUT`, must be connected to a `HAL_PORT` type signal. +You cannot call hal_set_p(3) or hal_get_p(3) on a `HAL_PORT` pin. +A call to hal_set_s(3) on the port signal will set the queue size. + == RETURN VALUE -Returns 0 on success, or a negative errno value on failure. +Returns zero (0) on success, or a negative errno value on failure. == SEE ALSO -hal_type_t(3), hal_link(3) +hal_param_new(3), +hal_getter(3), hal_setter(3), +hal_type_t(3), hal_pdir_t(3), +hal_link(3) diff --git a/docs/src/man/man3/hal_port.3.adoc b/docs/src/man/man3/hal_port.3.adoc index 08a0e9aca43..d44d3a561f0 100644 --- a/docs/src/man/man3/hal_port.3.adoc +++ b/docs/src/man/man3/hal_port.3.adoc @@ -1,14 +1,19 @@ +:manvolnum: 3 + = hal_port(3) == NAME -hal_port - a HAL pin type that acts as an asynchronous one way byte -stream +hal_port, hal_port_read, hal_port_peek, hal_port_peek_commit, hal_port_readable, +hal_port_clear, hal_port_write, hal_port_writable, +hal_port_buffer_size - a HAL pin type that acts as an asynchronous one way byte stream == SYNOPSIS -.... +[source,c] +---- #include + bool hal_port_read(hal_port_t port, char* dest, unsigned count); bool hal_port_peek(hal_port_t port, char* dest, unsigned count); bool hal_port_peek_commit(hal_port_t port, unsigned count); @@ -24,7 +29,7 @@ unsigned hal_port_buffer_size(hal_port_t port); void hal_port_wait_readable(hal_port_t** port, unsigned count, sig_atomic_t* stop); void hal_port_wait_writable(hal_port_t** port, unsigned count, sig_atomic_t* stop); #endif -.... +---- == DESCRIPTION @@ -37,66 +42,56 @@ link only a single writer and a single reader. A port also buffers data. Users should determine the proper buffer size based upon their intended application. -=== *hal_port_read* - -Reads count bytes from the port into destination buffer dest. -hal_port_read will read _count_ bytes if and only if _count_ bytes are -available for reading and otherwise it will leave the port unaffected. -Returns true if count bytes were read and false otherwise. This function -should only be called by the component that owns the IN PORT pin. - -=== *hal_port_peek* - -Behaves the same as hal_port_read, however it does not consume bytes -from the HAL port. Repeated calls to hal_port_peek will return the same -data. Returns true if count bytes were read and false otherwise. This -function should only be called by the component that owns the IN PORT -pin. - -=== *hal_port_peek_commit* - -Advances the read position in the port buffer by count bytes. -A hal_port_peek followed by a hal_port_peek_commit would function -equivalently to hal_port_read given the same count value. Returns true -if count readable bytes were skipped and are no longer accessible and -false if no bytes wer skipped. This function should only be called by -the component that owns the IN PORT pin. - -=== *hal_port_readable* - -Returns the number of bytes available for reading from port. It is safe -to call this function from any component. - -=== *hal_port_clear* - -Emptys a given port of all data. hal_port_clear should only be called by -the component that owns the IN PORT pin. - -=== *hal_port_write* - -Writes count bytes from src into the port. Returns true if count bytes -were written and false otherwise. This function should only be called by -the component that owns the OUT PORT pin. - -=== *hal_port_writable* - -Returns the number of bytes that can be written into the port. It is -safe to call this function from any component. - -=== *hal_port_buffer_size* - -Returns the maximum number of bytes that a port can buffer. It is safe -to call this function from any component. - -=== *hal_port_wait_readable* - -Waits until the port has count bytes or more available for reading or -the stop flag is set. - -=== *hal_port_wait_writable* - -Waits until the port has count bytes or more available for writing or -the stop flag is set. +hal_port_read():: + Reads count bytes from the port into destination buffer dest. + A call to *hal_port_read()* will read _count_ bytes if and only if _count_ + bytes are available for reading and otherwise it will leave the port unaffected. + Returns true if count bytes were read and false otherwise. This function + should only be called by the component that owns the IN PORT pin. + +hal_port_peek():: + Behaves the same as *hal_port_read()*, however it does not consume bytes + from the HAL port. Repeated calls to *hal_port_peek()* will return the same + data. Returns true if count bytes were read and false otherwise. This + function should only be called by the component that owns the IN PORT + pin. + +hal_port_peek_commit():: + Advances the read position in the port buffer by count bytes. + A *hal_port_peek()* followed by a *hal_port_peek_commit()* would function + equivalently to *hal_port_read()* given the same count value. Returns true + if count readable bytes were skipped and are no longer accessible and + false if no bytes wer skipped. This function should only be called by + the component that owns the IN PORT pin. + +hal_port_readable():: + Returns the number of bytes available for reading from port. + It is safe to call this function from any component. + +hal_port_clear():: + Emptys a given port of all data. hal_port_clear should only be called by + the component that owns the IN PORT pin. + +hal_port_write():: + Writes count bytes from src into the port. Returns true if count bytes + were written and false otherwise. This function should only be called by + the component that owns the OUT PORT pin. + +hal_port_writable():: + Returns the number of bytes that can be written into the port. + It is safe to call this function from any component. + +hal_port_buffer_size():: + Returns the maximum number of bytes that a port can buffer. + It is safe to call this function from any component. + +hal_port_wait_readable():: + Waits until the port has count bytes or more available for reading or the stop flag is set. + + This function cannot be called from realtime code. + +hal_port_wait_writable():: + Waits until the port has count bytes or more available for writing or the stop flag is set. + + This function cannot be called from realtime code. == ARGUMENTS @@ -124,11 +119,9 @@ that also programs the raster component from Python. == REALTIME CONSIDERATIONS -*hal_port_read*, *hal_port_peek*, *hal_port_peek_commit*, -*hal_port_readable*, *hal_port_clear*, *hal_port_write*, -*hal_port_writable*, *hal_port_buffer_size* may be called from realtime code. +Most **hal_port_*()** functions can be called from realtime code. -*hal_port_wait_writable*, *hal_port_wait_readable* may be called from ULAPI code. +The exceptions are *hal_port_wait_writable()* and *hal_port_wait_readable()*, which may be only called from ULAPI code. == SEE ALSO diff --git a/docs/src/man/man3/hal_query_t.3.adoc b/docs/src/man/man3/hal_query_t.3.adoc new file mode 100644 index 00000000000..eaedc87043e --- /dev/null +++ b/docs/src/man/man3/hal_query_t.3.adoc @@ -0,0 +1,414 @@ +:manvolnum: 3 + += hal_query_t(3) + +== NAME + +hal_query_t - HAL query API and data structure + +== DESCRIPTION + +The HAL query API is an interface to retrieve information about: + +* pins +* params +* signals +* components +* functions +* threads + +Additionally, the query API can set the value of pins, params and signals. +The query API uses a standard structure to capture both input and output. +Most query API functions use a callback function with the following signature: + +[source,c] +---- +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); +---- + +It is important to remember that the HAL mutex is held while the callback function is executing. +You may call other query API functions from within the callback (the HAL mutex is recursive). + +[WARNING] +==== +You should **never** exit your program from within a callback. +Doing so would keep HAL locked and all other programs are forever blocked from performing actions. +Beware of OS signals during callbacks (see signal(2) and signal(7)). + +You should also beware of performing blocking I/O. +Taking a long time in callbacks may be problematic for performance. +It may be better to collect data in the callback and handle the slow operations outside of it. +==== + +A query's details is defined by the query structure; + +[source,c] +---- +typedef struct { + const char *name; + hal_qtype_t qtype; + union { + void *vpval; + const void *cpval; + rtapi_intptr_t ipval; + rtapi_uintptr_t upval; + rtapi_sint sival; + rtapi_uint uival; + } callerdata; + union { + hal_query_pp_t pp; + hal_query_sig_t sig; + hal_query_comp_t comp; + hal_query_funct_t funct; + hal_query_thread_t thread; + }; +} hal_query_t; + +typedef enum { + HAL_QTYPE_ANY = 0, + HAL_QTYPE_PIN, + HAL_QTYPE_PARAM, + HAL_QTYPE_SIGNAL, + HAL_QTYPE_COMP, + HAL_QTYPE_FUNCT, + HAL_QTYPE_THREAD, + HAL_QTYPE_THREAD_FUNCT, +} hal_qtype_t; +---- + +The fields _name_ and _qtype_ are used as a selector. +The user may use the _callerdata_ fields to propagate additional data to the callback. +The _callerdata_ fields are never altered by any query function. + +Data is returned in the individual sub-field. + +[horizontal] +pp:: + Pin and param data. + The _qtype_ field is set to `HAL_QTYPE_PIN` when the data relates to a pin and `HAL_QTYPE_PARAM` for a param. +sig:: + Signal data. + The _qtype_ field is set to `HAL_QTYPE_SIGNAL` +comp:: + Component data. + The _qtype_ field is set to `HAL_QTYPE_COMP` +funct:: + Function data. + The _qtype_ field is set to `HAL_QTYPE_FUNCT` +thread:: + Thread data. + The _qtype_ field is set to `HAL_QTYPE_THREAD` if it was set at call start. + If the _qtype_ was set to `HAL_QTYPE_THREAD_FUNCT`, + then it will alternate between `HAL_QTYPE_THREAD` and `HAL_QTYPE_THREAD_FUNCT`, + depending whether the callback is about the thread or an attached function. + +== QUERY FUNCTIONS + +hal_get_p, hal_getref_p, hal_set_p:: + Retrieve or set the value of a pin or param. + + The value and opaque reference is retrieved with *hal_get_p*. + Only the opaque reference is retrieved with *hal_getref_p* (useful for existence test). + Setting a pin or param can be done with *hal_set_p*. + +hal_get_s, hal_getref_s, hal_set_s:: + Retrieve or set the value of a signal. + + The value and opaque reference is retrieved with *hal_get_s*. + Only the opaque reference is retrieved with *hal_getref_s* (useful for existence test). + Setting a signal can be done with *hal_set_s*. + +hal_list_p:: + Iterate all pins or params registered with HAL. + You can limit the search to pins, params or both. + The pin and param values, including reference, can be accessed in the callback. + +hal_list_s:: + Iterate all signals registered with HAL. + The signal values, including reference, can be accessed in the callback. + +hal_list_p_s:: + Iterate all pins connected to a specific signal. + The pin values, including reference, can be accessed in the callback. + +hal_list_comp:: + Iterate all components registered with HAL + +hal_list_funct:: + Iterate all functions registered with HAL + +hal_list_thread:: + Iterate all threads registered with HAL. + + You can select to iterate the functions attached to a threads while iterating threads. + +== PINS AND PARAMS + +Query data for pins and param is handled by the *hal_query_pp_t* structure: + +[source,c] +---- +typedef struct { + hal_type_t type; + hal_refs_u ref; + hal_query_value_u value; + hal_pdir_t dir; + const char *alias; + const char *signal; + const char *comp; + int comp_id; +} hal_query_pp_t; +---- + +The *hal_query_t* fields _name_ and _qtype_ will be set before the callback is invoked. +The _name_ fields will point to the actual live pin or parameter name. +The _qtype_ field will indicate whether the data contains a pin (`HAL_QTYPE_PIN`) or a param (`HAL_QTYPE_PARAM`). + +[horizontal] +type:: + The pin/param type as described in *hal_type_t(3)*. + + The _type_ field may be used as a selector/filter and set before calling *hal_set_p(3)*, *hal_get_p(3)*. + +ref:: + The opaque reference as described in *hal_refs_u(3)*. + +anchor:hal_query_value_u[]value:: + The value is a union *hal_query_value_u* of supported values, shown below. + The _type_ field indicates which value you should select from the union. + You should make sure to use the proper field. + + Must be set, including _type_ above, before the call to *hal_set_p(3)* when no callback is specified. ++ +[source,c] +---- +typedef union { + rtapi_bool b; + rtapi_sint s; + rtapi_uint u; + rtapi_real r; +} hal_query_value_u; +---- + +dir:: + The direction of the pin or param as described in *hal_pdir_t(3)*. + +alias:: + An pin/param name alias (also know as 'oldname') or NULL if none exists. + +signal:: + Pins only: + Set to the name of the signal the pin is connected to or NULL if not connected. + +comp:: + The name of the owner component of the pin/param. + +comp_id:: + The numerical ID of the owner component of the pin/param. + +== SIGNALS + +Query data for signals is handled by the *hal_query_sig_t* structure: + +[source,c] +---- +typedef struct { + hal_type_t type; + hal_refs_u ref; + hal_query_value_u value; + int writers; + int readers; + int bidirs; +} hal_query_sig_t; +---- + +The *hal_query_t* field _name_ will be set before the callback is invoked. +The _name_ fields will point to the actual live signal name. + +[horizontal] +type:: + The signal type as described in *hal_type_t(3)*. + + The _type_ field may be used as a selector/filter and set before calling *hal_set_s(3)*, *hal_get_s(3)*. + +ref:: + The opaque reference as described in *hal_refs_u(3)*. + +value:: + The value is a union *hal_query_value_u* of supported values. + The _type_ field indicates which value you should select from the union. + You should make sure to use the proper field. + See above under link:#hal_query_value_u[pins and parameters] for details. + + Must be set, including _type_ above, before the call to *hal_set_s(3)* when no callback is specified. + +writers:: + The number of `HAL_OUT` pins connected. + This value is either zero (0) when no `HAL_OUT` pin is connected or one (1) if a `HAL_OUT` pin is connected. + +readers:: + The number of `HAL_IN` pins connected to the signal. + Signals of type `HAL_PORT` can only have one (1) reader. + +bidirs:: + The number of `HAL_IO` pins connected to the signal. + Note that there is no guarantee that a value is ever written to the signal. + Writing bidirectional pins is only by the component's discretion. + +== COMPONENTS + +Query data for components is handled by the *hal_query_comp_t* structure: + +[source,c] +---- +typedef struct { + int comp_id; + hal_comp_type_t type; + int pid; + bool ready; + const char *insmod; +} hal_query_comp_t; +---- + +The *hal_query_t* field _name_ will be set before the callback is invoked. +The _name_ fields will point to the actual live component name. + +[horizontal] +comp_id:: + The component ID assigned to the component (returned by *hal_init(3)*). + +type:: + The component type (`typedef enum hal_comp_type_t`) + HAL_COMP_TYPE_UNKNOWN;; + No additional information is available. + HAL_COMP_TYPE_USER;; + A user-space program's component loaded with `loadusr`. + The _pid_ field will indicate the program's process ID. + HAL_COMP_TYPE_REALTIME;; + A realtime component loaded as a kernel module or uspace realtime application using `loadrt`. + HAL_COMP_TYPE_OTHER;; + An unknown type of component. + This should not happen...famous...last...words. + +pid:: + The process ID of the user-space program that created the component. + +ready:: + True if the component is in the ready state. + +insmod:: + The `loadrt` arguments passed to the realtime module at load time. + User-space programs will have this field set to NULL. + +== FUNCTIONS + +Query data for functions is handled by the *hal_query_funct_t* structure: + +[source,c] +---- +typedef struct { + int comp_id; + const char *comp; + int users; + rtapi_intptr_t arg; + rtapi_intptr_t funct; + bool reentrant; +} hal_query_funct_t; +---- + +The *hal_query_t* field _name_ will be set before the callback is invoked. +The _name_ fields will point to the actual live function name. + +[horizontal] +comp_id:: + The owning component's ID. + This is set by the calls to *hal_export_functf(3)*. + +comp:: + The owning component's name. + +users:: + The number of times the function is in use by one or more threads. + +arg:: + Internal reference to the argument passed to the function when executed. + You cannot dereference this value as it's address belongs to a different process. + +funct:: + Internal reference to the functions location in memory. + You cannot dereference this value as it's address belongs to a different process. + +reentrant:: + Set to true if the function has no static references and can be called twice or more at the same time. + +== THREADS + +Query data for threads is handled by the *hal_query_thread_t* structure: + +[source,c] +---- +typedef struct { + int comp_id; + const char *comp; + int priority; + long int period; + int functidx; + const char *funct; + bool is_init; +} hal_query_thread_t; +---- + +The *hal_query_t* field _name_ will be set before the callback is invoked. +The _name_ fields will point to the actual live thread name. + +[horizontal] +comp_id:: + The owning component's ID. + +comp:: + The owning component's name. + +priority:: + Internal priority of the thread. + +period:: + The cycle time of the thread in nanoseconds. + +functidx:: + Only set if iterating a thread's functions (HAL_QTYPE_THREAD_FUNCT). + + The zero-based call index/sequence of the function as executed by the thread. + +funct:: + Only set if iterating a thread's functions (HAL_QTYPE_THREAD_FUNCT). + + The function name at the _functidx_. + +is_init:: + Only set if iterating a thread's functions (HAL_QTYPE_THREAD_FUNCT). + + Set to true is this is an initialization function in the thread. + See *hal_init_funct_to_thread(3)* for details. + Iterating init functions is only possible if the thread is not running and has never been started. + +== REALTIME CONSIDERATIONS + +The query API functions are not available from realtime. +The HAL library query functions are not exported to realtime modules. +Only non-realtime user-space programs linking to HAL library can use the query functions. + +== RETURN VALUE + +All functions returns zero (0) on success. +A negative errno code is returned when an error is encountered. +The callback's return value is returned verbatim. + +== SEE ALSO + +hal_set_p(3), +hal_set_s(3), +hal_get_p(3), +hal_get_s(3), +hal_getref_p(3), +hal_getref_s(3), +hal_list_p(3), +hal_list_s(3), +hal_list_p_s(3), +hal_list_comp(3), +hal_list_funct(3), +hal_list_thread(3), +hal_comp_by_name(3), +hal_comp_by_id(3), +hal_statistics(3), +hal_type_t(3), +hal_refs_u(3). diff --git a/docs/src/man/man3/hal_ready.3.adoc b/docs/src/man/man3/hal_ready.3.adoc index 4bd61391bd3..5a9a6479918 100644 --- a/docs/src/man/man3/hal_ready.3.adoc +++ b/docs/src/man/man3/hal_ready.3.adoc @@ -1,25 +1,43 @@ +:manvolnum: 3 + = hal_ready(3) == NAME -hal_ready - indicates that this component is ready +hal_ready, hal_unready - Set the operational ready state of the component + +== SYNOPSIS -== SYNTAX +[source,c] +---- +#include -hal_ready(int _comp_id_) +int hal_ready(int comp_id); +int hal_unready(int comp_id); +---- == ARGUMENTS comp_id:: - A HAL component identifier returned by an earlier call to *hal_init*. + A HAL component identifier returned by an earlier call to hal_init(3). == DESCRIPTION -*hal_ready* indicates that this component is ready (has created all its -pins, parameters, and functions). This must be called in any realtime -HAL component before its *rtapi_app_init* exits, and in any non-realtime -component before it enters its main loop. +Calling hal_ready(3) indicates that the component is ready for operation. +Creation of pins, parameters, and functions is not allowed when the component is ready. +This must be called in any realtime HAL component before its rtapi_app_main(3) exits. +In any non-realtime component it should be called before it enters its main loop. + +You can call hal_unready(3) to again allow modifications of pins, params and functions. +This should only be done in non real-time applications. +After the modifications are done, you must call hal_ready(3) again. == RETURN VALUE -Returns a HAL status code. +Returns zero (0) on success, or a negative errno value to indicate the error. + +== SEE ALSO + +rtapi_app_main(3), +hal_init(3), +hal_exit(3) diff --git a/docs/src/man/man3/hal_refs_u.3.adoc b/docs/src/man/man3/hal_refs_u.3.adoc new file mode 100644 index 00000000000..44e36707fbc --- /dev/null +++ b/docs/src/man/man3/hal_refs_u.3.adoc @@ -0,0 +1,32 @@ +:manvolnum: 3 + += hal_refs_u(3) + +== NAME + +hal_refs_u - Combined pin, param and signal opaque data reference + +== DESCRIPTION + +A union of opaque references to all hal_type_t(3) types. +You need to have access to the type enumeration to select the correct union field. + +[source,c] +---- +typedef union { + hal_bool_t b; + hal_sint_t s; + hal_uint_t u; + hal_real_t r; + hal_port_t p; +} hal_refs_u; +---- + +HAL data cannot be read or written directly. +The *hal_refs_u* contains opaque structures that reference a value of the type indicated by the name. +Reading and writing HAL types is performed with getters and setters. + +== SEE ALSO + +hal_query_t(3), +hal_setter(3), hal_getter(3) diff --git a/docs/src/man/man3/hal_set_constructor.3.adoc b/docs/src/man/man3/hal_set_constructor.3.adoc index f1d22100821..59fb56ebd75 100644 --- a/docs/src/man/man3/hal_set_constructor.3.adoc +++ b/docs/src/man/man3/hal_set_constructor.3.adoc @@ -1,17 +1,24 @@ +:manvolnum: 3 + = hal_set_constructor(3) == NAME hal_set_constructor - sets the constructor function for this component -== SYNTAX +== SYNOPSIS + +[source,c] +---- +#include typedef int (*hal_constructor_t)(const char* prefix, const char* arg); -int hal_set_constructor(int _comp_id_, hal_constructor_t _constructor_) +int hal_set_constructor(int comp_id, hal_constructor_t constructor); +---- == ARGUMENTS -_comp_id_:: A HAL component identifier returned by an earlier call to *hal_init*. +_comp_id_:: A HAL component identifier returned by an earlier call to hal_init(3). _prefix_:: The prefix to be given to the pins, parameters, and functions in the new instance. diff --git a/docs/src/man/man3/hal_set_lock.3.adoc b/docs/src/man/man3/hal_set_lock.3.adoc index 9a3a15c2d55..8c92e3def6f 100644 --- a/docs/src/man/man3/hal_set_lock.3.adoc +++ b/docs/src/man/man3/hal_set_lock.3.adoc @@ -6,20 +6,31 @@ hal_set_lock, hal_get_lock - Set or get the HAL lock level -== SYNTAX +== SYNOPSIS -int hal_set_lock(unsigned char _lock_type_) +[source,c] +---- +#include -int hal_get_lock() +int hal_set_lock(unsigned char lock_type); +int hal_get_lock(); +---- == ARGUMENTS lock_type:: The desired lock type, which may be a bitwise combination of: - *HAL_LOCK_LOAD*, *HAL_LOCK_CONFIG*, *HAL_LOCK_PARAMS*, or *HAL_LOCK_PARAMS*. - *HAL_LOCK_NONE* or 0 locks nothing, and *HAL_LOCK_ALL locks everything.* ++ +* `HAL_LOCK_LOAD` - Lock creating new pins, params and functions. +* `HAL_LOCK_CONFIG` - Lock creating or altering threads. +* `HAL_LOCK_PARAMS` - Lock altering parameters (only partly functional). +* `HAL_LOCK_RUN` - Lock starting/stopping threads. +* `HAL_LOCK_NONE` - locks nothing (unlocks all). +* `HAL_LOCK_ALL` - Lock everything. == RETURN VALUE -*hal_set_lock* returns a HAL status code. -*hal_get_lock* returns the current HAL lock level or a HAL status code. +Function *hal_set_lock()* returns zero (0) on success or *-EFAULT* if HAL is not initialized. + +Function *hal_get_lock()* returns the current HAL lock level. +If HAL is not initialized, *hal_get_lock()* returns `HAL_LOCK_ALL`. diff --git a/docs/src/man/man3/hal_set_p.3.adoc b/docs/src/man/man3/hal_set_p.3.adoc new file mode 100644 index 00000000000..cedbd357b7d --- /dev/null +++ b/docs/src/man/man3/hal_set_p.3.adoc @@ -0,0 +1,134 @@ +:manvolnum: 3 + += hal_set_p(3) + +== NAME + +hal_set_p - Set a HAL pin or param value + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_set_p(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure containing the name to search for and value to set. + +callback:: + The callback function to invoke when the pin or param has been found to get the value to set. + This can also be NULL if no callback is required. + Both _query.pp.value_ *and* _query.pp.type_ must be appropriately set if _callback_ is NULL. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_set_p()* function will find the named pin or param and set its value to the user supplied value. +The _query_ structure should be set to zero before the call, except for the fields noted below. + +The _query.name_ must be set to the name of the pin or parameter you want to set. +Optionally, you can enforce to look exclusively for a pin or param by setting _query.qtype_ before the call to: + +* `0` - look for either pin or param +* `HAL_QTYPE_PIN` - only look for a pin +* `HAL_QTYPE_PARAM` - only look for a param + +Note that both pins and params share one namespace and cannot overlap. + +You can further limit the search by setting _query.pp.type_ to the HAL type you want to set. +If the pin or param is found, but has a different type, then *-EEXIST* is returned. + +Setting a pin connected to a signal or a pin of direction `HAL_OUT` will fail with an *-EACCES* error. +Setting a param of direction `HAL_RO` will fail with an *-EACCES* error. + +The _callback_ is called with all fields set appropriately, including data reference. +You must set the correct _query.pp.value_ subfield in the callback according to the _query.pp.type_ field. +The pin's or param's value will be set if the callback returns with zero (0). + +If you do not wish to use a callback, then you must set both _query.pp.type_ and _query.pp.value_ beforehand. +The actual type will be checked against what is found and a mismatch will result in an *-EEXIST* error. + +If found, *hal_set_p()* sets the _query.name_ field to the actual live pin or param name. +The _query.qtype_ field is set accordingly to whether a pin or a param was found. + +== RETURN VALUE + +The *hal_set_p()* function returns zero (0) on success. +The return value of the _callback_ is returned if it got called and was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The pin or param does not exist. +-EEXIST:: The pin or param exists but is of different type. +-EACCES:: Trying to write a `HAL_OUT` pin, a connected pin or a `HAL_RO` param. +-EBADF:: Attempt to set a `HAL_PORT` pin. +-EIO:: The internal data pointer is missing. + +== EXAMPLES + +[source,c] +---- +int set_pin_fpval(const char *ppname, rtapi_real val) +{ + hal_query_t query = {}; + query.name = ppname; + query.qtype = HAL_QTYPE_PIN; // Only look for pins + query.pp.type = HAL_REAL; // We want to set a floating point value + query.pp.value.r = val; // This is the value + + int rv = hal_set_p(&query, NULL, NULL); + + if(0 != rv) + printf("Failed to set '%s': %s\n", ppname, hal_strerror(rv)); + return rv; +} +---- + +[source,c] +---- +static int ppsetter_cb(hal_query_t *query, void *arg) +{ + const char *str = (const char *)arg; + + // Perform conversion based on type + switch(query->pp.type) { + case HAL_BOOL: query->pp.value.b = str2bool(str); break; + case HAL_REAL: query->pp.value.r = str2real(str); break; + case HAL_SINT: query->pp.value.s = str2sint(str); break; + case HAL_UINT: query->pp.value.u = str2uint(str); break; + default: + printf("unsupported value type %d\n", (int)query->pp.type); + return -EBADF; + } + + return 0; +} + +int set_p_val(const char *ppname, const char *str) +{ + hal_query_t query = {}; + query.name = ppname; + + int rv = hal_set_p(&query, ppsetter_cb, (void *)str); + + if(0 != rv) + printf("Failed to set '%s' to '%s': %s\n", ppname, str, hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3), hal_get_p(3), hal_set_s(3) diff --git a/docs/src/man/man3/hal_set_s.3.adoc b/docs/src/man/man3/hal_set_s.3.adoc new file mode 100644 index 00000000000..57fcd1e7d2a --- /dev/null +++ b/docs/src/man/man3/hal_set_s.3.adoc @@ -0,0 +1,132 @@ +:manvolnum: 3 + += hal_set_s(3) + +== NAME + +hal_set_s - Set a HAL signal value + +== SYNOPSIS + +[source,c] +---- +#include + +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +int hal_set_s(hal_query_t *query, hal_query_cb callback, void *arg); +---- + +== ARGUMENTS + +query:: + The query structure containing the name to search for and value to set. + +callback:: + The callback function to invoke when the signal has been found to get the value to set. + This can also be NULL if no callback is required. + Both _query.sig.value_ *and* _query.sig.type_ must be appropriately set if _callback_ is NULL. + +arg:: + A user defined pointer to a user defined data structure. + The _arg_ pointer is passed verbatim to the _callback_ function. + +== DESCRIPTION + +The *hal_set_s()* function will find the named signal and set its value to the user supplied value. +The _query_ structure should be set to zero before the call, except for the fields noted below. + +The _query.name_ must be set to the name of the signal you want to set. + +You can further limit the search by setting _query.sig.type_ to the HAL type you want to set. +If the signal is found, but has a different type, then *-EEXIST* is returned. + +Setting a signal with a writer pin connected will fail with an *-EACCES* error. + +The _callback_ is called with all fields set appropriately, including data reference. +You must set the correct _query.sig.value_ subfield in the callback according to the _query.sig.type_ field. +The signal's value will be set if the callback returns with zero (0). + +If you do not wish to use a callback, then you must set both _query.sig.type_ and _query.sig.value_ beforehand. +The actual type will be checked against what is found and a mismatch will result in an *-EEXIST* error. + +If found, *hal_set_s()* sets the _query.name_ field to the actual live signal name. + +Setting a signal of type `HAL_PORT` will allocate the port's message queue. +The size of the queue is determined by the value passed in _query.sig.value.u_. +A port's queue size cannot be larger than 65536 bytes. +Trying to reallocate a port's queue will fail with an *-EISCONN* error. + +== RETURN VALUE + +The *hal_set_s()* function returns zero (0) on success. +The return value of the _callback_ is returned if it got called and was non-zero. +A negative errno code is returned if any problem is detected: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. +-ENOENT:: The signal does not exist. +-EEXIST:: The signal exists but is of different type. +-EACCES:: Trying to write a signal with `HAL_OUT` a pin connected. +-EISCONN:: Attempt to set a `HAL_PORT` signal with an allocated queue. +-EBADF:: The signal type is not supported. +-EIO:: The internal data pointer is missing. + +== EXAMPLES + +[source,c] +---- +int set_sig_fpval(const char *signame, rtapi_real val) +{ + hal_query_t query = {}; + query.name = signame; + query.sig.type = HAL_REAL; // We want to set a floating point value + query.sig.value.r = val; // This is the value + + int rv = hal_set_s(&query, NULL, NULL); + + if(0 != rv) + printf("Failed to set '%s': %s\n", signame, hal_strerror(rv)); + return rv; +} +---- + +[source,c] +---- +static int sigsetter_cb(hal_query_t *query, void *arg) +{ + const char *str = (const char *)arg; + + // Perform conversion based on type + switch(query->sig.type) { + case HAL_BOOL: query->sig.value.b = str2bool(str); break; + case HAL_REAL: query->sig.value.r = str2real(str); break; + case HAL_SINT: query->sig.value.s = str2sint(str); break; + case HAL_UINT: query->sig.value.u = str2uint(str); break; + + case HAL_PORT: // This you'd normally handle as a special case in your code + default: + printf("unsupported value type %d\n", (int)query->sig.type); + return -EBADF; + } + + return 0; +} + +int set_s_val(const char *signame, const char *str) +{ + hal_query_t query = {}; + query.name = signame; + + int rv = hal_set_s(&query, sigsetter_cb, (void *)str); + + if(0 != rv) + printf("Failed to set '%s' to '%s': %s\n", signame, str, hal_strerror(rv)); + return rv; +} +---- + +== SEE ALSO + +hal_query_t(3), hal_get_p(3), hal_set_s(3) diff --git a/docs/src/man/man3/hal_setter.3.adoc b/docs/src/man/man3/hal_setter.3.adoc new file mode 100644 index 00000000000..94e02182c90 --- /dev/null +++ b/docs/src/man/man3/hal_setter.3.adoc @@ -0,0 +1,38 @@ +:manvolnum: 3 + += hal_setter(3) + +== NAME + +hal_setter, hal_set_bool, hal_set_real, hal_set_sint, hal_set_uint, +hal_set_si32, hal_set_ui32 - HAL pin and param data writer + +== SYNOPSIS + +[source,c] +---- +#include + +rtapi_bool hal_set_bool(hal_bool_t refp, rtapi_bool value); +rtapi_real hal_set_real(hal_real_t refp, rtapi_real value); +rtapi_sint hal_set_sint(hal_sint_t refp, rtapi_sint value); +rtapi_uint hal_set_uint(hal_uint_t refp, rtapi_uint value); +rtapi_s32 hal_set_si32(hal_sint_t refp, rtapi_s32 value); +rtapi_u32 hal_set_ui32(hal_uint_t refp, rtapi_u32 value); +---- + +== ARGUMENTS + +refp:: + Pin or param opaque reference. +value:: + The pin or parameter value to set according to the type of the function. + +== DESCRIPTION + +The **hal_set_*()** family of functions will set a pin or param to the value of the argument. +The setter ensures that booleans and 32-bit values are properly extended for the underlying storage. + +== SEE ALSO + +hal_getter(), hal_type_t(3), hal_pin_new(3), hal_param_new(3) diff --git a/docs/src/man/man3/hal_signal_new.3.adoc b/docs/src/man/man3/hal_signal_new.3.adoc index f2a695e9a52..7d239fd54a9 100644 --- a/docs/src/man/man3/hal_signal_new.3.adoc +++ b/docs/src/man/man3/hal_signal_new.3.adoc @@ -7,15 +7,17 @@ hal_signal_new, hal_signal_delete, hal_link, hal_unlink - Manipulate HAL signals -== SYNTAX +== SYNOPSIS -int hal_signal_new(const char* _signal_name_, hal_type_t _type_) +[source,c] +---- +#include -int hal_signal_delete(const char* _signal_name_) - -int hal_link(const char* _pin_name_, const char* _signal_name_) - -int hal_unlink(const char* _pin_name_) +int hal_signal_new(const char *signal_name, hal_type_t type); +int hal_signal_delete(const char *signal_name); +int hal_link(const char *pin_name, const char *signal_name); +int hal_unlink(const char pin_name); +---- == ARGUMENTS @@ -28,25 +30,25 @@ type:: == DESCRIPTION -*hal_signal_new* creates a new signal object. Once a signal has been -created, pins can be linked to it with *hal_link*. The signal object -contains the actual storage for the signal data. Pin objects linked to -the signal have pointers that point to the data. 'name' is the name of -the new signal. It may be no longer than HAL_NAME_LEN characters. If -there is already a signal with the same name the call will fail. - -*hal_link* links a pin to a signal. If the pin is already linked to the -desired signal, the command succeeds. If the pin is already linked to -some other signal, it is an error. In either case, the existing -connection is not modified. (Use 'hal_unlink' to break an existing -connection.) If the signal already has other pins linked to it, they are -unaffected - one signal can be linked to many pins, but a pin can be -linked to only one signal. - -*hal_unlink* unlinks any signal from the specified pin. - -*hal_signal_delete* deletes a signal object. Any pins linked to the -object are unlinked. +The *hal_signal_new()* function creates a new signal object. +Once a signal has been created, pins can be linked to it with *hal_link()*. +The signal object contains the actual storage for the signal data. +Pin objects linked to the signal have pointers that point to the data. +The _signal_name_ cannot be longer than HAL_NAME_LEN characters. +If there is already a signal with the same name the call will fail. + +The *hal_link()* function links a pin to a signal. +If the pin is already linked to the desired signal, the command succeeds. +If the pin is already linked to some other signal, it is an error. +In either case, the existing connection is not modified. +(Use *hal_unlink()* to break an existing connection.) +If the signal already has other pins linked to it, they are unaffected. +One signal can be linked to many pins, but a pin can be linked to only one signal. + +The *hal_unlink()* functions unlinks any signal from the specified pin. + +The *hal_signal_delete()* function deletes a signal object. +Any pins linked to the signal object are unlinked. == RETURN VALUE diff --git a/docs/src/man/man3/hal_start_threads.3.adoc b/docs/src/man/man3/hal_start_threads.3.adoc index 3ac4a137ea3..c13ecab07a4 100644 --- a/docs/src/man/man3/hal_start_threads.3.adoc +++ b/docs/src/man/man3/hal_start_threads.3.adoc @@ -1,21 +1,27 @@ +:manvolnum: 3 + = hal_start_threads(3) == NAME hal_start_threads - Allow HAL threads to begin executing -== SYNTAX +== SYNOPSIS -int hal_start_threads() +[source,c] +---- +#include -int hal_stop_threads() +int hal_start_threads(); +int hal_stop_threads(); +---- == DESCRIPTION -*hal_start_threads* starts all threads that have been created. +The *hal_start_threads()* function starts all threads that have been created. This is the point at which realtime functions start being called. -*hal_stop_threads* stops all threads that were previously started by *hal_start_threads*. +The *hal_stop_threads()* function stops all threads that were previously started by *hal_start_threads()*. It should be called before any component that is part of a system exits. == RETURN VALUE diff --git a/docs/src/man/man3/hal_statistics.3.adoc b/docs/src/man/man3/hal_statistics.3.adoc new file mode 100644 index 00000000000..37e86b22e93 --- /dev/null +++ b/docs/src/man/man3/hal_statistics.3.adoc @@ -0,0 +1,74 @@ +:manvolnum: 3 + += hal_statistics(3) + +== NAME + +hal_statistics - Retrieve statistical information about HAL + +== SYNOPSIS + +[source,c] +---- +#include + +int hal_statistics(hal_statistics_t *sts); +---- + +== ARGUMENTS + +sts:: + A pointer to a `hal_statistics_t` variable that will receive the data. + +== DESCRIPTION + +Retrieve the current statistics about memory, pin, param, signal, etc. usage. + +The data is provided in a structure with following layout: + +[source,c] +---- +typedef struct { + long mem_total; + long mem_free; + int ncomps; + int ncomps_free; + int npins; + int npins_free; + int nparams; + int nparams_free; + int naliases; + int naliases_free; + int nsignals; + int nsignals_free; + int nthreads; + int nthreads_free; + int nfuncts; + int nfuncts_free; +} hal_statistics_t; +---- + +Fields: + +[horizontal] +mem_total;; The shared memory segment's size. +mem_free;; The remaining amount of shared memory free for allocation. +ncomps, ncomps_free;; Component count and number of component reserve structures for reuse. +npins, npins_free;; Pin count and number of pin reserve structures for reuse. +nparams, nparams_free;; Param count and number of param reserve structures for reuse. +naliases, naliases_free;; Alias count (oldname) and number of alias reserve structures for reuse. +nsignals, nsignals_free;; Signal count and number of signal reserve structures for reuse. +nthreads, nthreads_free;; Thread count and number of thread reserve structures for reuse. +nfuncts, nfuncts_free;; Function count and number of function reserve structures for reuse. + +== RETURN VALUE + +Returns zero (0) on success or a negative errno code: + +[horizontal] +-EFAULT:: The shared memory was not mapped. +-EINVAL:: An invalid argument was passed. + +== SEE ALSO + +hal_query_t(3) diff --git a/docs/src/man/man3/hal_stream.3.adoc b/docs/src/man/man3/hal_stream.3.adoc index c2fa9373637..a86fa61f94e 100644 --- a/docs/src/man/man3/hal_stream.3.adoc +++ b/docs/src/man/man3/hal_stream.3.adoc @@ -1,3 +1,5 @@ +:manvolnum: 3 + = hal_stream(3) == NAME @@ -9,6 +11,7 @@ hal_stream - non-blocking realtime streams [source,c] ---- #include + int hal_stream_create(hal_stream_t* stream, int comp_id, int key, int depth, const char* typestring); void hal_stream_destroy(hal_stream_t* stream); int hal_stream_attach(hal_stream_t* stream, int comp_id, int key, const char* typestring); @@ -42,73 +45,82 @@ and a data structure specified by _typestring_. They must also agree which component (the first one loaded) will *hal_stream_create* the stream, and which component (the second one loaded) will *hal_stream_attach* to the already-created stream. -The non-realtime part can be *halstreamer* or *halsampler*. -In the case of *halstreamer* the key is 0x48535430 plus the channel number. -In the case of *halsampler* the key is 0x48534130 plus the channel number. +The non-realtime part can be halstreamer(1) or halsampler(1). +In the case of halstreamer(1) the key is 0x48535430 plus the channel number. +In the case of halsampler(1)* the key is 0x48534130 plus the channel number. -*hal_stream_create*:: +hal_stream_create():: Create the given stream, initializing the _stream_ which is passed by reference. It is an undiagnosed error if a stream has already been created with the same _key_. -*hal_stream_destroy*:: +hal_stream_destroy():: Destroy the given stream. It is an undiagnosed error if the stream is still attached by another component. It is an undiagnosed error if the - stream was attached with *hal_stream_attach* rather than created with - *hal_stream_create*. It is an undiagnosed error if the call to - *hal_stream_destroy* is omitted. + stream was attached with *hal_stream_attach()* rather than created with + *hal_stream_create()*. It is an undiagnosed error if the call to + *hal_stream_destroy()* is omitted. -*hal_stream_attach*:: - Attach the given stream, which was already created by *hal_stream_create*. +hal_stream_attach():: + Attach the given stream, which was already created by *hal_stream_create()*. If the typestring is specified, this call fails if it does not match the typestring the stream was created with. If the typestring argument is NULL, then any typestring is accepted. -*hal_stream_detach*:: +hal_stream_detach():: Detach the given stream. It is an undiagnosed error if the stream was - created with *hal_stream_create* rather than attached with *hal_stream_attach*. - It is an undiagnosed error if the call to *hal_stream_detach* is omitted. + created with *hal_stream_create()* rather than attached with *hal_stream_attach()*. + It is an undiagnosed error if the call to *hal_stream_detach()* is omitted. -*hal_stream_element_count*:: Returns the number of pins. +hal_stream_element_count():: Returns the number of pins. -*hal_stream_element_type*:: Returns the type of the given pin number. +hal_stream_element_type():: Returns the type of the given pin number. -*hal_stream_readable*:: Returns true if the stream has at least one sample to read +hal_stream_readable():: Returns true if the stream has at least one sample to read -*hal_stream_read*:: If the stream has one sample to read, stores it in buf. +hal_stream_read():: If the stream has one sample to read, stores it in buf. -*hal_stream_writable*:: Returns true if the stream has room for at least one sample to be written. +hal_stream_writable():: Returns true if the stream has room for at least one sample to be written. -*hal_stream_depth*:: Returns the number of samples waiting to be read. +hal_stream_depth():: Returns the number of samples waiting to be read. -*hal_stream_maxdepth*:: Returns the *depth* argument that the stream was created with. +hal_stream_maxdepth():: Returns the _depth_ argument that the stream was created with. -*hal_stream_num_overruns*:: Returns a number which is incremented each time *hal_stream_write* is called without space available. +hal_stream_num_overruns():: + Returns a number which is incremented each time *hal_stream_write()* is called without space available. -*hal_stream_num_underruns*:: Returns a number which is incremented each time *hal_stream_read* is called without a sample available. +hal_stream_num_underruns():: + Returns a number which is incremented each time *hal_stream_read()* is called without a sample available. -*hal_stream_wait_readable*:: Waits until the stream is readable or the stop flag is set. +hal_stream_wait_readable():: + Waits until the stream is readable or the stop flag is set. + + This function cannot be called from realtime. -*hal_stream_wait_writable*:: Waits until the stream is writable or the stop flag is set. +hal_stream_wait_writable():: + Waits until the stream is writable or the stop flag is set. + + This function cannot be called from realtime. -*hal_stream_read*:: Reads a record from stream. +hal_stream_read():: + Reads a record from stream. If successful, it is stored in the given buffer. - Optionally, the sample number can be retrieved. If no sample is available, _num_underruns_ is incremented. - It is an undetected error if more than one component or real-time function calls *hal_stream_read* concurrently. + Optionally, the sample number can be retrieved. + If no sample is available, _num_underruns_ is incremented. + It is an undetected error if more than one component or real-time function calls *hal_stream_read()* concurrently. -*hal_stream_write*:: Writes a record to the stream. +hal_stream_write():: + Writes a record to the stream. If successful, it copied from the given buffer. If no room is available, _num_overruns_ is incremented. In either case, the internal _sampleno_ value is incremented. - It is an undetected error if more than one component or real-time function calls *hal_stream_write* concurrently. + It is an undetected error if more than one component or real-time function calls *hal_stream_write()* concurrently. == ARGUMENTS stream:: - A pointer to a stream object. In the case of *hal_stream_create* and - *hal_stream_attach* this is an uninitialized stream; in other cases, + A pointer to a stream object. In the case of *hal_stream_create()* and + *hal_stream_attach()* this is an uninitialized stream; in other cases, it must be a stream created or attached by an earlier call and not yet detached or destroyed. hal_id:: - An HAL component identifier returned by an earlier call to *hal_init*. + An HAL component identifier returned by an earlier call to hal_init(3). key:: The key for the shared memory segment. depth:: @@ -145,19 +157,14 @@ In the source tree under `src/hal/components`, *sampler.c* and == REALTIME CONSIDERATIONS -*hal_stream_read*, *hal_stream_readable*, *hal_stream_write*, -*hal_stream_writable*, *hal_stream_element_count*, *hal_tream_pin_type*, -*hal_stream_depth*, *hal_stream_maxdepth*, *hal_stream_num_underruns*, -*hal_stream_number_overruns* may be called from realtime code. - -*hal_stream_wait_writable*, *hal_stream_wait_writable* may be called from ULAPI code. +The *hal_stream_wait_readable()* and *hal_stream_wait_writable()* cannot be called from realtime. Other functions may be called in any context, including realtime contexts. == RETURN VALUE -The functions *hal_stream_create*, *hal_stream_attach*, *hal_stream_read*, -*hal_stream_write*, *hal_stream_detach* and *hal_stream_destroy* return +The functions *hal_stream_create()*, *hal_stream_attach()*, *hal_stream_read()*, +*hal_stream_write()*, *hal_stream_detach()* and *hal_stream_destroy()* return an RTAPI status code. Other functions' return values are explained above. == BUGS diff --git a/docs/src/man/man3/hal_type_t-legacy.3.adoc b/docs/src/man/man3/hal_type_t-legacy.3.adoc new file mode 100644 index 00000000000..3973cc75fd6 --- /dev/null +++ b/docs/src/man/man3/hal_type_t-legacy.3.adoc @@ -0,0 +1,66 @@ +:manvolnum: 3 + += hal_type_t-legacy(3) + +== NAME + +hal_type_t-legacy, hal_bool-legacy, hal_bit_t-legacy, hal_s32_t-legacy, hal_u32_t-legacy, +hal_port_t-legacy, hal_float_t-legacy, real_t-legacy, ireal_t-legacy - typedefs for HAL datatypes + +== DESCRIPTION + +typedef ... *hal_bool;*:: + A type which may have a value of 0 or nonzero. +typedef ... *hal_bit_t;*:: + A volatile type which may have a value of 0 or nonzero. +typedef ... *hal_s32_t*;:: + A volatile type which may have a value from -2147483648 to 2147483647. +typedef ... *hal_u32_t*;:: + A volatile type which may have a value from 0 to 4294967295. +typedef ... *hal_port_t*;:: + A volatile handle to a port object. Used with hal_port* functions. +typedef ... *hal_float_t*;:: + A volatile floating-point type, which typically has the same precision + and range as the C type *double*. +typedef ... *real_t*;:: + A nonvolatile floating-point type with at least as much precision as + *hal_float_t*. +typedef ... *ireal_t*;:: + A nonvolatile unsigned integral type the same size as *hal_float_t*. +typedef enum *hal_type_t*;:: + + *HAL_BIT*;; + Corresponds to the type *hal_bit_t*. + *HAL_FLOAT*;; + Corresponds to the type *hal_float_t*. + *HAL_S32*;; + Corresponds to the type *hal_s32_t*. + *HAL_U32*;; + Corresponds to the type *hal_u32_t*. + +== NOTES + +*hal_bit_t* is typically a typedef to an integer type whose range is +larger than just 0 and 1. When testing the value of a *hal_bit_t*, never +compare it to 1. Prefer one of the following: + +* if(b) +* if(b != 0) + +It is often useful to refer to a type that can represent all the values +as a HAL type, but without the volatile qualifier. The following types +correspond with the HAL types: + +hal_bit_t:: int +hal_s32_t:: __s32 +hal_u32_t:: __u32 +hal_float_t:: hal_real_t +hal_port_t:: int + +Take care not to use the types *s32* and *u32*. These will compile in +kernel modules but not in userspace, and not for realtime components +when using uspace realtime. + +== SEE ALSO + +hal_pin_new(3), hal_param_new(3) diff --git a/docs/src/man/man3/hal_type_t.3.adoc b/docs/src/man/man3/hal_type_t.3.adoc index b48492d9f95..d2c50077d28 100644 --- a/docs/src/man/man3/hal_type_t.3.adoc +++ b/docs/src/man/man3/hal_type_t.3.adoc @@ -4,62 +4,41 @@ == NAME -hal_type_t, hal_bool, hal_bit_t, hal_s32_t, hal_u32_t, hal_port_t, hal_float_t, real_t, ireal_t - typedefs for HAL datatypes +hal_type_t, hal_bool_t, hal_real_t, hal_sint_t, hal_uint_t, hal_port_t - typedefs for HAL data types == DESCRIPTION -typedef ... *hal_bool;*:: - A type which may have a value of 0 or nonzero. -typedef ... *hal_bit_t;*:: - A volatile type which may have a value of 0 or nonzero. -typedef ... *hal_s32_t*;:: - A volatile type which may have a value from -2147483648 to 2147483647. -typedef ... *hal_u32_t*;:: - A volatile type which may have a value from 0 to 4294967295. +typedef ... *hal_bool_t*;:: + An opaque type reference for a boolean with a value of zero/false (0) or one/true (1). +typedef ... *hal_real_t*;:: + An opaque type reference for a floating-point value with the same precision as a C double type. +typedef ... *hal_sint_t*;:: + An opaque type reference for a value from -2^63^ ... +2^63^-1. +typedef ... *hal_uint_t*;:: + An opaque type reference for a value from 0 ... +2^64^-1. typedef ... *hal_port_t*;:: - A volatile handle to a port object. Used with hal_port* functions. -typedef ... *hal_float_t*;:: - A volatile floating-point type, which typically has the same precision - and range as the C type *double*. -typedef ... *real_t*;:: - A nonvolatile floating-point type with at least as much precision as - *hal_float_t*. -typedef ... *ireal_t*;:: - A nonvolatile unsigned integral type the same size as *hal_float_t*. + An opaque type reference as a handle to a port object. Used with hal_port*() functions. typedef enum *hal_type_t*;:: - - *HAL_BIT*;; - Corresponds to the type *hal_bit_t*. - *HAL_FLOAT*;; - Corresponds to the type *hal_float_t*. - *HAL_S32*;; - Corresponds to the type *hal_s32_t*. - *HAL_U32*;; - Corresponds to the type *hal_u32_t*. + *HAL_BOOL*;; + Corresponds to the type *hal_bool_t*. + *HAL_REAL*;; + Corresponds to the type *hal_real_t*. + *HAL_SINT*;; + Corresponds to the type *hal_sint_t*. + *HAL_UINT*;; + Corresponds to the type *hal_uint_t*. + *HAL_PORT*;; + Corresponds to the type *hal_port_t*. == NOTES -*hal_bit_t* is typically a typedef to an integer type whose range is -larger than just 0 and 1. When testing the value of a *hal_bit_t*, never -compare it to 1. Prefer one of the following: - -* if(b) -* if(b != 0) - -It is often useful to refer to a type that can represent all the values -as a HAL type, but without the volatile qualifier. The following types -correspond with the HAL types: - -hal_bit_t:: int -hal_s32_t:: __s32 -hal_u32_t:: __u32 -hal_float_t:: hal_real_t -hal_port_t:: int - -Take care not to use the types *s32* and *u32*. These will compile in -kernel modules but not in userspace, and not for realtime components -when using uspace realtime. +HAL types cannot be read or written directly. +They are opaque structures that reference a value of the type indicated by the name. +Reading and writing HAL types is done with getters and setters. +There are 32-bit compatibility getters and setters to handle smaller coding types. == SEE ALSO -hal_pin_new(3), hal_param_new(3) +hal_pin_new(3), hal_param_new(3), +hal_query_t(3), +hal_setter(3), hal_getter(3) diff --git a/docs/src/man/man3/hm2_pktuart.3.adoc b/docs/src/man/man3/hm2_pktuart.3.adoc index 489628c0a96..ce10b709dbc 100644 --- a/docs/src/man/man3/hm2_pktuart.3.adoc +++ b/docs/src/man/man3/hm2_pktuart.3.adoc @@ -176,7 +176,7 @@ I.e., the data is filled right-to-left and right-justified with consecutive pack Because the transactions are necessarily split over multiple reads, and some steps will have serial-port latency delays it is recommended to use a state machine in the realtime code where waiting on input is not possible. -[source, C] +[source,c] ---- int process(void *arg, long period) { static int state = START; diff --git a/docs/src/man/man3/rtapi_bool.3.adoc b/docs/src/man/man3/rtapi_bool.3.adoc index 39d03115b1f..6133750e15e 100644 --- a/docs/src/man/man3/rtapi_bool.3.adoc +++ b/docs/src/man/man3/rtapi_bool.3.adoc @@ -9,6 +9,9 @@ rtapi_bool - RTAPI wrappers for linux kernel functionality [source,c] ---- #include + +// Specific abstraction for HAL +typedef bool rtapi_bool; ---- == DESCRIPTION @@ -19,7 +22,3 @@ to obtain suitable declarations of "bool", "true" and "false". == REALTIME CONSIDERATIONS None. - -== NOTES - -Also permitted in C++ programs, where including it has no effect. diff --git a/docs/src/man/man3/rtapi_stdint.3.adoc b/docs/src/man/man3/rtapi_stdint.3.adoc index f06791e7734..405a5690755 100644 --- a/docs/src/man/man3/rtapi_stdint.3.adoc +++ b/docs/src/man/man3/rtapi_stdint.3.adoc @@ -23,6 +23,16 @@ typedef ... rtapi_uintptr_t; #define RTAPI_INT__xx___MIN ... #define RTAPI_INT__xx___MAX ... #define RTAPI_UINT__xx___MAX ... + +// Specific abstractions for HAL +typedef ... rtapi_real; +typedef ... rtapi_sint; +typedef ... rtapi_uint; +typedef ... rtapi_port; + +#define RTAPI_SINT_MIN ... +#define RTAPI_SINT_MAX ... +#define RTAPI_UINT_MAX ... ---- == DESCRIPTION diff --git a/src/emc/ini/inihal.cc b/src/emc/ini/inihal.cc index d86840cbaaf..9126ca95b7a 100644 --- a/src/emc/ini/inihal.cc +++ b/src/emc/ini/inihal.cc @@ -24,6 +24,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #include #include #include +#include #include "inihal.hh" #include "iniaxis.hh" #include "inispindle.hh" @@ -36,19 +37,11 @@ static ptr_inihal_data *the_inihal_data; #define PREFIX "ini." #define EPSILON .00001 -#define CLOSE(a,b,eps) ((a)-(b) < +(eps) && (a)-(b) > -(eps)) #define NEW(NAME) new_inihal_data.NAME -#define CHANGED(NAME) \ - ((old_inihal_data.NAME) - (new_inihal_data.NAME) > +(EPSILON)) \ - || \ - ((old_inihal_data.NAME) - (new_inihal_data.NAME) < -(EPSILON)) - -#define CHANGED_IDX(NAME,IDX) \ - ((old_inihal_data.NAME[IDX]) - (new_inihal_data.NAME[IDX]) > +(EPSILON)) \ - || \ - ((old_inihal_data.NAME[IDX]) - (new_inihal_data.NAME[IDX]) < -(EPSILON)) +#define CHANGED(NAME) (fabs((old_inihal_data.NAME) - (new_inihal_data.NAME)) > (EPSILON)) +#define CHANGED_IDX(NAME,IDX) (fabs((old_inihal_data.NAME[IDX]) - (new_inihal_data.NAME[IDX])) > (EPSILON)) #define UPDATE(NAME) old_inihal_data.NAME = new_inihal_data.NAME @@ -86,44 +79,46 @@ static ptr_inihal_data *the_inihal_data; new_inihal_data.NAME[IDX]); #define MAKE_BIT_PIN(NAME,DIR) \ do { \ - retval = hal_pin_bit_newf(DIR,&(the_inihal_data->NAME),comp_id,PREFIX#NAME); \ + int retval = hal_pin_new_bool(comp_id, DIR, &(the_inihal_data->NAME), 0, PREFIX#NAME); \ if (retval < 0) return retval; \ } while (0) #define MAKE_S32_PIN(NAME,DIR) \ do { \ - retval = hal_pin_s32_newf(DIR,&(the_inihal_data->NAME),comp_id,PREFIX#NAME); \ + int retval = hal_pin_new_si32(comp_id, DIR, &(the_inihal_data->NAME), 0, PREFIX#NAME); \ if (retval < 0) return retval; \ } while (0) #define MAKE_S32_PIN_IDX(NAME,HALPIN_NAME,DIR,IDX) \ do { \ - retval = hal_pin_s32_newf(DIR,&(the_inihal_data->NAME[IDX]),\ - comp_id,PREFIX"%d."#HALPIN_NAME,IDX); \ + int retval = hal_pin_new_si32(comp_id, DIR, &(the_inihal_data->NAME[IDX]),\ + 0, PREFIX"%d."#HALPIN_NAME, IDX); \ if (retval < 0) return retval; \ } while (0) #define MAKE_FLOAT_PIN(NAME,DIR) \ do { \ - retval = hal_pin_float_newf(DIR,&(the_inihal_data->NAME),comp_id,PREFIX#NAME); \ + int retval = hal_pin_new_real(comp_id, DIR, &(the_inihal_data->NAME), 0,PREFIX#NAME); \ if (retval < 0) return retval; \ } while (0) #define MAKE_FLOAT_PIN_IDX(NAME,HALPIN_NAME,DIR,IDX) \ do { \ - retval = hal_pin_float_newf(DIR,&(the_inihal_data->NAME[IDX]),\ - comp_id,PREFIX"%d."#HALPIN_NAME,IDX); \ + int retval = hal_pin_new_real(comp_id, DIR, &(the_inihal_data->NAME[IDX]),\ + 0.0, PREFIX"%d."#HALPIN_NAME, IDX); \ if (retval < 0) return retval; \ } while (0) #define MAKE_FLOAT_PIN_LETTER(NAME,HALPIN_NAME,DIR,IDX,LETTER) \ do { \ - retval = hal_pin_float_newf(DIR,&(the_inihal_data->NAME[IDX]),\ - comp_id,PREFIX"%c."#HALPIN_NAME,LETTER); \ + int retval = hal_pin_new_real(comp_id, DIR, &(the_inihal_data->NAME[IDX]),\ + 0.0, PREFIX"%c."#HALPIN_NAME, LETTER); \ if (retval < 0) return retval; \ } while (0) -#define INIT_PIN(NAME) *(the_inihal_data->NAME) = old_inihal_data.NAME; +#define INIT_PIN_R(NAME) hal_set_real(the_inihal_data->NAME, old_inihal_data.NAME); +#define INIT_PIN_S(NAME) hal_set_si32(the_inihal_data->NAME, old_inihal_data.NAME); +#define INIT_PIN_B(NAME) hal_set_bool(the_inihal_data->NAME, old_inihal_data.NAME); int ini_hal_exit(void) { @@ -134,8 +129,6 @@ int ini_hal_exit(void) int ini_hal_init(int numjoints) { - int retval; - comp_id = hal_init("inihal"); if (comp_id < 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -193,39 +186,39 @@ int ini_hal_init(int numjoints) int ini_hal_init_pins(int numjoints) { - INIT_PIN(traj_default_velocity); - INIT_PIN(traj_max_velocity); - INIT_PIN(traj_default_acceleration); - INIT_PIN(traj_max_acceleration); - INIT_PIN(traj_max_jerk); - INIT_PIN(traj_planner_type); - - INIT_PIN(traj_arc_blend_enable); - INIT_PIN(traj_arc_blend_fallback_enable); - INIT_PIN(traj_arc_blend_optimization_depth); - INIT_PIN(traj_arc_blend_gap_cycles); - INIT_PIN(traj_arc_blend_ramp_freq); - INIT_PIN(traj_arc_blend_tangent_kink_ratio); + INIT_PIN_R(traj_default_velocity); + INIT_PIN_R(traj_max_velocity); + INIT_PIN_R(traj_default_acceleration); + INIT_PIN_R(traj_max_acceleration); + INIT_PIN_R(traj_max_jerk); + INIT_PIN_S(traj_planner_type); + + INIT_PIN_B(traj_arc_blend_enable); + INIT_PIN_B(traj_arc_blend_fallback_enable); + INIT_PIN_S(traj_arc_blend_optimization_depth); + INIT_PIN_R(traj_arc_blend_gap_cycles); + INIT_PIN_R(traj_arc_blend_ramp_freq); + INIT_PIN_R(traj_arc_blend_tangent_kink_ratio); for (int idx = 0; idx < numjoints; idx++) { - INIT_PIN(joint_backlash[idx]); - INIT_PIN(joint_ferror[idx]); - INIT_PIN(joint_min_ferror[idx]); - INIT_PIN(joint_min_limit[idx]); - INIT_PIN(joint_max_limit[idx]); - INIT_PIN(joint_max_velocity[idx]); - INIT_PIN(joint_max_acceleration[idx]); - INIT_PIN(joint_jerk[idx]); - INIT_PIN(joint_home[idx]); - INIT_PIN(joint_home_offset[idx]); - INIT_PIN(joint_home_sequence[idx]); + INIT_PIN_R(joint_backlash[idx]); + INIT_PIN_R(joint_ferror[idx]); + INIT_PIN_R(joint_min_ferror[idx]); + INIT_PIN_R(joint_min_limit[idx]); + INIT_PIN_R(joint_max_limit[idx]); + INIT_PIN_R(joint_max_velocity[idx]); + INIT_PIN_R(joint_max_acceleration[idx]); + INIT_PIN_R(joint_jerk[idx]); + INIT_PIN_R(joint_home[idx]); + INIT_PIN_R(joint_home_offset[idx]); + INIT_PIN_S(joint_home_sequence[idx]); } for (int idx = 0; idx < EMCMOT_MAX_AXIS; idx++) { - INIT_PIN(axis_min_limit[idx]); - INIT_PIN(axis_max_limit[idx]); - INIT_PIN(axis_max_velocity[idx]); - INIT_PIN(axis_max_acceleration[idx]); - INIT_PIN(axis_jerk[idx]); + INIT_PIN_R(axis_min_limit[idx]); + INIT_PIN_R(axis_max_limit[idx]); + INIT_PIN_R(axis_max_velocity[idx]); + INIT_PIN_R(axis_max_acceleration[idx]); + INIT_PIN_R(axis_jerk[idx]); } return 0; @@ -233,9 +226,18 @@ int ini_hal_init_pins(int numjoints) static void copy_hal_data(const ptr_inihal_data &i, value_inihal_data &j) { - int x; -#define FIELD(t,f) j.f = (i.f)?*i.f:0; -#define ARRAY(t,f,n) do { for (x = 0; x < n; x++) j.f[x] = (i.f[x])?*i.f[x]:0; } while (0); +#define FIELD(t,f) do { \ + if(i.f) { \ + j.f = hal_get_##t(i.f); \ + } \ + } while(0); +#define ARRAY(t,f,n) do { \ + for (int x = 0; x < n; x++) { \ + if(i.f[x]) { \ + j.f[x] = hal_get_##t(i.f[x]); \ + } \ + } \ + } while (0); HAL_FIELDS #undef FIELD #undef ARRAY @@ -243,7 +245,7 @@ static void copy_hal_data(const ptr_inihal_data &i, value_inihal_data &j) int check_ini_hal_items(int numjoints) { - value_inihal_data new_inihal_data_mutable; + value_inihal_data new_inihal_data_mutable = {}; copy_hal_data(*the_inihal_data, new_inihal_data_mutable); const value_inihal_data &new_inihal_data = new_inihal_data_mutable; diff --git a/src/emc/ini/inihal.hh b/src/emc/ini/inihal.hh index da1ecd58801..6316980e570 100644 --- a/src/emc/ini/inihal.hh +++ b/src/emc/ini/inihal.hh @@ -47,42 +47,50 @@ int ini_hal_init_pins(int numjoints); [JOINT_n]COMP_FILE_TYPE [JOINT_n]COMP */ +// FIXME: This will have to go again when we do proper 64-bit +// The typedefs are necessary to map to hal_[gs]et_[su]i32() in the expansion +// of below macros because they are selected based on text-concatenation in the +// preprocessor. Even the 32-bit version use sint/uint, but the expansion would +// then select the 64-bit versions. +typedef hal_sint_t hal_si32_t; +typedef hal_uint_t hal_ui32_t; + #define HAL_FIELDS \ - FIELD(hal_float_t,traj_default_velocity) \ - FIELD(hal_float_t,traj_max_velocity) \ - FIELD(hal_float_t,traj_default_acceleration) \ - FIELD(hal_float_t,traj_max_acceleration) \ - FIELD(hal_float_t,traj_max_jerk) \ - FIELD(hal_s32_t,traj_planner_type) \ + FIELD(real,traj_default_velocity) \ + FIELD(real,traj_max_velocity) \ + FIELD(real,traj_default_acceleration) \ + FIELD(real,traj_max_acceleration) \ + FIELD(real,traj_max_jerk) \ + FIELD(si32,traj_planner_type) \ \ - FIELD(hal_bit_t,traj_arc_blend_enable) \ - FIELD(hal_bit_t,traj_arc_blend_fallback_enable) \ - FIELD(hal_s32_t,traj_arc_blend_optimization_depth) \ - FIELD(hal_float_t,traj_arc_blend_gap_cycles) \ - FIELD(hal_float_t,traj_arc_blend_ramp_freq) \ - FIELD(hal_float_t,traj_arc_blend_tangent_kink_ratio) \ + FIELD(bool,traj_arc_blend_enable) \ + FIELD(bool,traj_arc_blend_fallback_enable) \ + FIELD(si32,traj_arc_blend_optimization_depth) \ + FIELD(real,traj_arc_blend_gap_cycles) \ + FIELD(real,traj_arc_blend_ramp_freq) \ + FIELD(real,traj_arc_blend_tangent_kink_ratio) \ \ - ARRAY(hal_float_t,joint_backlash,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_ferror,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_min_ferror,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_min_limit,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_max_limit,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_max_velocity,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_max_acceleration,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_jerk,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_home,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_float_t,joint_home_offset,EMCMOT_MAX_JOINTS) \ - ARRAY(hal_s32_t, joint_home_sequence,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_backlash,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_ferror,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_min_ferror,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_min_limit,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_max_limit,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_max_velocity,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_max_acceleration,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_jerk,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_home,EMCMOT_MAX_JOINTS) \ + ARRAY(real,joint_home_offset,EMCMOT_MAX_JOINTS) \ + ARRAY(si32,joint_home_sequence,EMCMOT_MAX_JOINTS) \ \ - ARRAY(hal_float_t,axis_min_limit,EMCMOT_MAX_AXIS) \ - ARRAY(hal_float_t,axis_max_limit,EMCMOT_MAX_AXIS) \ - ARRAY(hal_float_t,axis_max_velocity,EMCMOT_MAX_AXIS) \ - ARRAY(hal_float_t,axis_max_acceleration,EMCMOT_MAX_AXIS) \ - ARRAY(hal_float_t,axis_jerk,EMCMOT_MAX_AXIS) \ + ARRAY(real,axis_min_limit,EMCMOT_MAX_AXIS) \ + ARRAY(real,axis_max_limit,EMCMOT_MAX_AXIS) \ + ARRAY(real,axis_max_velocity,EMCMOT_MAX_AXIS) \ + ARRAY(real,axis_max_acceleration,EMCMOT_MAX_AXIS) \ + ARRAY(real,axis_jerk,EMCMOT_MAX_AXIS) \ struct PTR { template - struct field { typedef T *type; }; + struct field { typedef T type; }; }; #pragma GCC diagnostic push @@ -90,10 +98,14 @@ struct PTR { #pragma GCC diagnostic ignored "-Wignored-attributes" #endif template struct NATIVE {}; -template<> struct NATIVE { typedef bool type; }; -template<> struct NATIVE { typedef rtapi_s32 type; }; -template<> struct NATIVE { typedef rtapi_u32 type; }; -template<> struct NATIVE { typedef double type; }; +template<> struct NATIVE { typedef rtapi_bool type; }; +template<> struct NATIVE { typedef rtapi_s32 type; }; +template<> struct NATIVE { typedef rtapi_u32 type; }; +// FIXME: These need to be 64-bit. Can't set them now because the compiler sees +// the typedef mapped overlap. +//template<> struct NATIVE { typedef rtapi_sint type; }; +//template<> struct NATIVE { typedef rtapi_uint type; }; +template<> struct NATIVE { typedef rtapi_real type; }; struct VALUE { template struct field { typedef typename NATIVE::type type; }; }; @@ -101,8 +113,8 @@ struct VALUE { template struct inihal_base { -#define FIELD(t,f) typename T::template field::type f; -#define ARRAY(t,f,n) typename T::template field::type f[n]; +#define FIELD(t,f) typename T::template field::type f; +#define ARRAY(t,f,n) typename T::template field::type f[n]; HAL_FIELDS #undef FIELD #undef ARRAY diff --git a/src/emc/kinematics/5axiskins.c b/src/emc/kinematics/5axiskins.c index 4b688f19f4f..fe9463247e7 100644 --- a/src/emc/kinematics/5axiskins.c +++ b/src/emc/kinematics/5axiskins.c @@ -64,7 +64,7 @@ #include "switchkins.h" struct haldata { - hal_float_t *pivot_length; + hal_real_t pivot_length; } *haldata; static int fiveaxis_max_joints; @@ -103,14 +103,15 @@ static int fiveaxis_KinematicsForward(const double *joints, { (void)fflags; (void)iflags; - PmCartesian r = s2r(*(haldata->pivot_length) + joints[JW], + rtapi_real pivot_length = hal_get_real(haldata->pivot_length); + PmCartesian r = s2r(pivot_length + joints[JW], joints[JC], 180.0 - joints[JB]); // Note: 'principal' joints are used pos->tran.x = joints[JX] + r.x; pos->tran.y = joints[JY] + r.y; - pos->tran.z = joints[JZ] + *(haldata->pivot_length) + r.z; + pos->tran.z = joints[JZ] + pivot_length + r.z; pos->b = joints[JB]; pos->c = joints[JC]; pos->w = joints[JW]; @@ -130,14 +131,15 @@ static int fiveaxis_KinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - PmCartesian r = s2r(*(haldata->pivot_length) + pos->w, + rtapi_real pivot_length = hal_get_real(haldata->pivot_length); + PmCartesian r = s2r(pivot_length + pos->w, pos->c, 180.0 - pos->b); EmcPose P; // computed position P.tran.x = pos->tran.x - r.x; P.tran.y = pos->tran.y - r.y; - P.tran.z = pos->tran.z - *(haldata->pivot_length) - r.z; + P.tran.z = pos->tran.z - pivot_length - r.z; P.b = pos->b; P.c = pos->c; @@ -212,12 +214,10 @@ int fiveaxis_KinematicsSetup(const int comp_id, haldata = hal_malloc(sizeof(struct haldata)); - result = hal_pin_float_newf(HAL_IN,&(haldata->pivot_length),comp_id, - "%s.pivot-length",kp->halprefix); + result = hal_pin_new_real(comp_id, HAL_IN,&(haldata->pivot_length), + DEFAULT_PIVOT_LENGTH, "%s.pivot-length",kp->halprefix); if(result < 0) goto error; - *haldata->pivot_length = DEFAULT_PIVOT_LENGTH; - rtapi_print("Kinematics Module %s\n",__FILE__); rtapi_print(" module name = %s\n" " coordinates = %s Requires: [KINS]JOINTS>=%d\n" @@ -225,7 +225,7 @@ int fiveaxis_KinematicsSetup(const int comp_id, kp->kinsname, coordinates,fiveaxis_max_joints, kp->sparm?kp->sparm:"NOTSPECIFIED"); - rtapi_print(" default pivot-length = %.3f\n",*haldata->pivot_length); + rtapi_print(" default pivot-length = %.3f\n", hal_get_real(haldata->pivot_length)); return 0; diff --git a/src/emc/kinematics/corexykins.c b/src/emc/kinematics/corexykins.c index df39c42c54b..0d6d0940b78 100644 --- a/src/emc/kinematics/corexykins.c +++ b/src/emc/kinematics/corexykins.c @@ -13,10 +13,6 @@ #include #include -static struct data { - hal_s32_t joints[EMCMOT_MAX_JOINTS]; -} *data; - int kinematicsForward(const double *joints ,EmcPose *pos ,const KINEMATICS_FORWARD_FLAGS *fflags @@ -80,8 +76,6 @@ int rtapi_app_main(void) { comp_id = hal_init("corexykins"); if(comp_id < 0) return comp_id; - data = hal_malloc(sizeof(struct data)); - hal_ready(comp_id); return 0; } diff --git a/src/emc/kinematics/genhexkins.c b/src/emc/kinematics/genhexkins.c index 5a858c2a1b2..3cddd9a72bc 100644 --- a/src/emc/kinematics/genhexkins.c +++ b/src/emc/kinematics/genhexkins.c @@ -116,46 +116,46 @@ #include "switchkins.h" static struct haldata { - hal_float_t *basex[NUM_STRUTS]; - hal_float_t *basey[NUM_STRUTS]; - hal_float_t *basez[NUM_STRUTS]; - hal_float_t *platformx[NUM_STRUTS]; - hal_float_t *platformy[NUM_STRUTS]; - hal_float_t *platformz[NUM_STRUTS]; - hal_float_t *basenx[NUM_STRUTS]; - hal_float_t *baseny[NUM_STRUTS]; - hal_float_t *basenz[NUM_STRUTS]; - hal_float_t *platformnx[NUM_STRUTS]; - hal_float_t *platformny[NUM_STRUTS]; - hal_float_t *platformnz[NUM_STRUTS]; - hal_float_t *correction[NUM_STRUTS]; - hal_float_t *screw_lead; - hal_u32_t *last_iter; - hal_u32_t *max_iter; - hal_u32_t *iter_limit; - hal_float_t *max_error; - hal_float_t *conv_criterion; - hal_float_t *tool_offset; - hal_float_t *spindle_offset; - hal_bit_t *fwd_kins_fail; - - hal_float_t *gui_x; - hal_float_t *gui_y; - hal_float_t *gui_z; - hal_float_t *gui_a; - hal_float_t *gui_b; - hal_float_t *gui_c; + hal_real_t basex[NUM_STRUTS]; + hal_real_t basey[NUM_STRUTS]; + hal_real_t basez[NUM_STRUTS]; + hal_real_t platformx[NUM_STRUTS]; + hal_real_t platformy[NUM_STRUTS]; + hal_real_t platformz[NUM_STRUTS]; + hal_real_t basenx[NUM_STRUTS]; + hal_real_t baseny[NUM_STRUTS]; + hal_real_t basenz[NUM_STRUTS]; + hal_real_t platformnx[NUM_STRUTS]; + hal_real_t platformny[NUM_STRUTS]; + hal_real_t platformnz[NUM_STRUTS]; + hal_real_t correction[NUM_STRUTS]; + hal_real_t screw_lead; + hal_uint_t last_iter; + hal_uint_t max_iter; + hal_uint_t iter_limit; + hal_real_t max_error; + hal_real_t conv_criterion; + hal_real_t tool_offset; + hal_real_t spindle_offset; + hal_bool_t fwd_kins_fail; + + hal_real_t gui_x; + hal_real_t gui_y; + hal_real_t gui_z; + hal_real_t gui_a; + hal_real_t gui_b; + hal_real_t gui_c; } *haldata; static int genhex_gui_forward_kins(EmcPose *pos) { - *haldata->gui_x = pos->tran.x; - *haldata->gui_y = pos->tran.y; - *haldata->gui_z = pos->tran.z; - *haldata->gui_a = pos->a; - *haldata->gui_b = pos->b; - *haldata->gui_c = pos->c; + hal_set_real(haldata->gui_x, pos->tran.x); + hal_set_real(haldata->gui_y, pos->tran.y); + hal_set_real(haldata->gui_z, pos->tran.z); + hal_set_real(haldata->gui_a, pos->a); + hal_set_real(haldata->gui_b, pos->b); + hal_set_real(haldata->gui_c, pos->c); return 0; } // genhex_gui_forward_kins @@ -275,20 +275,22 @@ static int genhex_read_hal_pins(void) { int t; /* set the base and platform coordinates from hal pin values */ + rtapi_real spindle_offset = hal_get_real(haldata->spindle_offset); + rtapi_real tool_offset = hal_get_real(haldata->tool_offset); for (t = 0; t < NUM_STRUTS; t++) { - b[t].x = *haldata->basex[t]; - b[t].y = *haldata->basey[t]; - b[t].z = *haldata->basez[t] + *haldata->spindle_offset + *haldata->tool_offset; - a[t].x = *haldata->platformx[t]; - a[t].y = *haldata->platformy[t]; - a[t].z = *haldata->platformz[t] + *haldata->spindle_offset + *haldata->tool_offset; - - nb1[t].x = *haldata->basenx[t]; - nb1[t].y = *haldata->baseny[t]; - nb1[t].z = *haldata->basenz[t]; - na0[t].x = *haldata->platformnx[t]; - na0[t].y = *haldata->platformny[t]; - na0[t].z = *haldata->platformnz[t]; + b[t].x = hal_get_real(haldata->basex[t]); + b[t].y = hal_get_real(haldata->basey[t]); + b[t].z = hal_get_real(haldata->basez[t]) + spindle_offset + tool_offset; + a[t].x = hal_get_real(haldata->platformx[t]); + a[t].y = hal_get_real(haldata->platformy[t]); + a[t].z = hal_get_real(haldata->platformz[t]) + spindle_offset + tool_offset; + + nb1[t].x = hal_get_real(haldata->basenx[t]); + nb1[t].y = hal_get_real(haldata->baseny[t]); + nb1[t].z = hal_get_real(haldata->basenz[t]); + na0[t].x = hal_get_real(haldata->platformnx[t]); + na0[t].y = hal_get_real(haldata->platformny[t]); + na0[t].z = hal_get_real(haldata->platformnz[t]); } return 0; @@ -317,7 +319,7 @@ static int StrutLengthCorrection(const PmCartesian * StrutVectUnit, /* define dot product */ pmCartCartDot(&nb3, &na2, &dotprod); - *correction = *haldata->screw_lead * asin(dotprod) / PM_2_PI; + *correction = hal_get_real(haldata->screw_lead) * asin(dotprod) / PM_2_PI; return 0; } // StrutLengthCorrection() @@ -374,12 +376,13 @@ static int genhexKinematicsForward(const double * joints, q_trans.z = pos->tran.z; /* Enter Newton-Raphson iterative method */ + rtapi_real max_error = hal_get_real(haldata->max_error); while (iterate) { /* check for large error and return error flag if no convergence */ - if ((conv_err > +(*haldata->max_error)) || - (conv_err < -(*haldata->max_error))) { + if ((conv_err > +max_error) || + (conv_err < -max_error)) { /* we can't converge */ - *haldata->fwd_kins_fail = 1; + hal_set_bool(haldata->fwd_kins_fail, 1); return -2; }; @@ -387,9 +390,9 @@ static int genhexKinematicsForward(const double * joints, /* check iteration to see if the kinematics can reach the convergence criterion and return error flag if it can't */ - if (iteration > *haldata->iter_limit) { + if (iteration > hal_get_ui32(haldata->iter_limit)) { /* we can't converge */ - *haldata->fwd_kins_fail = 1; + hal_set_bool(haldata->fwd_kins_fail, 1); return -5; } @@ -404,12 +407,12 @@ static int genhexKinematicsForward(const double * joints, pmCartCartAdd(&q_trans, &RMatrix_a, &aw); pmCartCartSub(&aw, &b[i], &InvKinStrutVect); if (0 != pmCartUnit(&InvKinStrutVect, &InvKinStrutVectUnit)) { - *haldata->fwd_kins_fail = 1; + hal_set_bool(haldata->fwd_kins_fail, 1); return -1; } pmCartMag(&InvKinStrutVect, &InvKinStrutLength); - if (*haldata->screw_lead != 0.0) { + if (hal_get_real(haldata->screw_lead) != 0.0) { /* enable strut length correction */ StrutLengthCorrection(&InvKinStrutVectUnit, &RMatrix, i, &corr); /* define corrected joint lengths */ @@ -452,8 +455,9 @@ static int genhexKinematicsForward(const double * joints, /* enter loop to determine if a strut needs another iteration */ iterate = 0; /*assume iteration is done */ + rtapi_real conv_criterion = hal_get_real(haldata->conv_criterion); for (i = 0; i < NUM_STRUTS; i++) { - if (fabs(StrutLengthDiff[i]) > *haldata->conv_criterion) { + if (fabs(StrutLengthDiff[i]) > conv_criterion) { iterate = 1; } } @@ -469,12 +473,12 @@ static int genhexKinematicsForward(const double * joints, pos->tran.y = q_trans.y; pos->tran.z = q_trans.z; - *haldata->last_iter = iteration; + hal_set_ui32(haldata->last_iter, iteration); - if (iteration > *haldata->max_iter){ - *haldata->max_iter = iteration; + if (iteration > hal_get_ui32(haldata->max_iter)){ + hal_set_ui32(haldata->max_iter, iteration); } - *haldata->fwd_kins_fail = 0; + hal_set_bool(haldata->fwd_kins_fail, 0); genhex_gui_forward_kins(pos); @@ -522,7 +526,7 @@ static int genhexKinematicsInverse(const EmcPose * pos, pmCartCartSub(&aw, &b[i], &InvKinStrutVect); pmCartMag(&InvKinStrutVect, &InvKinStrutLength); - if (*haldata->screw_lead != 0.0) { + if (hal_get_real(haldata->screw_lead) != 0.0) { /* enable strut length correction */ /* define unit strut vector */ if (0 != pmCartUnit(&InvKinStrutVect, &InvKinStrutVectUnit)) { @@ -530,7 +534,7 @@ static int genhexKinematicsInverse(const EmcPose * pos, } /* define correction value and corrected joint lengths */ StrutLengthCorrection(&InvKinStrutVectUnit, &RMatrix, i, &corr); - *haldata->correction[i] = corr; + hal_set_real(haldata->correction[i], corr); InvKinStrutLength += corr; } @@ -540,6 +544,57 @@ static int genhexKinematicsInverse(const EmcPose * pos, return 0; } //genhexKinematicsInverse() +// HAL pin initializaion values. In small arrays so we can easily +// address them in the pin creation loop. +static const rtapi_real init_basex[NUM_STRUTS] = { + DEFAULT_BASE_0_X, DEFAULT_BASE_1_X, DEFAULT_BASE_2_X, + DEFAULT_BASE_3_X, DEFAULT_BASE_4_X, DEFAULT_BASE_5_X, +}; +static const rtapi_real init_basey[NUM_STRUTS] = { + DEFAULT_BASE_0_Y, DEFAULT_BASE_1_Y, DEFAULT_BASE_2_Y, + DEFAULT_BASE_3_Y, DEFAULT_BASE_4_Y, DEFAULT_BASE_5_Y, +}; +static const rtapi_real init_basez[NUM_STRUTS] = { + DEFAULT_BASE_0_Z, DEFAULT_BASE_1_Z, DEFAULT_BASE_2_Z, + DEFAULT_BASE_3_Z, DEFAULT_BASE_4_Z, DEFAULT_BASE_5_Z, +}; +static const rtapi_real init_platformx[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_X, DEFAULT_PLATFORM_1_X, DEFAULT_PLATFORM_2_X, + DEFAULT_PLATFORM_3_X, DEFAULT_PLATFORM_4_X, DEFAULT_PLATFORM_5_X, +}; +static const rtapi_real init_platformy[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_Y, DEFAULT_PLATFORM_1_Y, DEFAULT_PLATFORM_2_Y, + DEFAULT_PLATFORM_3_Y, DEFAULT_PLATFORM_4_Y, DEFAULT_PLATFORM_5_Y, +}; +static const rtapi_real init_platformz[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_Z, DEFAULT_PLATFORM_1_Z, DEFAULT_PLATFORM_2_Z, + DEFAULT_PLATFORM_3_Z, DEFAULT_PLATFORM_4_Z, DEFAULT_PLATFORM_5_Z, +}; +static const rtapi_real init_basenx[NUM_STRUTS] = { + DEFAULT_BASE_0_NX, DEFAULT_BASE_1_NX, DEFAULT_BASE_2_NX, + DEFAULT_BASE_3_NX, DEFAULT_BASE_4_NX, DEFAULT_BASE_5_NX, +}; +static const rtapi_real init_baseny[NUM_STRUTS] = { + DEFAULT_BASE_0_NY, DEFAULT_BASE_1_NY, DEFAULT_BASE_2_NY, + DEFAULT_BASE_3_NY, DEFAULT_BASE_4_NY, DEFAULT_BASE_5_NY, +}; +static const rtapi_real init_basenz[NUM_STRUTS] = { + DEFAULT_BASE_0_NZ, DEFAULT_BASE_1_NZ, DEFAULT_BASE_2_NZ, + DEFAULT_BASE_3_NZ, DEFAULT_BASE_4_NZ, DEFAULT_BASE_5_NZ, +}; +static const rtapi_real init_platformnx[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_NX, DEFAULT_PLATFORM_1_NX, DEFAULT_PLATFORM_2_NX, + DEFAULT_PLATFORM_3_NX, DEFAULT_PLATFORM_4_NX, DEFAULT_PLATFORM_5_NX, +}; +static const rtapi_real init_platformny[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_NY, DEFAULT_PLATFORM_1_NY, DEFAULT_PLATFORM_2_NY, + DEFAULT_PLATFORM_3_NY, DEFAULT_PLATFORM_4_NY, DEFAULT_PLATFORM_5_NY, +}; +static const rtapi_real init_platformnz[NUM_STRUTS] = { + DEFAULT_PLATFORM_0_NZ, DEFAULT_PLATFORM_1_NZ, DEFAULT_PLATFORM_2_NZ, + DEFAULT_PLATFORM_3_NZ, DEFAULT_PLATFORM_4_NZ, DEFAULT_PLATFORM_5_NZ, +}; + static int genhexKinematicsSetup(const int comp_id, const char* coordinates, @@ -548,6 +603,12 @@ int genhexKinematicsSetup(const int comp_id, (void)coordinates; int i,res=0; + if (kp->max_joints < 0 || kp->max_joints > NUM_STRUTS) { + rtapi_print_msg(RTAPI_MSG_ERR, "genhexKinematicsSetup: max_joints %d less than 0 or larger NUM_STRUTS %d\n", + kp->max_joints, NUM_STRUTS); + return -1; + } + haldata = hal_malloc(sizeof(struct haldata)); if (!haldata) { rtapi_print_msg(RTAPI_MSG_ERR,"genhexKinematicsSetup: hal_malloc fail\n"); @@ -555,150 +616,64 @@ int genhexKinematicsSetup(const int comp_id, } for (i = 0; i < kp->max_joints; i++) { - res += hal_pin_float_newf(HAL_IN, &(haldata->basex[i]), comp_id, - "%s.base.%d.x", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->basey[i], comp_id, - "%s.base.%d.y", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->basez[i], comp_id, - "%s.base.%d.z", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformx[i], comp_id, - "%s.platform.%d.x", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformy[i], comp_id, - "%s.platform.%d.y", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformz[i], comp_id, - "%s.platform.%d.z", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->basenx[i], comp_id, - "%s.base-n.%d.x", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->baseny[i], comp_id, - "%s.base-n.%d.y", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->basenz[i], comp_id, - "%s.base-n.%d.z", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformnx[i], comp_id, - "%s.platform-n.%d.x", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformny[i], comp_id, - "%s.platform-n.%d.y", kp->halprefix, i); - res += hal_pin_float_newf(HAL_IN, &haldata->platformnz[i], comp_id, - "%s.platform-n.%d.z", kp->halprefix, i); - res += hal_pin_float_newf(HAL_OUT, &haldata->correction[i], comp_id, - "%s.correction.%d", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->basex[i]), + init_basex[i], "%s.base.%d.x", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->basey[i], + init_basey[i], "%s.base.%d.y", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->basez[i], + init_basez[i], "%s.base.%d.z", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformx[i], + init_platformx[i], "%s.platform.%d.x", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformy[i], + init_platformy[i], "%s.platform.%d.y", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformz[i], + init_platformz[i], "%s.platform.%d.z", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->basenx[i], + init_basenx[i], "%s.base-n.%d.x", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->baseny[i], + init_baseny[i], "%s.base-n.%d.y", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->basenz[i], + init_basenz[i], "%s.base-n.%d.z", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformnx[i], + init_platformnx[i], "%s.platform-n.%d.x", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformny[i], + init_platformny[i], "%s.platform-n.%d.y", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->platformnz[i], + init_platformnz[i], "%s.platform-n.%d.z", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_OUT, &haldata->correction[i], + 0.0, "%s.correction.%d", kp->halprefix, i); if (res) {goto error;} - *haldata->correction[i] = 0.0; - } - res += hal_pin_u32_newf(HAL_OUT, &haldata->last_iter, comp_id, - "genhexkins.last-iterations"); - *haldata->last_iter = 0; - res += hal_pin_u32_newf(HAL_OUT, &haldata->max_iter, comp_id, - "genhexkins.max-iterations"); - *haldata->max_iter = 0; - res += hal_pin_float_newf(HAL_IN, &haldata->max_error, comp_id, - "genhexkins.max-error"); - *haldata->max_error = 500.0; - res += hal_pin_float_newf(HAL_IN, &haldata->conv_criterion, comp_id, - "genhexkins.convergence-criterion"); - *haldata->conv_criterion = 1e-9; - res += hal_pin_u32_newf(HAL_IN, &haldata->iter_limit, comp_id, - "genhexkins.limit-iterations"); - *haldata->iter_limit = 120; - res += hal_pin_float_newf(HAL_IN, &haldata->tool_offset, comp_id, - "genhexkins.tool-offset"); - *haldata->tool_offset = 0.0; - res += hal_pin_float_newf(HAL_IN, &haldata->spindle_offset, comp_id, - "genhexkins.spindle-offset"); - *haldata->spindle_offset = 0.0; - res += hal_pin_float_newf(HAL_IN, &haldata->screw_lead, comp_id, - "genhexkins.screw-lead"); - *haldata->screw_lead = DEFAULT_SCREW_LEAD; + res += hal_pin_new_ui32(comp_id, HAL_OUT, &haldata->last_iter, + 0, "genhexkins.last-iterations"); + res += hal_pin_new_ui32(comp_id, HAL_OUT, &haldata->max_iter, + 0, "genhexkins.max-iterations"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->max_error, + 500.0, "genhexkins.max-error"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->conv_criterion, + 1e-9, "genhexkins.convergence-criterion"); + res += hal_pin_new_ui32(comp_id, HAL_IN, &haldata->iter_limit, + 120, "genhexkins.limit-iterations"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->tool_offset, + 0.0, "genhexkins.tool-offset"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->spindle_offset, + 0.0, "genhexkins.spindle-offset"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->screw_lead, + DEFAULT_SCREW_LEAD, "genhexkins.screw-lead"); if (res) {goto error;} - *haldata->basex[0] = DEFAULT_BASE_0_X; - *haldata->basey[0] = DEFAULT_BASE_0_Y; - *haldata->basez[0] = DEFAULT_BASE_0_Z; - *haldata->basex[1] = DEFAULT_BASE_1_X; - *haldata->basey[1] = DEFAULT_BASE_1_Y; - *haldata->basez[1] = DEFAULT_BASE_1_Z; - *haldata->basex[2] = DEFAULT_BASE_2_X; - *haldata->basey[2] = DEFAULT_BASE_2_Y; - *haldata->basez[2] = DEFAULT_BASE_2_Z; - *haldata->basex[3] = DEFAULT_BASE_3_X; - *haldata->basey[3] = DEFAULT_BASE_3_Y; - *haldata->basez[3] = DEFAULT_BASE_3_Z; - *haldata->basex[4] = DEFAULT_BASE_4_X; - *haldata->basey[4] = DEFAULT_BASE_4_Y; - *haldata->basez[4] = DEFAULT_BASE_4_Z; - *haldata->basex[5] = DEFAULT_BASE_5_X; - *haldata->basey[5] = DEFAULT_BASE_5_Y; - *haldata->basez[5] = DEFAULT_BASE_5_Z; - - *haldata->platformx[0] = DEFAULT_PLATFORM_0_X; - *haldata->platformy[0] = DEFAULT_PLATFORM_0_Y; - *haldata->platformz[0] = DEFAULT_PLATFORM_0_Z; - *haldata->platformx[1] = DEFAULT_PLATFORM_1_X; - *haldata->platformy[1] = DEFAULT_PLATFORM_1_Y; - *haldata->platformz[1] = DEFAULT_PLATFORM_1_Z; - *haldata->platformx[2] = DEFAULT_PLATFORM_2_X; - *haldata->platformy[2] = DEFAULT_PLATFORM_2_Y; - *haldata->platformz[2] = DEFAULT_PLATFORM_2_Z; - *haldata->platformx[3] = DEFAULT_PLATFORM_3_X; - *haldata->platformy[3] = DEFAULT_PLATFORM_3_Y; - *haldata->platformz[3] = DEFAULT_PLATFORM_3_Z; - *haldata->platformx[4] = DEFAULT_PLATFORM_4_X; - *haldata->platformy[4] = DEFAULT_PLATFORM_4_Y; - *haldata->platformz[4] = DEFAULT_PLATFORM_4_Z; - *haldata->platformx[5] = DEFAULT_PLATFORM_5_X; - *haldata->platformy[5] = DEFAULT_PLATFORM_5_Y; - *haldata->platformz[5] = DEFAULT_PLATFORM_5_Z; - - *haldata->basenx[0] = DEFAULT_BASE_0_NX; - *haldata->baseny[0] = DEFAULT_BASE_0_NY; - *haldata->basenz[0] = DEFAULT_BASE_0_NZ; - *haldata->basenx[1] = DEFAULT_BASE_1_NX; - *haldata->baseny[1] = DEFAULT_BASE_1_NY; - *haldata->basenz[1] = DEFAULT_BASE_1_NZ; - *haldata->basenx[2] = DEFAULT_BASE_2_NX; - *haldata->baseny[2] = DEFAULT_BASE_2_NY; - *haldata->basenz[2] = DEFAULT_BASE_2_NZ; - *haldata->basenx[3] = DEFAULT_BASE_3_NX; - *haldata->baseny[3] = DEFAULT_BASE_3_NY; - *haldata->basenz[3] = DEFAULT_BASE_3_NZ; - *haldata->basenx[4] = DEFAULT_BASE_4_NX; - *haldata->baseny[4] = DEFAULT_BASE_4_NY; - *haldata->basenz[4] = DEFAULT_BASE_4_NZ; - *haldata->basenx[5] = DEFAULT_BASE_5_NX; - *haldata->baseny[5] = DEFAULT_BASE_5_NY; - *haldata->basenz[5] = DEFAULT_BASE_5_NZ; - - *haldata->platformnx[0] = DEFAULT_PLATFORM_0_NX; - *haldata->platformny[0] = DEFAULT_PLATFORM_0_NY; - *haldata->platformnz[0] = DEFAULT_PLATFORM_0_NZ; - *haldata->platformnx[1] = DEFAULT_PLATFORM_1_NX; - *haldata->platformny[1] = DEFAULT_PLATFORM_1_NY; - *haldata->platformnz[1] = DEFAULT_PLATFORM_1_NZ; - *haldata->platformnx[2] = DEFAULT_PLATFORM_2_NX; - *haldata->platformny[2] = DEFAULT_PLATFORM_2_NY; - *haldata->platformnz[2] = DEFAULT_PLATFORM_2_NZ; - *haldata->platformnx[3] = DEFAULT_PLATFORM_3_NX; - *haldata->platformny[3] = DEFAULT_PLATFORM_3_NY; - *haldata->platformnz[3] = DEFAULT_PLATFORM_3_NZ; - *haldata->platformnx[4] = DEFAULT_PLATFORM_4_NX; - *haldata->platformny[4] = DEFAULT_PLATFORM_4_NY; - *haldata->platformnz[4] = DEFAULT_PLATFORM_4_NZ; - *haldata->platformnx[5] = DEFAULT_PLATFORM_5_NX; - *haldata->platformny[5] = DEFAULT_PLATFORM_5_NY; - *haldata->platformnz[5] = DEFAULT_PLATFORM_5_NZ; - //note: switchkins does not uses these as it provides gui.x, gui.y, etc. - res += hal_pin_float_newf(HAL_IN, &haldata->gui_x, comp_id, "genhexkins.x"); - res += hal_pin_float_newf(HAL_IN, &haldata->gui_y, comp_id, "genhexkins.y"); - res += hal_pin_float_newf(HAL_IN, &haldata->gui_z, comp_id, "genhexkins.z"); - res += hal_pin_float_newf(HAL_IN, &haldata->gui_a, comp_id, "genhexkins.a"); - res += hal_pin_float_newf(HAL_IN, &haldata->gui_b, comp_id, "genhexkins.b"); - res += hal_pin_float_newf(HAL_IN, &haldata->gui_c, comp_id, "genhexkins.c"); - - res += hal_pin_bit_newf(HAL_OUT, &haldata->fwd_kins_fail, comp_id, - "genhexkins.fwd-kins-fail"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_x, 0.0, "genhexkins.x"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_y, 0.0, "genhexkins.y"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_z, 0.0, "genhexkins.z"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_a, 0.0, "genhexkins.a"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_b, 0.0, "genhexkins.b"); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->gui_c, 0.0, "genhexkins.c"); + + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->fwd_kins_fail, + 0, "genhexkins.fwd-kins-fail"); if (res) goto error; return 0; diff --git a/src/emc/kinematics/genserfuncs.c b/src/emc/kinematics/genserfuncs.c index 8b005f7ca69..3d8aa726132 100644 --- a/src/emc/kinematics/genserfuncs.c +++ b/src/emc/kinematics/genserfuncs.c @@ -53,12 +53,12 @@ #endif static struct haldata { - hal_u32_t *max_iterations; - hal_u32_t *last_iterations; - hal_float_t *a[GENSER_MAX_JOINTS]; - hal_float_t *alpha[GENSER_MAX_JOINTS]; - hal_float_t *d[GENSER_MAX_JOINTS]; - hal_s32_t *unrotate[GENSER_MAX_JOINTS]; + hal_uint_t max_iterations; + hal_uint_t last_iterations; + hal_real_t a[GENSER_MAX_JOINTS]; + hal_real_t alpha[GENSER_MAX_JOINTS]; + hal_real_t d[GENSER_MAX_JOINTS]; + hal_sint_t unrotate[GENSER_MAX_JOINTS]; genser_struct *kins; go_pose *pos; // used in various functions, we malloc it // only once in genserKinematicsSetup() @@ -67,10 +67,6 @@ static struct haldata { static int total_joints; double j[GENSER_MAX_JOINTS]; -#define A(i) (*(haldata->a[i])) -#define ALPHA(i) (*(haldata->alpha[i])) -#define D(i) (*(haldata->d[i])) - #define KINS_PTR (haldata->kins) #if GENSER_MAX_JOINTS < 6 @@ -87,9 +83,9 @@ int genser_kin_init(void) { /* init them all and make them revolute joints */ /* FIXME: should allow LINEAR joints based on HAL param too */ for (t = 0; t < GENSER_MAX_JOINTS; t++) { - genser->links[t].u.dh.a = A(t); - genser->links[t].u.dh.alpha = ALPHA(t); - genser->links[t].u.dh.d = D(t); + genser->links[t].u.dh.a = hal_get_real(haldata->a[t]); + genser->links[t].u.dh.alpha = hal_get_real(haldata->alpha[t]); + genser->links[t].u.dh.d = hal_get_real(haldata->d[t]); genser->links[t].u.dh.theta = 0; genser->links[t].type = GO_LINK_DH; genser->links[t].quantity = GO_QUANTITY_ANGLE; @@ -341,8 +337,9 @@ int genserKinematicsForward(const double *joint, if (!GO_ROT_CLOSE(j[i],joint[i])) changed = 1; // convert to radians to pass to genser_kin_fwd jcopy[i] = joint[i] * PM_PI / 180; - if ((i) && *(haldata->unrotate[i])) - jcopy[i] -= *(haldata->unrotate[i])*jcopy[i-1]; + rtapi_s32 unrotate = hal_get_si32(haldata->unrotate[i]); + if ((i) && unrotate) + jcopy[i] -= unrotate * jcopy[i-1]; } if (changed) { @@ -473,9 +470,9 @@ int genserKinematicsInverse(const EmcPose * world, } for (genser->iterations = 0; - genser->iterations < *haldata->max_iterations; + genser->iterations < hal_get_ui32(haldata->max_iterations); genser->iterations++) { - *(haldata->last_iterations) = genser->iterations; + hal_set_ui32(haldata->last_iterations, genser->iterations); /* update the Jacobians */ for (link = 0; link < genser->link_num; link++) { go_link_joint_set(&genser->links[link], jest[link], &linkout[link]); @@ -557,8 +554,9 @@ int genserKinematicsInverse(const EmcPose * world, for (link = 0; link < genser->link_num; link++) { // convert from radians back to angles joints[link] = jest[link] * 180 / PM_PI; - if ((link) && *(haldata->unrotate[link])) - joints[link] += *(haldata->unrotate[link]) * joints[link-1]; + rtapi_s32 unrotate = hal_get_si32(haldata->unrotate[link]); + if ((link) && unrotate) + joints[link] += unrotate * joints[link-1]; } //rtapi_print("DONEkineInverse(joints: %f %f %f %f %f %f), (iterations=%d)\n", // joints[0],joints[1],joints[2],joints[3],joints[4],joints[5], genser->iterations); @@ -591,15 +589,26 @@ int genser_kin_inv_iterations(genser_struct * genser) int genser_kin_inv_set_max_iterations(int i) { if (i <= 0) return GO_RESULT_ERROR; - *haldata->max_iterations = i; + hal_set_ui32(haldata->max_iterations, i); return GO_RESULT_OK; } int genser_kin_inv_get_max_iterations() { - return *haldata->max_iterations; + return hal_get_ui32(haldata->max_iterations); } +static const rtapi_real init_a[GENSER_MAX_JOINTS] = { + DEFAULT_A1, DEFAULT_A2, DEFAULT_A3, DEFAULT_A4, DEFAULT_A5, DEFAULT_A6 +}; +static const rtapi_real init_alpha[GENSER_MAX_JOINTS] = { + DEFAULT_ALPHA1, DEFAULT_ALPHA2, DEFAULT_ALPHA3, DEFAULT_ALPHA4, DEFAULT_ALPHA5, DEFAULT_ALPHA6 +}; +static const rtapi_real init_d[GENSER_MAX_JOINTS] = { + DEFAULT_D1, DEFAULT_D2, DEFAULT_D3, DEFAULT_D4, DEFAULT_D5, DEFAULT_D6 +}; + + int genserKinematicsSetup(const int comp_id, const char* coordinates, kparms* kp) @@ -613,53 +622,28 @@ int genserKinematicsSetup(const int comp_id, total_joints = kp->max_joints; // only the first 6 joints have A,ALPHA,D,unrotate pins - for (i = 0; i < 6; i++) { - res += hal_pin_float_newf(HAL_IN, &(haldata->a[i]), comp_id, - "%s.A-%d", kp->halprefix, i); - *(haldata->a[i])=0; - res += hal_pin_float_newf(HAL_IN, &(haldata->alpha[i]), comp_id, - "%s.ALPHA-%d", kp->halprefix, i); - *(haldata->alpha[i])=0; - res += hal_pin_float_newf(HAL_IN, &(haldata->d[i]), comp_id, - "%s.D-%d", kp->halprefix, i); - *(haldata->d[i])=0; - res += hal_pin_s32_newf(HAL_IN, &(haldata->unrotate[i]), comp_id, - "%s.unrotate-%d", kp->halprefix, i); - *haldata->unrotate[i]=0; + for (i = 0; i < GENSER_MAX_JOINTS; i++) { + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->a[i]), + init_a[i], "%s.A-%d", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->alpha[i]), + init_alpha[i], "%s.ALPHA-%d", kp->halprefix, i); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d[i]), + init_d[i], "%s.D-%d", kp->halprefix, i); + res += hal_pin_new_si32(comp_id, HAL_IN, &(haldata->unrotate[i]), + 0, "%s.unrotate-%d", kp->halprefix, i); } - res += hal_pin_u32_newf(HAL_OUT, &(haldata->last_iterations), comp_id, - "%s.last-iterations",kp->halprefix); + res += hal_pin_new_ui32(comp_id, HAL_OUT, &(haldata->last_iterations), + 0, "%s.last-iterations",kp->halprefix); KINS_PTR = hal_malloc(sizeof(genser_struct)); haldata->pos = (go_pose *) hal_malloc(sizeof(go_pose)); if (KINS_PTR == NULL) {goto error;} if (haldata->pos == NULL) {goto error;} - res += hal_pin_u32_newf(HAL_IN, &haldata->max_iterations, comp_id, - "%s.max-iterations",kp->halprefix); + res += hal_pin_new_ui32(comp_id, HAL_IN, &haldata->max_iterations, + GENSER_DEFAULT_MAX_ITERATIONS, "%s.max-iterations",kp->halprefix); if (res) {goto error;} - *haldata->max_iterations = GENSER_DEFAULT_MAX_ITERATIONS; - - A(0) = DEFAULT_A1; - A(1) = DEFAULT_A2; - A(2) = DEFAULT_A3; - A(3) = DEFAULT_A4; - A(4) = DEFAULT_A5; - A(5) = DEFAULT_A6; - ALPHA(0) = DEFAULT_ALPHA1; - ALPHA(1) = DEFAULT_ALPHA2; - ALPHA(2) = DEFAULT_ALPHA3; - ALPHA(3) = DEFAULT_ALPHA4; - ALPHA(4) = DEFAULT_ALPHA5; - ALPHA(5) = DEFAULT_ALPHA6; - D(0) = DEFAULT_D1; - D(1) = DEFAULT_D2; - D(2) = DEFAULT_D3; - D(3) = DEFAULT_D4; - D(4) = DEFAULT_D5; - D(5) = DEFAULT_D6; - genser_hal_inited = 1; return 0; diff --git a/src/emc/kinematics/genserkins.h b/src/emc/kinematics/genserkins.h index eda6f9033b5..74c9b5d7ebf 100644 --- a/src/emc/kinematics/genserkins.h +++ b/src/emc/kinematics/genserkins.h @@ -76,7 +76,7 @@ typedef struct { go_link links[GENSER_MAX_JOINTS]; /*!< The link description of the device. */ int link_num; /*!< How many are actually present. */ - hal_u32_t iterations; /*!< How many iterations were actually used to compute the inverse kinematics. */ + unsigned iterations; /*!< How many iterations were actually used to compute the inverse kinematics. */ } genser_struct; extern int genser_kin_size(void); diff --git a/src/emc/kinematics/lineardeltakins.c b/src/emc/kinematics/lineardeltakins.c index 156338f1e4f..c12472a19fc 100644 --- a/src/emc/kinematics/lineardeltakins.c +++ b/src/emc/kinematics/lineardeltakins.c @@ -23,7 +23,8 @@ struct haldata { - hal_float_t *r, *l; + hal_real_t r; + hal_real_t l; } *haldata; int comp_id; @@ -34,7 +35,7 @@ int kinematicsForward(const double * joints, KINEMATICS_INVERSE_FLAGS * iflags) { (void)fflags; (void)iflags; - set_geometry(*haldata->r, *haldata->l); + set_geometry(hal_get_real(haldata->r), hal_get_real(haldata->l)); return kinematics_forward(joints, pos); } @@ -43,7 +44,7 @@ int kinematicsInverse(const EmcPose *pos, double *joints, KINEMATICS_FORWARD_FLAGS *fflags) { (void)iflags; (void)fflags; - set_geometry(*haldata->r, *haldata->l); + set_geometry(hal_get_real(haldata->r), hal_get_real(haldata->l)); return kinematics_inverse(pos, joints); } @@ -66,18 +67,12 @@ int rtapi_app_main(void) } if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->r, comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->r, DELTA_RADIUS, "lineardeltakins.R"); if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->l, comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->l, DELTA_DIAGONAL_ROD, "lineardeltakins.L"); - if(retval == 0) - { - *haldata->r = DELTA_RADIUS; - *haldata->l = DELTA_DIAGONAL_ROD; - } - if(retval == 0) { hal_ready(comp_id); diff --git a/src/emc/kinematics/maxkins.c b/src/emc/kinematics/maxkins.c index ebb38a10ed0..db8a9a7a0da 100644 --- a/src/emc/kinematics/maxkins.c +++ b/src/emc/kinematics/maxkins.c @@ -30,8 +30,8 @@ #endif struct haldata { - hal_float_t *pivot_length; - hal_bit_t *conventional_directions; //default is false + hal_real_t pivot_length; + hal_bool_t conventional_directions; //default is false } *haldata; int kinematicsForward(const double *joints, @@ -42,11 +42,12 @@ int kinematicsForward(const double *joints, (void)fflags; (void)iflags; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real pivot_length = hal_get_real(haldata->pivot_length); // B correction - const double zb = (*(haldata->pivot_length) + joints[8]) * cos(d2r(joints[4])); - const double xb = (*(haldata->pivot_length) + joints[8]) * sin(d2r(joints[4])); + const double zb = (pivot_length + joints[8]) * cos(d2r(joints[4])); + const double xb = (pivot_length + joints[8]) * sin(d2r(joints[4])); // C correction const double xyr = hypot(joints[0], joints[1]); @@ -60,7 +61,7 @@ int kinematicsForward(const double *joints, pos->tran.x = xyr * cos(xytheta) - (con * xb) - xv; pos->tran.y = xyr * sin(xytheta) - joints[7]; - pos->tran.z = joints[2] - zb - (con * zv) + *(haldata->pivot_length); + pos->tran.z = joints[2] - zb - (con * zv) + pivot_length; pos->a = joints[3]; pos->b = joints[4]; @@ -80,11 +81,12 @@ int kinematicsInverse(const EmcPose * pos, (void)iflags; (void)fflags; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real pivot_length = hal_get_real(haldata->pivot_length); // B correction - const double zb = (*(haldata->pivot_length) + pos->w) * cos(d2r(pos->b)); - const double xb = (*(haldata->pivot_length) + pos->w) * sin(d2r(pos->b)); + const double zb = (pivot_length + pos->w) * cos(d2r(pos->b)); + const double xb = (pivot_length + pos->w) * sin(d2r(pos->b)); // C correction const double xyr = hypot(pos->tran.x, pos->tran.y); @@ -98,7 +100,7 @@ int kinematicsInverse(const EmcPose * pos, joints[0] = xyr * cos(xytheta) + (con * xb) + xv; joints[1] = xyr * sin(xytheta) + pos->v; - joints[2] = pos->tran.z + zb - (con * zv) - *(haldata->pivot_length); + joints[2] = pos->tran.z + zb - (con * zv) - pivot_length; joints[3] = pos->a; joints[4] = pos->b; @@ -129,14 +131,12 @@ int rtapi_app_main(void) { haldata = hal_malloc(sizeof(struct haldata)); - result = hal_pin_float_new("maxkins.pivot-length", HAL_IO, &(haldata->pivot_length), comp_id); - - result += hal_pin_bit_new("maxkins.conventional-directions", HAL_IN, &(haldata->conventional_directions), comp_id); + result = hal_pin_new_real(comp_id, HAL_IO, &(haldata->pivot_length), 0.666, "maxkins.pivot-length"); + // default is unconventional + result += hal_pin_new_bool(comp_id, HAL_IN, &(haldata->conventional_directions), 0, "maxkins.conventional-directions"); if(result < 0) goto error; - *(haldata->pivot_length) = 0.666; - *(haldata->conventional_directions) = 0; // default is unconventional hal_ready(comp_id); return 0; diff --git a/src/emc/kinematics/pentakins.c b/src/emc/kinematics/pentakins.c index bf9c1bc96c2..18487be3134 100644 --- a/src/emc/kinematics/pentakins.c +++ b/src/emc/kinematics/pentakins.c @@ -56,17 +56,17 @@ #include "pentakins.h" struct haldata { - hal_float_t basex[NUM_STRUTS]; - hal_float_t basey[NUM_STRUTS]; - hal_float_t basez[NUM_STRUTS]; - hal_float_t effectorr[NUM_STRUTS]; - hal_float_t effectorz[NUM_STRUTS]; - hal_u32_t *last_iter; - hal_u32_t *max_iter; - hal_u32_t *iter_limit; - hal_float_t *max_error; - hal_float_t *conv_criterion; - hal_float_t *tool_offset; + hal_real_t basex[NUM_STRUTS]; + hal_real_t basey[NUM_STRUTS]; + hal_real_t basez[NUM_STRUTS]; + hal_real_t effectorr[NUM_STRUTS]; + hal_real_t effectorz[NUM_STRUTS]; + hal_uint_t last_iter; + hal_uint_t max_iter; + hal_uint_t iter_limit; + hal_real_t max_error; + hal_real_t conv_criterion; + hal_real_t tool_offset; } *haldata; @@ -189,12 +189,13 @@ int pentakins_read_hal_pins(void) { int t; /* set the base and effector coordinates from hal pin values */ + rtapi_real tool_offset = hal_get_real(haldata->tool_offset); for (t = 0; t < NUM_STRUTS; t++) { - b[t].x = haldata->basex[t]; - b[t].y = haldata->basey[t]; - b[t].z = haldata->basez[t] + *haldata->tool_offset; - ra[t] = haldata->effectorr[t]; - za[t] = haldata->effectorz[t] + *haldata->tool_offset; + b[t].x = hal_get_real(haldata->basex[t]); + b[t].y = hal_get_real(haldata->basey[t]); + b[t].z = hal_get_real(haldata->basez[t]) + tool_offset; + ra[t] = hal_get_real(haldata->effectorr[t]); + za[t] = hal_get_real(haldata->effectorz[t]) + tool_offset; } return 0; } @@ -285,10 +286,11 @@ int kinematicsForward(const double * joints, coord[4] = pos->b * PM_PI / 180.0; /* Enter Newton-Raphson iterative method */ + rtapi_real max_error = hal_get_real(haldata->max_error); while (iterate) { /* check for large error and return error flag if no convergence */ - if ((conv_err > +(*haldata->max_error)) || - (conv_err < -(*haldata->max_error))) { + if ((conv_err > +(max_error)) || + (conv_err < -(max_error))) { /* we can't converge */ return -2; }; @@ -297,7 +299,7 @@ int kinematicsForward(const double * joints, /* check iteration to see if the kinematics can reach the convergence criterion and return error flag if it can't */ - if (iteration > *haldata->iter_limit) { + if (iteration > hal_get_ui32(haldata->iter_limit)) { /* we can't converge */ return -5; } @@ -340,8 +342,9 @@ int kinematicsForward(const double * joints, /* enter loop to determine if a strut needs another iteration */ iterate = 0; /*assume iteration is done */ + rtapi_real conv_criterion = hal_get_real(haldata->conv_criterion); for (i = 0; i < NUM_STRUTS; i++) { - if (fabs(StrutLengthDiff[i]) > *haldata->conv_criterion) { + if (fabs(StrutLengthDiff[i]) > conv_criterion) { iterate = 1; } } @@ -354,10 +357,10 @@ int kinematicsForward(const double * joints, pos->a = coord[3] * 180.0 / PM_PI; pos->b = coord[4] * 180.0 / PM_PI; - *haldata->last_iter = iteration; + hal_set_ui32(haldata->last_iter, iteration); - if (iteration > *haldata->max_iter){ - *haldata->max_iter = iteration; + if (iteration > hal_get_ui32(haldata->max_iter)){ + hal_set_ui32(haldata->max_iter, iteration); } return 0; } @@ -410,6 +413,22 @@ MODULE_LICENSE("GPL"); int comp_id; +static const rtapi_real init_basex[NUM_STRUTS] = { + DEFAULT_BASE_0_X, DEFAULT_BASE_1_X, DEFAULT_BASE_2_X, DEFAULT_BASE_3_X, DEFAULT_BASE_4_X +}; +static const rtapi_real init_basey[NUM_STRUTS] = { + DEFAULT_BASE_0_Y, DEFAULT_BASE_1_Y, DEFAULT_BASE_2_Y, DEFAULT_BASE_3_Y, DEFAULT_BASE_4_Y +}; +static const rtapi_real init_basez[NUM_STRUTS] = { + DEFAULT_BASE_0_Z, DEFAULT_BASE_1_Z, DEFAULT_BASE_2_Z, DEFAULT_BASE_3_Z, DEFAULT_BASE_4_Z +}; +static const rtapi_real init_effectorr[NUM_STRUTS] = { + DEFAULT_EFFECTOR_0_R, DEFAULT_EFFECTOR_1_R, DEFAULT_EFFECTOR_2_R, DEFAULT_EFFECTOR_3_R, DEFAULT_EFFECTOR_4_R +}; +static const rtapi_real init_effectorz[NUM_STRUTS] = { + DEFAULT_EFFECTOR_0_Z, DEFAULT_EFFECTOR_1_Z, DEFAULT_EFFECTOR_2_Z, DEFAULT_EFFECTOR_3_Z, DEFAULT_EFFECTOR_4_Z +}; + int rtapi_app_main(void) { int res = 0, i; @@ -423,86 +442,52 @@ int rtapi_app_main(void) goto error; - for (i = 0; i < 6; i++) { + for (i = 0; i < NUM_STRUTS; i++) { - if ((res = hal_param_float_newf(HAL_RW, &(haldata->basex[i]), comp_id, - "pentakins.base.%d.x", i)) < 0) - goto error; + if ((res = hal_param_new_real(comp_id, HAL_RW, &(haldata->basex[i]), + init_basex[i], "pentakins.base.%d.x", i)) < 0) + goto error; - if ((res = hal_param_float_newf(HAL_RW, &haldata->basey[i], comp_id, - "pentakins.base.%d.y", i)) < 0) - goto error; + if ((res = hal_param_new_real(comp_id, HAL_RW, &haldata->basey[i], + init_basey[i], "pentakins.base.%d.y", i)) < 0) + goto error; - if ((res = hal_param_float_newf(HAL_RW, &haldata->basez[i], comp_id, - "pentakins.base.%d.z", i)) < 0) - goto error; + if ((res = hal_param_new_real(comp_id, HAL_RW, &haldata->basez[i], + init_basez[i], "pentakins.base.%d.z", i)) < 0) + goto error; - if ((res = hal_param_float_newf(HAL_RW, &haldata->effectorr[i], comp_id, - "pentakins.effector.%d.r", i)) < 0) - goto error; + if ((res = hal_param_new_real(comp_id, HAL_RW, &haldata->effectorr[i], + init_effectorr[i], "pentakins.effector.%d.r", i)) < 0) + goto error; - if ((res = hal_param_float_newf(HAL_RW, &haldata->effectorz[i], comp_id, - "pentakins.effector.%d.z", i)) < 0) - goto error; + if ((res = hal_param_new_real(comp_id, HAL_RW, &haldata->effectorz[i], + init_effectorz[i], "pentakins.effector.%d.z", i)) < 0) + goto error; } - if ((res = hal_pin_u32_newf(HAL_OUT, &haldata->last_iter, comp_id, - "pentakins.last-iterations")) < 0) - goto error; - *haldata->last_iter = 0; + if ((res = hal_pin_new_ui32(comp_id, HAL_OUT, &haldata->last_iter, + 0, "pentakins.last-iterations")) < 0) + goto error; - if ((res = hal_pin_u32_newf(HAL_OUT, &haldata->max_iter, comp_id, - "pentakins.max-iterations")) < 0) - goto error; - *haldata->max_iter = 0; + if ((res = hal_pin_new_ui32(comp_id, HAL_OUT, &haldata->max_iter, + 0, "pentakins.max-iterations")) < 0) + goto error; - if ((res = hal_pin_float_newf(HAL_IO, &haldata->max_error, comp_id, - "pentakins.max-error")) < 0) - goto error; - *haldata->max_error = 100; + if ((res = hal_pin_new_real(comp_id, HAL_IO, &haldata->max_error, + 100.0, "pentakins.max-error")) < 0) + goto error; - if ((res = hal_pin_float_newf(HAL_IO, &haldata->conv_criterion, comp_id, - "pentakins.convergence-criterion")) < 0) - goto error; - *haldata->conv_criterion = 1e-9; + if ((res = hal_pin_new_real(comp_id, HAL_IO, &haldata->conv_criterion, + 1e-9, "pentakins.convergence-criterion")) < 0) + goto error; - if ((res = hal_pin_u32_newf(HAL_IO, &haldata->iter_limit, comp_id, - "pentakins.limit-iterations")) < 0) - goto error; - *haldata->iter_limit = 120; + if ((res = hal_pin_new_ui32(comp_id, HAL_IO, &haldata->iter_limit, + 120, "pentakins.limit-iterations")) < 0) + goto error; - if ((res = hal_pin_float_newf(HAL_IN, &haldata->tool_offset, comp_id, - "pentakins.tool-offset")) < 0) - goto error; - *haldata->tool_offset = 0.0; - - haldata->basex[0] = DEFAULT_BASE_0_X; - haldata->basey[0] = DEFAULT_BASE_0_Y; - haldata->basez[0] = DEFAULT_BASE_0_Z; - haldata->basex[1] = DEFAULT_BASE_1_X; - haldata->basey[1] = DEFAULT_BASE_1_Y; - haldata->basez[1] = DEFAULT_BASE_1_Z; - haldata->basex[2] = DEFAULT_BASE_2_X; - haldata->basey[2] = DEFAULT_BASE_2_Y; - haldata->basez[2] = DEFAULT_BASE_2_Z; - haldata->basex[3] = DEFAULT_BASE_3_X; - haldata->basey[3] = DEFAULT_BASE_3_Y; - haldata->basez[3] = DEFAULT_BASE_3_Z; - haldata->basex[4] = DEFAULT_BASE_4_X; - haldata->basey[4] = DEFAULT_BASE_4_Y; - haldata->basez[4] = DEFAULT_BASE_4_Z; - - haldata->effectorz[0] = DEFAULT_EFFECTOR_0_Z; - haldata->effectorz[1] = DEFAULT_EFFECTOR_1_Z; - haldata->effectorz[2] = DEFAULT_EFFECTOR_2_Z; - haldata->effectorz[3] = DEFAULT_EFFECTOR_3_Z; - haldata->effectorz[4] = DEFAULT_EFFECTOR_4_Z; - - haldata->effectorr[0] = DEFAULT_EFFECTOR_0_R; - haldata->effectorr[1] = DEFAULT_EFFECTOR_1_R; - haldata->effectorr[2] = DEFAULT_EFFECTOR_2_R; - haldata->effectorr[3] = DEFAULT_EFFECTOR_3_R; - haldata->effectorr[4] = DEFAULT_EFFECTOR_4_R; + if ((res = hal_pin_new_real(comp_id, HAL_IN, &haldata->tool_offset, + 0.0, "pentakins.tool-offset")) < 0) + goto error; hal_ready(comp_id); return 0; diff --git a/src/emc/kinematics/pumakins.c b/src/emc/kinematics/pumakins.c index ab718a69503..f055e73a502 100644 --- a/src/emc/kinematics/pumakins.c +++ b/src/emc/kinematics/pumakins.c @@ -26,14 +26,8 @@ #include "switchkins.h" struct haldata { - hal_float_t *a2, *a3, *d3, *d4, *d6; -} *haldata = 0; - -#define PUMA_A2 (*(haldata->a2)) -#define PUMA_A3 (*(haldata->a3)) -#define PUMA_D3 (*(haldata->d3)) -#define PUMA_D4 (*(haldata->d4)) -#define PUMA_D6 (*(haldata->d6)) + hal_real_t a2, a3, d3, d4, d6; +} *haldata = NULL; static int pumaKinematicsForward(const double * joint, EmcPose * world, @@ -105,6 +99,11 @@ static int pumaKinematicsForward(const double * joint, hom.rot.z.y = -s1 * t1 + c1 * s4 * s5; hom.rot.z.z = s23 * c4 * s5 - c23 * c5; + rtapi_real PUMA_A2 = hal_get_real(haldata->a2); + rtapi_real PUMA_A3 = hal_get_real(haldata->a3); + rtapi_real PUMA_D3 = hal_get_real(haldata->d3); + rtapi_real PUMA_D4 = hal_get_real(haldata->d4); + /* Calculate term to be used in definition of... */ /* position vector. */ t1 = PUMA_A2 * c2 + PUMA_A3 * c23 - PUMA_D4 * s23; @@ -156,6 +155,7 @@ static int pumaKinematicsForward(const double * joint, *iflags |= PUMA_WRIST_FLIP; } } + rtapi_real PUMA_D6 = hal_get_real(haldata->d6); /* add effect of d6 parameter */ hom.tran.x = hom.tran.x + hom.rot.z.x*PUMA_D6; hom.tran.y = hom.tran.y + hom.rot.z.y*PUMA_D6; @@ -214,6 +214,12 @@ static int pumaKinematicsInverse(const EmcPose * world, pmRpyQuatConvert(&rpy,&worldPose.rot); pmPoseHomConvert(&worldPose, &hom); + rtapi_real PUMA_A2 = hal_get_real(haldata->a2); + rtapi_real PUMA_A3 = hal_get_real(haldata->a3); + rtapi_real PUMA_D3 = hal_get_real(haldata->d3); + rtapi_real PUMA_D4 = hal_get_real(haldata->d4); + rtapi_real PUMA_D6 = hal_get_real(haldata->d6); + /* remove effect of d6 parameter */ px = hom.tran.x - PUMA_D6*hom.rot.z.x; py = hom.tran.y - PUMA_D6*hom.rot.z.y; @@ -336,19 +342,13 @@ int pumaKinematicsSetup(const int comp_id, if (!haldata) goto error; - res += hal_pin_float_newf(HAL_IN, &(haldata->a2), comp_id,"%s.A2",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->a3), comp_id,"%s.A3",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d3), comp_id,"%s.D3",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d4), comp_id,"%s.D4",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d6), comp_id,"%s.D6",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->a2), DEFAULT_PUMA560_A2, "%s.A2", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->a3), DEFAULT_PUMA560_A3, "%s.A3", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d3), DEFAULT_PUMA560_D3, "%s.D3", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d4), DEFAULT_PUMA560_D4, "%s.D4", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d6), DEFAULT_PUMA560_D6, "%s.D6", kp->halprefix); if (res) { goto error; } - PUMA_A2 = DEFAULT_PUMA560_A2; - PUMA_A3 = DEFAULT_PUMA560_A3; - PUMA_D3 = DEFAULT_PUMA560_D3; - PUMA_D4 = DEFAULT_PUMA560_D4; - PUMA_D6 = DEFAULT_PUMA560_D6; - return 0; error: diff --git a/src/emc/kinematics/rosekins.c b/src/emc/kinematics/rosekins.c index 46d8f7f64c3..5bbcef6ff06 100644 --- a/src/emc/kinematics/rosekins.c +++ b/src/emc/kinematics/rosekins.c @@ -33,9 +33,9 @@ MODULE_LICENSE("GPL"); #endif struct haldata { - hal_float_t *revolutions; - hal_float_t *theta_degrees; - hal_float_t *bigtheta_degrees; + hal_real_t revolutions; + hal_real_t theta_degrees; + hal_real_t bigtheta_degrees; } *haldata; int kinematicsForward(const double *joints, @@ -94,9 +94,9 @@ int kinematicsInverse(const EmcPose * pos, theta = atan2(y,x); bigtheta = theta + PM_2_PI * revolutions; - *(haldata->revolutions) = revolutions; - *(haldata->theta_degrees) = theta * TO_DEG; - *(haldata->bigtheta_degrees) = bigtheta * TO_DEG; + hal_set_real(haldata->revolutions, revolutions); + hal_set_real(haldata->theta_degrees, theta * TO_DEG); + hal_set_real(haldata->bigtheta_degrees, bigtheta * TO_DEG); joints[0] = hypot(x,y); joints[1] = z; @@ -128,12 +128,12 @@ int rtapi_app_main(void) { haldata = hal_malloc(sizeof(struct haldata)); - if((ans = hal_pin_float_new("rosekins.revolutions", - HAL_OUT, &(haldata->revolutions), comp_id)) < 0) goto error; - if((ans = hal_pin_float_new("rosekins.theta_degrees", - HAL_OUT, &(haldata->theta_degrees), comp_id)) < 0) goto error; - if((ans = hal_pin_float_new("rosekins.bigtheta_degrees", - HAL_OUT, &(haldata->bigtheta_degrees), comp_id)) < 0) goto error; + if((ans = hal_pin_new_real(comp_id, HAL_OUT, &(haldata->revolutions), 0.0, "rosekins.revolutions")) < 0) + goto error; + if((ans = hal_pin_new_real(comp_id, HAL_OUT, &(haldata->theta_degrees), 0.0, "rosekins.theta_degrees")) < 0) + goto error; + if((ans = hal_pin_new_real(comp_id, HAL_OUT, &(haldata->bigtheta_degrees), 0.0, "rosekins.bigtheta_degrees")) < 0) + goto error; hal_ready(comp_id); return 0; diff --git a/src/emc/kinematics/rotarydeltakins.c b/src/emc/kinematics/rotarydeltakins.c index 099d18f5f4e..1a2d465cc5a 100644 --- a/src/emc/kinematics/rotarydeltakins.c +++ b/src/emc/kinematics/rotarydeltakins.c @@ -24,10 +24,10 @@ struct haldata { - hal_float_t *pfr; - hal_float_t *tl; - hal_float_t *sl; - hal_float_t *fr; + hal_real_t pfr; + hal_real_t tl; + hal_real_t sl; + hal_real_t fr; } *haldata; int comp_id; @@ -38,7 +38,7 @@ int kinematicsForward(const double * joints, KINEMATICS_INVERSE_FLAGS * iflags) { (void)fflags; (void)iflags; - set_geometry(*haldata->pfr, *haldata->tl, *haldata->sl, *haldata->fr); + set_geometry(hal_get_real(haldata->pfr), hal_get_real(haldata->tl), hal_get_real(haldata->sl), hal_get_real(haldata->fr)); return kinematics_forward(joints, pos); } @@ -47,7 +47,7 @@ int kinematicsInverse(const EmcPose *pos, double *joints, KINEMATICS_FORWARD_FLAGS *fflags) { (void)iflags; (void)fflags; - set_geometry(*haldata->pfr, *haldata->tl, *haldata->sl, *haldata->fr); + set_geometry(hal_get_real(haldata->pfr), hal_get_real(haldata->tl), hal_get_real(haldata->sl), hal_get_real(haldata->fr)); return kinematics_inverse(pos, joints); } @@ -70,25 +70,17 @@ int rtapi_app_main(void) } if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->pfr, comp_id, - "rotarydeltakins.platformradius"); + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->pfr, + RDELTA_PFR, "rotarydeltakins.platformradius"); if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->tl, comp_id, - "rotarydeltakins.thighlength"); + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->tl, + RDELTA_TL, "rotarydeltakins.thighlength"); if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->sl, comp_id, - "rotarydeltakins.shinlength"); + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->sl, + RDELTA_SL, "rotarydeltakins.shinlength"); if(retval == 0) - retval = hal_pin_float_newf(HAL_IN, &haldata->fr, comp_id, - "rotarydeltakins.footradius"); - - if(retval == 0) - { - *haldata->pfr = RDELTA_PFR; - *haldata->tl = RDELTA_TL; - *haldata->sl = RDELTA_SL; - *haldata->fr = RDELTA_FR; - } + retval = hal_pin_new_real(comp_id, HAL_IN, &haldata->fr, + RDELTA_FR, "rotarydeltakins.footradius"); if(retval == 0) { diff --git a/src/emc/kinematics/scarakins.c b/src/emc/kinematics/scarakins.c index 235cf6ae873..c20125dbb98 100644 --- a/src/emc/kinematics/scarakins.c +++ b/src/emc/kinematics/scarakins.c @@ -24,8 +24,8 @@ #include "switchkins.h" struct scara_data { - hal_float_t *d1, *d2, *d3, *d4, *d5, *d6; -} *haldata = 0; + hal_real_t d1, d2, d3, d4, d5, d6; +} *haldata = NULL; /* key dimensions @@ -63,13 +63,6 @@ struct scara_data { on the value of joint[3]. */ -#define D1 (*(haldata->d1)) -#define D2 (*(haldata->d2)) -#define D3 (*(haldata->d3)) -#define D4 (*(haldata->d4)) -#define D5 (*(haldata->d5)) -#define D6 (*(haldata->d6)) - /* joint[0], joint[1] and joint[3] are in degrees and joint[2] is in length units */ static int scaraKinematicsForward(const double * joint, @@ -91,6 +84,13 @@ int scaraKinematicsForward(const double * joint, a1 = a1 + a0; a3 = a3 + a1; + rtapi_real D1 = hal_get_real(haldata->d1); + rtapi_real D2 = hal_get_real(haldata->d2); + rtapi_real D3 = hal_get_real(haldata->d3); + rtapi_real D4 = hal_get_real(haldata->d4); + rtapi_real D5 = hal_get_real(haldata->d5); + rtapi_real D6 = hal_get_real(haldata->d6); + x = D2*cos(a0) + D4*cos(a1) + D6*cos(a3); y = D2*sin(a0) + D4*sin(a1) + D6*sin(a3); z = D1 + D3 - joint[2] - D5; @@ -129,6 +129,13 @@ static int scaraKinematicsInverse(const EmcPose * world, /* convert degrees to radians */ a3 = c * ( PM_PI / 180 ); + rtapi_real D1 = hal_get_real(haldata->d1); + rtapi_real D2 = hal_get_real(haldata->d2); + rtapi_real D3 = hal_get_real(haldata->d3); + rtapi_real D4 = hal_get_real(haldata->d4); + rtapi_real D5 = hal_get_real(haldata->d5); + rtapi_real D6 = hal_get_real(haldata->d6); + /* center of end effector (correct for D6) */ xt = x - D6*cos(a3); yt = y - D6*sin(a3); @@ -188,21 +195,14 @@ static int scaraKinematicsSetup(const int comp_id, haldata = hal_malloc(sizeof(*haldata)); if (!haldata) goto error; - res += hal_pin_float_newf(HAL_IN, &(haldata->d1), comp_id,"%s.D1",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d2), comp_id,"%s.D2",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d3), comp_id,"%s.D3",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d4), comp_id,"%s.D4",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d5), comp_id,"%s.D5",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->d6), comp_id,"%s.D6",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d1), DEFAULT_D1, "%s.D1", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d2), DEFAULT_D2, "%s.D2", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d3), DEFAULT_D3, "%s.D3", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d4), DEFAULT_D4, "%s.D4", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d5), DEFAULT_D5, "%s.D5", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->d6), DEFAULT_D6, "%s.D6", kp->halprefix); if (res) { goto error; } - D1 = DEFAULT_D1; - D2 = DEFAULT_D2; - D3 = DEFAULT_D3; - D4 = DEFAULT_D4; - D5 = DEFAULT_D5; - D6 = DEFAULT_D6; - return 0; error: diff --git a/src/emc/kinematics/switchkins.c b/src/emc/kinematics/switchkins.c index 9eb492e6da9..19a7ac23bbd 100644 --- a/src/emc/kinematics/switchkins.c +++ b/src/emc/kinematics/switchkins.c @@ -38,26 +38,26 @@ // kinematic functions (default=0 for err detection): static kparms kp; // kinematics parms (common all types) -static KF kfwd0 = 0; // 0==switchkins_type kinematics forward -static KF kfwd1 = 0; // 1 -static KF kfwd2 = 0; // 2 +static KF kfwd0 = NULL; // 0==switchkins_type kinematics forward +static KF kfwd1 = NULL; // 1 +static KF kfwd2 = NULL; // 2 -static KI kinv0 = 0; // 0==switchkins_type kinematics inverse -static KI kinv1 = 0; // 1 -static KI kinv2 = 0; // 2 +static KI kinv0 = NULL; // 0==switchkins_type kinematics inverse +static KI kinv1 = NULL; // 1 +static KI kinv2 = NULL; // 2 -static hal_u32_t switchkins_type; +static int switchkins_type; static struct swdata { - hal_bit_t *kinstype_is_0; - hal_bit_t *kinstype_is_1; - hal_bit_t *kinstype_is_2; - - hal_float_t *gui_x; - hal_float_t *gui_y; - hal_float_t *gui_z; - hal_float_t *gui_a; - hal_float_t *gui_b; - hal_float_t *gui_c; + hal_bool_t kinstype_is_0; + hal_bool_t kinstype_is_1; + hal_bool_t kinstype_is_2; + + hal_real_t gui_x; + hal_real_t gui_y; + hal_real_t gui_z; + hal_real_t gui_a; + hal_real_t gui_b; + hal_real_t gui_c; } *swdata; // Note: parallel kinematics (like genhexkins) often @@ -113,12 +113,12 @@ static int gui_forward_kins(const double *joints) kp.gui_kinstype); return -1; } - *swdata->gui_x = lastpose[kp.gui_kinstype].tran.x; - *swdata->gui_y = lastpose[kp.gui_kinstype].tran.y; - *swdata->gui_z = lastpose[kp.gui_kinstype].tran.z; - *swdata->gui_a = lastpose[kp.gui_kinstype].a; - *swdata->gui_b = lastpose[kp.gui_kinstype].b; - *swdata->gui_c = lastpose[kp.gui_kinstype].c; + hal_set_real(swdata->gui_x, lastpose[kp.gui_kinstype].tran.x); + hal_set_real(swdata->gui_y, lastpose[kp.gui_kinstype].tran.y); + hal_set_real(swdata->gui_z, lastpose[kp.gui_kinstype].tran.z); + hal_set_real(swdata->gui_a, lastpose[kp.gui_kinstype].a); + hal_set_real(swdata->gui_b, lastpose[kp.gui_kinstype].b); + hal_set_real(swdata->gui_c, lastpose[kp.gui_kinstype].c); return res; } // gui_forward_kins @@ -134,28 +134,28 @@ int kinematicsSwitch(int new_switchkins_type) switch (switchkins_type) { case 0: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE0\n"); - *swdata->kinstype_is_0 = 1; - *swdata->kinstype_is_1 = 0; - *swdata->kinstype_is_2 = 0; + hal_set_bool(swdata->kinstype_is_0, 1); + hal_set_bool(swdata->kinstype_is_1, 0); + hal_set_bool(swdata->kinstype_is_2, 0); break; case 1: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *swdata->kinstype_is_0 = 0; - *swdata->kinstype_is_1 = 1; - *swdata->kinstype_is_2 = 0; + hal_set_bool(swdata->kinstype_is_0, 0); + hal_set_bool(swdata->kinstype_is_1, 1); + hal_set_bool(swdata->kinstype_is_2, 0); break; case 2: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE2\n"); - *swdata->kinstype_is_0 = 0; - *swdata->kinstype_is_1 = 0; - *swdata->kinstype_is_2 = 1; + hal_set_bool(swdata->kinstype_is_0, 0); + hal_set_bool(swdata->kinstype_is_1, 0); + hal_set_bool(swdata->kinstype_is_2, 1); break; default: rtapi_print_msg(RTAPI_MSG_ERR, "kinematicsSwitch:BAD VALUE <%d>\n", switchkins_type); - *swdata->kinstype_is_1 = 0; - *swdata->kinstype_is_0 = 0; - *swdata->kinstype_is_2 = 0; + hal_set_bool(swdata->kinstype_is_1, 0); + hal_set_bool(swdata->kinstype_is_0, 0); + hal_set_bool(swdata->kinstype_is_2, 0); return -1; // FAIL } if (fwd_iterates[switchkins_type]) { @@ -259,9 +259,9 @@ int rtapi_app_main(void) kp.sparm = sparm; // module parm passed to kins - KS ksetup0 = 0; - KS ksetup1 = 0; - KS ksetup2 = 0; + KS ksetup0 = NULL; + KS ksetup1 = NULL; + KS ksetup2 = NULL; res = switchkinsSetup(&kp, &ksetup0, &ksetup1, &ksetup2, @@ -306,17 +306,17 @@ int rtapi_app_main(void) swdata = hal_malloc(sizeof(struct swdata)); if (!swdata) goto error; - res += hal_pin_bit_new("kinstype.is-0", HAL_OUT, &(swdata->kinstype_is_0), comp_id); - res += hal_pin_bit_new("kinstype.is-1", HAL_OUT, &(swdata->kinstype_is_1), comp_id); - res += hal_pin_bit_new("kinstype.is-2", HAL_OUT, &(swdata->kinstype_is_2), comp_id); + res += hal_pin_new_bool(comp_id, HAL_OUT, &(swdata->kinstype_is_0), 0, "kinstype.is-0"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &(swdata->kinstype_is_1), 0, "kinstype.is-1"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &(swdata->kinstype_is_2), 0, "kinstype.is-2"); if (kp.gui_kinstype >=0) { - res += hal_pin_float_newf(HAL_IN, &swdata->gui_x, comp_id, "skgui.x"); - res += hal_pin_float_newf(HAL_IN, &swdata->gui_y, comp_id, "skgui.y"); - res += hal_pin_float_newf(HAL_IN, &swdata->gui_z, comp_id, "skgui.z"); - res += hal_pin_float_newf(HAL_IN, &swdata->gui_a, comp_id, "skgui.a"); - res += hal_pin_float_newf(HAL_IN, &swdata->gui_b, comp_id, "skgui.b"); - res += hal_pin_float_newf(HAL_IN, &swdata->gui_c, comp_id, "skgui.c"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_x, 0.0, "skgui.x"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_y, 0.0, "skgui.y"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_z, 0.0, "skgui.z"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_a, 0.0, "skgui.a"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_b, 0.0, "skgui.b"); + res += hal_pin_new_real(comp_id, HAL_IN, &swdata->gui_c, 0.0, "skgui.c"); if (res) {emsg = "hal pin create fail";goto error;} } diff --git a/src/emc/kinematics/tripodkins.c b/src/emc/kinematics/tripodkins.c index d0a12dcb32e..b3a7d996987 100644 --- a/src/emc/kinematics/tripodkins.c +++ b/src/emc/kinematics/tripodkins.c @@ -76,12 +76,10 @@ #endif struct haldata { - hal_float_t *bx, *cx, *cy; -} *haldata = 0; - -#define Bx (*(haldata->bx)) -#define Cx (*(haldata->cx)) -#define Cy (*(haldata->cy)) + hal_real_t bx; + hal_real_t cx; + hal_real_t cy; +} *haldata = NULL; #define sq(x) ((x)*(x)) @@ -139,6 +137,9 @@ int kinematicsForward(const double * joints, #define Dz (pos->tran.z) double P, Q, R; double s, t, u; + rtapi_real Bx = hal_get_real(haldata->bx); + rtapi_real Cx = hal_get_real(haldata->cx); + rtapi_real Cy = hal_get_real(haldata->cy); P = sq(AD); Q = sq(BD) - sq(Bx); @@ -194,6 +195,9 @@ int kinematicsInverse(const EmcPose * pos, #define Dx (pos->tran.x) #define Dy (pos->tran.y) #define Dz (pos->tran.z) + rtapi_real Bx = hal_get_real(haldata->bx); + rtapi_real Cx = hal_get_real(haldata->cx); + rtapi_real Cy = hal_get_real(haldata->cy); AD = sqrt(sq(Dx) + sq(Dy) + sq(Dz)); BD = sqrt(sq(Dx - Bx) + sq(Dy) + sq(Dz)); @@ -367,11 +371,10 @@ int rtapi_app_main(void) { haldata = hal_malloc(sizeof(struct haldata)); if(!haldata) goto error; - if((res = hal_pin_float_new("tripodkins.Bx", HAL_IO, &(haldata->bx), comp_id)) < 0) goto error; - if((res = hal_pin_float_new("tripodkins.Cx", HAL_IO, &(haldata->cx), comp_id)) < 0) goto error; - if((res = hal_pin_float_new("tripodkins.Cy", HAL_IO, &(haldata->cy), comp_id)) < 0) goto error; + if((res = hal_pin_new_real(comp_id, HAL_IO, &(haldata->bx), 1.0, "tripodkins.Bx")) < 0) goto error; + if((res = hal_pin_new_real(comp_id, HAL_IO, &(haldata->cx), 1.0, "tripodkins.Cx")) < 0) goto error; + if((res = hal_pin_new_real(comp_id, HAL_IO, &(haldata->cy), 1.0, "tripodkins.Cy")) < 0) goto error; - Bx = Cx = Cy = 1.0; hal_ready(comp_id); return 0; diff --git a/src/emc/kinematics/trtfuncs.c b/src/emc/kinematics/trtfuncs.c index ac9e18c6b32..1a991b0068f 100644 --- a/src/emc/kinematics/trtfuncs.c +++ b/src/emc/kinematics/trtfuncs.c @@ -54,14 +54,14 @@ static int JV = -1; static int JW = -1; struct haldata { - hal_float_t *x_rot_point; - hal_float_t *y_rot_point; - hal_float_t *z_rot_point; - hal_float_t *x_offset; - hal_float_t *y_offset; - hal_float_t *z_offset; - hal_float_t *tool_offset; - hal_bit_t *conventional_directions; // default: false + hal_real_t x_rot_point; + hal_real_t y_rot_point; + hal_real_t z_rot_point; + hal_real_t x_offset; + hal_real_t y_offset; + hal_real_t z_offset; + hal_real_t tool_offset; + hal_bool_t conventional_directions; // default: false } *haldata; @@ -128,22 +128,22 @@ int trtKinematicsSetup(const int comp_id, haldata = hal_malloc(sizeof(struct haldata)); if (!haldata) {goto error;} - res += hal_pin_float_newf(HAL_IN, &(haldata->x_rot_point), comp_id, - "%s.x-rot-point",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->y_rot_point), comp_id, - "%s.y-rot-point",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->z_rot_point), comp_id, - "%s.z-rot-point",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->x_offset), comp_id, - "%s.x-offset",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->y_offset), comp_id, - "%s.y-offset",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->z_offset), comp_id, - "%s.z-offset",kp->halprefix); - res += hal_pin_float_newf(HAL_IN, &(haldata->tool_offset), comp_id, - "%s.tool-offset",kp->halprefix); - res += hal_pin_bit_newf(HAL_IN, &(haldata->conventional_directions), comp_id, - "%s.conventional-directions", kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->x_rot_point), + 0.0, "%s.x-rot-point",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->y_rot_point), + 0.0, "%s.y-rot-point",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->z_rot_point), + 0.0, "%s.z-rot-point",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->x_offset), + 0.0, "%s.x-offset",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->y_offset), + 0.0, "%s.y-offset",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->z_offset), + 0.0, "%s.z-offset",kp->halprefix); + res += hal_pin_new_real(comp_id, HAL_IN, &(haldata->tool_offset), + 0.0, "%s.tool-offset",kp->halprefix); + res += hal_pin_new_bool(comp_id, HAL_IN, &(haldata->conventional_directions), + 0, "%s.conventional-directions", kp->halprefix); if (res) {goto error;} return 0; @@ -159,16 +159,16 @@ int xyzacKinematicsForward(const double *joints, { (void)fflags; (void)iflags; - const double x_rot_point = *(haldata->x_rot_point); - const double y_rot_point = *(haldata->y_rot_point); - const double z_rot_point = *(haldata->z_rot_point); - const double dt = *(haldata->tool_offset); - const double dy = *(haldata->y_offset); - const double dz = *(haldata->z_offset) + dt; + const double x_rot_point = hal_get_real(haldata->x_rot_point); + const double y_rot_point = hal_get_real(haldata->y_rot_point); + const double z_rot_point = hal_get_real(haldata->z_rot_point); + const double dt = hal_get_real(haldata->tool_offset); + const double dy = hal_get_real(haldata->y_offset); + const double dz = hal_get_real(haldata->z_offset) + dt; const double a_rad = joints[JA]*TO_RAD; const double c_rad = joints[JC]*TO_RAD; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; pos->tran.x = + cos(c_rad) * (joints[JX] - x_rot_point) - con * sin(c_rad) * cos(a_rad) * (joints[JY] - dy - y_rot_point) @@ -207,16 +207,16 @@ int xyzacKinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - const double x_rot_point = *(haldata->x_rot_point); - const double y_rot_point = *(haldata->y_rot_point); - const double z_rot_point = *(haldata->z_rot_point); - const double dy = *(haldata->y_offset); - const double dt = *(haldata->tool_offset); - const double dz = *(haldata->z_offset) + dt; + const double x_rot_point = hal_get_real(haldata->x_rot_point); + const double y_rot_point = hal_get_real(haldata->y_rot_point); + const double z_rot_point = hal_get_real(haldata->z_rot_point); + const double dy = hal_get_real(haldata->y_offset); + const double dt = hal_get_real(haldata->tool_offset); + const double dz = hal_get_real(haldata->z_offset) + dt; const double a_rad = pos->a*TO_RAD; const double c_rad = pos->c*TO_RAD; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; EmcPose P; // computed position @@ -268,16 +268,16 @@ int xyzbcKinematicsForward(const double *joints, (void)fflags; (void)iflags; // Note: 'principal' joints are used - const double x_rot_point = *(haldata->x_rot_point); - const double y_rot_point = *(haldata->y_rot_point); - const double z_rot_point = *(haldata->z_rot_point); - const double dx = *(haldata->x_offset); - const double dt = *(haldata->tool_offset); - const double dz = *(haldata->z_offset) + dt; + const double x_rot_point = hal_get_real(haldata->x_rot_point); + const double y_rot_point = hal_get_real(haldata->y_rot_point); + const double z_rot_point = hal_get_real(haldata->z_rot_point); + const double dx = hal_get_real(haldata->x_offset); + const double dt = hal_get_real(haldata->tool_offset); + const double dz = hal_get_real(haldata->z_offset) + dt; const double b_rad = joints[JB]*TO_RAD; const double c_rad = joints[JC]*TO_RAD; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; pos->tran.x = cos(c_rad) * cos(b_rad) * (joints[JX] - dx - x_rot_point) - con * sin(c_rad) * (joints[JY] - y_rot_point) @@ -315,18 +315,18 @@ int xyzbcKinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - const double x_rot_point = *(haldata->x_rot_point); - const double y_rot_point = *(haldata->y_rot_point); - const double z_rot_point = *(haldata->z_rot_point); - const double dx = *(haldata->x_offset); - const double dt = *(haldata->tool_offset); - const double dz = *(haldata->z_offset) + dt; + const double x_rot_point = hal_get_real(haldata->x_rot_point); + const double y_rot_point = hal_get_real(haldata->y_rot_point); + const double z_rot_point = hal_get_real(haldata->z_rot_point); + const double dx = hal_get_real(haldata->x_offset); + const double dt = hal_get_real(haldata->tool_offset); + const double dz = hal_get_real(haldata->z_offset) + dt; const double b_rad = pos->b*TO_RAD; const double c_rad = pos->c*TO_RAD; const double dpx = -cos(b_rad)*dx + sin(b_rad)*dz + dx; const double dpz = -sin(b_rad)*dx - cos(b_rad)*dz + dz; - const real_t con = *(haldata->conventional_directions) ? 1.0 : -1.0; + rtapi_real con = hal_get_bool(haldata->conventional_directions) ? 1.0 : -1.0; EmcPose P; // computed position diff --git a/src/emc/kinematics/userkfuncs.c b/src/emc/kinematics/userkfuncs.c index d1c6b6a4c4e..81aa4c2d942 100644 --- a/src/emc/kinematics/userkfuncs.c +++ b/src/emc/kinematics/userkfuncs.c @@ -28,8 +28,8 @@ static int userk_inited = 0; static struct udata { - hal_s32_t *fct; - hal_s32_t *ict; + hal_sint_t fct; + hal_sint_t ict; } *udata; //********************************************************************** @@ -48,8 +48,8 @@ int userkKinematicsSetup(const int comp_id, if (!udata) goto error; // HAL_IO used to allow resetting demo pins: - res += hal_pin_s32_new("userk.fct", HAL_IO, &(udata->fct), comp_id); - res += hal_pin_s32_new("userk.ict", HAL_IO, &(udata->ict), comp_id); + res += hal_pin_new_si32(comp_id, HAL_IO, &(udata->fct), 0, "userk.fct"); + res += hal_pin_new_si32(comp_id, HAL_IO, &(udata->ict), 0, "userk.ict"); if (res) goto error; userk_inited = 1; @@ -69,7 +69,7 @@ int userkKinematicsForward(const double *joint, "userkKinematics: not initialized\n"); return -1; } - (*udata->fct)++; + hal_set_si32(udata->fct, hal_get_si32(udata->fct) + 1); return identityKinematicsForward(joint,world,fflags,iflags); } @@ -78,6 +78,6 @@ int userkKinematicsInverse(const EmcPose * pos, const KINEMATICS_INVERSE_FLAGS * iflags, KINEMATICS_FORWARD_FLAGS * fflags) { - (*udata->ict)++; + hal_set_si32(udata->ict, hal_get_si32(udata->ict) + 1); return identityKinematicsInverse(pos,joint,iflags,fflags); } diff --git a/src/emc/motion-logger/motion-logger.c b/src/emc/motion-logger/motion-logger.c index 9b184f632b4..cd74c3e04bd 100644 --- a/src/emc/motion-logger/motion-logger.c +++ b/src/emc/motion-logger/motion-logger.c @@ -38,7 +38,7 @@ #include "motion/axis.h" static struct motion_logger_data_t { - hal_bit_t *reopen; + hal_bool_t reopen; } *motion_logger_data; FILE *logfile = NULL; @@ -234,12 +234,12 @@ static void mark_joint_homed(int joint_num) { } void maybe_reopen_logfile() { - if(*motion_logger_data->reopen) { + if(hal_get_bool(motion_logger_data->reopen)) { if(logfile != stdout) { fclose(logfile); logfile = NULL; } - *motion_logger_data->reopen = 0; + hal_set_bool(motion_logger_data->reopen, 0); } } @@ -296,13 +296,12 @@ int main(int argc, char* argv[]) { exit(EXIT_FAILURE); } int r; - if((r = hal_pin_bit_new("motion-logger.reopen-log", HAL_IO, &motion_logger_data->reopen, mot_comp_id)) < 0) { + if((r = hal_pin_new_bool(mot_comp_id, HAL_IO, &motion_logger_data->reopen, 0, "motion-logger.reopen-log")) < 0) { hal_exit(mot_comp_id); errno = -r; perror("hal_pin_bit_new"); exit(EXIT_FAILURE); } - *motion_logger_data->reopen = 0; if((r = hal_ready(mot_comp_id)) < 0) { hal_exit(mot_comp_id); errno = -r; diff --git a/src/emc/motion/axis.c b/src/emc/motion/axis.c index 25b74309be3..6e2e29ddb18 100644 --- a/src/emc/motion/axis.c +++ b/src/emc/motion/axis.c @@ -28,26 +28,26 @@ typedef struct { } emcmot_axis_t; typedef struct { - hal_float_t *pos_cmd; /* RPI: commanded position */ - hal_float_t *teleop_vel_cmd; /* RPI: commanded velocity */ - hal_float_t *teleop_pos_cmd; /* RPI: teleop traj planner pos cmd */ - hal_float_t *teleop_vel_lim; /* RPI: teleop traj planner vel limit */ - hal_bit_t *teleop_tp_enable; /* RPI: teleop traj planner is running */ - - hal_s32_t *ajog_counts; /* WPI: jogwheel position input */ - hal_bit_t *ajog_enable; /* RPI: enable jogwheel */ - hal_float_t *ajog_scale; /* RPI: distance to jog on each count */ - hal_float_t *ajog_accel_fraction; /* RPI: to limit wheel jog accel */ - hal_bit_t *ajog_vel_mode; /* RPI: true for "velocity mode" jogwheel */ - hal_bit_t *kb_ajog_active; /* RPI: executing keyboard jog */ - hal_bit_t *wheel_ajog_active; /* RPI: executing handwheel jog */ - - hal_bit_t *eoffset_enable; - hal_bit_t *eoffset_clear; - hal_s32_t *eoffset_counts; - hal_float_t *eoffset_scale; - hal_float_t *external_offset; - hal_float_t *external_offset_requested; + hal_real_t pos_cmd; /* RPI: commanded position */ + hal_real_t teleop_vel_cmd; /* RPI: commanded velocity */ + hal_real_t teleop_pos_cmd; /* RPI: teleop traj planner pos cmd */ + hal_real_t teleop_vel_lim; /* RPI: teleop traj planner vel limit */ + hal_bool_t teleop_tp_enable; /* RPI: teleop traj planner is running */ + + hal_sint_t ajog_counts; /* WPI: jogwheel position input */ + hal_bool_t ajog_enable; /* RPI: enable jogwheel */ + hal_real_t ajog_scale; /* RPI: distance to jog on each count */ + hal_real_t ajog_accel_fraction; /* RPI: to limit wheel jog accel */ + hal_bool_t ajog_vel_mode; /* RPI: true for "velocity mode" jogwheel */ + hal_bool_t kb_ajog_active; /* RPI: executing keyboard jog */ + hal_bool_t wheel_ajog_active; /* RPI: executing handwheel jog */ + + hal_bool_t eoffset_enable; + hal_bool_t eoffset_clear; + hal_sint_t eoffset_counts; + hal_real_t eoffset_scale; + hal_real_t external_offset; + hal_real_t external_offset_requested; } axis_hal_t; @@ -79,8 +79,8 @@ void axis_initialize_external_offsets(void) for (n = 0; n < EMCMOT_MAX_AXIS; n++) { axis_data = &hal_data->axis[n]; - *(axis_data->external_offset) = 0; - *(axis_data->external_offset_requested) = 0; + hal_set_real(axis_data->external_offset, 0); + hal_set_real(axis_data->external_offset_requested, 0); axis_array[n].ext_offset_tp.pos_cmd = 0; axis_array[n].ext_offset_tp.curr_pos = 0; axis_array[n].ext_offset_tp.curr_vel = 0; @@ -100,15 +100,15 @@ static int export_axis(int mot_comp_id, char c, axis_hal_t * addr) msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(addr->ajog_enable), mot_comp_id,"axis.%c.jog-enable", c)); - CALL_CHECK(hal_pin_float_newf(HAL_IN, &(addr->ajog_scale), mot_comp_id,"axis.%c.jog-scale", c)); - CALL_CHECK(hal_pin_s32_newf(HAL_IN, &(addr->ajog_counts), mot_comp_id,"axis.%c.jog-counts", c)); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(addr->ajog_vel_mode), mot_comp_id,"axis.%c.jog-vel-mode", c)); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(addr->kb_ajog_active), mot_comp_id,"axis.%c.kb-jog-active", c)); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(addr->wheel_ajog_active), mot_comp_id,"axis.%c.wheel-jog-active", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->ajog_enable), 0, "axis.%c.jog-enable", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->ajog_scale), 0.0, "axis.%c.jog-scale", c)); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_IN, &(addr->ajog_counts), 0, "axis.%c.jog-counts", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->ajog_vel_mode), 0, "axis.%c.jog-vel-mode", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->kb_ajog_active), 0, "axis.%c.kb-jog-active", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->wheel_ajog_active), 0, "axis.%c.wheel-jog-active", c)); - CALL_CHECK(hal_pin_float_newf(HAL_IN,&(addr->ajog_accel_fraction), mot_comp_id,"axis.%c.jog-accel-fraction", c)); - *addr->ajog_accel_fraction = 1.0; // fraction of accel for wheel ajogs + // init: 1.0 fraction of accel for wheel ajogs + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN,&(addr->ajog_accel_fraction), 1.0, "axis.%c.jog-accel-fraction", c)); rtapi_set_msg_level(msg); return 0; @@ -128,18 +128,18 @@ int axis_init_hal_io(int mot_comp_id) for (n = 0; n < EMCMOT_MAX_AXIS; n++) { char c = "xyzabcuvw"[n]; axis_hal_t *axis_data = &(hal_data->axis[n]); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->pos_cmd, mot_comp_id, "axis.%c.pos-cmd", c)); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->teleop_vel_cmd, mot_comp_id, "axis.%c.teleop-vel-cmd", c)); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->teleop_pos_cmd, mot_comp_id, "axis.%c.teleop-pos-cmd", c)); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->teleop_vel_lim, mot_comp_id, "axis.%c.teleop-vel-lim", c)); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &axis_data->teleop_tp_enable, mot_comp_id, "axis.%c.teleop-tp-enable",c)); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &axis_data->eoffset_enable, mot_comp_id, "axis.%c.eoffset-enable", c)); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &axis_data->eoffset_clear, mot_comp_id, "axis.%c.eoffset-clear", c)); - CALL_CHECK(hal_pin_s32_newf(HAL_IN, &axis_data->eoffset_counts, mot_comp_id, "axis.%c.eoffset-counts", c)); - CALL_CHECK(hal_pin_float_newf(HAL_IN, &axis_data->eoffset_scale, mot_comp_id, "axis.%c.eoffset-scale", c)); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->external_offset, mot_comp_id, "axis.%c.eoffset", c)); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &axis_data->external_offset_requested, - mot_comp_id, "axis.%c.eoffset-request", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->pos_cmd, 0.0, "axis.%c.pos-cmd", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->teleop_vel_cmd, 0.0, "axis.%c.teleop-vel-cmd", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->teleop_pos_cmd, 0.0, "axis.%c.teleop-pos-cmd", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->teleop_vel_lim, 0.0, "axis.%c.teleop-vel-lim", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &axis_data->teleop_tp_enable, 0, "axis.%c.teleop-tp-enable",c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &axis_data->eoffset_enable, 0, "axis.%c.eoffset-enable", c)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &axis_data->eoffset_clear, 0, "axis.%c.eoffset-clear", c)); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_IN, &axis_data->eoffset_counts, 0, "axis.%c.eoffset-counts", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &axis_data->eoffset_scale, 0.0, "axis.%c.eoffset-scale", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->external_offset, 0.0, "axis.%c.eoffset", c)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &axis_data->external_offset_requested, + 0.0, "axis.%c.eoffset-request", c)); retval = export_axis(mot_comp_id, c, axis_data); if (retval) { @@ -159,16 +159,16 @@ void axis_output_to_hal(double *pcmd_p[]) for (n = 0; n < EMCMOT_MAX_AXIS; n++) { emcmot_axis_t *axis = &axis_array[n]; axis_hal_t *axis_data = &hal_data->axis[n]; - *(axis_data->teleop_vel_cmd) = axis->teleop_vel_cmd; - *(axis_data->teleop_pos_cmd) = axis->teleop_tp.pos_cmd; - *(axis_data->teleop_vel_lim) = axis->teleop_tp.max_vel; - *(axis_data->teleop_tp_enable) = axis->teleop_tp.enable; - *(axis_data->kb_ajog_active) = axis->kb_ajog_active; - *(axis_data->wheel_ajog_active) = axis->wheel_ajog_active; + hal_set_real(axis_data->teleop_vel_cmd, axis->teleop_vel_cmd); + hal_set_real(axis_data->teleop_pos_cmd, axis->teleop_tp.pos_cmd); + hal_set_real(axis_data->teleop_vel_lim, axis->teleop_tp.max_vel); + hal_set_bool(axis_data->teleop_tp_enable, axis->teleop_tp.enable); + hal_set_bool(axis_data->kb_ajog_active, axis->kb_ajog_active); + hal_set_bool(axis_data->wheel_ajog_active, axis->wheel_ajog_active); // hal pins: axis.L.pos-cmd reported without applied offsets: - *(axis_data->pos_cmd) = *pcmd_p[n] - - axis->ext_offset_tp.curr_pos; + hal_set_real(axis_data->pos_cmd, *pcmd_p[n] + - axis->ext_offset_tp.curr_pos); } } @@ -380,14 +380,14 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo axis_data = &hal_data->axis[axis_num]; // disallow accel bogus fractions - if ( (*(axis_data->ajog_accel_fraction) > 1) - || (*(axis_data->ajog_accel_fraction) < 0) ) { + if ( (hal_get_real(axis_data->ajog_accel_fraction) > 1) + || (hal_get_real(axis_data->ajog_accel_fraction) < 0) ) { aaccel_limit = axis->acc_limit; } else { - aaccel_limit = *(axis_data->ajog_accel_fraction) * axis->acc_limit; + aaccel_limit = hal_get_real(axis_data->ajog_accel_fraction) * axis->acc_limit; } - new_ajog_counts = *(axis_data->ajog_counts); + new_ajog_counts = hal_get_si32(axis_data->ajog_counts); delta = new_ajog_counts - axis->old_ajog_counts; axis->old_ajog_counts = new_ajog_counts; if ( first_pass ) { continue; } @@ -400,7 +400,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo return; } if (!motion_enable_flag) { continue; } - if ( *(axis_data->ajog_enable) == 0 ) { continue; } + if (!hal_get_bool(axis_data->ajog_enable)) { continue; } if (homing_is_active) { continue; } if (axis->kb_ajog_active) { continue; } @@ -411,9 +411,9 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo continue; } - distance = delta * *(axis_data->ajog_scale); + distance = delta * hal_get_real(axis_data->ajog_scale); pos = axis->teleop_tp.pos_cmd + distance; - if ( *(axis_data->ajog_vel_mode) ) { + if ( hal_get_bool(axis_data->ajog_vel_mode) ) { double v = axis->vel_limit; /* compute stopping distance at max speed */ stop_dist = v * v / ( 2 * aaccel_limit); @@ -488,9 +488,7 @@ bool axis_plan_external_offsets(double servo_period, bool motion_enable_flag, bo int new_eoffset_counts, delta; static int last_eoffset_enable[EMCMOT_MAX_AXIS]; double ext_offset_epsilon; - hal_bit_t eoffset_active; - - eoffset_active = 0; + bool eoffset_active = 0; for (n = 0; n < EMCMOT_MAX_AXIS; n++) { axis = &axis_array[n]; @@ -500,29 +498,29 @@ bool axis_plan_external_offsets(double servo_period, bool motion_enable_flag, bo axis_data = &hal_data->axis[n]; - new_eoffset_counts = *(axis_data->eoffset_counts); + new_eoffset_counts = hal_get_si32(axis_data->eoffset_counts); delta = new_eoffset_counts - axis->old_eoffset_counts; axis->old_eoffset_counts = new_eoffset_counts; - *(axis_data->external_offset) = axis->ext_offset_tp.curr_pos; + hal_set_real(axis_data->external_offset, axis->ext_offset_tp.curr_pos); axis->ext_offset_tp.enable = 1; if ( first_pass ) { - *(axis_data->external_offset) = 0; + hal_set_real(axis_data->external_offset, 0); continue; } // Use stopping criterion of simple_tp.c: ext_offset_epsilon = TINY_DP(axis->ext_offset_tp.max_acc, servo_period); - if (fabs(*(axis_data->external_offset)) > ext_offset_epsilon) { + if (fabs(hal_get_real(axis_data->external_offset)) > ext_offset_epsilon) { eoffset_active = 1; } - if ( !*(axis_data->eoffset_enable) ) { + if ( !hal_get_bool(axis_data->eoffset_enable) ) { axis->ext_offset_tp.enable = 0; // Detect disabling of eoffsets: // At very high accel, simple planner may terminate with // a larger position value than occurs at more realistic accels. if (last_eoffset_enable[n] - && (fabs(*(axis_data->external_offset)) > ext_offset_epsilon) + && (fabs(hal_get_real(axis_data->external_offset)) > ext_offset_epsilon) && motion_enable_flag && axis->ext_offset_tp.enable) { // to stdout only: @@ -531,7 +529,7 @@ bool axis_plan_external_offsets(double servo_period, bool motion_enable_flag, bo "*** External Offset disabled while NON-zero\n" "*** To clear: re-enable & zero or use Machine-Off\n", "XYZABCUVW"[n], - *(axis_data->external_offset), + hal_get_real(axis_data->external_offset), ext_offset_epsilon); } last_eoffset_enable[n] = 0; @@ -540,17 +538,17 @@ bool axis_plan_external_offsets(double servo_period, bool motion_enable_flag, bo // useful for eoffset_pid hold } last_eoffset_enable[n] = 1; - if (*(axis_data->eoffset_clear)) { + if (hal_get_bool(axis_data->eoffset_clear)) { axis->ext_offset_tp.pos_cmd = 0; - *(axis_data->external_offset_requested) = 0; + hal_set_real(axis_data->external_offset_requested, 0); continue; } if (delta == 0) { continue; } if (!all_homed) { continue; } if (!motion_enable_flag) { continue; } - axis->ext_offset_tp.pos_cmd += delta * *(axis_data->eoffset_scale); - *(axis_data->external_offset_requested) = axis->ext_offset_tp.pos_cmd; + axis->ext_offset_tp.pos_cmd += delta * hal_get_real(axis_data->eoffset_scale); + hal_set_real(axis_data->external_offset_requested, axis->ext_offset_tp.pos_cmd); } // for n first_pass = 0; diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c index 2f4509d0987..b1b2a0fbdcd 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -305,7 +305,7 @@ void emcmotSetRotaryUnlock(int jnum, int unlock) { jnum,1<joint[jnum].unlock) = unlock; + hal_set_bool(emcmot_hal_data->joint[jnum].unlock, unlock); } int emcmotGetRotaryIsUnlocked(int jnum) { @@ -320,7 +320,7 @@ int emcmotGetRotaryIsUnlocked(int jnum) { gave_message = 1; return 0; } - return *(emcmot_hal_data->joint[jnum].is_unlocked); + return hal_get_bool(emcmot_hal_data->joint[jnum].is_unlocked); } /*! \function emcmotDioWrite() @@ -336,11 +336,7 @@ void emcmotDioWrite(int index, char value) if ((index >= emcmotConfig->numDIO) || (index < 0)) { rtapi_print_msg(RTAPI_MSG_ERR, "ERROR: index out of range, %d not in [0..%d] (increase num_dio/EMCMOT_MAX_DIO=%d)\n", index, emcmotConfig->numDIO, EMCMOT_MAX_DIO); } else { - if (value != 0) { - *(emcmot_hal_data->synch_do[index])=1; - } else { - *(emcmot_hal_data->synch_do[index])=0; - } + hal_set_bool(emcmot_hal_data->synch_do[index], value != 0); } } @@ -357,7 +353,7 @@ void emcmotAioWrite(int index, double value) if ((index >= emcmotConfig->numAIO) || (index < 0)) { rtapi_print_msg(RTAPI_MSG_ERR, "ERROR: index out of range, %d not in [0..%d] (increase num_aio/EMCMOT_MAX_AIO=%d)\n", index, emcmotConfig->numAIO, EMCMOT_MAX_AIO); } else { - *(emcmot_hal_data->analog_output[index]) = value; + hal_set_real(emcmot_hal_data->analog_output[index], value); } } @@ -550,13 +546,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->atspeed_next_feed = 0; // Clear pins on abort so tests see a clean state if (emcmot_hal_data) { - *(emcmot_hal_data->interp_arc_radius) = 0.0; - *(emcmot_hal_data->interp_arc_center_x) = 0.0; - *(emcmot_hal_data->interp_arc_center_y) = 0.0; - *(emcmot_hal_data->interp_arc_center_z) = 0.0; - *(emcmot_hal_data->interp_straight_heading) = 0.0; - *(emcmot_hal_data->interp_normal_heading) = 0.0; - *(emcmot_hal_data->iscircle) = 0.0; + hal_set_real(emcmot_hal_data->interp_arc_radius, 0.0); + hal_set_real(emcmot_hal_data->interp_arc_center_x, 0.0); + hal_set_real(emcmot_hal_data->interp_arc_center_y, 0.0); + hal_set_real(emcmot_hal_data->interp_arc_center_z, 0.0); + hal_set_real(emcmot_hal_data->interp_straight_heading, 0.0); + hal_set_real(emcmot_hal_data->interp_normal_heading, 0.0); + hal_set_bool(emcmot_hal_data->iscircle, 0); } break; @@ -809,7 +805,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); break; } @@ -878,7 +874,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); break; } @@ -958,7 +954,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); break; } @@ -1373,7 +1369,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) /* set the emcmotInternal->enabling flag to defer enable until controller cycle */ rtapi_print_msg(RTAPI_MSG_DBG, "ENABLE"); - if ( *(emcmot_hal_data->enable) == 0 ) { + if ( !hal_get_bool(emcmot_hal_data->enable) ) { reportError(_("can't enable motion, enable input is false")); } else { emcmotInternal->enabling = 1; @@ -1421,7 +1417,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) reportError(_("must be in joint mode to home")); return; } - if (*(emcmot_hal_data->homing_inhibit)) { + if (hal_get_bool(emcmot_hal_data->homing_inhibit)) { reportError(_("Homing denied by motion.homing-inhibit joint=%d\n"), joint_num); return; @@ -1497,7 +1493,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } else if (!(emcmotCommand->probe_type & 1)) { // if suppress errors = off... - int probeval = !!*(emcmot_hal_data->probe_input); + int probeval = hal_get_bool(emcmot_hal_data->probe_input); int probe_whenclears = !!(emcmotCommand->probe_type & 2); if (probeval != probe_whenclears) { @@ -1662,12 +1658,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } for (n = s0; n<=s1; n++){ - if (*(emcmot_hal_data->spindle[n].spindle_orient)) + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) rtapi_print_msg(RTAPI_MSG_DBG, "SPINDLE_ORIENT cancelled by SPINDLE_ON\n"); - if (*(emcmot_hal_data->spindle[n].spindle_locked)) + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_locked)) rtapi_print_msg(RTAPI_MSG_DBG, "spindle-locked cleared by SPINDLE_ON\n"); - *(emcmot_hal_data->spindle[n].spindle_locked) = 0; - *(emcmot_hal_data->spindle[n].spindle_orient) = 0; + hal_set_bool(emcmot_hal_data->spindle[n].spindle_locked, 0); + hal_set_bool(emcmot_hal_data->spindle[n].spindle_orient, 0); emcmotStatus->spindle_status[n].orient_state = EMCMOT_ORIENT_NONE; /* if (emcmotStatus->spindle.orient) { */ @@ -1719,13 +1715,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->spindle_status[n].speed = 0; emcmotStatus->spindle_status[n].direction = 0; emcmotStatus->spindle_status[n].brake = 1; // engage brake - if (*(emcmot_hal_data->spindle[n].spindle_orient)) + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) rtapi_print_msg(RTAPI_MSG_DBG, "SPINDLE_ORIENT cancelled by SPINDLE_OFF"); - if (*(emcmot_hal_data->spindle[n].spindle_locked)){ + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_locked)){ rtapi_print_msg(RTAPI_MSG_DBG, "spindle-locked cleared by SPINDLE_OFF"); - *(emcmot_hal_data->spindle[n].spindle_locked) = 0; + hal_set_bool(emcmot_hal_data->spindle[n].spindle_locked, 0); } - *(emcmot_hal_data->spindle[n].spindle_orient) = 0; + hal_set_bool(emcmot_hal_data->spindle[n].spindle_orient, 0); emcmotStatus->spindle_status[n].orient_state = EMCMOT_ORIENT_NONE; } /* Optionally make the spindle stop an at-speed barrier: the next feed @@ -1754,7 +1750,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; } - if (*(emcmot_hal_data->spindle[n].spindle_orient)) { + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) { rtapi_print_msg(RTAPI_MSG_DBG, "orient already in progress"); // mah:FIXME unsure whether this is ok or an error @@ -1771,13 +1767,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) // https://github.com/LinuxCNC/linuxcnc/issues/3389 emcmotStatus->spindle_status[n].state = 0; - *(emcmot_hal_data->spindle[n].spindle_on) = 0; + hal_set_bool(emcmot_hal_data->spindle[n].spindle_on, 0); // https://github.com/LinuxCNC/linuxcnc/issues/3389 - *(emcmot_hal_data->spindle[n].spindle_orient_angle) = emcmotCommand->orientation; - *(emcmot_hal_data->spindle[n].spindle_orient_mode) = emcmotCommand->mode; - *(emcmot_hal_data->spindle[n].spindle_locked) = 0; - *(emcmot_hal_data->spindle[n].spindle_orient) = 1; + hal_set_real(emcmot_hal_data->spindle[n].spindle_orient_angle, emcmotCommand->orientation); + hal_set_si32(emcmot_hal_data->spindle[n].spindle_orient_mode, emcmotCommand->mode); + hal_set_bool(emcmot_hal_data->spindle[n].spindle_locked, 0); + hal_set_bool(emcmot_hal_data->spindle[n].spindle_orient, 1); // mirror in spindle status emcmotStatus->spindle_status[n].orient_fault = 0; // this pin read during spindle-orient == 1 diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c index 9e23ea480ae..542079f6074 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -227,7 +227,7 @@ void emcmotController(void *arg, long period) long long int now = rtapi_get_time(); long int this_run = (long int)(now - last); - *(emcmot_hal_data->last_period) = this_run; + hal_set_ui32(emcmot_hal_data->last_period, this_run); // we need this for next time last = now; @@ -252,10 +252,10 @@ void emcmotController(void *arg, long period) process_probe_inputs(); check_for_faults(); set_operating_mode(); - if (!*emcmot_hal_data->jog_inhibit) { + if (!hal_get_bool(emcmot_hal_data->jog_inhibit)) { handle_jjogwheels(); } - if (!emcmotStatus->on_soft_limit && !*emcmot_hal_data->jog_inhibit) { // change from teleop to move off joint soft limit + if (!emcmotStatus->on_soft_limit && !hal_get_bool(emcmot_hal_data->jog_inhibit)) { // change from teleop to move off joint soft limit axis_handle_jogwheels(GET_MOTION_TELEOP_FLAG(), GET_MOTION_ENABLE_FLAG(), get_homing_is_active()); } if ( (emcmotStatus->motion_state == EMCMOT_MOTION_FREE) @@ -265,7 +265,7 @@ void emcmotController(void *arg, long period) get_pos_cmds(period); compute_screw_comp(); - *(emcmot_hal_data->eoffset_active) = axis_plan_external_offsets(servo_period, GET_MOTION_ENABLE_FLAG(), get_allhomed()); + hal_set_bool(emcmot_hal_data->eoffset_active, axis_plan_external_offsets(servo_period, GET_MOTION_ENABLE_FLAG(), get_allhomed())); output_to_hal(); write_homing_out_pins(ALL_JOINTS); update_status(); @@ -299,7 +299,7 @@ static void handle_kinematicsSwitch(void) { int hal_switchkins_type = 0; if (!kinematicsSwitchable()) return; - hal_switchkins_type = (int)*emcmot_hal_data->switchkins_type; + hal_switchkins_type = (int)hal_get_real(emcmot_hal_data->switchkins_type); if (switchkins_type == hal_switchkins_type) return; switchkins_type = hal_switchkins_type; @@ -316,7 +316,7 @@ static void handle_kinematicsSwitch(void) { if (kinematicsSwitch(switchkins_type)) { rtapi_print_msg(RTAPI_MSG_ERR,"kinematicsSwitch() FAIL<%f>\n", - *emcmot_hal_data->switchkins_type); + hal_get_real(emcmot_hal_data->switchkins_type)); SET_MOTION_ERROR_FLAG(1); // abort return; // no updates for abort } @@ -354,11 +354,11 @@ static void process_inputs(void) /* read spindle angle (for threading, etc) */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ emcmotStatus->spindle_status[spindle_num].spindleRevs = - *emcmot_hal_data->spindle[spindle_num].spindle_revs; + hal_get_real(emcmot_hal_data->spindle[spindle_num].spindle_revs); emcmotStatus->spindle_status[spindle_num].spindleSpeedIn = - *emcmot_hal_data->spindle[spindle_num].spindle_speed_in; + hal_get_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_in); emcmotStatus->spindle_status[spindle_num].at_speed = - *emcmot_hal_data->spindle[spindle_num].spindle_is_atspeed; + hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_is_atspeed); } /* compute net feed and spindle scale factors */ if ( emcmotStatus->motion_state == EMCMOT_MOTION_COORD ) { @@ -380,7 +380,7 @@ static void process_inputs(void) } if ( enables & AF_ENABLED ) { /* read and clamp adaptive feed HAL pin */ - double adaptive_feed_in = *emcmot_hal_data->adaptive_feed; + double adaptive_feed_in = hal_get_real(emcmot_hal_data->adaptive_feed); // Clip range to +/- MAX_FEED_OVERRIDE from the [DISPLAY] section of the ini file if (adaptive_feed_in > emcmotConfig->maxFeedScale) { adaptive_feed_in = emcmotConfig->maxFeedScale; @@ -409,12 +409,12 @@ static void process_inputs(void) } if ( enables & FH_ENABLED ) { /* read feed hold HAL pin */ - if ( *emcmot_hal_data->feed_hold ) { + if ( hal_get_bool(emcmot_hal_data->feed_hold) ) { scale = 0; } } /*non maskable (except during spinndle synch move) feed hold inhibit pin */ - if ( enables & *emcmot_hal_data->feed_inhibit ) { + if ( enables & hal_get_bool(emcmot_hal_data->feed_inhibit) ) { scale = 0; } /* save the resulting combined scale factor */ @@ -427,7 +427,7 @@ static void process_inputs(void) scale *= emcmotStatus->spindle_status[spindle_num].scale; } /*non maskable (except during spindle synch move) spindle inhibit pin */ - if ( enables & *emcmot_hal_data->spindle[spindle_num].spindle_inhibit ) { + if ( enables & hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_inhibit) ) { scale = 0; } /* save the resulting combined scale factor */ @@ -445,7 +445,7 @@ static void process_inputs(void) continue; } /* copy data from HAL to joint structure */ - joint->motor_pos_fb = *(joint_data->motor_pos_fb); + joint->motor_pos_fb = hal_get_real(joint_data->motor_pos_fb); /* calculate pos_fb */ if (( get_homing_at_index_search_wait(joint_num) ) && ( get_index_enable(joint_num) == 0 )) { @@ -490,12 +490,12 @@ static void process_inputs(void) } /* read limit switches */ - if (*(joint_data->pos_lim_sw)) { + if (hal_get_bool(joint_data->pos_lim_sw)) { SET_JOINT_PHL_FLAG(joint, 1); } else { SET_JOINT_PHL_FLAG(joint, 0); } - if (*(joint_data->neg_lim_sw)) { + if (hal_get_bool(joint_data->neg_lim_sw)) { SET_JOINT_NHL_FLAG(joint, 1); } else { SET_JOINT_NHL_FLAG(joint, 0); @@ -503,7 +503,7 @@ static void process_inputs(void) joint->on_pos_limit = GET_JOINT_PHL_FLAG(joint); joint->on_neg_limit = GET_JOINT_NHL_FLAG(joint); /* read amp fault input */ - if (*(joint_data->amp_fault)) { + if (hal_get_bool(joint_data->amp_fault)) { SET_JOINT_FAULT_FLAG(joint, 1); } else { SET_JOINT_FAULT_FLAG(joint, 0); @@ -513,25 +513,25 @@ static void process_inputs(void) // a fault was signalled during a spindle-orient in progress // signal error, and cancel the orient for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ - if(*(emcmot_hal_data->spindle[spindle_num].spindle_amp_fault)){ + if(hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_amp_fault)){ emcmotStatus->spindle_status[spindle_num].fault = 1; }else{ emcmotStatus->spindle_status[spindle_num].fault = 0; } - if (*(emcmot_hal_data->spindle[spindle_num].spindle_orient)) { - if (*(emcmot_hal_data->spindle[spindle_num].spindle_orient_fault)) { + if (hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_orient)) { + if (hal_get_si32(emcmot_hal_data->spindle[spindle_num].spindle_orient_fault)) { emcmotStatus->spindle_status[spindle_num].orient_state = EMCMOT_ORIENT_FAULTED; - *(emcmot_hal_data->spindle[spindle_num].spindle_orient) = 0; + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_orient, 0); emcmotStatus->spindle_status[spindle_num].orient_fault = - *(emcmot_hal_data->spindle[spindle_num].spindle_orient_fault); + hal_get_si32(emcmot_hal_data->spindle[spindle_num].spindle_orient_fault); reportError(_("fault %d during orient in progress"), emcmotStatus->spindle_status[spindle_num].orient_fault); emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; tpAbort(&emcmotInternal->coord_tp); SET_MOTION_ERROR_FLAG(1); - } else if (*(emcmot_hal_data->spindle[spindle_num].spindle_is_oriented)) { - *(emcmot_hal_data->spindle[spindle_num].spindle_orient) = 0; - *(emcmot_hal_data->spindle[spindle_num].spindle_locked) = 1; + } else if (hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_is_oriented)) { + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_orient, 0); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_locked, 1); emcmotStatus->spindle_status[spindle_num].locked = 1; emcmotStatus->spindle_status[spindle_num].brake = 1; emcmotStatus->spindle_status[spindle_num].orient_state = EMCMOT_ORIENT_COMPLETE; @@ -540,10 +540,10 @@ static void process_inputs(void) } } // if jog in progress stop the jog if requested - if (enables & *(emcmot_hal_data->jog_is_active) && (*(emcmot_hal_data->jog_stop) || *(emcmot_hal_data->jog_stop_immediate))) { - joint_jog_abort_all(*(emcmot_hal_data->jog_stop_immediate)); - axis_jog_abort_all(*(emcmot_hal_data->jog_stop_immediate)); - if (*(emcmot_hal_data->jog_stop_immediate)) { + if (enables & hal_get_bool(emcmot_hal_data->jog_is_active) && (hal_get_bool(emcmot_hal_data->jog_stop) || hal_get_bool(emcmot_hal_data->jog_stop_immediate))) { + joint_jog_abort_all(hal_get_bool(emcmot_hal_data->jog_stop_immediate)); + axis_jog_abort_all(hal_get_bool(emcmot_hal_data->jog_stop_immediate)); + if (hal_get_bool(emcmot_hal_data->jog_stop_immediate)) { reportError("Jog aborted by jog-stop-immediate"); } else { reportError("Jog aborted by jog-stop"); @@ -688,7 +688,7 @@ static void process_probe_inputs(void) char probe_whenclears = !!(probe_type & 2); /* read probe input */ - emcmotStatus->probeVal = !!*(emcmot_hal_data->probe_input); + emcmotStatus->probeVal = hal_get_bool(emcmot_hal_data->probe_input); if (emcmotStatus->probing) { /* check if the probe has been tripped */ if (emcmotStatus->probeVal ^ probe_whenclears) { @@ -788,7 +788,7 @@ static void check_for_faults(void) /* check for various global fault conditions */ /* only check enable input if running */ if ( GET_MOTION_ENABLE_FLAG() != 0 ) { - if ( *(emcmot_hal_data->enable) == 0 ) { + if ( !hal_get_bool(emcmot_hal_data->enable) ) { reportError(_("motion stopped by enable input")); emcmotInternal->enabling = 0; } @@ -896,10 +896,10 @@ static void set_operating_mode(void) /* check for emcmotInternal->enabling */ if (emcmotInternal->enabling && !GET_MOTION_ENABLE_FLAG()) { - if (*(emcmot_hal_data->eoffset_limited)) { + if (hal_get_bool(emcmot_hal_data->eoffset_limited)) { reportError("Note: Motion enabled after reaching a coordinate " "soft limit with active external offsets"); - *(emcmot_hal_data->eoffset_limited) = 0; + hal_set_bool(emcmot_hal_data->eoffset_limited, 0); } axis_initialize_external_offsets(); tpSetPos(&emcmotInternal->coord_tp, &emcmotStatus->carte_pos_cmd); @@ -936,7 +936,7 @@ static void set_operating_mode(void) if (joint_num < NO_OF_KINS_JOINTS) { /* point to joint data */ joint = &joints[joint_num]; - if (coord_cubic_active && *(emcmot_hal_data->eoffset_active)) { + if (coord_cubic_active && hal_get_bool(emcmot_hal_data->eoffset_active)) { //skip } else { cubicDrain(&(joint->cubic)); @@ -1055,14 +1055,15 @@ static void handle_jjogwheels(void) } // disallow accel bogus fractions - if ( (*(joint_data->jjog_accel_fraction) > 1) - || (*(joint_data->jjog_accel_fraction) < 0) ) { + rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); + if ( (jjog_accel_fraction > 1) + || (jjog_accel_fraction < 0) ) { jaccel_limit = joint->acc_limit; } else { - jaccel_limit = (*(joint_data->jjog_accel_fraction)) * joint->acc_limit; + jaccel_limit = jjog_accel_fraction * joint->acc_limit; } /* get counts from jogwheel */ - new_jjog_counts = *(joint_data->jjog_counts); + new_jjog_counts = hal_get_si32(joint_data->jjog_counts); delta = new_jjog_counts - joint->old_jjog_counts; /* save value for next time */ joint->old_jjog_counts = new_jjog_counts; @@ -1087,7 +1088,7 @@ static void handle_jjogwheels(void) continue; } /* the jogwheel input for this joint must be enabled */ - if ( *(joint_data->jjog_enable) == 0 ) { + if ( !hal_get_bool(joint_data->jjog_enable) ) { continue; } /* must not be homing */ @@ -1120,7 +1121,7 @@ static void handle_jjogwheels(void) continue; } /* calculate distance to jog */ - distance = delta * *(joint_data->jjog_scale); + distance = delta * hal_get_real(joint_data->jjog_scale); /* check for joint already on hard limit */ if (distance > 0.0 && GET_JOINT_PHL_FLAG(joint)) { continue; @@ -1145,7 +1146,7 @@ static void handle_jjogwheels(void) commanded distance. Velocity mode is for those folks. If the command is faster than the machine can track, excess command is simply dropped. */ - if ( *(joint_data->jjog_vel_mode) ) { + if ( hal_get_bool(joint_data->jjog_vel_mode) ) { double v = joint->vel_limit * emcmotStatus->net_feed_scale; /* compute stopping distance at max speed */ stop_dist = v * v / ( 2 * jaccel_limit); @@ -1245,11 +1246,12 @@ static void get_pos_cmds(long period) double jaccel_limit; joint_hal_t *joint_data; joint_data = &(emcmot_hal_data->joint[joint_num]); - if ( (*(joint_data->jjog_accel_fraction) > 1) - || (*(joint_data->jjog_accel_fraction) < 0) ) { + rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); + if ( (jjog_accel_fraction > 1) + || (jjog_accel_fraction < 0) ) { jaccel_limit = joint->acc_limit; } else { - jaccel_limit = (*(joint_data->jjog_accel_fraction)) * joint->acc_limit; + jaccel_limit = jjog_accel_fraction * joint->acc_limit; } joint->free_tp.max_acc = jaccel_limit; } else { @@ -1582,9 +1584,9 @@ static void get_pos_cmds(long period) axis_jog_abort_all(1); } if (ext_offset_teleop_limit || ext_offset_coord_limit) { - *(emcmot_hal_data->eoffset_limited) = 1; + hal_set_bool(emcmot_hal_data->eoffset_limited, 1); } else { - *(emcmot_hal_data->eoffset_limited) = 0; + hal_set_bool(emcmot_hal_data->eoffset_limited, 0); } } // get_pos_cmds() @@ -1879,20 +1881,20 @@ static void output_to_hal(void) static int old_hal_index[EMCMOT_MAX_SPINDLES] = {0}; /* output machine info to HAL for scoping, etc */ - *(emcmot_hal_data->motion_enabled) = GET_MOTION_ENABLE_FLAG(); - *(emcmot_hal_data->in_position) = GET_MOTION_INPOS_FLAG(); - *(emcmot_hal_data->coord_mode) = GET_MOTION_COORD_FLAG(); - *(emcmot_hal_data->teleop_mode) = GET_MOTION_TELEOP_FLAG(); - *(emcmot_hal_data->coord_error) = GET_MOTION_ERROR_FLAG(); - *(emcmot_hal_data->on_soft_limit) = emcmotStatus->on_soft_limit; + hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); + hal_set_bool(emcmot_hal_data->in_position, GET_MOTION_INPOS_FLAG()); + hal_set_bool(emcmot_hal_data->coord_mode, GET_MOTION_COORD_FLAG()); + hal_set_bool(emcmot_hal_data->teleop_mode, GET_MOTION_TELEOP_FLAG()); + hal_set_bool(emcmot_hal_data->coord_error, GET_MOTION_ERROR_FLAG()); + hal_set_bool(emcmot_hal_data->on_soft_limit, emcmotStatus->on_soft_limit); /* Performance Metadata */ - *(emcmot_hal_data->interp_feedrate) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED]; + hal_set_real(emcmot_hal_data->interp_feedrate, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED]); /* Line and Motion Type (Casting to int for s32 HAL pins) */ - *(emcmot_hal_data->interp_line_number) = (int)emcmotStatus->tag.fields[GM_FIELD_LINE_NUMBER]; - *(emcmot_hal_data->interp_motion_type) = (int)emcmotStatus->tag.fields[GM_FIELD_MOTION_MODE]; - *(emcmot_hal_data->iscircle) = (hal_bit_t)((emcmotStatus->tag.packed_flags & (1UL << GM_FLAG_IS_CIRCLE)) != 0); + hal_set_si32(emcmot_hal_data->interp_line_number, (int)emcmotStatus->tag.fields[GM_FIELD_LINE_NUMBER]); + hal_set_si32(emcmot_hal_data->interp_motion_type, (int)emcmotStatus->tag.fields[GM_FIELD_MOTION_MODE]); + hal_set_bool(emcmot_hal_data->iscircle, (emcmotStatus->tag.packed_flags & (1UL << GM_FLAG_IS_CIRCLE)) != 0); switch (emcmotStatus->motionType) { case EMC_MOTION_TYPE_FEED: //fall thru case EMC_MOTION_TYPE_ARC: @@ -1901,19 +1903,19 @@ static void output_to_hal(void) } else { inch_mult = 1 / 25.4; } - *(emcmot_hal_data->feed_upm) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED] - * emcmotStatus->net_feed_scale; - *(emcmot_hal_data->feed_inches_per_minute) = *emcmot_hal_data->feed_upm * inch_mult; - *(emcmot_hal_data->feed_inches_per_second) = *emcmot_hal_data->feed_inches_per_minute / 60; - *(emcmot_hal_data->feed_mm_per_minute) = *emcmot_hal_data->feed_inches_per_minute * 25.4; - *(emcmot_hal_data->feed_mm_per_second) = *emcmot_hal_data->feed_mm_per_minute / 60; + hal_set_real(emcmot_hal_data->feed_upm, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED] + * emcmotStatus->net_feed_scale); + hal_set_real(emcmot_hal_data->feed_inches_per_minute, hal_get_real(emcmot_hal_data->feed_upm) * inch_mult); + hal_set_real(emcmot_hal_data->feed_inches_per_second, hal_get_real(emcmot_hal_data->feed_inches_per_minute) / 60); + hal_set_real(emcmot_hal_data->feed_mm_per_minute, hal_get_real(emcmot_hal_data->feed_inches_per_minute) * 25.4); + hal_set_real(emcmot_hal_data->feed_mm_per_second, hal_get_real(emcmot_hal_data->feed_mm_per_minute) / 60); break; default: - *(emcmot_hal_data->feed_upm) = 0; - *(emcmot_hal_data->feed_inches_per_minute) = 0; - *(emcmot_hal_data->feed_inches_per_second) = 0; - *(emcmot_hal_data->feed_mm_per_minute) = 0; - *(emcmot_hal_data->feed_mm_per_second) = 0; + hal_set_real(emcmot_hal_data->feed_upm, 0); + hal_set_real(emcmot_hal_data->feed_inches_per_minute, 0); + hal_set_real(emcmot_hal_data->feed_inches_per_second, 0); + hal_set_real(emcmot_hal_data->feed_mm_per_minute, 0); + hal_set_real(emcmot_hal_data->feed_mm_per_second, 0); } for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1952,31 +1954,29 @@ static void output_to_hal(void) } } - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out) = speed; - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps) = speed/60.; - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_abs) = fabs(speed); - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps_abs) = fabs(speed / 60); - *(emcmot_hal_data->spindle[spindle_num].spindle_on) = - ((emcmotStatus->spindle_status[spindle_num].state) !=0) ? 1 : 0; - *(emcmot_hal_data->spindle[spindle_num].spindle_forward) = (speed > 0) ? 1 : 0; - *(emcmot_hal_data->spindle[spindle_num].spindle_reverse) = (speed < 0) ? 1 : 0; - *(emcmot_hal_data->spindle[spindle_num].spindle_brake) = - (emcmotStatus->spindle_status[spindle_num].brake != 0) ? 1 : 0; + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out, speed); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps, speed/60.); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_abs, fabs(speed)); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps_abs, fabs(speed / 60)); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_on, (emcmotStatus->spindle_status[spindle_num].state) != 0); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_forward, speed > 0); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_reverse, speed < 0); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_brake, emcmotStatus->spindle_status[spindle_num].brake != 0); // What is this for? Docs don't say - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps) = - emcmotStatus->spindle_status[spindle_num].speed / 60.; + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, + emcmotStatus->spindle_status[spindle_num].speed / 60.); } - *(emcmot_hal_data->program_line) = emcmotStatus->id; - *(emcmot_hal_data->tp_reverse) = emcmotStatus->reverse_run; - *(emcmot_hal_data->motion_type) = emcmotStatus->motionType; - *(emcmot_hal_data->distance_to_go) = emcmotStatus->distance_to_go; + hal_set_si32(emcmot_hal_data->program_line, emcmotStatus->id); + hal_set_bool(emcmot_hal_data->tp_reverse, emcmotStatus->reverse_run); + hal_set_si32(emcmot_hal_data->motion_type, emcmotStatus->motionType); + hal_set_real(emcmot_hal_data->distance_to_go, emcmotStatus->distance_to_go); if(GET_MOTION_COORD_FLAG()) { - *(emcmot_hal_data->current_vel) = emcmotStatus->current_vel; - *(emcmot_hal_data->requested_vel) = emcmotStatus->requested_vel; + hal_set_real(emcmot_hal_data->current_vel, emcmotStatus->current_vel); + hal_set_real(emcmot_hal_data->requested_vel, emcmotStatus->requested_vel); } else if (GET_MOTION_TELEOP_FLAG()) { - emcmotStatus->current_vel = (*emcmot_hal_data->current_vel) = axis_get_compound_velocity(); - *(emcmot_hal_data->requested_vel) = 0.0; + emcmotStatus->current_vel = hal_set_real(emcmot_hal_data->current_vel, axis_get_compound_velocity()); + hal_set_real(emcmot_hal_data->requested_vel, 0.0); } else { int i; double v2 = 0.0; @@ -1984,10 +1984,10 @@ static void output_to_hal(void) if(GET_JOINT_ACTIVE_FLAG(&(joints[i])) && joints[i].free_tp.active) v2 += joints[i].vel_cmd * joints[i].vel_cmd; if(v2 > 0.0) - emcmotStatus->current_vel = (*emcmot_hal_data->current_vel) = sqrt(v2); + emcmotStatus->current_vel = hal_set_real(emcmot_hal_data->current_vel, sqrt(v2)); else - emcmotStatus->current_vel = (*emcmot_hal_data->current_vel) = 0.0; - *(emcmot_hal_data->requested_vel) = 0.0; + emcmotStatus->current_vel = hal_set_real(emcmot_hal_data->current_vel, 0.0); + hal_set_real(emcmot_hal_data->requested_vel, 0.0); } /* These params can be used to examine any internal variable. */ @@ -1995,24 +1995,24 @@ static void output_to_hal(void) to one of the debug parameters. You can also comment out these lines and copy elsewhere if you want to observe an automatic variable that isn't in scope here. */ - emcmot_hal_data->debug_bit_0 = joints[1].free_tp.active; - emcmot_hal_data->debug_bit_1 = emcmotStatus->enables_new & AF_ENABLED; - emcmot_hal_data->debug_float_0 = emcmotStatus->spindle_status[0].speed; - emcmot_hal_data->debug_float_1 = emcmotStatus->spindleSync; - emcmot_hal_data->debug_float_2 = emcmotStatus->vel; - emcmot_hal_data->debug_float_3 = emcmotStatus->spindle_status[0].net_scale; - emcmot_hal_data->debug_s32_0 = emcmotStatus->overrideLimitMask; - emcmot_hal_data->debug_s32_1 = emcmotStatus->tcqlen; + hal_set_bool(emcmot_hal_data->debug_bit_0, joints[1].free_tp.active); + hal_set_bool(emcmot_hal_data->debug_bit_1, emcmotStatus->enables_new & AF_ENABLED); + hal_set_real(emcmot_hal_data->debug_float_0, emcmotStatus->spindle_status[0].speed); + hal_set_real(emcmot_hal_data->debug_float_1, emcmotStatus->spindleSync); + hal_set_real(emcmot_hal_data->debug_float_2, emcmotStatus->vel); + hal_set_real(emcmot_hal_data->debug_float_3, emcmotStatus->spindle_status[0].net_scale); + hal_set_si32(emcmot_hal_data->debug_s32_0, emcmotStatus->overrideLimitMask); + hal_set_si32(emcmot_hal_data->debug_s32_1, emcmotStatus->tcqlen); /* two way handshaking for the spindle encoder */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { - *emcmot_hal_data->spindle[spindle_num].spindle_index_enable = 1; + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); rtapi_print_msg(RTAPI_MSG_DBG, "setting index-enable on spindle %d\n", spindle_num); } - if(!*emcmot_hal_data->spindle[spindle_num].spindle_index_enable + if(!hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable) && old_hal_index[spindle_num]) { emcmotStatus->spindle_status[spindle_num].spindle_index_enable = 0; } @@ -2020,18 +2020,18 @@ static void output_to_hal(void) old_motion_index[spindle_num] = emcmotStatus->spindle_status[spindle_num].spindle_index_enable; old_hal_index[spindle_num] = - *emcmot_hal_data->spindle[spindle_num].spindle_index_enable; + hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable); } - *(emcmot_hal_data->tooloffset_x) = emcmotStatus->tool_offset.tran.x; - *(emcmot_hal_data->tooloffset_y) = emcmotStatus->tool_offset.tran.y; - *(emcmot_hal_data->tooloffset_z) = emcmotStatus->tool_offset.tran.z; - *(emcmot_hal_data->tooloffset_a) = emcmotStatus->tool_offset.a; - *(emcmot_hal_data->tooloffset_b) = emcmotStatus->tool_offset.b; - *(emcmot_hal_data->tooloffset_c) = emcmotStatus->tool_offset.c; - *(emcmot_hal_data->tooloffset_u) = emcmotStatus->tool_offset.u; - *(emcmot_hal_data->tooloffset_v) = emcmotStatus->tool_offset.v; - *(emcmot_hal_data->tooloffset_w) = emcmotStatus->tool_offset.w; + hal_set_real(emcmot_hal_data->tooloffset_x, emcmotStatus->tool_offset.tran.x); + hal_set_real(emcmot_hal_data->tooloffset_y, emcmotStatus->tool_offset.tran.y); + hal_set_real(emcmot_hal_data->tooloffset_z, emcmotStatus->tool_offset.tran.z); + hal_set_real(emcmot_hal_data->tooloffset_a, emcmotStatus->tool_offset.a); + hal_set_real(emcmot_hal_data->tooloffset_b, emcmotStatus->tool_offset.b); + hal_set_real(emcmot_hal_data->tooloffset_c, emcmotStatus->tool_offset.c); + hal_set_real(emcmot_hal_data->tooloffset_u, emcmotStatus->tool_offset.u); + hal_set_real(emcmot_hal_data->tooloffset_v, emcmotStatus->tool_offset.v); + hal_set_real(emcmot_hal_data->tooloffset_w, emcmotStatus->tool_offset.w); /* output joint info to HAL for scoping, etc */ for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { @@ -2044,39 +2044,39 @@ static void output_to_hal(void) joint->pos_cmd + joint->backlash_filt + joint->motor_offset; /* point to HAL data */ /* write to HAL pins */ - *(joint_data->motor_offset) = joint->motor_offset; - *(joint_data->motor_pos_cmd) = joint->motor_pos_cmd; - *(joint_data->joint_pos_cmd) = joint->pos_cmd; - *(joint_data->joint_pos_fb) = joint->pos_fb; - *(joint_data->amp_enable) = GET_JOINT_ENABLE_FLAG(joint); - - *(joint_data->coarse_pos_cmd) = joint->coarse_pos; - *(joint_data->joint_vel_cmd) = joint->vel_cmd; - *(joint_data->joint_acc_cmd) = joint->acc_cmd; - *(joint_data->joint_jerk_cmd) = joint->jerk_cmd; - *(joint_data->backlash_corr) = joint->backlash_corr; - *(joint_data->backlash_filt) = joint->backlash_filt; - *(joint_data->backlash_vel) = joint->backlash_vel; - *(joint_data->f_error) = joint->ferror; - *(joint_data->f_error_lim) = joint->ferror_limit; - - *(joint_data->free_pos_cmd) = joint->free_tp.pos_cmd; - *(joint_data->free_vel_lim) = joint->free_tp.max_vel; - *(joint_data->free_tp_enable) = joint->free_tp.enable; - *(joint_data->kb_jjog_active) = joint->kb_jjog_active; - *(joint_data->wheel_jjog_active) = joint->wheel_jjog_active; - - *(joint_data->active) = GET_JOINT_ACTIVE_FLAG(joint); - *(joint_data->in_position) = GET_JOINT_INPOS_FLAG(joint); - *(joint_data->error) = GET_JOINT_ERROR_FLAG(joint); - *(joint_data->phl) = GET_JOINT_PHL_FLAG(joint); - *(joint_data->nhl) = GET_JOINT_NHL_FLAG(joint); - *(joint_data->f_errored) = GET_JOINT_FERROR_FLAG(joint); - *(joint_data->faulted) = GET_JOINT_FAULT_FLAG(joint); + hal_set_real(joint_data->motor_offset, joint->motor_offset); + hal_set_real(joint_data->motor_pos_cmd, joint->motor_pos_cmd); + hal_set_real(joint_data->joint_pos_cmd, joint->pos_cmd); + hal_set_real(joint_data->joint_pos_fb, joint->pos_fb); + hal_set_bool(joint_data->amp_enable, GET_JOINT_ENABLE_FLAG(joint)); + + hal_set_real(joint_data->coarse_pos_cmd, joint->coarse_pos); + hal_set_real(joint_data->joint_vel_cmd, joint->vel_cmd); + hal_set_real(joint_data->joint_acc_cmd, joint->acc_cmd); + hal_set_real(joint_data->joint_jerk_cmd, joint->jerk_cmd); + hal_set_real(joint_data->backlash_corr, joint->backlash_corr); + hal_set_real(joint_data->backlash_filt, joint->backlash_filt); + hal_set_real(joint_data->backlash_vel, joint->backlash_vel); + hal_set_real(joint_data->f_error, joint->ferror); + hal_set_real(joint_data->f_error_lim, joint->ferror_limit); + + hal_set_real(joint_data->free_pos_cmd, joint->free_tp.pos_cmd); + hal_set_real(joint_data->free_vel_lim, joint->free_tp.max_vel); + hal_set_bool(joint_data->free_tp_enable, joint->free_tp.enable); + hal_set_bool(joint_data->kb_jjog_active, joint->kb_jjog_active); + hal_set_bool(joint_data->wheel_jjog_active, joint->wheel_jjog_active); + + hal_set_bool(joint_data->active, GET_JOINT_ACTIVE_FLAG(joint)); + hal_set_bool(joint_data->in_position, GET_JOINT_INPOS_FLAG(joint)); + hal_set_bool(joint_data->error, GET_JOINT_ERROR_FLAG(joint)); + hal_set_bool(joint_data->phl, GET_JOINT_PHL_FLAG(joint)); + hal_set_bool(joint_data->nhl, GET_JOINT_NHL_FLAG(joint)); + hal_set_bool(joint_data->f_errored, GET_JOINT_FERROR_FLAG(joint)); + hal_set_bool(joint_data->faulted, GET_JOINT_FAULT_FLAG(joint)); // conditionally remove outstanding requests to unlock rotaries: if ( !GET_MOTION_ENABLE_FLAG() && (joint_is_lockable(joint_num))) { - *(joint_data->unlock) = 0; + hal_set_bool(joint_data->unlock, 0); } if (IS_EXTRA_JOINT(joint_num) && get_homed(joint_num)) { @@ -2085,15 +2085,15 @@ static void output_to_hal(void) extrajoint_hal_t *ejoint_data; int e = joint_num - NO_OF_KINS_JOINTS; ejoint_data = &(emcmot_hal_data->ejoint[e]); - *(joint_data->motor_pos_cmd) = *(ejoint_data->posthome_cmd) - + joint->motor_offset; + hal_set_real(joint_data->motor_pos_cmd, hal_get_real(ejoint_data->posthome_cmd) + + joint->motor_offset); continue; } } // for joint_num axis_output_to_hal(pcmd_p); - *(emcmot_hal_data->jog_is_active) = axis_jog_is_active() || joint_jog_is_active(); + hal_set_bool(emcmot_hal_data->jog_is_active, axis_jog_is_active() || joint_jog_is_active()); } @@ -2151,9 +2151,9 @@ static void update_status(void) joint_status->max_ferror = joint->max_ferror; } if (get_allhomed()) { - *emcmot_hal_data->is_all_homed = 1; + hal_set_bool(emcmot_hal_data->is_all_homed, 1); } else { - *emcmot_hal_data->is_all_homed = 0; + hal_set_bool(emcmot_hal_data->is_all_homed, 0); } @@ -2175,23 +2175,23 @@ static void update_status(void) emcmotStatus->eoffset_pose.v = axis_get_ext_offset_curr_pos(7); emcmotStatus->eoffset_pose.w = axis_get_ext_offset_curr_pos(8); - emcmotStatus->external_offsets_applied = *(emcmot_hal_data->eoffset_active); + emcmotStatus->external_offsets_applied = hal_get_bool(emcmot_hal_data->eoffset_active); for (dio = 0; dio < emcmotConfig->numDIO; dio++) { - emcmotStatus->synch_di[dio] = *(emcmot_hal_data->synch_di[dio]); - emcmotStatus->synch_do[dio] = *(emcmot_hal_data->synch_do[dio]); + emcmotStatus->synch_di[dio] = hal_get_bool(emcmot_hal_data->synch_di[dio]); + emcmotStatus->synch_do[dio] = hal_get_bool(emcmot_hal_data->synch_do[dio]); } for (aio = 0; aio < emcmotConfig->numAIO; aio++) { - emcmotStatus->analog_input[aio] = *(emcmot_hal_data->analog_input[aio]); - emcmotStatus->analog_output[aio] = *(emcmot_hal_data->analog_output[aio]); + emcmotStatus->analog_input[aio] = hal_get_real(emcmot_hal_data->analog_input[aio]); + emcmotStatus->analog_output[aio] = hal_get_real(emcmot_hal_data->analog_output[aio]); } for (misc_error=0; misc_error < emcmotConfig->numMiscError; misc_error++){ - emcmotStatus->misc_error[misc_error] = *(emcmot_hal_data->misc_error[misc_error]); + emcmotStatus->misc_error[misc_error] = hal_get_bool(emcmot_hal_data->misc_error[misc_error]); } - emcmotStatus->jogging_active = *(emcmot_hal_data->jog_is_active); + emcmotStatus->jogging_active = hal_get_bool(emcmot_hal_data->jog_is_active); /*! \todo FIXME - the rest of this function is stuff that was apparently dropped in the initial move from emcmot.c to control.c. I @@ -2220,23 +2220,23 @@ static void update_status(void) // Get the current executing trajectory component (the "Source of Truth") /* Update the HAL Output Pins from the active tag */ // Line and Motion Type - *(emcmot_hal_data->interp_line_number) = (int)emcmotStatus->tag.fields[GM_FIELD_LINE_NUMBER]; + hal_set_si32(emcmot_hal_data->interp_line_number, (int)emcmotStatus->tag.fields[GM_FIELD_LINE_NUMBER]); // Performance Metadata - *(emcmot_hal_data->interp_feedrate) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED]; + hal_set_real(emcmot_hal_data->interp_feedrate, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_FEED]); // Geometric Metadata - *(emcmot_hal_data->interp_arc_radius) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_RADIUS]; - *(emcmot_hal_data->interp_arc_center_x) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_X]; - *(emcmot_hal_data->interp_arc_center_y) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_Y]; - *(emcmot_hal_data->interp_arc_center_z) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_Z]; + hal_set_real(emcmot_hal_data->interp_arc_radius, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_RADIUS]); + hal_set_real(emcmot_hal_data->interp_arc_center_x, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_X]); + hal_set_real(emcmot_hal_data->interp_arc_center_y, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_Y]); + hal_set_real(emcmot_hal_data->interp_arc_center_z, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_ARC_CENTER_Z]); // Get the current motion type from the tag (1=G1, 2=G2, 3=G3) int motion_type = (int)emcmotStatus->tag.fields[GM_FIELD_MOTION_MODE]; if (motion_type == 10 || motion_type == 0) { /* --- G1/G0 STATIC HEADING --- */ // For linear moves, the heading doesn't change during the segment. - *(emcmot_hal_data->interp_straight_heading) = emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_STRAIGHT_HEADING]; + hal_set_real(emcmot_hal_data->interp_straight_heading, emcmotStatus->tag.fields_float[GM_FIELD_FLOAT_STRAIGHT_HEADING]); } else if (motion_type == 20 || motion_type == 30) { /* --- G2/G3: DYNAMIC ARC HEADING --- */ @@ -2270,7 +2270,7 @@ static void update_status(void) double normal_deg = (angle_rad * (180.0 / M_PI)) + 180.0; while (normal_deg < 0) normal_deg += 360.0; while (normal_deg >= 360.0) normal_deg -= 360.0; - *(emcmot_hal_data->interp_normal_heading) = normal_deg; + hal_set_real(emcmot_hal_data->interp_normal_heading, normal_deg); // 5. Calculate Tangent Heading (Direction of Travel) double tangent_rad = (motion_type == 30) ? (angle_rad + (M_PI / 2.0)) : (angle_rad - (M_PI / 2.0)); @@ -2281,7 +2281,7 @@ static void update_status(void) while (heading_deg >= 360.0) heading_deg -= 360.0; if (emcmot_hal_data->interp_straight_heading) { - *(emcmot_hal_data->interp_straight_heading) = heading_deg; + hal_set_real(emcmot_hal_data->interp_straight_heading, heading_deg); } } #ifdef WATCH_FLAGS diff --git a/src/emc/motion/homing.c b/src/emc/motion/homing.c index 800ab0fb0eb..6bf17dd03a3 100644 --- a/src/emc/motion/homing.c +++ b/src/emc/motion/homing.c @@ -129,12 +129,12 @@ static home_local_data H[EMCMOT_MAX_JOINTS]; // data for per-joint homing-specific hal pins: typedef struct { - hal_bit_t *home_sw; // home switch input - hal_bit_t *homing; // joint is homing - hal_bit_t *homed; // joint was homed - hal_bit_t *index_enable; // motmod sets: request reset on index + hal_bool_t home_sw; // home switch input + hal_bool_t homing; // joint is homing + hal_bool_t homed; // joint was homed + hal_bool_t index_enable; // motmod sets: request reset on index // encoder clears: index arrived - hal_s32_t *home_state; // homing state machine state + hal_sint_t home_state; // homing state machine state } one_joint_home_data_t; typedef struct { @@ -233,7 +233,7 @@ static int base_make_joint_home_pins(int id,int njoints) int jno,retval; one_joint_home_data_t *addr; - joint_home_data = hal_malloc(sizeof(all_joints_home_data_t)); + joint_home_data = hal_malloc(sizeof(*joint_home_data)); if (joint_home_data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, _("HOMING: all_joints_home_data_t malloc failed\n")); return -1; @@ -243,16 +243,16 @@ static int base_make_joint_home_pins(int id,int njoints) for (jno = 0; jno < njoints; jno++) { addr = &(joint_home_data->jhd[jno]); - retval += hal_pin_bit_newf(HAL_IN, &(addr->home_sw), id, - "joint.%d.home-sw-in", jno); - retval += hal_pin_bit_newf(HAL_OUT, &(addr->homing), id, - "joint.%d.homing", jno); - retval += hal_pin_bit_newf(HAL_OUT, &(addr->homed), id, - "joint.%d.homed", jno); - retval += hal_pin_s32_newf(HAL_OUT, &(addr->home_state), id, - "joint.%d.home-state", jno); - retval += hal_pin_bit_newf(HAL_IO, &(addr->index_enable), id, - "joint.%d.index-enable", jno); + retval += hal_pin_new_bool(id, HAL_IN, &(addr->home_sw), + 0, "joint.%d.home-sw-in", jno); + retval += hal_pin_new_bool(id, HAL_OUT, &(addr->homing), + 0, "joint.%d.homing", jno); + retval += hal_pin_new_bool(id, HAL_OUT, &(addr->homed), + 0, "joint.%d.homed", jno); + retval += hal_pin_new_si32(id, HAL_OUT, &(addr->home_state), + 0, "joint.%d.home-state", jno); + retval += hal_pin_new_bool(id, HAL_IO, &(addr->index_enable), + 0, "joint.%d.index-enable", jno); } return retval; } // base_make_joint_home_pins() @@ -533,8 +533,8 @@ static void base_read_homing_in_pins(int njoints) one_joint_home_data_t *addr; for (jno = 0; jno < njoints; jno++) { addr = &(joint_home_data->jhd[jno]); - H[jno].home_sw = *(addr->home_sw); // IN - H[jno].index_enable = *(addr->index_enable); // IO + H[jno].home_sw = hal_get_bool(addr->home_sw); // IN + H[jno].index_enable = hal_get_bool(addr->index_enable); // IO } } @@ -544,7 +544,7 @@ static void base_write_homing_out_pins(int njoints) one_joint_home_data_t *addr; for (jno = 0; jno < njoints; jno++) { addr = &(joint_home_data->jhd[jno]); - if(!(*(addr->homing) && !H[jno].homing && homing_active)) { + if(!(hal_get_bool(addr->homing) && !H[jno].homing && homing_active)) { // Prevent race condition. // (See also emc/motion/control.c: update_status()) // The homing status variable turns false before homing_active state @@ -555,19 +555,19 @@ static void base_write_homing_out_pins(int njoints) // Do not update the homing status when going from homing --> not homing // and the state machine is still active. The homing status deassertion // must be delayed until the state machine is done. - *(addr->homing) = H[jno].homing; + hal_set_bool(addr->homing, H[jno].homing); } - *(addr->homing) = H[jno].homing; // OUT - *(addr->homed) = H[jno].homed; // OUT - *(addr->home_state) = H[jno].home_state; // OUT + hal_set_bool(addr->homing, H[jno].homing); // OUT + hal_set_bool(addr->homed, H[jno].homed); // OUT + hal_set_si32(addr->home_state, H[jno].home_state); // OUT // index_enable is a HAL_IO pin: the encoder driver also writes it // (clears it on the index pulse). We do not own it, so we must not // clamp it every cycle; drive it only on our own edges and otherwise // leave it to whoever else is on the signal. if (H[jno].index_enable && !H[jno].index_enable_prev) { - *(addr->index_enable) = 1; // arm the index search + hal_set_bool(addr->index_enable, 1); // arm the index search } else if (!H[jno].index_enable && H[jno].index_enable_prev) { - *(addr->index_enable) = 0; // release if aborted while armed + hal_set_bool(addr->index_enable, 0); // release if aborted while armed } H[jno].index_enable_prev = H[jno].index_enable; } diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h index 5eba0f6711d..fc966f43dee 100644 --- a/src/emc/motion/mot_priv.h +++ b/src/emc/motion/mot_priv.h @@ -35,182 +35,182 @@ typedef struct { // the user needs only a subset of these // simplest way of spindle control (output start/stop) - hal_bit_t *spindle_on; /* spindle spin output */ + hal_bool_t spindle_on; /* spindle spin output */ // same thing for 2 directions - hal_bit_t *spindle_forward; /* spindle spin-forward output */ - hal_bit_t *spindle_reverse; /* spindle spin-reverse output */ + hal_bool_t spindle_forward; /* spindle spin-forward output */ + hal_bool_t spindle_reverse; /* spindle spin-reverse output */ // simple velocity control (as long as the output is active the spindle // should accelerate/decelerate - hal_bit_t *spindle_incr_speed; /* spindle spin-increase output */ - hal_bit_t *spindle_decr_speed; /* spindle spin-decrease output */ + hal_bool_t spindle_incr_speed; /* spindle spin-increase output */ + hal_bool_t spindle_decr_speed; /* spindle spin-decrease output */ // simple output for brake - hal_bit_t *spindle_brake; /* spindle brake output */ + hal_bool_t spindle_brake; /* spindle brake output */ // output of a prescribed speed (to hook-up to a velocity controller) - hal_float_t *spindle_speed_out; /* spindle speed output */ - hal_float_t *spindle_speed_out_rps; /* spindle speed output */ - hal_float_t *spindle_speed_out_abs; /* spindle speed output absolute*/ - hal_float_t *spindle_speed_out_rps_abs; /* spindle speed output absolute*/ - hal_float_t *spindle_speed_cmd_rps; /* spindle speed command without SO applied */ - hal_float_t *spindle_speed_in; /* spindle speed measured */ - hal_bit_t *spindle_index_enable; /* spindle inde I/O pin */ - hal_bit_t *spindle_inhibit; - hal_float_t *spindle_revs; - hal_bit_t *spindle_is_atspeed; - hal_bit_t *spindle_amp_fault; + hal_real_t spindle_speed_out; /* spindle speed output */ + hal_real_t spindle_speed_out_rps; /* spindle speed output */ + hal_real_t spindle_speed_out_abs; /* spindle speed output absolute*/ + hal_real_t spindle_speed_out_rps_abs; /* spindle speed output absolute*/ + hal_real_t spindle_speed_cmd_rps; /* spindle speed command without SO applied */ + hal_real_t spindle_speed_in; /* spindle speed measured */ + hal_bool_t spindle_index_enable; /* spindle inde I/O pin */ + hal_bool_t spindle_inhibit; + hal_real_t spindle_revs; + hal_bool_t spindle_is_atspeed; + hal_bool_t spindle_amp_fault; // spindle orient - hal_float_t *spindle_orient_angle; /* out: desired spindle angle, degrees */ - hal_s32_t *spindle_orient_mode; /* out: 0: least travel; 1: cw; 2: ccw */ - hal_bit_t *spindle_orient; /* out: signal orient in progress */ - hal_bit_t *spindle_locked; /* out: signal orient complete, spindle locked */ - hal_bit_t *spindle_is_oriented; /* in: orientation completed */ - hal_s32_t *spindle_orient_fault; /* in: error code of failed operation */ + hal_real_t spindle_orient_angle; /* out: desired spindle angle, degrees */ + hal_sint_t spindle_orient_mode; /* out: 0: least travel; 1: cw; 2: ccw */ + hal_bool_t spindle_orient; /* out: signal orient in progress */ + hal_bool_t spindle_locked; /* out: signal orient complete, spindle locked */ + hal_bool_t spindle_is_oriented; /* in: orientation completed */ + hal_sint_t spindle_orient_fault; /* in: error code of failed operation */ } spindle_hal_t; typedef struct { - hal_float_t *coarse_pos_cmd;/* RPI: commanded position, w/o comp */ - hal_float_t *joint_vel_cmd; /* RPI: commanded velocity, w/o comp */ - hal_float_t *joint_acc_cmd; /* RPI: commanded acceleration, w/o comp */ - hal_float_t *joint_jerk_cmd;/* RPI: commanded jerk, w/o comp */ - hal_float_t *backlash_corr; /* RPI: correction for backlash */ - hal_float_t *backlash_filt; /* RPI: filtered backlash correction */ - hal_float_t *backlash_vel; /* RPI: backlash speed variable */ - hal_float_t *motor_offset; /* RPI: motor offset, for checking homing stability */ - hal_float_t *motor_pos_cmd; /* WPI: commanded position, with comp */ - hal_float_t *motor_pos_fb; /* RPI: position feedback, with comp */ - hal_float_t *joint_pos_cmd; /* WPI: commanded position w/o comp, not ofs */ - hal_float_t *joint_pos_fb; /* RPI: position feedback, w/o comp */ - hal_float_t *f_error; /* RPI: following error */ - hal_float_t *f_error_lim; /* RPI: following error limit */ - - hal_float_t *free_pos_cmd; /* RPI: free traj planner pos cmd */ - hal_float_t *free_vel_lim; /* RPI: free traj planner vel limit */ - hal_bit_t *free_tp_enable; /* RPI: free traj planner is running */ - hal_bit_t *kb_jjog_active; /* RPI: executing keyboard jog */ - hal_bit_t *wheel_jjog_active;/* RPI: executing handwheel jog */ - - hal_bit_t *active; /* RPI: joint is active, whatever that means */ - hal_bit_t *in_position; /* RPI: joint is in position */ - hal_bit_t *error; /* RPI: joint has an error */ - hal_bit_t *phl; /* RPI: joint is at positive hard limit */ - hal_bit_t *nhl; /* RPI: joint is at negative hard limit */ - hal_bit_t *f_errored; /* RPI: joint had too much following error */ - hal_bit_t *faulted; /* RPI: joint amp faulted */ - hal_bit_t *pos_lim_sw; /* RPI: positive limit switch input */ - hal_bit_t *neg_lim_sw; /* RPI: negative limit switch input */ - hal_bit_t *amp_fault; /* RPI: amp fault input */ - hal_bit_t *amp_enable; /* WPI: amp enable output */ - - hal_bit_t *unlock; /* WPI: command that axis should unlock for rotation */ - hal_bit_t *is_unlocked; /* RPI: axis is currently unlocked */ - - hal_s32_t *jjog_counts; /* WPI: jogwheel position input */ - hal_bit_t *jjog_enable; /* RPI: enable jogwheel */ - hal_float_t *jjog_scale; /* RPI: distance to jog on each count */ - hal_float_t *jjog_accel_fraction; /* RPI: to limit wheel jog accel */ - hal_bit_t *jjog_vel_mode; /* RPI: true for "velocity mode" jogwheel */ + hal_real_t coarse_pos_cmd;/* RPI: commanded position, w/o comp */ + hal_real_t joint_vel_cmd; /* RPI: commanded velocity, w/o comp */ + hal_real_t joint_acc_cmd; /* RPI: commanded acceleration, w/o comp */ + hal_real_t joint_jerk_cmd;/* RPI: commanded jerk, w/o comp */ + hal_real_t backlash_corr; /* RPI: correction for backlash */ + hal_real_t backlash_filt; /* RPI: filtered backlash correction */ + hal_real_t backlash_vel; /* RPI: backlash speed variable */ + hal_real_t motor_offset; /* RPI: motor offset, for checking homing stability */ + hal_real_t motor_pos_cmd; /* WPI: commanded position, with comp */ + hal_real_t motor_pos_fb; /* RPI: position feedback, with comp */ + hal_real_t joint_pos_cmd; /* WPI: commanded position w/o comp, not ofs */ + hal_real_t joint_pos_fb; /* RPI: position feedback, w/o comp */ + hal_real_t f_error; /* RPI: following error */ + hal_real_t f_error_lim; /* RPI: following error limit */ + + hal_real_t free_pos_cmd; /* RPI: free traj planner pos cmd */ + hal_real_t free_vel_lim; /* RPI: free traj planner vel limit */ + hal_bool_t free_tp_enable; /* RPI: free traj planner is running */ + hal_bool_t kb_jjog_active; /* RPI: executing keyboard jog */ + hal_bool_t wheel_jjog_active;/* RPI: executing handwheel jog */ + + hal_bool_t active; /* RPI: joint is active, whatever that means */ + hal_bool_t in_position; /* RPI: joint is in position */ + hal_bool_t error; /* RPI: joint has an error */ + hal_bool_t phl; /* RPI: joint is at positive hard limit */ + hal_bool_t nhl; /* RPI: joint is at negative hard limit */ + hal_bool_t f_errored; /* RPI: joint had too much following error */ + hal_bool_t faulted; /* RPI: joint amp faulted */ + hal_bool_t pos_lim_sw; /* RPI: positive limit switch input */ + hal_bool_t neg_lim_sw; /* RPI: negative limit switch input */ + hal_bool_t amp_fault; /* RPI: amp fault input */ + hal_bool_t amp_enable; /* WPI: amp enable output */ + + hal_bool_t unlock; /* WPI: command that axis should unlock for rotation */ + hal_bool_t is_unlocked; /* RPI: axis is currently unlocked */ + + hal_sint_t jjog_counts; /* WPI: jogwheel position input */ + hal_bool_t jjog_enable; /* RPI: enable jogwheel */ + hal_real_t jjog_scale; /* RPI: distance to jog on each count */ + hal_real_t jjog_accel_fraction; /* RPI: to limit wheel jog accel */ + hal_bool_t jjog_vel_mode; /* RPI: true for "velocity mode" jogwheel */ } joint_hal_t; typedef struct { - hal_float_t *posthome_cmd; // IN pin extrajoint + hal_real_t posthome_cmd; // IN pin extrajoint } extrajoint_hal_t; /* machine data */ typedef struct { - hal_bit_t *probe_input; /* RPI: probe switch input */ - hal_bit_t *enable; /* RPI: motion inhibit input */ - hal_float_t *adaptive_feed; /* RPI: adaptive feedrate, 0.0 to 1.0 */ - hal_bit_t *feed_hold; /* RPI: set TRUE to stop motion maskable with g53 P1*/ - hal_bit_t *feed_inhibit; /* RPI: set TRUE to stop motion (non maskable)*/ - hal_bit_t *homing_inhibit; /* RPI: set TRUE to inhibit homing*/ - hal_bit_t *jog_inhibit; /* RPI: set TRUE to inhibit jogging*/ - hal_bit_t *jog_stop; /* RPI: set TRUE to stop jogging following accel values*/ - hal_bit_t *jog_stop_immediate; /* RPI: set TRUE to stop jogging immediately*/ - hal_bit_t *jog_is_active; /* RPI: TRUE if active jogging*/ - hal_bit_t *tp_reverse; /* Set true if trajectory planner is running in reverse*/ - hal_bit_t *motion_enabled; /* RPI: motion enable for all joints */ - hal_bit_t *is_all_homed; /* RPI: TRUE if all active joints is homed */ - hal_bit_t *in_position; /* RPI: all joints are in position */ - hal_bit_t *coord_mode; /* RPA: TRUE if coord, FALSE if free */ - hal_bit_t *teleop_mode; /* RPA: TRUE if teleop mode */ - hal_bit_t *coord_error; /* RPA: TRUE if coord mode error */ - hal_bit_t *on_soft_limit; /* RPA: TRUE if outside a limit */ - - hal_s32_t *program_line; /* RPA: program line causing current motion */ - hal_s32_t *motion_type; /* RPA: type (feed/rapid) of currently commanded motion */ - hal_float_t *current_vel; /* RPI: velocity magnitude in machine units */ - hal_float_t *requested_vel; /* RPI: requested velocity magnitude in machine units */ - hal_float_t *distance_to_go;/* RPI: distance to go in current move*/ - - hal_bit_t debug_bit_0; /* RPA: generic param, for debugging */ - hal_bit_t debug_bit_1; /* RPA: generic param, for debugging */ - hal_float_t debug_float_0; /* RPA: generic param, for debugging */ - hal_float_t debug_float_1; /* RPA: generic param, for debugging */ - hal_float_t debug_float_2; /* RPA: generic param, for debugging */ - hal_float_t debug_float_3; /* RPA: generic param, for debugging */ - hal_s32_t debug_s32_0; /* RPA: generic param, for debugging */ - hal_s32_t debug_s32_1; /* RPA: generic param, for debugging */ - - hal_bit_t *synch_do[EMCMOT_MAX_DIO]; /* WPI array: output pins for motion synched IO */ - hal_bit_t *synch_di[EMCMOT_MAX_DIO]; /* RPI array: input pins for motion synched IO */ - hal_float_t *analog_input[EMCMOT_MAX_AIO]; /* RPI array: input pins for analog Inputs */ - hal_float_t *analog_output[EMCMOT_MAX_AIO]; /* RPI array: output pins for analog Inputs */ - hal_bit_t *misc_error[EMCMOT_MAX_MISC_ERROR]; /* RPI array: output pins for misc error Inputs */ + hal_bool_t probe_input; /* RPI: probe switch input */ + hal_bool_t enable; /* RPI: motion inhibit input */ + hal_real_t adaptive_feed; /* RPI: adaptive feedrate, 0.0 to 1.0 */ + hal_bool_t feed_hold; /* RPI: set TRUE to stop motion maskable with g53 P1*/ + hal_bool_t feed_inhibit; /* RPI: set TRUE to stop motion (non maskable)*/ + hal_bool_t homing_inhibit; /* RPI: set TRUE to inhibit homing*/ + hal_bool_t jog_inhibit; /* RPI: set TRUE to inhibit jogging*/ + hal_bool_t jog_stop; /* RPI: set TRUE to stop jogging following accel values*/ + hal_bool_t jog_stop_immediate; /* RPI: set TRUE to stop jogging immediately*/ + hal_bool_t jog_is_active; /* RPI: TRUE if active jogging*/ + hal_bool_t tp_reverse; /* Set true if trajectory planner is running in reverse*/ + hal_bool_t motion_enabled; /* RPI: motion enable for all joints */ + hal_bool_t is_all_homed; /* RPI: TRUE if all active joints is homed */ + hal_bool_t in_position; /* RPI: all joints are in position */ + hal_bool_t coord_mode; /* RPA: TRUE if coord, FALSE if free */ + hal_bool_t teleop_mode; /* RPA: TRUE if teleop mode */ + hal_bool_t coord_error; /* RPA: TRUE if coord mode error */ + hal_bool_t on_soft_limit; /* RPA: TRUE if outside a limit */ + + hal_sint_t program_line; /* RPA: program line causing current motion */ + hal_sint_t motion_type; /* RPA: type (feed/rapid) of currently commanded motion */ + hal_real_t current_vel; /* RPI: velocity magnitude in machine units */ + hal_real_t requested_vel; /* RPI: requested velocity magnitude in machine units */ + hal_real_t distance_to_go; /* RPI: distance to go in current move*/ + + hal_bool_t debug_bit_0; /* RPA: generic param, for debugging */ + hal_bool_t debug_bit_1; /* RPA: generic param, for debugging */ + hal_real_t debug_float_0; /* RPA: generic param, for debugging */ + hal_real_t debug_float_1; /* RPA: generic param, for debugging */ + hal_real_t debug_float_2; /* RPA: generic param, for debugging */ + hal_real_t debug_float_3; /* RPA: generic param, for debugging */ + hal_sint_t debug_s32_0; /* RPA: generic param, for debugging */ + hal_sint_t debug_s32_1; /* RPA: generic param, for debugging */ + + hal_bool_t synch_do[EMCMOT_MAX_DIO]; /* WPI array: output pins for motion synched IO */ + hal_bool_t synch_di[EMCMOT_MAX_DIO]; /* RPI array: input pins for motion synched IO */ + hal_real_t analog_input[EMCMOT_MAX_AIO]; /* RPI array: input pins for analog Inputs */ + hal_real_t analog_output[EMCMOT_MAX_AIO]; /* RPI array: output pins for analog Inputs */ + hal_bool_t misc_error[EMCMOT_MAX_MISC_ERROR]; /* RPI array: output pins for misc error Inputs */ // FIXME - debug only, remove later - hal_float_t traj_pos_out; /* RPA: traj internals, for debugging */ - hal_float_t traj_vel_out; /* RPA: traj internals, for debugging */ - hal_u32_t traj_active_tc; /* RPA: traj internals, for debugging */ - hal_float_t tc_pos[4]; /* RPA: traj internals, for debugging */ - hal_float_t tc_vel[4]; /* RPA: traj internals, for debugging */ - hal_float_t tc_acc[4]; /* RPA: traj internals, for debugging */ + hal_real_t traj_pos_out; /* RPA: traj internals, for debugging */ + hal_real_t traj_vel_out; /* RPA: traj internals, for debugging */ + hal_uint_t traj_active_tc; /* RPA: traj internals, for debugging */ + hal_real_t tc_pos[4]; /* RPA: traj internals, for debugging */ + hal_real_t tc_vel[4]; /* RPA: traj internals, for debugging */ + hal_real_t tc_acc[4]; /* RPA: traj internals, for debugging */ // realtime overrun detection - hal_u32_t *last_period; /* pin: last period in nanoseconds */ - - hal_float_t *tooloffset_x; - hal_float_t *tooloffset_y; - hal_float_t *tooloffset_z; - hal_float_t *tooloffset_a; - hal_float_t *tooloffset_b; - hal_float_t *tooloffset_c; - hal_float_t *tooloffset_u; - hal_float_t *tooloffset_v; - hal_float_t *tooloffset_w; + hal_uint_t last_period; /* pin: last period in nanoseconds */ + + hal_real_t tooloffset_x; + hal_real_t tooloffset_y; + hal_real_t tooloffset_z; + hal_real_t tooloffset_a; + hal_real_t tooloffset_b; + hal_real_t tooloffset_c; + hal_real_t tooloffset_u; + hal_real_t tooloffset_v; + hal_real_t tooloffset_w; spindle_hal_t spindle[EMCMOT_MAX_SPINDLES]; /*spindle data */ joint_hal_t joint[EMCMOT_MAX_JOINTS]; /* data for each joint */ extrajoint_hal_t ejoint[EMCMOT_MAX_EXTRAJOINTS]; /* data for each extrajoint */ - hal_bit_t *eoffset_active; /* ext offsets active */ - hal_bit_t *eoffset_limited; /* ext offsets exceed limit */ + hal_bool_t eoffset_active; /* ext offsets active */ + hal_bool_t eoffset_limited; /* ext offsets exceed limit */ - hal_float_t *feed_upm; /* feed G-code units per minute*/ - hal_float_t *feed_inches_per_minute; /* feed inches per minute*/ - hal_float_t *feed_inches_per_second; /* feed inches per second*/ - hal_float_t *feed_mm_per_minute; /* feed mm per minute*/ - hal_float_t *feed_mm_per_second; /* feed mm per second*/ + hal_real_t feed_upm; /* feed G-code units per minute*/ + hal_real_t feed_inches_per_minute; /* feed inches per minute*/ + hal_real_t feed_inches_per_second; /* feed inches per second*/ + hal_real_t feed_mm_per_minute; /* feed mm per minute*/ + hal_real_t feed_mm_per_second; /* feed mm per second*/ - hal_float_t *switchkins_type; + hal_real_t switchkins_type; /* Interp State Pins */ - hal_s32_t *interp_line_number; - hal_s32_t *interp_motion_type; - hal_float_t *interp_feedrate; + hal_sint_t interp_line_number; + hal_sint_t interp_motion_type; + hal_real_t interp_feedrate; /* New Geometric Metadata Pins */ - hal_float_t *interp_arc_radius; - hal_float_t *interp_arc_center_x; - hal_float_t *interp_arc_center_y; - hal_float_t *interp_arc_center_z; - hal_float_t *interp_straight_heading; - hal_float_t *interp_normal_heading; - hal_bit_t *iscircle; + hal_real_t interp_arc_radius; + hal_real_t interp_arc_center_x; + hal_real_t interp_arc_center_y; + hal_real_t interp_arc_center_z; + hal_real_t interp_straight_heading; + hal_real_t interp_normal_heading; + hal_bool_t iscircle; } emcmot_hal_data_t; /*********************************************************************** diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c index 041aa7ea182..b6147426886 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c @@ -515,38 +515,44 @@ static int init_hal_io(void) } /* export machine wide hal pins */ - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->probe_input), mot_comp_id, "motion.probe-input")); - CALL_CHECK(hal_pin_float_newf(HAL_IN, &(emcmot_hal_data->adaptive_feed), mot_comp_id, "motion.adaptive-feed")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->feed_hold), mot_comp_id, "motion.feed-hold")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->feed_inhibit), mot_comp_id, "motion.feed-inhibit")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->homing_inhibit), mot_comp_id, "motion.homing-inhibit")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->jog_inhibit), mot_comp_id, "motion.jog-inhibit")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->jog_stop), mot_comp_id, "motion.jog-stop")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->jog_stop_immediate), mot_comp_id, "motion.jog-stop-immediate")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->tp_reverse), mot_comp_id, "motion.tp-reverse")); - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->enable), mot_comp_id, "motion.enable")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->is_all_homed), mot_comp_id, "motion.is-all-homed")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->probe_input), 0, "motion.probe-input")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(emcmot_hal_data->adaptive_feed), 1.0, "motion.adaptive-feed")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->feed_hold), 0, "motion.feed-hold")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->feed_inhibit), 0, "motion.feed-inhibit")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->homing_inhibit), 0, "motion.homing-inhibit")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->jog_inhibit), 0, "motion.jog-inhibit")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->jog_stop), 0, "motion.jog-stop")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->jog_stop_immediate), 0, "motion.jog-stop-immediate")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tp_reverse), 0, "motion.tp-reverse")); + // default value of enable is TRUE, so simple machines can leave it disconnected + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->enable), 1, "motion.enable")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->is_all_homed), 0, "motion.is-all-homed")); /* state tags pins */ - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->feed_upm), mot_comp_id, "motion.feed-upm")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->feed_inches_per_minute), mot_comp_id, "motion.feed-inches-per-minute")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->feed_inches_per_second), mot_comp_id, "motion.feed-inches-per-second")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->feed_mm_per_minute), mot_comp_id, "motion.feed-mm-per-minute")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->feed_mm_per_second), mot_comp_id, "motion.feed-mm-per-second")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->feed_upm), 0.0, "motion.feed-upm")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->feed_inches_per_minute), 0.0, "motion.feed-inches-per-minute")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->feed_inches_per_second), 0.0, "motion.feed-inches-per-second")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->feed_mm_per_minute), 0.0, "motion.feed-mm-per-minute")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->feed_mm_per_second), 0.0, "motion.feed-mm-per-second")); /* export motion-synched digital output pins */ /* export motion digital input pins */ in = 0, out = 0; + /* motion synched dio, init to not enabled */ for (n = 0; n < num_dio; n++) { if (n < num_din && names_din[n]) { - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->synch_di[n]), mot_comp_id, "motion.din-%s", names_din[n])); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->synch_di[n]), + 0, "motion.din-%s", names_din[n])); } else { - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->synch_di[n]), mot_comp_id, "motion.digital-in-%02d", in++)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->synch_di[n]), + 0, "motion.digital-in-%02d", in++)); } if (n < num_dout && names_dout[n]) { - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->synch_do[n]), mot_comp_id, "motion.dout-%s", names_dout[n])); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->synch_do[n]), + 0, "motion.dout-%s", names_dout[n])); } else { - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->synch_do[n]), mot_comp_id, "motion.digital-out-%02d",out++)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->synch_do[n]), + 0, "motion.digital-out-%02d",out++)); } } @@ -555,149 +561,104 @@ static int init_hal_io(void) in = 0, out = 0; for (n = 0; n < num_aio; n++) { if (n < num_ain && names_ain[n]) { - CALL_CHECK(hal_pin_float_newf(HAL_IN, &(emcmot_hal_data->analog_input[n]), mot_comp_id, "motion.ain-%s", names_ain[n])); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(emcmot_hal_data->analog_input[n]), + 0.0, "motion.ain-%s", names_ain[n])); } else { - CALL_CHECK(hal_pin_float_newf(HAL_IN, &(emcmot_hal_data->analog_input[n]), mot_comp_id, "motion.analog-in-%02d", in++)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(emcmot_hal_data->analog_input[n]), + 0.0, "motion.analog-in-%02d", in++)); } if (n < num_aout && names_aout[n]) { - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->analog_output[n]), mot_comp_id, "motion.aout-%s", names_aout[n])); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->analog_output[n]), + 0.0, "motion.aout-%s", names_aout[n])); } else { - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->analog_output[n]), mot_comp_id, "motion.analog-out-%02d", out++)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->analog_output[n]), + 0.0, "motion.analog-out-%02d", out++)); } } if (names_misc_errors[0]) { for (n = 0; n < num_misc_error; n++) { if (names_misc_errors[n] == NULL || (*names_misc_errors[n] == 0)) {break;} - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->misc_error[n]), mot_comp_id, "motion.err-%s", names_misc_errors[n])); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->misc_error[n]), 0, "motion.err-%s", names_misc_errors[n])); } } else { /* export misc error input pins */ for (n = 0; n < num_misc_error; n++) { - CALL_CHECK(hal_pin_bit_newf(HAL_IN, &(emcmot_hal_data->misc_error[n]), mot_comp_id, "motion.misc-error-%02d", n)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(emcmot_hal_data->misc_error[n]), 0, "motion.misc-error-%02d", n)); } } /* export machine wide hal pins */ - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->motion_enabled), mot_comp_id, "motion.motion-enabled")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->in_position), mot_comp_id, "motion.in-position")); - CALL_CHECK(hal_pin_s32_newf(HAL_OUT, &(emcmot_hal_data->motion_type), mot_comp_id, "motion.motion-type")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->coord_mode), mot_comp_id, "motion.coord-mode")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->teleop_mode), mot_comp_id, "motion.teleop-mode")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->coord_error), mot_comp_id, "motion.coord-error")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->on_soft_limit), mot_comp_id, "motion.on-soft-limit")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->current_vel), mot_comp_id, "motion.current-vel")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->requested_vel), mot_comp_id, "motion.requested-vel")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->distance_to_go), mot_comp_id, "motion.distance-to-go")); - CALL_CHECK(hal_pin_s32_newf(HAL_OUT, &(emcmot_hal_data->program_line), mot_comp_id, "motion.program-line")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->jog_is_active), mot_comp_id, "motion.jog-is-active")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->motion_enabled), 0, "motion.motion-enabled")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->in_position), 0, "motion.in-position")); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_OUT, &(emcmot_hal_data->motion_type), 0, "motion.motion-type")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->coord_mode), 0, "motion.coord-mode")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->teleop_mode), 0, "motion.teleop-mode")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->coord_error), 0, "motion.coord-error")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->on_soft_limit), 0, "motion.on-soft-limit")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->current_vel), 0.0, "motion.current-vel")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->requested_vel), 0.0, "motion.requested-vel")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->distance_to_go), 0.0, "motion.distance-to-go")); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_OUT, &(emcmot_hal_data->program_line), 0, "motion.program-line")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->jog_is_active), 0, "motion.jog-is-active")); /* Standard Interp State Pins */ - CALL_CHECK(hal_pin_s32_newf(HAL_OUT, &(emcmot_hal_data->interp_line_number), mot_comp_id, "motion.interp.line-number")); - CALL_CHECK(hal_pin_s32_newf(HAL_OUT, &(emcmot_hal_data->interp_motion_type), mot_comp_id, "motion.interp.motion-type")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_feedrate), mot_comp_id, "motion.interp.feedrate")); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_line_number), 0, "motion.interp.line-number")); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_motion_type), 0, "motion.interp.motion-type")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_feedrate), 0.0, "motion.interp.feedrate")); /* New Geometric Metadata Pins */ - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_arc_radius), mot_comp_id, "motion.interp.arc-radius")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_arc_center_x), mot_comp_id, "motion.interp.arc-center-x")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_arc_center_y), mot_comp_id, "motion.interp.arc-center-y")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_arc_center_z), mot_comp_id, "motion.interp.arc-center-z")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_straight_heading), mot_comp_id, "motion.interp.heading")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->interp_normal_heading), mot_comp_id, "motion.interp.normal-heading")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &emcmot_hal_data->iscircle, mot_comp_id, "motion.interp.iscircle")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_arc_radius), 0.0, "motion.interp.arc-radius")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_arc_center_x), 0.0, "motion.interp.arc-center-x")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_arc_center_y), 0.0, "motion.interp.arc-center-y")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_arc_center_z), 0.0, "motion.interp.arc-center-z")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_straight_heading), 0.0, "motion.interp.heading")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->interp_normal_heading), 0.0, "motion.interp.normal-heading")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &emcmot_hal_data->iscircle, 0, "motion.interp.iscircle")); /* export debug parameters */ /* these can be used to view any internal variable, simply change a line in control.c:output_to_hal() and recompile */ - CALL_CHECK(hal_param_bit_newf(HAL_RO, &(emcmot_hal_data->debug_bit_0), mot_comp_id, "motion.debug-bit-0")); - CALL_CHECK(hal_param_bit_newf(HAL_RO, &(emcmot_hal_data->debug_bit_1), mot_comp_id, "motion.debug-bit-1")); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->debug_float_0), mot_comp_id, "motion.debug-float-0")); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->debug_float_1), mot_comp_id, "motion.debug-float-1")); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->debug_float_2), mot_comp_id, "motion.debug-float-2")); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->debug_float_3), mot_comp_id, "motion.debug-float-3")); - CALL_CHECK(hal_param_s32_newf(HAL_RO, &(emcmot_hal_data->debug_s32_0), mot_comp_id, "motion.debug-s32-0")); - CALL_CHECK(hal_param_s32_newf(HAL_RO, &(emcmot_hal_data->debug_s32_1), mot_comp_id, "motion.debug-s32-1")); + CALL_CHECK(hal_param_new_bool(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_bit_0), 0, "motion.debug-bit-0")); + CALL_CHECK(hal_param_new_bool(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_bit_1), 0, "motion.debug-bit-1")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_float_0), 0.0, "motion.debug-float-0")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_float_1), 0.0, "motion.debug-float-1")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_float_2), 0.0, "motion.debug-float-2")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_float_3), 0.0, "motion.debug-float-3")); + CALL_CHECK(hal_param_new_si32(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_s32_0), 0, "motion.debug-s32-0")); + CALL_CHECK(hal_param_new_si32(mot_comp_id, HAL_RO, &(emcmot_hal_data->debug_s32_1), 0, "motion.debug-s32-1")); // FIXME - debug only, remove later // export HAL parameters for some trajectory planner internal variables // so they can be scoped - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->traj_pos_out), mot_comp_id, "traj.pos_out")); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->traj_vel_out), mot_comp_id, "traj.vel_out")); - CALL_CHECK(hal_param_u32_newf(HAL_RO, &(emcmot_hal_data->traj_active_tc), mot_comp_id, "traj.active_tc")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->traj_pos_out), 0.0, "traj.pos_out")); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->traj_vel_out), 0.0, "traj.vel_out")); + CALL_CHECK(hal_param_new_ui32(mot_comp_id, HAL_RO, &(emcmot_hal_data->traj_active_tc), 0, "traj.active_tc")); for (n = 0; n < 4; n++) { - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->tc_pos[n]), mot_comp_id, "tc.%d.pos", n)); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->tc_vel[n]), mot_comp_id, "tc.%d.vel", n)); - CALL_CHECK(hal_param_float_newf(HAL_RO, &(emcmot_hal_data->tc_acc[n]), mot_comp_id, "tc.%d.acc", n)); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->tc_pos[n]), 0.0, "tc.%d.pos", n)); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->tc_vel[n]), 0.0, "tc.%d.vel", n)); + CALL_CHECK(hal_param_new_real(mot_comp_id, HAL_RO, &(emcmot_hal_data->tc_acc[n]), 0.0, "tc.%d.acc", n)); } // end of exporting trajectory planner internals // export timing related HAL pins so they can be scoped and/or connected - CALL_CHECK(hal_pin_u32_newf(HAL_OUT, &(emcmot_hal_data->last_period), mot_comp_id, "motion.servo.last-period")); + CALL_CHECK(hal_pin_new_ui32(mot_comp_id, HAL_OUT, &(emcmot_hal_data->last_period), 0, "motion.servo.last-period")); // export timing related HAL pins so they can be scoped - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_x), mot_comp_id, "motion.tooloffset.x")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_y), mot_comp_id, "motion.tooloffset.y")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_z), mot_comp_id, "motion.tooloffset.z")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_a), mot_comp_id, "motion.tooloffset.a")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_b), mot_comp_id, "motion.tooloffset.b")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_c), mot_comp_id, "motion.tooloffset.c")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_u), mot_comp_id, "motion.tooloffset.u")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_v), mot_comp_id, "motion.tooloffset.v")); - CALL_CHECK(hal_pin_float_newf(HAL_OUT, &(emcmot_hal_data->tooloffset_w), mot_comp_id, "motion.tooloffset.w")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_x), 0.0, "motion.tooloffset.x")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_y), 0.0, "motion.tooloffset.y")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_z), 0.0, "motion.tooloffset.z")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_a), 0.0, "motion.tooloffset.a")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_b), 0.0, "motion.tooloffset.b")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_c), 0.0, "motion.tooloffset.c")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_u), 0.0, "motion.tooloffset.u")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_v), 0.0, "motion.tooloffset.v")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(emcmot_hal_data->tooloffset_w), 0.0, "motion.tooloffset.w")); if (kinematicsSwitchable()) { - CALL_CHECK(hal_pin_float_newf(HAL_IN, &(emcmot_hal_data->switchkins_type), mot_comp_id, "motion.switchkins-type")); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(emcmot_hal_data->switchkins_type), 0.0, "motion.switchkins-type")); } - /* initialize machine wide pins and parameters */ - *(emcmot_hal_data->adaptive_feed) = 1.0; - *(emcmot_hal_data->feed_hold) = 0; - *(emcmot_hal_data->feed_inhibit) = 0; - *(emcmot_hal_data->homing_inhibit) = 0; - *(emcmot_hal_data->jog_inhibit) = 0; - *(emcmot_hal_data->jog_stop) = 0; - *(emcmot_hal_data->jog_stop_immediate) = 0; - *(emcmot_hal_data->is_all_homed) = 0; - - *(emcmot_hal_data->probe_input) = 0; - /* default value of enable is TRUE, so simple machines - can leave it disconnected */ - *(emcmot_hal_data->enable) = 1; - - /* motion synched dio, init to not enabled */ - for (n = 0; n < num_dio; n++) { - *(emcmot_hal_data->synch_do[n]) = 0; - *(emcmot_hal_data->synch_di[n]) = 0; - } - - for (n = 0; n < num_aio; n++) { - *(emcmot_hal_data->analog_output[n]) = 0.0; - *(emcmot_hal_data->analog_input[n]) = 0.0; - } - - for (n = 0; n < num_misc_error; n++) { - *(emcmot_hal_data->misc_error[n]) = 0; - } - - /*! \todo FIXME - these don't really need initialized, since they are written - with data from the emcmotStatus struct */ - *(emcmot_hal_data->motion_enabled) = 0; - *(emcmot_hal_data->in_position) = 0; - *(emcmot_hal_data->motion_type) = 0; - *(emcmot_hal_data->coord_mode) = 0; - *(emcmot_hal_data->teleop_mode) = 0; - *(emcmot_hal_data->coord_error) = 0; - *(emcmot_hal_data->on_soft_limit) = 0; - - /* init debug parameters */ - emcmot_hal_data->debug_bit_0 = 0; - emcmot_hal_data->debug_bit_1 = 0; - emcmot_hal_data->debug_float_0 = 0.0; - emcmot_hal_data->debug_float_1 = 0.0; - emcmot_hal_data->debug_float_2 = 0.0; - emcmot_hal_data->debug_float_3 = 0.0; - - *(emcmot_hal_data->last_period) = 0; /* export spindle pins and params */ for (n = 0; n < num_spindles; n++) { @@ -716,7 +677,7 @@ static int init_hal_io(void) rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: joint %d pin/param export failed\n"), n); return -1; } - *(joint_data->amp_enable) = 0; + hal_set_bool(joint_data->amp_enable, 0); /* We'll init the index model to EXT_ENCODER_INDEX_MODEL_RAW for now, because it is always supported. */ @@ -733,8 +694,8 @@ static int init_hal_io(void) CALL_CHECK(axis_init_hal_io(mot_comp_id)); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->eoffset_limited), mot_comp_id, "motion.eoffset-limited")); - CALL_CHECK(hal_pin_bit_newf(HAL_OUT, &(emcmot_hal_data->eoffset_active), mot_comp_id, "motion.eoffset-active")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->eoffset_limited), 0, "motion.eoffset-limited")); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(emcmot_hal_data->eoffset_active), 0, "motion.eoffset-active")); /* Done! */ rtapi_print_msg(RTAPI_MSG_INFO, "MOTION: init_hal_io() complete, %d axes.\n", n); @@ -742,43 +703,35 @@ static int init_hal_io(void) } static int export_spindle(int num, spindle_hal_t * addr){ - int retval, msg; - - msg = rtapi_get_msg_level(); + int msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); - if ((retval = hal_pin_bit_newf(HAL_IO, &(addr->spindle_index_enable), mot_comp_id, "spindle.%d.index-enable", num)) != 0) return retval; - - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_on), mot_comp_id, "spindle.%d.on", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_forward), mot_comp_id, "spindle.%d.forward", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_reverse), mot_comp_id, "spindle.%d.reverse", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_brake), mot_comp_id, "spindle.%d.brake", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_speed_out), mot_comp_id, "spindle.%d.speed-out", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_speed_out_abs), mot_comp_id, "spindle.%d.speed-out-abs", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_speed_out_rps), mot_comp_id, "spindle.%d.speed-out-rps", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_speed_out_rps_abs), mot_comp_id, "spindle.%d.speed-out-rps-abs", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_speed_cmd_rps), mot_comp_id, "spindle.%d.speed-cmd-rps", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->spindle_inhibit), mot_comp_id, "spindle.%d.inhibit", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->spindle_amp_fault), mot_comp_id, "spindle.%d.amp-fault-in", num)) != 0) return retval; - *(addr->spindle_inhibit) = 0; + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IO, &(addr->spindle_index_enable), 0, "spindle.%d.index-enable", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_on), 0, "spindle.%d.on", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_forward), 0, "spindle.%d.forward", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_reverse), 0, "spindle.%d.reverse", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_brake), 0, "spindle.%d.brake", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_speed_out), 0.0, "spindle.%d.speed-out", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_speed_out_abs), 0.0, "spindle.%d.speed-out-abs", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_speed_out_rps), 0.0, "spindle.%d.speed-out-rps", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_speed_out_rps_abs), 0.0, "spindle.%d.speed-out-rps-abs", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_speed_cmd_rps), 0.0, "spindle.%d.speed-cmd-rps", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->spindle_inhibit), 0, "spindle.%d.inhibit", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->spindle_amp_fault), 0, "spindle.%d.amp-fault-in", num)); // spindle orient pins - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->spindle_orient_angle), mot_comp_id, "spindle.%d.orient-angle", num)) < 0) return retval; - if ((retval = hal_pin_s32_newf(HAL_OUT, &(addr->spindle_orient_mode), mot_comp_id, "spindle.%d.orient-mode", num)) < 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_orient), mot_comp_id, "spindle.%d.orient", num)) < 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->spindle_locked), mot_comp_id, "spindle.%d.locked", num)) < 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->spindle_is_oriented), mot_comp_id, "spindle.%d.is-oriented", num)) < 0) return retval; - if ((retval = hal_pin_s32_newf(HAL_IN, &(addr->spindle_orient_fault), mot_comp_id, "spindle.%d.orient-fault", num)) < 0) return retval; - *(addr->spindle_orient_angle) = 0.0; - *(addr->spindle_orient_mode) = 0; - *(addr->spindle_orient) = 0; - - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->spindle_revs), mot_comp_id, "spindle.%d.revs", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->spindle_speed_in), mot_comp_id, "spindle.%d.speed-in", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->spindle_is_atspeed), mot_comp_id, "spindle.%d.at-speed", num)) != 0) return retval; + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->spindle_orient_angle), 0.0, "spindle.%d.orient-angle", num)); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_OUT, &(addr->spindle_orient_mode), 0, "spindle.%d.orient-mode", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_orient), 0, "spindle.%d.orient", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->spindle_locked), 0, "spindle.%d.locked", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->spindle_is_oriented), 0, "spindle.%d.is-oriented", num)); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_IN, &(addr->spindle_orient_fault), 0, "spindle.%d.orient-fault", num)); + + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->spindle_revs), 0.0, "spindle.%d.revs", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->spindle_speed_in), 0.0, "spindle.%d.speed-in", num)); /* Default 1: an unwired at-speed pin must never block motion. Do not change to 0 or machines without at-speed wired would idle forever. */ - *(addr->spindle_is_atspeed) = 1; + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->spindle_is_atspeed), 1, "spindle.%d.at-speed", num)); /* restore saved message level */ rtapi_set_msg_level(msg); return 0; @@ -786,58 +739,56 @@ static int export_spindle(int num, spindle_hal_t * addr){ static int export_joint(int num, joint_hal_t * addr) { - int retval, msg; - /* This function exports a lot of stuff, which results in a lot of logging if msg_level is at INFO or ALL. So we save the current value of msg_level and restore it later. If you actually need to log this function's actions, change the second line below */ - msg = rtapi_get_msg_level(); + int msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); /* export joint pins */ - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->coarse_pos_cmd), mot_comp_id, "joint.%d.coarse-pos-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->joint_pos_cmd), mot_comp_id, "joint.%d.pos-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->joint_pos_fb), mot_comp_id, "joint.%d.pos-fb", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->motor_pos_cmd), mot_comp_id, "joint.%d.motor-pos-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->motor_pos_fb), mot_comp_id, "joint.%d.motor-pos-fb", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->motor_offset), mot_comp_id, "joint.%d.motor-offset", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->pos_lim_sw), mot_comp_id, "joint.%d.pos-lim-sw-in", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->neg_lim_sw), mot_comp_id, "joint.%d.neg-lim-sw-in", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->amp_enable), mot_comp_id, "joint.%d.amp-enable-out", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->amp_fault), mot_comp_id, "joint.%d.amp-fault-in", num)) != 0) return retval; - if ((retval = hal_pin_s32_newf(HAL_IN, &(addr->jjog_counts), mot_comp_id, "joint.%d.jog-counts", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->jjog_enable), mot_comp_id, "joint.%d.jog-enable", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->jjog_scale), mot_comp_id, "joint.%d.jog-scale", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->jjog_vel_mode), mot_comp_id, "joint.%d.jog-vel-mode", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->joint_vel_cmd), mot_comp_id, "joint.%d.vel-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->joint_acc_cmd), mot_comp_id, "joint.%d.acc-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->joint_jerk_cmd), mot_comp_id, "joint.%d.jerk-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->backlash_corr), mot_comp_id, "joint.%d.backlash-corr", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->backlash_filt), mot_comp_id, "joint.%d.backlash-filt", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->backlash_vel), mot_comp_id, "joint.%d.backlash-vel", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->f_error), mot_comp_id, "joint.%d.f-error", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->f_error_lim), mot_comp_id, "joint.%d.f-error-lim", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->free_pos_cmd), mot_comp_id, "joint.%d.free-pos-cmd", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_OUT, &(addr->free_vel_lim), mot_comp_id, "joint.%d.free-vel-lim", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->free_tp_enable), mot_comp_id, "joint.%d.free-tp-enable", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->kb_jjog_active), mot_comp_id, "joint.%d.kb-jog-active", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->wheel_jjog_active), mot_comp_id, "joint.%d.wheel-jog-active", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->in_position), mot_comp_id, "joint.%d.in-position", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->phl), mot_comp_id, "joint.%d.pos-hard-limit", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->nhl), mot_comp_id, "joint.%d.neg-hard-limit", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->active), mot_comp_id, "joint.%d.active", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->error), mot_comp_id, "joint.%d.error", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->f_errored), mot_comp_id, "joint.%d.f-errored", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->faulted), mot_comp_id, "joint.%d.faulted", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN,&(addr->jjog_accel_fraction),mot_comp_id,"joint.%d.jog-accel-fraction", num)) != 0) return retval; - *addr->jjog_accel_fraction = 1.0; // fraction of accel for wheel jjogs + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->coarse_pos_cmd), 0.0, "joint.%d.coarse-pos-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->joint_pos_cmd), 0.0, "joint.%d.pos-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->joint_pos_fb), 0.0, "joint.%d.pos-fb", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->motor_pos_cmd), 0.0, "joint.%d.motor-pos-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->motor_pos_fb), 0.0, "joint.%d.motor-pos-fb", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->motor_offset), 0.0, "joint.%d.motor-offset", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->pos_lim_sw), 0, "joint.%d.pos-lim-sw-in", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->neg_lim_sw), 0, "joint.%d.neg-lim-sw-in", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->amp_enable), 0, "joint.%d.amp-enable-out", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->amp_fault), 0, "joint.%d.amp-fault-in", num)); + CALL_CHECK(hal_pin_new_si32(mot_comp_id, HAL_IN, &(addr->jjog_counts), 0, "joint.%d.jog-counts", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->jjog_enable), 0, "joint.%d.jog-enable", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->jjog_scale), 0.0, "joint.%d.jog-scale", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->jjog_vel_mode), 0, "joint.%d.jog-vel-mode", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->joint_vel_cmd), 0.0, "joint.%d.vel-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->joint_acc_cmd), 0.0, "joint.%d.acc-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->joint_jerk_cmd), 0.0, "joint.%d.jerk-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->backlash_corr), 0.0, "joint.%d.backlash-corr", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->backlash_filt), 0.0, "joint.%d.backlash-filt", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->backlash_vel), 0.0, "joint.%d.backlash-vel", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->f_error), 0.0, "joint.%d.f-error", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->f_error_lim), 0.0, "joint.%d.f-error-lim", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->free_pos_cmd), 0.0, "joint.%d.free-pos-cmd", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_OUT, &(addr->free_vel_lim), 0.0, "joint.%d.free-vel-lim", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->free_tp_enable), 0, "joint.%d.free-tp-enable", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->kb_jjog_active), 0, "joint.%d.kb-jog-active", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->wheel_jjog_active), 0, "joint.%d.wheel-jog-active", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->in_position), 0, "joint.%d.in-position", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->phl), 0, "joint.%d.pos-hard-limit", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->nhl), 0, "joint.%d.neg-hard-limit", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->active), 0, "joint.%d.active", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->error), 0, "joint.%d.error", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->f_errored), 0, "joint.%d.f-errored", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->faulted), 0, "joint.%d.faulted", num)); + // init 1.0: fraction of accel for wheel jjogs + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->jjog_accel_fraction), 1.0, "joint.%d.jog-accel-fraction", num)); if ( joint_is_lockable(num) ) { // these pins may be needed for rotary joints rtapi_print_msg(RTAPI_MSG_WARN,"motion.c: Creating unlock hal pins for joint %d\n",num); - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->unlock), mot_comp_id, "joint.%d.unlock", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->is_unlocked), mot_comp_id, "joint.%d.is-unlocked", num)) != 0) return retval; + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->unlock), 0, "joint.%d.unlock", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->is_unlocked), 0, "joint.%d.is-unlocked", num)); } /* restore saved message level */ @@ -849,7 +800,7 @@ static int export_extrajoint(int num, extrajoint_hal_t * addr) { int retval; /* export extrajoint pins */ - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->posthome_cmd), mot_comp_id, + if ((retval = hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->posthome_cmd), 0.0, "joint.%d.posthome-cmd", num)) != 0) return retval; return 0; } diff --git a/src/emc/rs274ngc/interp_namedparams.cc b/src/emc/rs274ngc/interp_namedparams.cc index 546535af75e..d4df82efe1f 100644 --- a/src/emc/rs274ngc/interp_namedparams.cc +++ b/src/emc/rs274ngc/interp_namedparams.cc @@ -246,26 +246,20 @@ int Interp::fetch_ini_param( const char *nameBuf, int *status, double *value) // the shortest possible INI variable is '_hal[x]' or 7 chars long . int Interp::fetch_hal_param( const char *nameBuf, int *status, double *value) { - static int comp_id; int retval; hal_type_t type = HAL_TYPE_UNINITIALIZED; - hal_data_u* ptr; - bool conn; - char hal_name[HAL_NAME_LEN]; + hal_query_value_u qval; + char hal_name[HAL_NAME_LEN + 1]; *status = 0; - if (!comp_id) { - char hal_comp[HAL_NAME_LEN]; - snprintf(hal_comp, sizeof(hal_comp),"interp%d",getpid()); - comp_id = hal_init(hal_comp); // manpage says: NULL ok - which fails miserably - CHKS(comp_id < 0,_("fetch_hal_param: hal_init(%s): %d"), hal_comp,comp_id); - CHKS((retval = hal_ready(comp_id)), _("fetch_hal_param: hal_ready(): %d"),retval); - } - char *s; - int n = strlen(nameBuf); - if ((n > 6) && - ((s = (char *) strchr(&nameBuf[5],']')) != NULL)) { + // Make sure we can query pins/params/signals + retval = hal_lib_init(); + CHKS(retval < 0, "fetch_hal_param: hal_lib_init(): error=%d", retval); + + const char *s; + int n = strlen(nameBuf); + if (n > 6 && NULL != (s = (const char *)strchr(&nameBuf[5],']'))) { int closeBracket = s - nameBuf; strncpy(hal_name, &nameBuf[5], closeBracket); @@ -273,41 +267,45 @@ int Interp::fetch_hal_param( const char *nameBuf, int *status, double *value) if (nameBuf[closeBracket + 1]) { logOword("%s: trailing garbage after closing bracket", hal_name); *status = 0; - ERS("%s: trailing garbage after closing bracket", nameBuf); + ERS(_("%s: trailing garbage after closing bracket"), nameBuf); } - // the result of these lookups could be cached in the parameter struct, but I'm not sure - // this is a good idea - a removed pin/signal will not be noticed - - // I dont think that's needed - no change in pins/sigs/params - // rtapi_mutex_get(&(hal_data->mutex)); - // rtapi_mutex_give(&(hal_data->mutex)); - if (hal_get_pin_value_by_name(hal_name, &type, &ptr, &conn) == 0) { - if (!conn) - logOword("%s: no signal connected", hal_name); - goto assign; - } - if (hal_get_signal_value_by_name(hal_name, &type, &ptr, &conn) == 0) { - if (!conn) - logOword("%s: signal has no writer", hal_name); - goto assign; - } - if (hal_get_param_value_by_name(hal_name, &type, &ptr) == 0) { - goto assign; - } + // Retrieve the active value from the pin/param/signal + hal_query_t q = {}; + q.name = hal_name; + if(0 == hal_get_p(&q, NULL, NULL)) { // Gets either pin or param + // FIXME: It is not logical to fail on an output pin that is not + // attached to a signal. HAL_OUT pins should always give a real + // result. HAL_IO pins could be fine, but that depends on whether + // there has been written proper data on it yet. + if(HAL_QTYPE_PIN == q.qtype && !q.pp.signal) + logOword("%s: no signal connected", hal_name); + qval = q.pp.value; + type = q.pp.type; + goto assign; + } + q = {}; + q.name = hal_name; + if(0 == hal_get_s(&q, NULL, NULL)) { + if(q.sig.writers <= 0) + logOword("%s: signal has no writer", hal_name); + qval = q.sig.value; + type = q.sig.type; + goto assign; + } *status = 0; - ERS("Named hal parameter #<%s> not found", nameBuf); + ERS(_("Named hal parameter #<%s> not found"), nameBuf); } return INTERP_OK; assign: switch (type) { - case HAL_BIT: *value = (double) (ptr->b); break; - case HAL_U32: *value = (double) (ptr->u); break; - case HAL_S32: *value = (double) (ptr->s); break; - case HAL_U64: *value = (double) (ptr->lu); break; - case HAL_S64: *value = (double) (ptr->ls); break; - case HAL_FLOAT: *value = (double) (ptr->f); break; + case HAL_BOOL: *value = (double)qval.b; break; + case HAL_U32: *value = (double)qval.u; break; + case HAL_S32: *value = (double)qval.s; break; + case HAL_UINT: *value = (double)qval.u; break; + case HAL_SINT: *value = (double)qval.s; break; + case HAL_REAL: *value = (double)qval.r; break; default: return -1; } logOword("%s: value=%f", hal_name, *value); diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc index 9e03dcd6940..c657448c79f 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -38,27 +38,40 @@ using namespace linuxcnc; * * Called By: main ********************************************************************/ +#define IOC0 "iocontrol.0" + +#define CHK(x) do { \ + int _rv = (x); \ + if(_rv < 0) { \ + rtapi_print_msg(RTAPI_MSG_ERR, IOC0": cannot create HAL pin\n"); \ + return -1; \ + } \ + } while(0) + int Task::iocontrol_hal_init(void) { - iocontrol.add_pin("user-enable-out", hal_dir::OUT, iocontrol_data.user_enable_out); - iocontrol.add_pin("emc-enable-in", hal_dir::IN, iocontrol_data.emc_enable_in); - iocontrol.add_pin("user-request-enable", hal_dir::OUT, iocontrol_data.user_request_enable); - iocontrol.add_pin("coolant-mist", hal_dir::OUT, iocontrol_data.coolant_mist); - iocontrol.add_pin("coolant-flood", hal_dir::OUT, iocontrol_data.coolant_flood); - iocontrol.add_pin("tool-prep-pocket", hal_dir::OUT, iocontrol_data.tool_prep_pocket); - iocontrol.add_pin("tool-from-pocket", hal_dir::OUT, iocontrol_data.tool_from_pocket); - iocontrol.add_pin("tool-prep-index", hal_dir::OUT, iocontrol_data.tool_prep_index); - iocontrol.add_pin("tool-prep-number", hal_dir::OUT, iocontrol_data.tool_prep_number); - iocontrol.add_pin("tool-number", hal_dir::OUT, iocontrol_data.tool_number); - iocontrol.add_pin("tool-prepare", hal_dir::OUT, iocontrol_data.tool_prepare); - iocontrol.add_pin("tool-prepared", hal_dir::IN, iocontrol_data.tool_prepared); - iocontrol.add_pin("tool-change", hal_dir::OUT, iocontrol_data.tool_change); - iocontrol.add_pin("tool-changed", hal_dir::IN, iocontrol_data.tool_changed); - iocontrol.ready(); - if (iocontrol.error < 0) + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->user_enable_out, 0, IOC0".user-enable-out")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &iocontrol_data->emc_enable_in, 0, IOC0".emc-enable-in")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->user_request_enable, 0, IOC0".user-request-enable")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->coolant_mist, 0, IOC0".coolant-mist")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->coolant_flood, 0, IOC0".coolant-flood")); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &iocontrol_data->tool_prep_pocket, 0, IOC0".tool-prep-pocket")); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &iocontrol_data->tool_from_pocket, 0, IOC0".tool-from-pocket")); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &iocontrol_data->tool_prep_index, 0, IOC0".tool-prep-index")); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &iocontrol_data->tool_prep_number, 0, IOC0".tool-prep-number")); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &iocontrol_data->tool_number, 0, IOC0".tool-number")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->tool_prepare, 0, IOC0".tool-prepare")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &iocontrol_data->tool_prepared, 0, IOC0".tool-prepared")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &iocontrol_data->tool_change, 0, IOC0".tool-change")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &iocontrol_data->tool_changed, 0, IOC0".tool-changed")); + if(hal_ready(comp_id) < 0) { + hal_exit(comp_id); + comp_id = -1; return -1; + } return 0; } +#undef CHK /******************************************************************** * @@ -70,17 +83,17 @@ int Task::iocontrol_hal_init(void) ********************************************************************/ void Task::hal_init_pins(void) { - iocontrol_data.user_enable_out=0; /* output, FALSE when EMC wants stop */ - iocontrol_data.user_request_enable=0;/* output, used to reset HAL latch */ - iocontrol_data.coolant_mist=0; /* coolant mist output pin */ - iocontrol_data.coolant_flood=0; /* coolant flood output pin */ - iocontrol_data.tool_prepare=0; /* output, pin that notifies HAL it needs to prepare a tool */ - iocontrol_data.tool_prep_number=0; /* output, pin that holds the tool number to be prepared, only valid when tool-prepare=TRUE */ - iocontrol_data.tool_prep_pocket=0; /* output, pin that holds the pocketno for the tool to be prepared, only valid when tool-prepare=TRUE */ - iocontrol_data.tool_from_pocket=0; /* output, always 0 at startup */ - iocontrol_data.tool_prep_index=0; /* output, pin that holds the internal index (idx) of the tool to be prepared, for debug */ - iocontrol_data.tool_change=0; /* output, notifies a tool-change should happen (emc should be in the tool-change position) */ - iocontrol_data.tool_number = emcioStatus.tool.toolInSpindle; + hal_set_bool(iocontrol_data->user_enable_out, 0); /* output, FALSE when EMC wants stop */ + hal_set_bool(iocontrol_data->user_request_enable, 0);/* output, used to reset HAL latch */ + hal_set_bool(iocontrol_data->coolant_mist, 0); /* coolant mist output pin */ + hal_set_bool(iocontrol_data->coolant_flood, 0); /* coolant flood output pin */ + hal_set_bool(iocontrol_data->tool_prepare, 0); /* output, pin that notifies HAL it needs to prepare a tool */ + hal_set_si32(iocontrol_data->tool_prep_number, 0); /* output, pin that holds the tool number to be prepared, only valid when tool-prepare=TRUE */ + hal_set_si32(iocontrol_data->tool_prep_pocket, 0); /* output, pin that holds the pocketno for the tool to be prepared, only valid when tool-prepare=TRUE */ + hal_set_si32(iocontrol_data->tool_from_pocket, 0); /* output, always 0 at startup */ + hal_set_si32(iocontrol_data->tool_prep_index, 0); /* output, pin that holds the internal index (idx) of the tool to be prepared, for debug */ + hal_set_bool(iocontrol_data->tool_change, 0); /* output, notifies a tool-change should happen (emc should be in the tool-change position) */ + hal_set_si32(iocontrol_data->tool_number, emcioStatus.tool.toolInSpindle); } Task *task_methods; @@ -110,7 +123,11 @@ int emcToolSetNumber(int number) { return task_methods->emcToolSetNumber(number) int emcTaskOnce(const char * /*filename*/, EMC_IO_STAT &emcioStatus) { - task_methods = new Task(emcioStatus); + task_methods = new Task(emcioStatus); + if(task_methods->comp_id < 0) { + // This happens when init is incomplete + return -1; + } if (int res = task_methods->iocontrol_hal_init()) { return res; } @@ -129,12 +146,25 @@ struct _inittab builtin_modules[] = { Task::Task(EMC_IO_STAT & emcioStatus_in) : emcioStatus(emcioStatus_in), - iocontrol_data{}, - iocontrol("iocontrol.0"), + iocontrol_data(nullptr), + comp_id(-1), ini_filename(emc_inifile), tool_status(0) { + comp_id = hal_init(IOC0); + if(comp_id < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, IOC0": ERROR: hal_init() failed\n"); + return; // emcTaskOnce() fails on comp_id + } + iocontrol_data = reinterpret_cast(hal_malloc(sizeof(*iocontrol_data))); + if(!iocontrol_data) { + rtapi_print_msg(RTAPI_MSG_ERR, IOC0": ERROR: hal_malloc() failed\n"); + hal_exit(comp_id); + comp_id = -1; + return; // emcTaskOnce() fails on comp_id + } + IniFile inifile(ini_filename); if (inifile) { @@ -365,10 +395,10 @@ int Task::emcIoAbort(EMC_ABORT /*reason*/)//EMC_TOOL_ABORT_TYPE rtapi_print_msg(RTAPI_MSG_DBG, "EMC_TOOL_ABORT\n"); emcioStatus.coolant.mist = 0; emcioStatus.coolant.flood = 0; - iocontrol_data.coolant_mist = 0; /* coolant mist output pin */ - iocontrol_data.coolant_flood = 0; /* coolant flood output pin */ - iocontrol_data.tool_change = 0; /* abort tool change if in progress */ - iocontrol_data.tool_prepare = 0; /* abort tool prepare if in progress */ + hal_set_bool(iocontrol_data->coolant_mist, 0); /* coolant mist output pin */ + hal_set_bool(iocontrol_data->coolant_flood, 0); /* coolant flood output pin */ + hal_set_bool(iocontrol_data->tool_change, 0); /* abort tool change if in progress */ + hal_set_bool(iocontrol_data->tool_prepare, 0); /* abort tool prepare if in progress */ // release task wait on pending tool-change/prepare (old NML iocontrol // returned RCS_DONE by default; in-process call must do it explicitly) emcioStatus.status = RCS_STATUS::DONE; @@ -378,8 +408,8 @@ int Task::emcIoAbort(EMC_ABORT /*reason*/)//EMC_TOOL_ABORT_TYPE int Task::emcAuxEstopOn()//EMC_AUX_ESTOP_ON_TYPE { /* assert an ESTOP to the outside world (thru HAL) */ - iocontrol_data.user_enable_out = 0; //disable on ESTOP_ON - iocontrol_data.user_request_enable = 0; + hal_set_bool(iocontrol_data->user_enable_out, 0); //disable on ESTOP_ON + hal_set_bool(iocontrol_data->user_request_enable, 0); hal_init_pins(); //resets all HAL pins to safe valuea return 0; } @@ -387,9 +417,9 @@ int Task::emcAuxEstopOn()//EMC_AUX_ESTOP_ON_TYPE int Task::emcAuxEstopOff() { /* remove ESTOP */ - iocontrol_data.user_enable_out = 1; //we're good to enable on ESTOP_OFF + hal_set_bool(iocontrol_data->user_enable_out, 1); //we're good to enable on ESTOP_OFF /* generate a rising edge to reset optional HAL latch */ - iocontrol_data.user_request_enable = 1; + hal_set_bool(iocontrol_data->user_request_enable, 1); emcioStatus.aux.estop = 0; return 0; } @@ -397,28 +427,28 @@ int Task::emcAuxEstopOff() int Task::emcCoolantMistOn() { emcioStatus.coolant.mist = 1; - iocontrol_data.coolant_mist = 1; + hal_set_bool(iocontrol_data->coolant_mist, 1); return 0; } int Task::emcCoolantMistOff() { emcioStatus.coolant.mist = 0; - iocontrol_data.coolant_mist = 0; + hal_set_bool(iocontrol_data->coolant_mist, 0); return 0; } int Task::emcCoolantFloodOn() { emcioStatus.coolant.flood = 1; - iocontrol_data.coolant_flood = 1; + hal_set_bool(iocontrol_data->coolant_flood, 1); return 0; } int Task::emcCoolantFloodOff() { emcioStatus.coolant.flood = 0; - iocontrol_data.coolant_flood = 0; + hal_set_bool(iocontrol_data->coolant_flood, 0); return 0; } @@ -438,29 +468,29 @@ int Task::emcToolPrepare(int toolno) } rtapi_print_msg(RTAPI_MSG_DBG, "EMC_TOOL_PREPARE tool=%d idx=%d\n", toolno, idx); - iocontrol_data.tool_prep_index = idx; // any type of changer + hal_set_si32(iocontrol_data->tool_prep_index, idx); // any type of changer // Note: some of the following logic could be simplified // but is maintained to preserve runtests expectations // Set HAL pins for tool number, pocket, and index. if (random_toolchanger) { // RANDOM_TOOLCHANGER - iocontrol_data.tool_prep_number = tdata.toolno; + hal_set_si32(iocontrol_data->tool_prep_number, tdata.toolno); if (idx == 0) { emcioStatus.tool.pocketPrepped = 0; // pocketPrepped is an idx - iocontrol_data.tool_prep_pocket = 0; + hal_set_si32(iocontrol_data->tool_prep_pocket, 0); return 0; } - (iocontrol_data.tool_prep_pocket) = tdata.pocketno; + hal_set_si32(iocontrol_data->tool_prep_pocket, tdata.pocketno); } else { // NON_RANDOM_TOOLCHANGER if (idx == 0) { emcioStatus.tool.pocketPrepped = 0; // pocketPrepped is an idx - iocontrol_data.tool_prep_number = 0; - iocontrol_data.tool_prep_pocket = 0; + hal_set_si32(iocontrol_data->tool_prep_number, 0); + hal_set_si32(iocontrol_data->tool_prep_pocket, 0); } else { - iocontrol_data.tool_prep_number = tdata.toolno; - iocontrol_data.tool_prep_pocket = tdata.pocketno; + hal_set_si32(iocontrol_data->tool_prep_number, tdata.toolno); + hal_set_si32(iocontrol_data->tool_prep_pocket, tdata.pocketno); } } // it doesn't make sense to prep the spindle pocket @@ -471,7 +501,7 @@ int Task::emcToolPrepare(int toolno) } /* then set the prepare pin to tell external logic to get started */ - iocontrol_data.tool_prepare = 1; + hal_set_bool(iocontrol_data->tool_prepare, 1); // the feedback logic is done inside read_hal_inputs() // we only need to set RCS_EXEC if RCS_DONE is not already set by the above logic if (tool_status != 10) //set above to 10 in case PREP already finished (HAL loopback machine) @@ -498,7 +528,7 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE if (emcioStatus.tool.pocketPrepped != -1) { //notify HW for toolchange - iocontrol_data.tool_change = 1; + hal_set_bool(iocontrol_data->tool_change, 1); // the feedback logic is done inside read_hal_inputs() we only // need to set RCS_EXEC if RCS_DONE is not already set by the // above logic @@ -589,9 +619,9 @@ int Task::emcToolSetNumber(int number)//EMC_TOOL_SET_NUMBER "EMC_TOOL_SET_NUMBER old_loaded_tool=%d new_idx_number=%d new_tool=%d\n" , emcioStatus.tool.toolInSpindle, idx, tdata.toolno); //likewise in HAL - iocontrol_data.tool_number = emcioStatus.tool.toolInSpindle; + hal_set_si32(iocontrol_data->tool_number, emcioStatus.tool.toolInSpindle); if (emcioStatus.tool.toolInSpindle == 0) { - emcioStatus.tool.toolFromPocket = iocontrol_data.tool_from_pocket = 0; // no tool in spindle + emcioStatus.tool.toolFromPocket = hal_set_si32(iocontrol_data->tool_from_pocket, 0); // no tool in spindle } return 0; @@ -613,17 +643,17 @@ int Task::emcToolSetNumber(int number)//EMC_TOOL_SET_NUMBER ********************************************************************/ int Task::read_tool_inputs(void) { - if (iocontrol_data.tool_prepare && iocontrol_data.tool_prepared) { - emcioStatus.tool.pocketPrepped = iocontrol_data.tool_prep_index; //check if tool has been (idx) prepared - iocontrol_data.tool_prepare = 0; + if (hal_get_bool(iocontrol_data->tool_prepare) && hal_get_bool(iocontrol_data->tool_prepared)) { + emcioStatus.tool.pocketPrepped = hal_get_si32(iocontrol_data->tool_prep_index); //check if tool has been (idx) prepared + hal_set_bool(iocontrol_data->tool_prepare, 0); emcioStatus.status = RCS_STATUS::DONE; // we finally finished to do tool-changing, signal task with RCS_DONE return 10; //prepped finished } - if (iocontrol_data.tool_change && iocontrol_data.tool_changed) { + if (hal_get_bool(iocontrol_data->tool_change) && hal_get_bool(iocontrol_data->tool_changed)) { if(!random_toolchanger && emcioStatus.tool.pocketPrepped == 0) { emcioStatus.tool.toolInSpindle = 0; - emcioStatus.tool.toolFromPocket = iocontrol_data.tool_from_pocket = 0; + emcioStatus.tool.toolFromPocket = hal_set_si32(iocontrol_data->tool_from_pocket, 0); } else { // the tool now in the spindle is the one that was prepared CANON_TOOL_TABLE tdata; @@ -631,18 +661,18 @@ int Task::read_tool_inputs(void) UNEXPECTED_MSG; return -1; } emcioStatus.tool.toolInSpindle = tdata.toolno; - emcioStatus.tool.toolFromPocket = iocontrol_data.tool_from_pocket = tdata.pocketno; + emcioStatus.tool.toolFromPocket = hal_set_si32(iocontrol_data->tool_from_pocket, tdata.pocketno); } if (emcioStatus.tool.toolInSpindle == 0) { - emcioStatus.tool.toolFromPocket = iocontrol_data.tool_from_pocket = 0; + emcioStatus.tool.toolFromPocket = hal_set_si32(iocontrol_data->tool_from_pocket, 0); } - iocontrol_data.tool_number = emcioStatus.tool.toolInSpindle; //likewise in HAL + hal_set_si32(iocontrol_data->tool_number, emcioStatus.tool.toolInSpindle); //likewise in HAL load_tool(emcioStatus.tool.pocketPrepped); emcioStatus.tool.pocketPrepped = -1; //reset the tool preped number, -1 to permit tool 0 to be loaded - iocontrol_data.tool_prep_number = 0; //likewise in HAL - iocontrol_data.tool_prep_pocket = 0; //likewise in HAL - iocontrol_data.tool_prep_index = 0; //likewise in HAL - iocontrol_data.tool_change = 0; //also reset the tool change signal + hal_set_si32(iocontrol_data->tool_prep_number, 0); //likewise in HAL + hal_set_si32(iocontrol_data->tool_prep_pocket, 0); //likewise in HAL + hal_set_si32(iocontrol_data->tool_prep_index, 0); //likewise in HAL + hal_set_bool(iocontrol_data->tool_change, 0); //also reset the tool change signal emcioStatus.status = RCS_STATUS::DONE; // we finally finished to do tool-changing, signal task with RCS_DONE return 11; //change finished } @@ -651,12 +681,12 @@ int Task::read_tool_inputs(void) void Task::run(){ // called periodically from emctaskmain.cc tool_status = read_tool_inputs(); - if (iocontrol_data.emc_enable_in == 0) //check for estop from HW + if (!hal_get_bool(iocontrol_data->emc_enable_in)) //check for estop from HW emcioStatus.aux.estop = 1; else { emcioStatus.aux.estop = 0; - if (iocontrol_data.user_request_enable == 1) { - iocontrol_data.user_request_enable = 0; + if (hal_get_bool(iocontrol_data->user_request_enable)) { + hal_set_bool(iocontrol_data->user_request_enable, 0); } } } diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh index b19c0a00aae..6f4aff780c9 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh @@ -20,31 +20,32 @@ #include "nml_intf/emc.hh" #include -#include "../../hal/hal.hh" +#include #include "tooldata/tooldata.hh" #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); +// This structure must live in HAL memory struct iocontrol_str { - hal_pin user_enable_out; /* output, TRUE when EMC wants stop */ - hal_pin emc_enable_in; /* input, TRUE on any external stop */ - hal_pin user_request_enable; /* output, used to reset ENABLE latch */ - hal_pin coolant_mist; /* coolant mist output pin */ - hal_pin coolant_flood; /* coolant flood output pin */ + hal_bool_t user_enable_out; /* output, TRUE when EMC wants stop */ + hal_bool_t emc_enable_in; /* input, TRUE on any external stop */ + hal_bool_t user_request_enable; /* output, used to reset ENABLE latch */ + hal_bool_t coolant_mist; /* coolant mist output pin */ + hal_bool_t coolant_flood; /* coolant flood output pin */ // the following pins are needed for toolchanging //tool-prepare - hal_pin tool_prepare; /* output, pin that notifies HAL it needs to prepare a tool */ - hal_pin tool_prep_pocket; /* output, pin that holds the pocketno for the tool table entry matching the tool to be prepared, - only valid when tool-prepare=TRUE */ - hal_pin tool_from_pocket; /* output, pin indicating pocket current load tool retrieved from*/ - hal_pin tool_prep_index; /* output, pin for internal index (idx) of prepped tool above */ - hal_pin tool_prep_number; /* output, pin that holds the tool number to be prepared, only valid when tool-prepare=TRUE */ - hal_pin tool_number; /* output, pin that holds the tool number currently in the spindle */ - hal_pin tool_prepared; /* input, pin that notifies that the tool has been prepared */ + hal_bool_t tool_prepare; /* output, pin that notifies HAL it needs to prepare a tool */ + hal_sint_t tool_prep_pocket; /* output, pin that holds the pocketno for the tool table entry matching the tool to + be prepared, only valid when tool-prepare=TRUE */ + hal_sint_t tool_from_pocket; /* output, pin indicating pocket current load tool retrieved from*/ + hal_sint_t tool_prep_index; /* output, pin for internal index (idx) of prepped tool above */ + hal_sint_t tool_prep_number; /* output, pin that holds the tool number to be prepared, only valid when tool-prepare=TRUE */ + hal_sint_t tool_number; /* output, pin that holds the tool number currently in the spindle */ + hal_bool_t tool_prepared; /* input, pin that notifies that the tool has been prepared */ //tool-change - hal_pin tool_change; /* output, notifies a tool-change should happen (emc should be in the tool-change position) */ - hal_pin tool_changed; /* input, notifies tool has been changed */ + hal_bool_t tool_change; /* output, notifies a tool-change should happen (emc should be in the tool-change position) */ + hal_bool_t tool_changed; /* input, notifies tool has been changed */ // note: spindle control has been moved to motion }; //pointer to the HAL-struct @@ -83,8 +84,8 @@ public: EMC_IO_STAT &emcioStatus; int random_toolchanger {0}; - iocontrol_str iocontrol_data; - hal_comp iocontrol; + iocontrol_str *iocontrol_data; // Lives in HAL memory + int comp_id; const char *ini_filename; const char *tooltable_filename {}; char db_program[LINELEN] {}; diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c index e5667b3f29c..82fba6a6ba6 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -384,11 +384,11 @@ STATIC inline double tpGetSignedSpindlePosition(spindle_status_t *status) { #ifdef MAKE_TP_HAL_PINS // { static struct tp_haldata { // Example pin pointers - hal_u32_t *in; - hal_u32_t *out; + hal_uint_t in; + hal_uint_t out; // Example parameters - hal_float_t param_rw; - hal_float_t param_ro; + hal_real_t param_rw; + hal_real_t param_ro; } *tp_haldata; static int makepins(int id) { @@ -399,12 +399,12 @@ static int makepins(int id) { if (!tp_haldata) goto error; // hal pin examples: - res += hal_pin_u32_newf(HAL_IN ,&(tp_haldata->in) ,id,"%s.in" ,HAL_PREFIX); - res += hal_pin_u32_newf(HAL_OUT,&(tp_haldata->out),id,"%s.out",HAL_PREFIX); + res += hal_pin_new_ui32(id, HAL_IN, &(tp_haldata->in), 0, "%s.in", HAL_PREFIX); + res += hal_pin_new_ui32(id, HAL_OUT, &(tp_haldata->out), 0, "%s.out", HAL_PREFIX); // hal parameter examples: - res += hal_param_float_newf(HAL_RW, &tp_haldata->param_rw,id,"%s.param-rw",HAL_PREFIX); - res += hal_param_float_newf(HAL_RO, &tp_haldata->param_ro,id,"%s.param-ro",HAL_PREFIX); + res += hal_param_new_real(id, HAL_RW, &tp_haldata->param_rw, 0.0, "%s.param-rw", HAL_PREFIX); + res += hal_param_new_real(id, HAL_RO, &tp_haldata->param_ro, 0.0, "%s.param-ro", HAL_PREFIX); if (res) goto error; rtapi_print("@@@ %s:%s: ok\n",__FILE__,__FUNCTION__); diff --git a/src/emc/usr_intf/halui.cc b/src/emc/usr_intf/halui.cc index 4e1761f64d9..6796e4cf48d 100644 --- a/src/emc/usr_intf/halui.cc +++ b/src/emc/usr_intf/halui.cc @@ -51,171 +51,178 @@ static int axis_mask = 0; #define MDI_MAX 64 -#pragma GCC diagnostic push -#if defined(__GNUC__) && (__GNUC__ > 4) -#pragma GCC diagnostic ignored "-Wignored-attributes" -#endif +// FIXME: This will have to go again when we do proper 64-bit +// The typedefs are necessary to map to hal_[gs]et_[su]i32() in the expansion +// of below macros because they are selected based on text-concatenation in the +// preprocessor. Even the 32-bit version use sint/uint, but the expansion would +// then select the 64-bit versions. +typedef hal_sint_t hal_si32_t; +typedef hal_uint_t hal_ui32_t; #define HAL_FIELDS \ - FIELD(hal_bit_t,machine_on) /* pin for setting machine On */ \ - FIELD(hal_bit_t,machine_off) /* pin for setting machine Off */ \ - FIELD(hal_bit_t,machine_is_on) /* pin for machine is On/Off */ \ - FIELD(hal_bit_t,estop_activate) /* pin for activating EMC ESTOP */ \ - FIELD(hal_bit_t,estop_reset) /* pin for resetting ESTOP */ \ - FIELD(hal_bit_t,estop_is_activated) /* pin for status ESTOP is activated */ \ + FIELD(bool,machine_on) /* pin for setting machine On */ \ + FIELD(bool,machine_off) /* pin for setting machine Off */ \ + FIELD(bool,machine_is_on) /* pin for machine is On/Off */ \ + FIELD(bool,estop_activate) /* pin for activating EMC ESTOP */ \ + FIELD(bool,estop_reset) /* pin for resetting ESTOP */ \ + FIELD(bool,estop_is_activated) /* pin for status ESTOP is activated */ \ \ - FIELD(hal_bit_t,mode_manual) /* pin for requesting manual mode */ \ - FIELD(hal_bit_t,mode_is_manual) /* pin for manual mode is on */ \ - FIELD(hal_bit_t,mode_auto) /* pin for requesting auto mode */ \ - FIELD(hal_bit_t,mode_is_auto) /* pin for auto mode is on */ \ - FIELD(hal_bit_t,mode_mdi) /* pin for requesting mdi mode */ \ - FIELD(hal_bit_t,mode_is_mdi) /* pin for mdi mode is on */ \ - FIELD(hal_bit_t,mode_teleop) /* pin for requesting teleop mode */ \ - FIELD(hal_bit_t,mode_is_teleop) /* pin for teleop mode is on */ \ - FIELD(hal_bit_t,mode_joint) /* pin for requesting joint mode */ \ - FIELD(hal_bit_t,mode_is_joint) /* pin for joint mode is on */ \ + FIELD(bool,mode_manual) /* pin for requesting manual mode */ \ + FIELD(bool,mode_is_manual) /* pin for manual mode is on */ \ + FIELD(bool,mode_auto) /* pin for requesting auto mode */ \ + FIELD(bool,mode_is_auto) /* pin for auto mode is on */ \ + FIELD(bool,mode_mdi) /* pin for requesting mdi mode */ \ + FIELD(bool,mode_is_mdi) /* pin for mdi mode is on */ \ + FIELD(bool,mode_teleop) /* pin for requesting teleop mode */ \ + FIELD(bool,mode_is_teleop) /* pin for teleop mode is on */ \ + FIELD(bool,mode_joint) /* pin for requesting joint mode */ \ + FIELD(bool,mode_is_joint) /* pin for joint mode is on */ \ \ - FIELD(hal_bit_t,mist_on) /* pin for starting mist */ \ - FIELD(hal_bit_t,mist_off) /* pin for stopping mist */ \ - FIELD(hal_bit_t,mist_is_on) /* pin for mist is on */ \ - FIELD(hal_bit_t,flood_on) /* pin for starting flood */ \ - FIELD(hal_bit_t,flood_off) /* pin for stopping flood */ \ - FIELD(hal_bit_t,flood_is_on) /* pin for flood is on */ \ + FIELD(bool,mist_on) /* pin for starting mist */ \ + FIELD(bool,mist_off) /* pin for stopping mist */ \ + FIELD(bool,mist_is_on) /* pin for mist is on */ \ + FIELD(bool,flood_on) /* pin for starting flood */ \ + FIELD(bool,flood_off) /* pin for stopping flood */ \ + FIELD(bool,flood_is_on) /* pin for flood is on */ \ \ - FIELD(hal_bit_t,program_is_idle) /* pin for notifying user that program is idle */ \ - FIELD(hal_bit_t,program_is_running) /* pin for notifying user that program is running */ \ - FIELD(hal_bit_t,halui_mdi_is_running) /* pin for notifying user that halui MDI commands is running */ \ - FIELD(hal_bit_t,program_is_paused) /* pin for notifying user that program is paused */ \ - FIELD(hal_bit_t,program_run) /* pin for running program */ \ - FIELD(hal_bit_t,program_pause) /* pin for pausing program */ \ - FIELD(hal_bit_t,program_resume) /* pin for resuming program */ \ - FIELD(hal_bit_t,program_step) /* pin for running one line of the program */ \ - FIELD(hal_bit_t,program_stop) /* pin for stopping the program */ \ - FIELD(hal_bit_t,program_os_on) /* pin for setting optional stop on */ \ - FIELD(hal_bit_t,program_os_off) /* pin for setting optional stop off */ \ - FIELD(hal_bit_t,program_os_is_on) /* status pin that optional stop is on */ \ - FIELD(hal_bit_t,program_bd_on) /* pin for setting block delete on */ \ - FIELD(hal_bit_t,program_bd_off) /* pin for setting block delete off */ \ - FIELD(hal_bit_t,program_bd_is_on) /* status pin that block delete is on */ \ + FIELD(bool,program_is_idle) /* pin for notifying user that program is idle */ \ + FIELD(bool,program_is_running) /* pin for notifying user that program is running */ \ + FIELD(bool,halui_mdi_is_running) /* pin for notifying user that halui MDI commands is running */ \ + FIELD(bool,program_is_paused) /* pin for notifying user that program is paused */ \ + FIELD(bool,program_run) /* pin for running program */ \ + FIELD(bool,program_pause) /* pin for pausing program */ \ + FIELD(bool,program_resume) /* pin for resuming program */ \ + FIELD(bool,program_step) /* pin for running one line of the program */ \ + FIELD(bool,program_stop) /* pin for stopping the program */ \ + FIELD(bool,program_os_on) /* pin for setting optional stop on */ \ + FIELD(bool,program_os_off) /* pin for setting optional stop off */ \ + FIELD(bool,program_os_is_on) /* status pin that optional stop is on */ \ + FIELD(bool,program_bd_on) /* pin for setting block delete on */ \ + FIELD(bool,program_bd_off) /* pin for setting block delete off */ \ + FIELD(bool,program_bd_is_on) /* status pin that block delete is on */ \ \ - FIELD(hal_u32_t,tool_number) /* pin for current selected tool */ \ - FIELD(hal_float_t,tool_length_offset_x) /* current applied x tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_y) /* current applied y tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_z) /* current applied z tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_a) /* current applied a tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_b) /* current applied b tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_c) /* current applied c tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_u) /* current applied u tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_v) /* current applied v tool-length-offset */ \ - FIELD(hal_float_t,tool_length_offset_w) /* current applied w tool-length-offset */ \ - FIELD(hal_float_t,tool_diameter) /* current tool diameter (0 if no tool) */ \ + FIELD(uint,tool_number) /* pin for current selected tool */ \ + FIELD(real,tool_length_offset_x) /* current applied x tool-length-offset */ \ + FIELD(real,tool_length_offset_y) /* current applied y tool-length-offset */ \ + FIELD(real,tool_length_offset_z) /* current applied z tool-length-offset */ \ + FIELD(real,tool_length_offset_a) /* current applied a tool-length-offset */ \ + FIELD(real,tool_length_offset_b) /* current applied b tool-length-offset */ \ + FIELD(real,tool_length_offset_c) /* current applied c tool-length-offset */ \ + FIELD(real,tool_length_offset_u) /* current applied u tool-length-offset */ \ + FIELD(real,tool_length_offset_v) /* current applied v tool-length-offset */ \ + FIELD(real,tool_length_offset_w) /* current applied w tool-length-offset */ \ + FIELD(real,tool_diameter) /* current tool diameter (0 if no tool) */ \ \ - ARRAY(hal_bit_t,spindle_start,EMCMOT_MAX_SPINDLES+1) /* pin for starting the spindle */ \ - ARRAY(hal_bit_t,spindle_stop,EMCMOT_MAX_SPINDLES+1) /* pin for stopping the spindle */ \ - ARRAY(hal_bit_t,spindle_is_on,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle is on */ \ - ARRAY(hal_bit_t,spindle_forward,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go forward */ \ - ARRAY(hal_bit_t,spindle_runs_forward,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle running forward */ \ - ARRAY(hal_bit_t,spindle_reverse,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go reverse */ \ - ARRAY(hal_bit_t,spindle_runs_backward,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle running backward */ \ - ARRAY(hal_bit_t,spindle_increase,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go faster */ \ - ARRAY(hal_bit_t,spindle_decrease,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go slower */ \ + ARRAY(bool,spindle_start,EMCMOT_MAX_SPINDLES+1) /* pin for starting the spindle */ \ + ARRAY(bool,spindle_stop,EMCMOT_MAX_SPINDLES+1) /* pin for stopping the spindle */ \ + ARRAY(bool,spindle_is_on,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle is on */ \ + ARRAY(bool,spindle_forward,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go forward */ \ + ARRAY(bool,spindle_runs_forward,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle running forward */ \ + ARRAY(bool,spindle_reverse,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go reverse */ \ + ARRAY(bool,spindle_runs_backward,EMCMOT_MAX_SPINDLES+1) /* status pin for spindle running backward */ \ + ARRAY(bool,spindle_increase,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go faster */ \ + ARRAY(bool,spindle_decrease,EMCMOT_MAX_SPINDLES+1) /* pin for making the spindle go slower */ \ \ - ARRAY(hal_bit_t,spindle_brake_on,EMCMOT_MAX_SPINDLES) /* pin for activating spindle-brake */ \ - ARRAY(hal_bit_t,spindle_brake_off, EMCMOT_MAX_SPINDLES) /* pin for deactivating spindle/brake */ \ - ARRAY(hal_bit_t,spindle_brake_is_on, EMCMOT_MAX_SPINDLES) /* status pin that tells us if brake is on */ \ + ARRAY(bool,spindle_brake_on,EMCMOT_MAX_SPINDLES) /* pin for activating spindle-brake */ \ + ARRAY(bool,spindle_brake_off, EMCMOT_MAX_SPINDLES) /* pin for deactivating spindle/brake */ \ + ARRAY(bool,spindle_brake_is_on, EMCMOT_MAX_SPINDLES) /* status pin that tells us if brake is on */ \ \ - ARRAY(hal_bit_t,joint_home,EMCMOT_MAX_JOINTS+1) /* pin for homing one joint */ \ - ARRAY(hal_bit_t,joint_unhome,EMCMOT_MAX_JOINTS+1) /* pin for unhoming one joint */ \ - ARRAY(hal_bit_t,joint_is_homed,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is homed */ \ - ARRAY(hal_bit_t,joint_on_soft_min_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the software min limit */ \ - ARRAY(hal_bit_t,joint_on_soft_max_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the software max limit */ \ - ARRAY(hal_bit_t,joint_on_hard_min_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware min limit */ \ - ARRAY(hal_bit_t,joint_on_hard_max_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware max limit */ \ - ARRAY(hal_bit_t,joint_override_limits,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware max limit */ \ - ARRAY(hal_bit_t,joint_has_fault,EMCMOT_MAX_JOINTS+1) /* status pin that the joint has a fault */ \ - FIELD(hal_u32_t,joint_selected) /* status pin for the joint selected */ \ - FIELD(hal_u32_t,axis_selected) /* status pin for the axis selected */ \ + ARRAY(bool,joint_home,EMCMOT_MAX_JOINTS+1) /* pin for homing one joint */ \ + ARRAY(bool,joint_unhome,EMCMOT_MAX_JOINTS+1) /* pin for unhoming one joint */ \ + ARRAY(bool,joint_is_homed,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is homed */ \ + ARRAY(bool,joint_on_soft_min_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the software min limit */ \ + ARRAY(bool,joint_on_soft_max_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the software max limit */ \ + ARRAY(bool,joint_on_hard_min_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware min limit */ \ + ARRAY(bool,joint_on_hard_max_limit,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware max limit */ \ + ARRAY(bool,joint_override_limits,EMCMOT_MAX_JOINTS+1) /* status pin that the joint is on the hardware max limit */ \ + ARRAY(bool,joint_has_fault,EMCMOT_MAX_JOINTS+1) /* status pin that the joint has a fault */ \ + FIELD(uint,joint_selected) /* status pin for the joint selected */ \ + FIELD(uint,axis_selected) /* status pin for the axis selected */ \ \ - ARRAY(hal_bit_t,joint_nr_select,EMCMOT_MAX_JOINTS) /* nr. of pins to select a joint */ \ - ARRAY(hal_bit_t,axis_nr_select,EMCMOT_MAX_AXIS) /* nr. of pins to select a axis */ \ + ARRAY(bool,joint_nr_select,EMCMOT_MAX_JOINTS) /* nr. of pins to select a joint */ \ + ARRAY(bool,axis_nr_select,EMCMOT_MAX_AXIS) /* nr. of pins to select a axis */ \ \ - ARRAY(hal_bit_t,joint_is_selected,EMCMOT_MAX_JOINTS) /* nr. of status pins for joint selected */ \ - ARRAY(hal_bit_t,axis_is_selected,EMCMOT_MAX_AXIS) /* nr. of status pins for axis selected */ \ + ARRAY(bool,joint_is_selected,EMCMOT_MAX_JOINTS) /* nr. of status pins for joint selected */ \ + ARRAY(bool,axis_is_selected,EMCMOT_MAX_AXIS) /* nr. of status pins for axis selected */ \ \ - ARRAY(hal_float_t,axis_pos_commanded,EMCMOT_MAX_AXIS+1) /* status pin for commanded cartesian position */ \ - ARRAY(hal_float_t,axis_pos_feedback,EMCMOT_MAX_AXIS+1) /* status pin for actual cartesian position */ \ - ARRAY(hal_float_t,axis_pos_relative,EMCMOT_MAX_AXIS+1) /* status pin for relative cartesian position */ \ + ARRAY(real,axis_pos_commanded,EMCMOT_MAX_AXIS+1) /* status pin for commanded cartesian position */ \ + ARRAY(real,axis_pos_feedback,EMCMOT_MAX_AXIS+1) /* status pin for actual cartesian position */ \ + ARRAY(real,axis_pos_relative,EMCMOT_MAX_AXIS+1) /* status pin for relative cartesian position */ \ \ - FIELD(hal_float_t,jjog_speed) /* pin for setting the jog speed (halui internal) */ \ - ARRAY(hal_bit_t,jjog_minus,EMCMOT_MAX_JOINTS+1) /* pin to jog in positive direction */ \ - ARRAY(hal_bit_t,jjog_plus,EMCMOT_MAX_JOINTS+1) /* pin to jog in negative direction */ \ - ARRAY(hal_float_t,jjog_analog,EMCMOT_MAX_JOINTS+1) /* pin for analog jogging (-1..0..1) */ \ - ARRAY(hal_float_t,jjog_increment,EMCMOT_MAX_JOINTS+1) /* Incremental jogging */ \ - ARRAY(hal_bit_t,jjog_increment_plus,EMCMOT_MAX_JOINTS+1) /* Incremental jogging, positive direction */ \ - ARRAY(hal_bit_t,jjog_increment_minus,EMCMOT_MAX_JOINTS+1) /* Incremental jogging, negative direction */ \ + FIELD(real,jjog_speed) /* pin for setting the jog speed (halui internal) */ \ + ARRAY(bool,jjog_minus,EMCMOT_MAX_JOINTS+1) /* pin to jog in positive direction */ \ + ARRAY(bool,jjog_plus,EMCMOT_MAX_JOINTS+1) /* pin to jog in negative direction */ \ + ARRAY(real,jjog_analog,EMCMOT_MAX_JOINTS+1) /* pin for analog jogging (-1..0..1) */ \ + ARRAY(real,jjog_increment,EMCMOT_MAX_JOINTS+1) /* Incremental jogging */ \ + ARRAY(bool,jjog_increment_plus,EMCMOT_MAX_JOINTS+1) /* Incremental jogging, positive direction */ \ + ARRAY(bool,jjog_increment_minus,EMCMOT_MAX_JOINTS+1) /* Incremental jogging, negative direction */ \ \ - FIELD(hal_float_t,ajog_speed) /* pin for setting the jog speed (halui internal) */ \ - ARRAY(hal_bit_t,ajog_minus,EMCMOT_MAX_AXIS+1) /* pin to jog in positive direction */ \ - ARRAY(hal_bit_t,ajog_plus,EMCMOT_MAX_AXIS+1) /* pin to jog in negative direction */ \ - ARRAY(hal_float_t,ajog_analog,EMCMOT_MAX_AXIS+1) /* pin for analog jogging (-1..0..1) */ \ - ARRAY(hal_float_t,ajog_increment,EMCMOT_MAX_AXIS+1) /* Incremental jogging */ \ - ARRAY(hal_bit_t,ajog_increment_plus,EMCMOT_MAX_AXIS+1) /* Incremental jogging, positive direction */ \ - ARRAY(hal_bit_t,ajog_increment_minus,EMCMOT_MAX_AXIS+1) /* Incremental jogging, negative direction */ \ + FIELD(real,ajog_speed) /* pin for setting the jog speed (halui internal) */ \ + ARRAY(bool,ajog_minus,EMCMOT_MAX_AXIS+1) /* pin to jog in positive direction */ \ + ARRAY(bool,ajog_plus,EMCMOT_MAX_AXIS+1) /* pin to jog in negative direction */ \ + ARRAY(real,ajog_analog,EMCMOT_MAX_AXIS+1) /* pin for analog jogging (-1..0..1) */ \ + ARRAY(real,ajog_increment,EMCMOT_MAX_AXIS+1) /* Incremental jogging */ \ + ARRAY(bool,ajog_increment_plus,EMCMOT_MAX_AXIS+1) /* Incremental jogging, positive direction */ \ + ARRAY(bool,ajog_increment_minus,EMCMOT_MAX_AXIS+1) /* Incremental jogging, negative direction */ \ \ - FIELD(hal_float_t,jjog_deadband) /* pin for setting the jog analog deadband (where not to move) */ \ - FIELD(hal_float_t,ajog_deadband) /* pin for setting the jog analog deadband (where not to move) */ \ + FIELD(real,jjog_deadband) /* pin for setting the jog analog deadband (where not to move) */ \ + FIELD(real,ajog_deadband) /* pin for setting the jog analog deadband (where not to move) */ \ \ - FIELD(hal_s32_t,mv_counts) /* pin for the Max Velocity counting */ \ - FIELD(hal_bit_t,mv_count_enable) /* pin for the Max Velocity counting enable */ \ - FIELD(hal_bit_t,mv_direct_value) /* pin for enabling direct value option instead of counts */ \ - FIELD(hal_float_t,mv_scale) /* scale for the Max Velocity counting */ \ - FIELD(hal_float_t,mv_value) /* current Max Velocity value */ \ - FIELD(hal_bit_t,mv_increase) /* pin for increasing the MV (+=scale) */ \ - FIELD(hal_bit_t,mv_decrease) /* pin for decreasing the MV (-=scale) */ \ + FIELD(sint,mv_counts) /* pin for the Max Velocity counting */ \ + FIELD(bool,mv_count_enable) /* pin for the Max Velocity counting enable */ \ + FIELD(bool,mv_direct_value) /* pin for enabling direct value option instead of counts */ \ + FIELD(real,mv_scale) /* scale for the Max Velocity counting */ \ + FIELD(real,mv_value) /* current Max Velocity value */ \ + FIELD(bool,mv_increase) /* pin for increasing the MV (+=scale) */ \ + FIELD(bool,mv_decrease) /* pin for decreasing the MV (-=scale) */ \ \ - FIELD(hal_s32_t,fo_counts) /* pin for the Feed Override counting */ \ - FIELD(hal_bit_t,fo_count_enable) /* pin for the Feed Override counting enable */ \ - FIELD(hal_bit_t,fo_direct_value) /* pin for enabling direct value option instead of counts */ \ - FIELD(hal_float_t,fo_scale) /* scale for the Feed Override counting */ \ - FIELD(hal_float_t,fo_value) /* current Feed Override value */ \ - FIELD(hal_bit_t,fo_increase) /* pin for increasing the FO (+=scale) */ \ - FIELD(hal_bit_t,fo_decrease) /* pin for decreasing the FO (-=scale) */ \ - FIELD(hal_bit_t,fo_reset) /* pin for resetting Feed Override */ \ + FIELD(sint,fo_counts) /* pin for the Feed Override counting */ \ + FIELD(bool,fo_count_enable) /* pin for the Feed Override counting enable */ \ + FIELD(bool,fo_direct_value) /* pin for enabling direct value option instead of counts */ \ + FIELD(real,fo_scale) /* scale for the Feed Override counting */ \ + FIELD(real,fo_value) /* current Feed Override value */ \ + FIELD(bool,fo_increase) /* pin for increasing the FO (+=scale) */ \ + FIELD(bool,fo_decrease) /* pin for decreasing the FO (-=scale) */ \ + FIELD(bool,fo_reset) /* pin for resetting Feed Override */ \ \ - FIELD(hal_s32_t,ro_counts) /* pin for the Feed Override counting */ \ - FIELD(hal_bit_t,ro_count_enable) /* pin for the Feed Override counting enable */ \ - FIELD(hal_bit_t,ro_direct_value) /* pin for enabling direct value option instead of counts */ \ - FIELD(hal_float_t,ro_scale) /* scale for the Feed Override counting */ \ - FIELD(hal_float_t,ro_value) /* current Feed Override value */ \ - FIELD(hal_bit_t,ro_increase) /* pin ror increasing the FO (+=scale) */ \ - FIELD(hal_bit_t,ro_decrease) /* pin for decreasing the FO (-=scale) */ \ - FIELD(hal_bit_t,ro_reset) /* pin for resetting Feed Override */ \ + FIELD(sint,ro_counts) /* pin for the Feed Override counting */ \ + FIELD(bool,ro_count_enable) /* pin for the Feed Override counting enable */ \ + FIELD(bool,ro_direct_value) /* pin for enabling direct value option instead of counts */ \ + FIELD(real,ro_scale) /* scale for the Feed Override counting */ \ + FIELD(real,ro_value) /* current Feed Override value */ \ + FIELD(bool,ro_increase) /* pin ror increasing the FO (+=scale) */ \ + FIELD(bool,ro_decrease) /* pin for decreasing the FO (-=scale) */ \ + FIELD(bool,ro_reset) /* pin for resetting Feed Override */ \ \ - ARRAY(hal_s32_t,so_counts,EMCMOT_MAX_SPINDLES+1) /* pin for the Spindle Speed Override counting */ \ - ARRAY(hal_bit_t,so_count_enable,EMCMOT_MAX_SPINDLES+1) /* pin for the Spindle Speed Override counting enable */ \ - ARRAY(hal_bit_t,so_direct_value,EMCMOT_MAX_SPINDLES+1) /* pin for enabling direct value option instead of counts */ \ - ARRAY(hal_float_t,so_scale,EMCMOT_MAX_SPINDLES+1) /* scale for the Spindle Speed Override counting */ \ - ARRAY(hal_float_t,so_value,EMCMOT_MAX_SPINDLES+1) /* current Spindle speed Override value */ \ - ARRAY(hal_bit_t,so_increase,EMCMOT_MAX_SPINDLES+1) /* pin for increasing the SO (+=scale) */ \ - ARRAY(hal_bit_t,so_decrease,EMCMOT_MAX_SPINDLES+1) /* pin for decreasing the SO (-=scale) */ \ - ARRAY(hal_bit_t,so_reset,EMCMOT_MAX_SPINDLES+1) /* pin for resetting Spindle Speed Override */ \ + ARRAY(sint,so_counts,EMCMOT_MAX_SPINDLES+1) /* pin for the Spindle Speed Override counting */ \ + ARRAY(bool,so_count_enable,EMCMOT_MAX_SPINDLES+1) /* pin for the Spindle Speed Override counting enable */ \ + ARRAY(bool,so_direct_value,EMCMOT_MAX_SPINDLES+1) /* pin for enabling direct value option instead of counts */ \ + ARRAY(real,so_scale,EMCMOT_MAX_SPINDLES+1) /* scale for the Spindle Speed Override counting */ \ + ARRAY(real,so_value,EMCMOT_MAX_SPINDLES+1) /* current Spindle speed Override value */ \ + ARRAY(bool,so_increase,EMCMOT_MAX_SPINDLES+1) /* pin for increasing the SO (+=scale) */ \ + ARRAY(bool,so_decrease,EMCMOT_MAX_SPINDLES+1) /* pin for decreasing the SO (-=scale) */ \ + ARRAY(bool,so_reset,EMCMOT_MAX_SPINDLES+1) /* pin for resetting Spindle Speed Override */ \ \ - FIELD(hal_bit_t,home_all) /* pin for homing all joints in sequence */ \ - FIELD(hal_bit_t,abort) /* pin for aborting */ \ - ARRAY(hal_bit_t,mdi_commands,MDI_MAX) \ + FIELD(bool,home_all) /* pin for homing all joints in sequence */ \ + FIELD(bool,abort) /* pin for aborting */ \ + ARRAY(bool,mdi_commands,MDI_MAX) \ \ - FIELD(hal_float_t,units_per_mm) \ + FIELD(real,units_per_mm) \ struct PTR { template - struct field { typedef T *type; }; + struct field { typedef T type; }; }; template struct NATIVE {}; -template<> struct NATIVE { typedef bool type; }; -template<> struct NATIVE { typedef rtapi_s32 type; }; -template<> struct NATIVE { typedef rtapi_u32 type; }; -template<> struct NATIVE { typedef double type; }; +template<> struct NATIVE { typedef rtapi_bool type; }; +template<> struct NATIVE { typedef rtapi_s32 type; }; +template<> struct NATIVE { typedef rtapi_u32 type; }; +// FIXME: These need to be 64-bit. Can't set them now because the compiler sees +// the typedef mapped overlap. +//template<> struct NATIVE { typedef rtapi_sint type; }; +//template<> struct NATIVE { typedef rtapi_uint type; }; +template<> struct NATIVE { typedef rtapi_real type; }; struct VALUE { template struct field { typedef typename NATIVE::type type; }; }; @@ -223,8 +230,8 @@ struct VALUE { template struct halui_str_base { -#define FIELD(t,f) typename T::template field::type f; -#define ARRAY(t,f,n) typename T::template field::type f[n]; +#define FIELD(t,f) typename T::template field::type f; +#define ARRAY(t,f,n) typename T::template field::type f[n]; HAL_FIELDS #undef FIELD #undef ARRAY @@ -232,7 +239,6 @@ HAL_FIELDS typedef halui_str_base halui_str; typedef halui_str_base local_halui_str; -#pragma GCC diagnostic pop static halui_str *halui_data; static local_halui_str old_halui_data; @@ -482,10 +488,10 @@ static ANGULAR_UNIT_CONVERSION angularUnitConversion = ANGULAR_UNITS_AUTO; #define GRAD_PER_DEG (100.0/90.0) #define RAD_PER_DEG TO_RAD // from posemath.h -int halui_export_pin_IN_bit(hal_bit_t **pin, const char *name) +int halui_export_pin_IN_bit(hal_bool_t *pin, const char *name) { int retval; - retval = hal_pin_bit_new(name, HAL_IN, pin, comp_id); + retval = hal_pin_new_bool(comp_id, HAL_IN, pin, 0, "%s", name); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR,"HALUI: ERROR: halui pin %s export failed with err=%i\n", name, retval); hal_exit(comp_id); @@ -494,10 +500,10 @@ int halui_export_pin_IN_bit(hal_bit_t **pin, const char *name) return 0; } -int halui_export_pin_IN_s32(hal_s32_t **pin, const char *name) +int halui_export_pin_IN_s32(hal_sint_t *pin, const char *name) { int retval; - retval = hal_pin_s32_new(name, HAL_IN, pin, comp_id); + retval = hal_pin_new_si32(comp_id, HAL_IN, pin, 0, "%s", name); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR,"HALUI: ERROR: halui pin %s export failed with err=%i\n", name, retval); hal_exit(comp_id); @@ -506,10 +512,10 @@ int halui_export_pin_IN_s32(hal_s32_t **pin, const char *name) return 0; } -int halui_export_pin_IN_float(hal_float_t **pin, const char *name) +int halui_export_pin_IN_float(hal_real_t *pin, const char *name) { int retval; - retval = hal_pin_float_new(name, HAL_IN, pin, comp_id); + retval = hal_pin_new_real(comp_id, HAL_IN, pin, 0.0, "%s", name); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR,"HALUI: ERROR: halui pin %s export failed with err=%i\n", name, retval); hal_exit(comp_id); @@ -519,10 +525,10 @@ int halui_export_pin_IN_float(hal_float_t **pin, const char *name) } -int halui_export_pin_OUT_bit(hal_bit_t **pin, const char *name) +int halui_export_pin_OUT_bit(hal_bool_t *pin, const char *name) { int retval; - retval = hal_pin_bit_new(name, HAL_OUT, pin, comp_id); + retval = hal_pin_new_bool(comp_id, HAL_OUT, pin, 0, "%s", name); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR,"HALUI: ERROR: halui pin %s export failed with err=%i\n", name, retval); hal_exit(comp_id); @@ -540,13 +546,14 @@ int halui_export_pin_OUT_bit(hal_bit_t **pin, const char *name) * * Called By: main ********************************************************************/ +#define CHK(x) do { \ + int rv = (x); \ + if(rv < 0) \ + return rv; \ + } while(0) + int halui_hal_init(void) { - int retval; - int joint; - int spindle; - int axis_num; - /* STEP 1: initialise the hal component */ comp_id = hal_init("halui"); if (comp_id < 0) { @@ -566,359 +573,203 @@ int halui_hal_init(void) /* STEP 3a: export the out-pin(s) */ - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->units_per_mm), comp_id, "halui.machine.units-per-mm"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->machine_is_on), "halui.machine.is-on"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->estop_is_activated), "halui.estop.is-activated"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mode_is_manual), "halui.mode.is-manual"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mode_is_auto), "halui.mode.is-auto"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mode_is_mdi), "halui.mode.is-mdi"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mode_is_teleop), "halui.mode.is-teleop"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mode_is_joint), "halui.mode.is-joint"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->mist_is_on), "halui.mist.is-on"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->flood_is_on), "halui.flood.is-on"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->program_is_idle), "halui.program.is-idle"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->program_is_running), "halui.program.is-running"); - if (retval < 0) return retval; + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->units_per_mm), 0.0, "halui.machine.units-per-mm")); + CHK(halui_export_pin_OUT_bit(&(halui_data->machine_is_on), "halui.machine.is-on")); + CHK(halui_export_pin_OUT_bit(&(halui_data->estop_is_activated), "halui.estop.is-activated")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mode_is_manual), "halui.mode.is-manual")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mode_is_auto), "halui.mode.is-auto")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mode_is_mdi), "halui.mode.is-mdi")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mode_is_teleop), "halui.mode.is-teleop")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mode_is_joint), "halui.mode.is-joint")); + CHK(halui_export_pin_OUT_bit(&(halui_data->mist_is_on), "halui.mist.is-on")); + CHK(halui_export_pin_OUT_bit(&(halui_data->flood_is_on), "halui.flood.is-on")); + CHK(halui_export_pin_OUT_bit(&(halui_data->program_is_idle), "halui.program.is-idle")); + CHK(halui_export_pin_OUT_bit(&(halui_data->program_is_running), "halui.program.is-running")); - if (num_mdi_commands>0){ - retval = halui_export_pin_OUT_bit(&(halui_data->halui_mdi_is_running), "halui.halui-mdi-is-running"); - if (retval < 0) return retval; - } + if (num_mdi_commands > 0) { + CHK(halui_export_pin_OUT_bit(&(halui_data->halui_mdi_is_running), "halui.halui-mdi-is-running")); + } - retval = halui_export_pin_OUT_bit(&(halui_data->program_is_paused), "halui.program.is-paused"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->program_os_is_on), "halui.program.optional-stop.is-on"); - if (retval < 0) return retval; - retval = halui_export_pin_OUT_bit(&(halui_data->program_bd_is_on), "halui.program.block-delete.is-on"); + CHK(halui_export_pin_OUT_bit(&(halui_data->program_is_paused), "halui.program.is-paused")); + CHK(halui_export_pin_OUT_bit(&(halui_data->program_os_is_on), "halui.program.optional-stop.is-on")); + CHK(halui_export_pin_OUT_bit(&(halui_data->program_bd_is_on), "halui.program.block-delete.is-on")); - for (spindle = 0; spindle < num_spindles; spindle++){ - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->spindle_is_on[spindle]), comp_id, "halui.spindle.%i.is-on", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->spindle_runs_forward[spindle]),comp_id, "halui.spindle.%i.runs-forward", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->spindle_runs_backward[spindle]), comp_id, "halui.spindle.%i.runs-backward", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->spindle_brake_is_on[spindle]), comp_id, "halui.spindle.%i.brake-is-on", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_start[spindle]), comp_id, "halui.spindle.%i.start", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_stop[spindle]), comp_id, "halui.spindle.%i.stop", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_forward[spindle]), comp_id, "halui.spindle.%i.forward", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_reverse[spindle]), comp_id, "halui.spindle.%i.reverse", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_increase[spindle]), comp_id, "halui.spindle.%i.increase", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_decrease[spindle]), comp_id, "halui.spindle.%i.decrease", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_brake_on[spindle]), comp_id, "halui.spindle.%i.brake-on", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->spindle_brake_off[spindle]), comp_id, "halui.spindle.%i.brake-off", spindle); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->so_value[spindle]), comp_id, "halui.spindle.%i.override.value", spindle); - if (retval < 0) return retval; - retval = hal_pin_s32_newf(HAL_IN, &(halui_data->so_counts[spindle]), comp_id, "halui.spindle.%i.override.counts", spindle); - if (retval < 0) return retval; - *halui_data->so_counts[spindle] = 0; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->so_count_enable[spindle]), comp_id, "halui.spindle.%i.override.count-enable", spindle); - if (retval < 0) return retval; - *halui_data->so_count_enable[spindle] = 1; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->so_direct_value[spindle]), comp_id, "halui.spindle.%i.override.direct-value", spindle); - if (retval < 0) return retval; - *halui_data->so_direct_value[spindle] = 0; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->so_scale[spindle]), comp_id, "halui.spindle.%i.override.scale", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->so_increase[spindle]), comp_id, "halui.spindle.%i.override.increase", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->so_decrease[spindle]), comp_id, "halui.spindle.%i.override.decrease", spindle); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->so_reset[spindle]), comp_id, "halui.spindle.%i.override.reset", spindle); - } - - for (joint=0; joint < num_joints ; joint++) { - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_is_homed[joint]), comp_id, "halui.joint.%d.is-homed", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_is_selected[joint]), comp_id, "halui.joint.%d.is-selected", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_soft_min_limit[joint]), comp_id, "halui.joint.%d.on-soft-min-limit", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_soft_max_limit[joint]), comp_id, "halui.joint.%d.on-soft-max-limit", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_hard_min_limit[joint]), comp_id, "halui.joint.%d.on-hard-min-limit", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_hard_max_limit[joint]), comp_id, "halui.joint.%d.on-hard-max-limit", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_override_limits[joint]), comp_id, "halui.joint.%d.override-limits", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_has_fault[joint]), comp_id, "halui.joint.%d.has-fault", joint); - if (retval < 0) return retval; - } - - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_soft_min_limit[num_joints]), comp_id, "halui.joint.selected.on-soft-min-limit"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_soft_max_limit[num_joints]), comp_id, "halui.joint.selected.on-soft-max-limit"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_hard_min_limit[num_joints]), comp_id, "halui.joint.selected.on-hard-min-limit"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_on_hard_max_limit[num_joints]), comp_id, "halui.joint.selected.on-hard-max-limit"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_override_limits[num_joints]), comp_id, "halui.joint.selected.override-limits"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_has_fault[num_joints]), comp_id, "halui.joint.selected.has-fault"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->joint_is_homed[num_joints]), comp_id, "halui.joint.selected.is-homed"); - if (retval < 0) return retval; + for (int spindle = 0; spindle < num_spindles; spindle++){ + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->spindle_is_on[spindle]), 0, "halui.spindle.%i.is-on", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->spindle_runs_forward[spindle]), 0, "halui.spindle.%i.runs-forward", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->spindle_runs_backward[spindle]), 0, "halui.spindle.%i.runs-backward", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->spindle_brake_is_on[spindle]), 0, "halui.spindle.%i.brake-is-on", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_start[spindle]), 0, "halui.spindle.%i.start", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_stop[spindle]), 0, "halui.spindle.%i.stop", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_forward[spindle]), 0, "halui.spindle.%i.forward", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_reverse[spindle]), 0, "halui.spindle.%i.reverse", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_increase[spindle]), 0, "halui.spindle.%i.increase", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_decrease[spindle]), 0, "halui.spindle.%i.decrease", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_brake_on[spindle]), 0, "halui.spindle.%i.brake-on", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->spindle_brake_off[spindle]), 0, "halui.spindle.%i.brake-off", spindle)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->so_value[spindle]), 0.0, "halui.spindle.%i.override.value", spindle)); + CHK(hal_pin_new_si32(comp_id, HAL_IN, &(halui_data->so_counts[spindle]), 0, "halui.spindle.%i.override.counts", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->so_count_enable[spindle]), 1, "halui.spindle.%i.override.count-enable", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->so_direct_value[spindle]), 0, "halui.spindle.%i.override.direct-value", spindle)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->so_scale[spindle]), 0.0, "halui.spindle.%i.override.scale", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->so_increase[spindle]), 0, "halui.spindle.%i.override.increase", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->so_decrease[spindle]), 0, "halui.spindle.%i.override.decrease", spindle)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->so_reset[spindle]), 0, "halui.spindle.%i.override.reset", spindle)); + } + + for (int joint = 0; joint < num_joints ; joint++) { + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_is_homed[joint]), 0, "halui.joint.%d.is-homed", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_is_selected[joint]), 0, "halui.joint.%d.is-selected", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_soft_min_limit[joint]), 0, "halui.joint.%d.on-soft-min-limit", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_soft_max_limit[joint]), 0, "halui.joint.%d.on-soft-max-limit", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_hard_min_limit[joint]), 0, "halui.joint.%d.on-hard-min-limit", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_hard_max_limit[joint]), 0, "halui.joint.%d.on-hard-max-limit", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_override_limits[joint]), 0, "halui.joint.%d.override-limits", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_has_fault[joint]), 0, "halui.joint.%d.has-fault", joint)); + } + + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_soft_min_limit[num_joints]), 0, "halui.joint.selected.on-soft-min-limit")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_soft_max_limit[num_joints]), 0, "halui.joint.selected.on-soft-max-limit")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_hard_min_limit[num_joints]), 0, "halui.joint.selected.on-hard-min-limit")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_on_hard_max_limit[num_joints]), 0, "halui.joint.selected.on-hard-max-limit")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_override_limits[num_joints]), 0, "halui.joint.selected.override-limits")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_has_fault[num_joints]), 0, "halui.joint.selected.has-fault")); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->joint_is_homed[num_joints]), 0, "halui.joint.selected.is-homed")); bool first_axis = true; - for (axis_num=0; axis_num < EMCMOT_MAX_AXIS ; axis_num++) { + for (int axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { if ( !(axis_mask & (1 << axis_num)) ) { continue; } char c = "xyzabcuvw"[axis_num]; - retval = hal_pin_bit_newf(HAL_OUT, &(halui_data->axis_is_selected[axis_num]), comp_id, "halui.axis.%c.is-selected", c); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->axis_pos_commanded[axis_num]), comp_id, "halui.axis.%c.pos-commanded", c); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->axis_pos_feedback[axis_num]), comp_id, "halui.axis.%c.pos-feedback", c); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->axis_pos_relative[axis_num]), comp_id, "halui.axis.%c.pos-relative", c); - if (retval < 0) return retval; + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(halui_data->axis_is_selected[axis_num]), 0, "halui.axis.%c.is-selected", c)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->axis_pos_commanded[axis_num]), 0.0, "halui.axis.%c.pos-commanded", c)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->axis_pos_feedback[axis_num]), 0.0, "halui.axis.%c.pos-feedback", c)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->axis_pos_relative[axis_num]), 0.0, "halui.axis.%c.pos-relative", c)); if (first_axis) { // at startup, indicate first item is selected: - *halui_data->joint_is_selected[0] = 1; - *halui_data->axis_is_selected[axis_num] = 1; + hal_set_bool(halui_data->joint_is_selected[0], 1); + hal_set_bool(halui_data->axis_is_selected[axis_num], 1); } first_axis = false; } - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->mv_value), comp_id, "halui.max-velocity.value"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->fo_value), comp_id, "halui.feed-override.value"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->ro_value), comp_id, "halui.rapid-override.value"); - if (retval < 0) return retval; - retval = hal_pin_u32_newf(HAL_OUT, &(halui_data->joint_selected), comp_id, "halui.joint.selected"); - if (retval < 0) return retval; - retval = hal_pin_u32_newf(HAL_OUT, &(halui_data->axis_selected), comp_id, "halui.axis.selected"); - if (retval < 0) return retval; - retval = hal_pin_u32_newf(HAL_OUT, &(halui_data->tool_number), comp_id, "halui.tool.number"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_x), comp_id, "halui.tool.length_offset.x"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_y), comp_id, "halui.tool.length_offset.y"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_z), comp_id, "halui.tool.length_offset.z"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_a), comp_id, "halui.tool.length_offset.a"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_b), comp_id, "halui.tool.length_offset.b"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_c), comp_id, "halui.tool.length_offset.c"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_u), comp_id, "halui.tool.length_offset.u"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_v), comp_id, "halui.tool.length_offset.v"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_length_offset_w), comp_id, "halui.tool.length_offset.w"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_OUT, &(halui_data->tool_diameter), comp_id, "halui.tool.diameter"); - if (retval < 0) return retval; + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->mv_value), 0.0, "halui.max-velocity.value")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->fo_value), 0.0, "halui.feed-override.value")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->ro_value), 0.0, "halui.rapid-override.value")); + CHK(hal_pin_new_ui32(comp_id, HAL_OUT, &(halui_data->joint_selected), 0, "halui.joint.selected")); + CHK(hal_pin_new_ui32(comp_id, HAL_OUT, &(halui_data->axis_selected), 0, "halui.axis.selected")); + CHK(hal_pin_new_ui32(comp_id, HAL_OUT, &(halui_data->tool_number), 0, "halui.tool.number")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_x), 0.0, "halui.tool.length_offset.x")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_y), 0.0, "halui.tool.length_offset.y")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_z), 0.0, "halui.tool.length_offset.z")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_a), 0.0, "halui.tool.length_offset.a")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_b), 0.0, "halui.tool.length_offset.b")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_c), 0.0, "halui.tool.length_offset.c")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_u), 0.0, "halui.tool.length_offset.u")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_v), 0.0, "halui.tool.length_offset.v")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_length_offset_w), 0.0, "halui.tool.length_offset.w")); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(halui_data->tool_diameter), 0.0, "halui.tool.diameter")); /* STEP 3b: export the in-pin(s) */ - retval = halui_export_pin_IN_bit(&(halui_data->machine_on), "halui.machine.on"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->machine_off), "halui.machine.off"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->estop_activate), "halui.estop.activate"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->estop_reset), "halui.estop.reset"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mode_manual), "halui.mode.manual"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mode_auto), "halui.mode.auto"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mode_mdi), "halui.mode.mdi"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mode_teleop), "halui.mode.teleop"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mode_joint), "halui.mode.joint"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mist_on), "halui.mist.on"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mist_off), "halui.mist.off"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->flood_on), "halui.flood.on"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->flood_off), "halui.flood.off"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_run), "halui.program.run"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_pause), "halui.program.pause"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_resume), "halui.program.resume"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_step), "halui.program.step"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_stop), "halui.program.stop"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_os_on), "halui.program.optional-stop.on"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_os_off), "halui.program.optional-stop.off"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_bd_on), "halui.program.block-delete.on"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->program_bd_off), "halui.program.block-delete.off"); - if (retval < 0) return retval; - - retval = halui_export_pin_IN_s32(&(halui_data->mv_counts), "halui.max-velocity.counts"); - if (retval < 0) return retval; - *halui_data->mv_counts = 0; - retval = halui_export_pin_IN_bit(&(halui_data->mv_count_enable), "halui.max-velocity.count-enable"); - if (retval < 0) return retval; - *halui_data->mv_count_enable = 1; - retval = halui_export_pin_IN_bit(&(halui_data->mv_direct_value), "halui.max-velocity.direct-value"); - if (retval < 0) return retval; - *halui_data->mv_direct_value = 0; - retval = halui_export_pin_IN_float(&(halui_data->mv_scale), "halui.max-velocity.scale"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mv_increase), "halui.max-velocity.increase"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->mv_decrease), "halui.max-velocity.decrease"); - if (retval < 0) return retval; - - retval = halui_export_pin_IN_s32(&(halui_data->fo_counts), "halui.feed-override.counts"); - if (retval < 0) return retval; - *halui_data->fo_counts = 0; - retval = halui_export_pin_IN_bit(&(halui_data->fo_count_enable), "halui.feed-override.count-enable"); - if (retval < 0) return retval; - *halui_data->fo_count_enable = 1; - retval = halui_export_pin_IN_bit(&(halui_data->fo_direct_value), "halui.feed-override.direct-value"); - if (retval < 0) return retval; - *halui_data->fo_direct_value = 0; - retval = halui_export_pin_IN_float(&(halui_data->fo_scale), "halui.feed-override.scale"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->fo_increase), "halui.feed-override.increase"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->fo_decrease), "halui.feed-override.decrease"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->fo_reset), "halui.feed-override.reset"); - if (retval < 0) return retval; - - retval = halui_export_pin_IN_s32(&(halui_data->ro_counts), "halui.rapid-override.counts"); - if (retval < 0) return retval; - *halui_data->ro_counts = 0; - retval = halui_export_pin_IN_bit(&(halui_data->ro_count_enable), "halui.rapid-override.count-enable"); - if (retval < 0) return retval; - *halui_data->ro_count_enable = 1; - retval = halui_export_pin_IN_bit(&(halui_data->ro_direct_value), "halui.rapid-override.direct-value"); - if (retval < 0) return retval; - *halui_data->ro_direct_value = 0; - retval = halui_export_pin_IN_float(&(halui_data->ro_scale), "halui.rapid-override.scale"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->ro_increase), "halui.rapid-override.increase"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->ro_decrease), "halui.rapid-override.decrease"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_bit(&(halui_data->ro_reset), "halui.rapid-override.reset"); - if (retval < 0) return retval; + CHK(halui_export_pin_IN_bit(&(halui_data->machine_on), "halui.machine.on")); + CHK(halui_export_pin_IN_bit(&(halui_data->machine_off), "halui.machine.off")); + CHK(halui_export_pin_IN_bit(&(halui_data->estop_activate), "halui.estop.activate")); + CHK(halui_export_pin_IN_bit(&(halui_data->estop_reset), "halui.estop.reset")); + CHK(halui_export_pin_IN_bit(&(halui_data->mode_manual), "halui.mode.manual")); + CHK(halui_export_pin_IN_bit(&(halui_data->mode_auto), "halui.mode.auto")); + CHK(halui_export_pin_IN_bit(&(halui_data->mode_mdi), "halui.mode.mdi")); + CHK(halui_export_pin_IN_bit(&(halui_data->mode_teleop), "halui.mode.teleop")); + CHK(halui_export_pin_IN_bit(&(halui_data->mode_joint), "halui.mode.joint")); + CHK(halui_export_pin_IN_bit(&(halui_data->mist_on), "halui.mist.on")); + CHK(halui_export_pin_IN_bit(&(halui_data->mist_off), "halui.mist.off")); + CHK(halui_export_pin_IN_bit(&(halui_data->flood_on), "halui.flood.on")); + CHK(halui_export_pin_IN_bit(&(halui_data->flood_off), "halui.flood.off")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_run), "halui.program.run")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_pause), "halui.program.pause")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_resume), "halui.program.resume")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_step), "halui.program.step")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_stop), "halui.program.stop")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_os_on), "halui.program.optional-stop.on")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_os_off), "halui.program.optional-stop.off")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_bd_on), "halui.program.block-delete.on")); + CHK(halui_export_pin_IN_bit(&(halui_data->program_bd_off), "halui.program.block-delete.off")); + + CHK(halui_export_pin_IN_s32(&(halui_data->mv_counts), "halui.max-velocity.counts")); + CHK(halui_export_pin_IN_bit(&(halui_data->mv_count_enable), "halui.max-velocity.count-enable")); + hal_set_bool(halui_data->mv_count_enable, 1); + CHK(halui_export_pin_IN_bit(&(halui_data->mv_direct_value), "halui.max-velocity.direct-value")); + CHK(halui_export_pin_IN_float(&(halui_data->mv_scale), "halui.max-velocity.scale")); + CHK(halui_export_pin_IN_bit(&(halui_data->mv_increase), "halui.max-velocity.increase")); + CHK(halui_export_pin_IN_bit(&(halui_data->mv_decrease), "halui.max-velocity.decrease")); + + CHK(halui_export_pin_IN_s32(&(halui_data->fo_counts), "halui.feed-override.counts")); + CHK(halui_export_pin_IN_bit(&(halui_data->fo_count_enable), "halui.feed-override.count-enable")); + hal_set_bool(halui_data->fo_count_enable, 1); + CHK(halui_export_pin_IN_bit(&(halui_data->fo_direct_value), "halui.feed-override.direct-value")); + CHK(halui_export_pin_IN_float(&(halui_data->fo_scale), "halui.feed-override.scale")); + CHK(halui_export_pin_IN_bit(&(halui_data->fo_increase), "halui.feed-override.increase")); + CHK(halui_export_pin_IN_bit(&(halui_data->fo_decrease), "halui.feed-override.decrease")); + CHK(halui_export_pin_IN_bit(&(halui_data->fo_reset), "halui.feed-override.reset")); + + CHK(halui_export_pin_IN_s32(&(halui_data->ro_counts), "halui.rapid-override.counts")); + CHK(halui_export_pin_IN_bit(&(halui_data->ro_count_enable), "halui.rapid-override.count-enable")); + hal_set_bool(halui_data->ro_count_enable, 1); + CHK(halui_export_pin_IN_bit(&(halui_data->ro_direct_value), "halui.rapid-override.direct-value")); + CHK(halui_export_pin_IN_float(&(halui_data->ro_scale), "halui.rapid-override.scale")); + CHK(halui_export_pin_IN_bit(&(halui_data->ro_increase), "halui.rapid-override.increase")); + CHK(halui_export_pin_IN_bit(&(halui_data->ro_decrease), "halui.rapid-override.decrease")); + CHK(halui_export_pin_IN_bit(&(halui_data->ro_reset), "halui.rapid-override.reset")); if (have_home_all) { - retval = halui_export_pin_IN_bit(&(halui_data->home_all), "halui.home-all"); - if (retval < 0) return retval; - } - - retval = halui_export_pin_IN_bit(&(halui_data->abort), "halui.abort"); - if (retval < 0) return retval; - - for (joint=0; joint < num_joints ; joint++) { - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->joint_home[joint]), comp_id, "halui.joint.%d.home", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->joint_unhome[joint]), comp_id, "halui.joint.%d.unhome", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->joint_nr_select[joint]), comp_id, "halui.joint.%d.select", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_plus[joint]), comp_id, "halui.joint.%d.plus", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_minus[joint]), comp_id, "halui.joint.%d.minus", joint); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->jjog_analog[joint]), comp_id, "halui.joint.%d.analog", joint); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->jjog_increment[joint]), comp_id, "halui.joint.%d.increment", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_increment_plus[joint]), comp_id, "halui.joint.%d.increment-plus", joint); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_increment_minus[joint]), comp_id, "halui.joint.%d.increment-minus", joint); - if (retval < 0) return retval; + CHK(halui_export_pin_IN_bit(&(halui_data->home_all), "halui.home-all")); } - for (axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { + CHK(halui_export_pin_IN_bit(&(halui_data->abort), "halui.abort")); + + for (int joint = 0; joint < num_joints ; joint++) { + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->joint_home[joint]), 0, "halui.joint.%d.home", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->joint_unhome[joint]), 0, "halui.joint.%d.unhome", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->joint_nr_select[joint]), 0, "halui.joint.%d.select", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_plus[joint]), 0, "halui.joint.%d.plus", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_minus[joint]), 0, "halui.joint.%d.minus", joint)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->jjog_analog[joint]), 0.0, "halui.joint.%d.analog", joint)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->jjog_increment[joint]), 0.0, "halui.joint.%d.increment", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_increment_plus[joint]), 0, "halui.joint.%d.increment-plus", joint)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_increment_minus[joint]), 0, "halui.joint.%d.increment-minus", joint)); + } + + for (int axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { char c = "xyzabcuvw"[axis_num]; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->axis_nr_select[axis_num]), comp_id, "halui.axis.%c.select", c); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_plus[axis_num]), comp_id, "halui.axis.%c.plus", c); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_minus[axis_num]), comp_id, "halui.axis.%c.minus", c); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->ajog_analog[axis_num]), comp_id, "halui.axis.%c.analog", c); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->ajog_increment[axis_num]), comp_id, "halui.axis.%c.increment", c); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_increment_plus[axis_num]), comp_id, "halui.axis.%c.increment-plus", c); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_increment_minus[axis_num]), comp_id, "halui.axis.%c.increment-minus", c); - if (retval < 0) return retval; - } - - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->joint_home[num_joints]), comp_id, "halui.joint.selected.home"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->joint_unhome[num_joints]), comp_id, "halui.joint.selected.unhome"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_plus[num_joints]), comp_id, "halui.joint.selected.plus"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_minus[num_joints]), comp_id, "halui.joint.selected.minus"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->jjog_increment[num_joints]), comp_id, "halui.joint.selected.increment"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_increment_plus[num_joints]), comp_id, "halui.joint.selected.increment-plus"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->jjog_increment_minus[num_joints]), comp_id, "halui.joint.selected.increment-minus"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_plus[EMCMOT_MAX_AXIS]), comp_id, "halui.axis.selected.plus"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_minus[EMCMOT_MAX_AXIS]), comp_id, "halui.axis.selected.minus"); - if (retval < 0) return retval; - retval = hal_pin_float_newf(HAL_IN, &(halui_data->ajog_increment[EMCMOT_MAX_AXIS]), comp_id, "halui.axis.selected.increment"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_increment_plus[EMCMOT_MAX_AXIS]), comp_id, "halui.axis.selected.increment-plus"); - if (retval < 0) return retval; - retval = hal_pin_bit_newf(HAL_IN, &(halui_data->ajog_increment_minus[EMCMOT_MAX_AXIS]), comp_id, "halui.axis.selected.increment-minus"); - if (retval < 0) return retval; - - retval = halui_export_pin_IN_float(&(halui_data->jjog_speed), "halui.joint.jog-speed"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_float(&(halui_data->jjog_deadband), "halui.joint.jog-deadband"); - if (retval < 0) return retval; - - retval = halui_export_pin_IN_float(&(halui_data->ajog_speed), "halui.axis.jog-speed"); - if (retval < 0) return retval; - retval = halui_export_pin_IN_float(&(halui_data->ajog_deadband), "halui.axis.jog-deadband"); - if (retval < 0) return retval; - - for (int n=0; nmdi_commands[n]), comp_id, "halui.mdi-command-%02d", n); - if (retval < 0) return retval; + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->axis_nr_select[axis_num]), 0, "halui.axis.%c.select", c)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_plus[axis_num]), 0, "halui.axis.%c.plus", c)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_minus[axis_num]), 0, "halui.axis.%c.minus", c)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->ajog_analog[axis_num]), 0.0, "halui.axis.%c.analog", c)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->ajog_increment[axis_num]), 0.0, "halui.axis.%c.increment", c)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_increment_plus[axis_num]), 0, "halui.axis.%c.increment-plus", c)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_increment_minus[axis_num]), 0, "halui.axis.%c.increment-minus", c)); + } + + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->joint_home[num_joints]), 0, "halui.joint.selected.home")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->joint_unhome[num_joints]), 0, "halui.joint.selected.unhome")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_plus[num_joints]), 0, "halui.joint.selected.plus")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_minus[num_joints]), 0, "halui.joint.selected.minus")); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->jjog_increment[num_joints]), 0.0, "halui.joint.selected.increment")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_increment_plus[num_joints]), 0, "halui.joint.selected.increment-plus")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->jjog_increment_minus[num_joints]), 0, "halui.joint.selected.increment-minus")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_plus[EMCMOT_MAX_AXIS]), 0, "halui.axis.selected.plus")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_minus[EMCMOT_MAX_AXIS]), 0, "halui.axis.selected.minus")); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(halui_data->ajog_increment[EMCMOT_MAX_AXIS]), 0.0, "halui.axis.selected.increment")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_increment_plus[EMCMOT_MAX_AXIS]), 0, "halui.axis.selected.increment-plus")); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->ajog_increment_minus[EMCMOT_MAX_AXIS]), 0, "halui.axis.selected.increment-minus")); + + CHK(halui_export_pin_IN_float(&(halui_data->jjog_speed), "halui.joint.jog-speed")); + CHK(halui_export_pin_IN_float(&(halui_data->jjog_deadband), "halui.joint.jog-deadband")); + + CHK(halui_export_pin_IN_float(&(halui_data->ajog_speed), "halui.axis.jog-speed")); + CHK(halui_export_pin_IN_float(&(halui_data->ajog_deadband), "halui.axis.jog-deadband")); + + for (int n = 0; n < num_mdi_commands; n++) { + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(halui_data->mdi_commands[n]), 0, "halui.mdi-command-%02d", n)); } hal_ready(comp_id); @@ -1011,7 +862,7 @@ static int sendMdiCommand(int n) halui_sent_mdi = 1; if (num_mdi_commands>0){ - *(halui_data->halui_mdi_is_running) = halui_sent_mdi; + hal_set_bool(halui_data->halui_mdi_is_running, halui_sent_mdi); updateStatus(); } @@ -1498,63 +1349,63 @@ static void hal_init_pins() int axis_num; int spindle; - *(halui_data->machine_on) = old_halui_data.machine_on = 0; - *(halui_data->machine_off) = old_halui_data.machine_off = 0; + hal_set_bool(halui_data->machine_on, old_halui_data.machine_on = 0); + hal_set_bool(halui_data->machine_off, old_halui_data.machine_off = 0); - *(halui_data->estop_activate) = old_halui_data.estop_activate = 0; - *(halui_data->estop_reset) = old_halui_data.estop_reset = 0; + hal_set_bool(halui_data->estop_activate, old_halui_data.estop_activate = 0); + hal_set_bool(halui_data->estop_reset, old_halui_data.estop_reset = 0); for (joint=0; joint < num_joints; joint++) { - *(halui_data->joint_home[joint]) = old_halui_data.joint_home[joint] = 0; - *(halui_data->joint_unhome[joint]) = old_halui_data.joint_unhome[joint] = 0; - *(halui_data->joint_nr_select[joint]) = old_halui_data.joint_nr_select[joint] = 0; - *(halui_data->jjog_minus[joint]) = old_halui_data.jjog_minus[joint] = 0; - *(halui_data->jjog_plus[joint]) = old_halui_data.jjog_plus[joint] = 0; - *(halui_data->jjog_analog[joint]) = old_halui_data.jjog_analog[joint] = 0; - *(halui_data->jjog_increment[joint]) = old_halui_data.jjog_increment[joint] = 0.0; - *(halui_data->jjog_increment_plus[joint]) = old_halui_data.jjog_increment_plus[joint] = 0; - *(halui_data->jjog_increment_minus[joint]) = old_halui_data.jjog_increment_minus[joint] = 0; + hal_set_bool(halui_data->joint_home[joint], old_halui_data.joint_home[joint] = 0); + hal_set_bool(halui_data->joint_unhome[joint], old_halui_data.joint_unhome[joint] = 0); + hal_set_bool(halui_data->joint_nr_select[joint], old_halui_data.joint_nr_select[joint] = 0); + hal_set_bool(halui_data->jjog_minus[joint], old_halui_data.jjog_minus[joint] = 0); + hal_set_bool(halui_data->jjog_plus[joint], old_halui_data.jjog_plus[joint] = 0); + hal_set_real(halui_data->jjog_analog[joint], old_halui_data.jjog_analog[joint] = 0.0); + hal_set_real(halui_data->jjog_increment[joint], old_halui_data.jjog_increment[joint] = 0.0); + hal_set_bool(halui_data->jjog_increment_plus[joint], old_halui_data.jjog_increment_plus[joint] = 0); + hal_set_bool(halui_data->jjog_increment_minus[joint], old_halui_data.jjog_increment_minus[joint] = 0); } for (axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { if ( !(axis_mask & (1 << axis_num)) ) { continue; } - *(halui_data->axis_nr_select[axis_num]) = old_halui_data.axis_nr_select[axis_num] = 0; - *(halui_data->ajog_minus[axis_num]) = old_halui_data.ajog_minus[axis_num] = 0; - *(halui_data->ajog_plus[axis_num]) = old_halui_data.ajog_plus[axis_num] = 0; - *(halui_data->ajog_analog[axis_num]) = old_halui_data.ajog_analog[axis_num] = 0; - *(halui_data->ajog_increment[axis_num]) = old_halui_data.ajog_increment[axis_num] = 0.0; - *(halui_data->ajog_increment_plus[axis_num]) = old_halui_data.ajog_increment_plus[axis_num] = 0; - *(halui_data->ajog_increment_minus[axis_num]) = old_halui_data.ajog_increment_minus[axis_num] = 0; - } - - *(halui_data->joint_home[num_joints]) = old_halui_data.joint_home[num_joints] = 0; - *(halui_data->jjog_minus[num_joints]) = old_halui_data.jjog_minus[num_joints] = 0; - *(halui_data->jjog_plus[num_joints]) = old_halui_data.jjog_plus[num_joints] = 0; - *(halui_data->jjog_increment[num_joints]) = old_halui_data.jjog_increment[num_joints] = 0.0; - *(halui_data->jjog_increment_plus[num_joints]) = old_halui_data.jjog_increment_plus[num_joints] = 0; - *(halui_data->jjog_increment_minus[num_joints]) = old_halui_data.jjog_increment_minus[num_joints] = 0; - *(halui_data->jjog_deadband) = 0.2; - *(halui_data->jjog_speed) = 0; - *(halui_data->ajog_minus[EMCMOT_MAX_AXIS]) = old_halui_data.ajog_minus[EMCMOT_MAX_AXIS] = 0; - *(halui_data->ajog_plus[EMCMOT_MAX_AXIS]) = old_halui_data.ajog_plus[EMCMOT_MAX_AXIS] = 0; - *(halui_data->ajog_increment[EMCMOT_MAX_AXIS]) = old_halui_data.ajog_increment[EMCMOT_MAX_AXIS] = 0.0; - *(halui_data->ajog_increment_plus[EMCMOT_MAX_AXIS]) = old_halui_data.ajog_increment_plus[EMCMOT_MAX_AXIS] = 0; - *(halui_data->ajog_increment_minus[EMCMOT_MAX_AXIS]) = old_halui_data.ajog_increment_minus[EMCMOT_MAX_AXIS] = 0; - *(halui_data->ajog_deadband) = 0.2; - *(halui_data->ajog_speed) = 0; - - *(halui_data->joint_selected) = 0; // select joint 0 by default - *(halui_data->axis_selected) = 0; // select axis 0 by default - - *(halui_data->fo_scale) = old_halui_data.fo_scale = 0.1; //sane default - *(halui_data->ro_scale) = old_halui_data.ro_scale = 0.1; //sane default + hal_set_bool(halui_data->axis_nr_select[axis_num], old_halui_data.axis_nr_select[axis_num] = 0); + hal_set_bool(halui_data->ajog_minus[axis_num], old_halui_data.ajog_minus[axis_num] = 0); + hal_set_bool(halui_data->ajog_plus[axis_num], old_halui_data.ajog_plus[axis_num] = 0); + hal_set_real(halui_data->ajog_analog[axis_num], old_halui_data.ajog_analog[axis_num] = 0); + hal_set_real(halui_data->ajog_increment[axis_num], old_halui_data.ajog_increment[axis_num] = 0.0); + hal_set_bool(halui_data->ajog_increment_plus[axis_num], old_halui_data.ajog_increment_plus[axis_num] = 0); + hal_set_bool(halui_data->ajog_increment_minus[axis_num], old_halui_data.ajog_increment_minus[axis_num] = 0); + } + + hal_set_bool(halui_data->joint_home[num_joints], old_halui_data.joint_home[num_joints] = 0); + hal_set_bool(halui_data->jjog_minus[num_joints], old_halui_data.jjog_minus[num_joints] = 0); + hal_set_bool(halui_data->jjog_plus[num_joints], old_halui_data.jjog_plus[num_joints] = 0); + hal_set_real(halui_data->jjog_increment[num_joints], old_halui_data.jjog_increment[num_joints] = 0.0); + hal_set_bool(halui_data->jjog_increment_plus[num_joints], old_halui_data.jjog_increment_plus[num_joints] = 0); + hal_set_bool(halui_data->jjog_increment_minus[num_joints], old_halui_data.jjog_increment_minus[num_joints] = 0); + hal_set_real(halui_data->jjog_deadband, 0.2); + hal_set_real(halui_data->jjog_speed, 0); + hal_set_bool(halui_data->ajog_minus[EMCMOT_MAX_AXIS], old_halui_data.ajog_minus[EMCMOT_MAX_AXIS] = 0); + hal_set_bool(halui_data->ajog_plus[EMCMOT_MAX_AXIS], old_halui_data.ajog_plus[EMCMOT_MAX_AXIS] = 0); + hal_set_real(halui_data->ajog_increment[EMCMOT_MAX_AXIS], old_halui_data.ajog_increment[EMCMOT_MAX_AXIS] = 0.0); + hal_set_bool(halui_data->ajog_increment_plus[EMCMOT_MAX_AXIS], old_halui_data.ajog_increment_plus[EMCMOT_MAX_AXIS] = 0); + hal_set_bool(halui_data->ajog_increment_minus[EMCMOT_MAX_AXIS], old_halui_data.ajog_increment_minus[EMCMOT_MAX_AXIS] = 0); + hal_set_real(halui_data->ajog_deadband, 0.2); + hal_set_real(halui_data->ajog_speed, 0); + + hal_set_ui32(halui_data->joint_selected, 0); // select joint 0 by default + hal_set_ui32(halui_data->axis_selected, 0); // select axis 0 by default + + hal_set_real(halui_data->fo_scale, old_halui_data.fo_scale = 0.1); //sane default + hal_set_real(halui_data->ro_scale, old_halui_data.ro_scale = 0.1); //sane default for (spindle = 0; spindle < num_spindles; spindle++){ - *(halui_data->so_scale[spindle]) = old_halui_data.so_scale[spindle] = 0.1; //sane default - *(halui_data->so_increase[spindle]) = old_halui_data.so_increase[spindle] = 0; - *(halui_data->so_decrease[spindle]) = old_halui_data.so_decrease[spindle] = 0; - *(halui_data->spindle_increase[spindle]) = old_halui_data.spindle_increase[spindle] = 0; - *(halui_data->spindle_decrease[spindle]) = old_halui_data.spindle_decrease[spindle] = 0; + hal_set_real(halui_data->so_scale[spindle], old_halui_data.so_scale[spindle] = 0.1); //sane default + hal_set_bool(halui_data->so_increase[spindle], old_halui_data.so_increase[spindle] = 0); + hal_set_bool(halui_data->so_decrease[spindle], old_halui_data.so_decrease[spindle] = 0); + hal_set_bool(halui_data->spindle_increase[spindle], old_halui_data.spindle_increase[spindle] = 0); + hal_set_bool(halui_data->spindle_decrease[spindle], old_halui_data.spindle_decrease[spindle] = 0); } } @@ -1569,9 +1420,18 @@ static int check_bit_changed(bool halpin, bool &newpin) static void copy_hal_data(const halui_str &i, local_halui_str &j) { - int x; -#define FIELD(t,f) j.f = (i.f)?*i.f:0; -#define ARRAY(t,f,n) do { for (x = 0; x < n; x++) j.f[x] = (i.f[x])?*i.f[x]:0; } while (0); +#define FIELD(t,f) do { \ + if(i.f) { \ + j.f = hal_get_##t(i.f); \ + } else { j.f = 0; } \ + } while(0); +#define ARRAY(t,f,n) do { \ + for (int x = 0; x < n; x++) { \ + if(i.f[x]) { \ + j.f[x] = hal_get_##t(i.f[x]); \ + } else { j.f[x] = 0; } \ + } \ + } while (0); HAL_FIELDS #undef FIELD #undef ARRAY @@ -1605,12 +1465,12 @@ static bool jogging_selected_axis(local_halui_str &hal) { // and sends appropriate messages if so static void check_hal_changes() { - hal_s32_t counts; + rtapi_s32 counts; int jselect_changed, joint; int aselect_changed, axis_num; - hal_bit_t bit; + rtapi_bool bit; int js; - hal_float_t floatt; + rtapi_real floatt; int jjog_speed_changed; int ajog_speed_changed; @@ -1618,7 +1478,6 @@ static void check_hal_changes() copy_hal_data(*halui_data, new_halui_data_mutable); const local_halui_str &new_halui_data = new_halui_data_mutable; - //check if machine_on pin has changed (the rest work exactly the same) if (check_bit_changed(new_halui_data.machine_on, old_halui_data.machine_on) != 0) sendMachineOn(); //send MachineOn NML command @@ -1891,7 +1750,7 @@ static void check_hal_changes() bit = new_halui_data.joint_nr_select[joint]; if (bit != old_halui_data.joint_nr_select[joint]) { if (bit != 0) { - *halui_data->joint_selected = joint; + hal_set_ui32(halui_data->joint_selected, joint); jselect_changed = joint; // flag that we changed the selected joint } old_halui_data.joint_nr_select[joint] = bit; @@ -1902,15 +1761,15 @@ static void check_hal_changes() if (jselect_changed >= 0) { for (joint = 0; joint < num_joints; joint++) { if (joint != jselect_changed) { - *(halui_data->joint_is_selected[joint]) = 0; + hal_set_bool(halui_data->joint_is_selected[joint], 0); if (jogging_selected_joint(old_halui_data) && !jogging_joint(old_halui_data, joint)) { sendJogStop(joint,JOGJOINT); } } else { - *(halui_data->joint_is_selected[joint]) = 1; - if (*halui_data->jjog_plus[num_joints]) { + hal_set_bool(halui_data->joint_is_selected[joint], 1); + if (hal_get_bool(halui_data->jjog_plus[num_joints])) { sendJogCont(joint, new_halui_data.jjog_speed,JOGJOINT); - } else if (*halui_data->jjog_minus[num_joints]) { + } else if (hal_get_bool(halui_data->jjog_minus[num_joints])) { sendJogCont(joint, -new_halui_data.jjog_speed,JOGJOINT); } } @@ -1965,7 +1824,7 @@ static void check_hal_changes() bit = new_halui_data.axis_nr_select[axis_num]; if (bit != old_halui_data.axis_nr_select[axis_num]) { if (bit != 0) { - *halui_data->axis_selected = axis_num; + hal_set_ui32(halui_data->axis_selected, axis_num); aselect_changed = axis_num; // flag that we changed the selected axis } old_halui_data.axis_nr_select[axis_num] = bit; @@ -1976,15 +1835,15 @@ static void check_hal_changes() for (axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { if ( !(axis_mask & (1 << axis_num)) ) { continue; } if (axis_num != aselect_changed) { - *(halui_data->axis_is_selected[axis_num]) = 0; + hal_set_bool(halui_data->axis_is_selected[axis_num], 0); if (jogging_selected_axis(old_halui_data) && !jogging_axis(old_halui_data, axis_num)) { sendJogStop(axis_num,JOGTELEOP); } } else { - *(halui_data->axis_is_selected[axis_num]) = 1; - if (*halui_data->ajog_plus[num_axes]) { + hal_set_bool(halui_data->axis_is_selected[axis_num], 1); + if (hal_get_bool(halui_data->ajog_plus[num_axes])) { sendJogCont(axis_num, new_halui_data.ajog_speed,JOGTELEOP); - } else if (*halui_data->ajog_minus[num_axes]) { + } else if (hal_get_bool(halui_data->ajog_minus[num_axes])) { sendJogCont(axis_num, -new_halui_data.ajog_speed,JOGTELEOP); } } @@ -2082,17 +1941,8 @@ static void modify_hal_pins() int joint; int spindle; - if (emcStatus->task.state == EMC_TASK_STATE::ON) { - *(halui_data->machine_is_on)=1; - } else { - *(halui_data->machine_is_on)=0; - } - - if (emcStatus->task.state == EMC_TASK_STATE::ESTOP) { - *(halui_data->estop_is_activated)=1; - } else { - *(halui_data->estop_is_activated)=0; - } + hal_set_bool(halui_data->machine_is_on, emcStatus->task.state == EMC_TASK_STATE::ON); + hal_set_bool(halui_data->estop_is_activated, emcStatus->task.state == EMC_TASK_STATE::ESTOP); if (halui_sent_mdi) { // we have an ongoing MDI command if (emcStatus->status == RCS_STATUS::DONE) { //which seems to have finished @@ -2106,40 +1956,16 @@ static void modify_hal_pins() } - if (emcStatus->task.mode == EMC_TASK_MODE::MANUAL) { - *(halui_data->mode_is_manual)=1; - } else { - *(halui_data->mode_is_manual)=0; - } - - if (emcStatus->task.mode == EMC_TASK_MODE::AUTO) { - *(halui_data->mode_is_auto)=1; - } else { - *(halui_data->mode_is_auto)=0; - } - - if (emcStatus->task.mode == EMC_TASK_MODE::MDI) { - *(halui_data->mode_is_mdi)=1; - } else { - *(halui_data->mode_is_mdi)=0; - } - - if (emcStatus->motion.traj.mode == EMC_TRAJ_MODE::TELEOP) { - *(halui_data->mode_is_teleop)=1; - } else { - *(halui_data->mode_is_teleop)=0; - } - - if (emcStatus->motion.traj.mode == EMC_TRAJ_MODE::FREE) { - *(halui_data->mode_is_joint)=1; - } else { - *(halui_data->mode_is_joint)=0; - } + hal_set_bool(halui_data->mode_is_manual, emcStatus->task.mode == EMC_TASK_MODE::MANUAL); + hal_set_bool(halui_data->mode_is_auto, emcStatus->task.mode == EMC_TASK_MODE::AUTO); + hal_set_bool(halui_data->mode_is_mdi, emcStatus->task.mode == EMC_TASK_MODE::MDI); + hal_set_bool(halui_data->mode_is_teleop, emcStatus->motion.traj.mode == EMC_TRAJ_MODE::TELEOP); + hal_set_bool(halui_data->mode_is_joint, emcStatus->motion.traj.mode == EMC_TRAJ_MODE::FREE); - *(halui_data->program_is_paused) = emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED; - *(halui_data->program_is_running) = emcStatus->task.interpState == EMC_TASK_INTERP::READING || - emcStatus->task.interpState == EMC_TASK_INTERP::WAITING; - *(halui_data->program_is_idle) = emcStatus->task.interpState == EMC_TASK_INTERP::IDLE; + hal_set_bool(halui_data->program_is_paused, emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED); + hal_set_bool(halui_data->program_is_running, emcStatus->task.interpState == EMC_TASK_INTERP::READING || + emcStatus->task.interpState == EMC_TASK_INTERP::WAITING); + hal_set_bool(halui_data->program_is_idle, emcStatus->task.interpState == EMC_TASK_INTERP::IDLE); if (num_mdi_commands>0){ // we wants initialize program_is_idle and mode_is_mdi before halui_sent_mdi @@ -2151,34 +1977,34 @@ static void modify_hal_pins() esleep(0.02); //sleep for a while } } - *(halui_data->halui_mdi_is_running) = halui_sent_mdi; + hal_set_bool(halui_data->halui_mdi_is_running, halui_sent_mdi); } - *(halui_data->program_os_is_on) = emcStatus->task.optional_stop_state; - *(halui_data->program_bd_is_on) = emcStatus->task.block_delete_state; - - *(halui_data->mv_value) = emcStatus->motion.traj.maxVelocity; - *(halui_data->fo_value) = emcStatus->motion.traj.scale; //feedoverride from 0 to 1 for 100% - *(halui_data->ro_value) = emcStatus->motion.traj.rapid_scale; //rapid override from 0 to 1 for 100% - - *(halui_data->mist_is_on) = emcStatus->io.coolant.mist; - *(halui_data->flood_is_on) = emcStatus->io.coolant.flood; - - *(halui_data->tool_number) = emcStatus->io.tool.toolInSpindle; - *(halui_data->tool_length_offset_x) = emcStatus->task.toolOffset.tran.x; - *(halui_data->tool_length_offset_y) = emcStatus->task.toolOffset.tran.y; - *(halui_data->tool_length_offset_z) = emcStatus->task.toolOffset.tran.z; - *(halui_data->tool_length_offset_a) = emcStatus->task.toolOffset.a; - *(halui_data->tool_length_offset_b) = emcStatus->task.toolOffset.b; - *(halui_data->tool_length_offset_c) = emcStatus->task.toolOffset.c; - *(halui_data->tool_length_offset_u) = emcStatus->task.toolOffset.u; - *(halui_data->tool_length_offset_v) = emcStatus->task.toolOffset.v; - *(halui_data->tool_length_offset_w) = emcStatus->task.toolOffset.w; + hal_set_bool(halui_data->program_os_is_on, emcStatus->task.optional_stop_state); + hal_set_bool(halui_data->program_bd_is_on, emcStatus->task.block_delete_state); + + hal_set_real(halui_data->mv_value, emcStatus->motion.traj.maxVelocity); + hal_set_real(halui_data->fo_value, emcStatus->motion.traj.scale); //feedoverride from 0 to 1 for 100% + hal_set_real(halui_data->ro_value, emcStatus->motion.traj.rapid_scale); //rapid override from 0 to 1 for 100% + + hal_set_bool(halui_data->mist_is_on, emcStatus->io.coolant.mist); + hal_set_bool(halui_data->flood_is_on, emcStatus->io.coolant.flood); + + hal_set_ui32(halui_data->tool_number, emcStatus->io.tool.toolInSpindle); + hal_set_real(halui_data->tool_length_offset_x, emcStatus->task.toolOffset.tran.x); + hal_set_real(halui_data->tool_length_offset_y, emcStatus->task.toolOffset.tran.y); + hal_set_real(halui_data->tool_length_offset_z, emcStatus->task.toolOffset.tran.z); + hal_set_real(halui_data->tool_length_offset_a, emcStatus->task.toolOffset.a); + hal_set_real(halui_data->tool_length_offset_b, emcStatus->task.toolOffset.b); + hal_set_real(halui_data->tool_length_offset_c, emcStatus->task.toolOffset.c); + hal_set_real(halui_data->tool_length_offset_u, emcStatus->task.toolOffset.u); + hal_set_real(halui_data->tool_length_offset_v, emcStatus->task.toolOffset.v); + hal_set_real(halui_data->tool_length_offset_w, emcStatus->task.toolOffset.w); if (emcStatus->io.tool.toolInSpindle == 0) { - *(halui_data->tool_diameter) = 0.0; + hal_set_real(halui_data->tool_diameter, 0.0); } else { int idx; for (idx = 0; idx <= tooldata_last_index_get(); idx ++) { // note <= @@ -2187,101 +2013,102 @@ static void modify_hal_pins() fprintf(stderr,"UNEXPECTED idx %s %d\n",__FILE__,__LINE__); } if (tdata.toolno == emcStatus->io.tool.toolInSpindle) { - *(halui_data->tool_diameter) = tdata.diameter; + hal_set_real(halui_data->tool_diameter, tdata.diameter); break; } } if (idx == CANON_POCKETS_MAX) { // didn't find the tool - *(halui_data->tool_diameter) = 0.0; + hal_set_real(halui_data->tool_diameter, 0.0); } } for (spindle = 0; spindle < num_spindles; spindle++){ - *(halui_data->spindle_is_on[spindle]) = (emcStatus->motion.spindle[spindle].enabled); - *(halui_data->spindle_runs_forward[spindle]) = (emcStatus->motion.spindle[spindle].direction == 1); - *(halui_data->spindle_runs_backward[spindle]) = (emcStatus->motion.spindle[spindle].direction == -1); - *(halui_data->spindle_brake_is_on[spindle]) = emcStatus->motion.spindle[spindle].brake; - *(halui_data->so_value[spindle]) = emcStatus->motion.spindle[spindle].spindle_scale; //spindle-speed-override from 0 to 1 for 100% + hal_set_bool(halui_data->spindle_is_on[spindle], (emcStatus->motion.spindle[spindle].enabled)); + hal_set_bool(halui_data->spindle_runs_forward[spindle], (emcStatus->motion.spindle[spindle].direction == 1)); + hal_set_bool(halui_data->spindle_runs_backward[spindle], (emcStatus->motion.spindle[spindle].direction == -1)); + hal_set_bool(halui_data->spindle_brake_is_on[spindle], emcStatus->motion.spindle[spindle].brake); + hal_set_real(halui_data->so_value[spindle], emcStatus->motion.spindle[spindle].spindle_scale); //spindle-speed-override from 0 to 1 for 100% } for (joint=0; joint < num_joints; joint++) { - *(halui_data->joint_is_homed[joint]) = emcStatus->motion.joint[joint].homed; - *(halui_data->joint_on_soft_min_limit[joint]) = emcStatus->motion.joint[joint].minSoftLimit; - *(halui_data->joint_on_soft_max_limit[joint]) = emcStatus->motion.joint[joint].maxSoftLimit; - *(halui_data->joint_on_hard_min_limit[joint]) = emcStatus->motion.joint[joint].minHardLimit; - *(halui_data->joint_on_hard_max_limit[joint]) = emcStatus->motion.joint[joint].maxHardLimit; - *(halui_data->joint_override_limits[joint]) = emcStatus->motion.joint[joint].overrideLimits; - *(halui_data->joint_has_fault[joint]) = emcStatus->motion.joint[joint].fault; + hal_set_bool(halui_data->joint_is_homed[joint], emcStatus->motion.joint[joint].homed); + hal_set_bool(halui_data->joint_on_soft_min_limit[joint], emcStatus->motion.joint[joint].minSoftLimit); + hal_set_bool(halui_data->joint_on_soft_max_limit[joint], emcStatus->motion.joint[joint].maxSoftLimit); + hal_set_bool(halui_data->joint_on_hard_min_limit[joint], emcStatus->motion.joint[joint].minHardLimit); + hal_set_bool(halui_data->joint_on_hard_max_limit[joint], emcStatus->motion.joint[joint].maxHardLimit); + hal_set_bool(halui_data->joint_override_limits[joint], emcStatus->motion.joint[joint].overrideLimits); + hal_set_bool(halui_data->joint_has_fault[joint], emcStatus->motion.joint[joint].fault); } if (axis_mask & 0x0001) { - *(halui_data->axis_pos_commanded[0]) = emcStatus->motion.traj.position.tran.x; - *(halui_data->axis_pos_feedback[0]) = emcStatus->motion.traj.actualPosition.tran.x; + hal_set_real(halui_data->axis_pos_commanded[0], emcStatus->motion.traj.position.tran.x); + hal_set_real(halui_data->axis_pos_feedback[0], emcStatus->motion.traj.actualPosition.tran.x); double x = emcStatus->motion.traj.actualPosition.tran.x - emcStatus->task.g5x_offset.tran.x - emcStatus->task.toolOffset.tran.x; double y = emcStatus->motion.traj.actualPosition.tran.y - emcStatus->task.g5x_offset.tran.y - emcStatus->task.toolOffset.tran.y; x = x * cos(-emcStatus->task.rotation_xy * TO_RAD) - y * sin(-emcStatus->task.rotation_xy * TO_RAD); - *(halui_data->axis_pos_relative[0]) = x - emcStatus->task.g92_offset.tran.x; + hal_set_real(halui_data->axis_pos_relative[0], x - emcStatus->task.g92_offset.tran.x); } if (axis_mask & 0x0002) { - *(halui_data->axis_pos_commanded[1]) = emcStatus->motion.traj.position.tran.y; - *(halui_data->axis_pos_feedback[1]) = emcStatus->motion.traj.actualPosition.tran.y; + hal_set_real(halui_data->axis_pos_commanded[1], emcStatus->motion.traj.position.tran.y); + hal_set_real(halui_data->axis_pos_feedback[1], emcStatus->motion.traj.actualPosition.tran.y); double x = emcStatus->motion.traj.actualPosition.tran.x - emcStatus->task.g5x_offset.tran.x - emcStatus->task.toolOffset.tran.x; double y = emcStatus->motion.traj.actualPosition.tran.y - emcStatus->task.g5x_offset.tran.y - emcStatus->task.toolOffset.tran.y; y = y * cos(-emcStatus->task.rotation_xy * TO_RAD) + x * sin(-emcStatus->task.rotation_xy * TO_RAD); - *(halui_data->axis_pos_relative[1]) = y - emcStatus->task.g92_offset.tran.y; + hal_set_real(halui_data->axis_pos_relative[1], y - emcStatus->task.g92_offset.tran.y); } if (axis_mask & 0x0004) { - *(halui_data->axis_pos_commanded[2]) = emcStatus->motion.traj.position.tran.z; - *(halui_data->axis_pos_feedback[2]) = emcStatus->motion.traj.actualPosition.tran.z; - *(halui_data->axis_pos_relative[2]) = emcStatus->motion.traj.actualPosition.tran.z - emcStatus->task.g5x_offset.tran.z - emcStatus->task.g92_offset.tran.z - emcStatus->task.toolOffset.tran.z; + hal_set_real(halui_data->axis_pos_commanded[2], emcStatus->motion.traj.position.tran.z); + hal_set_real(halui_data->axis_pos_feedback[2], emcStatus->motion.traj.actualPosition.tran.z); + hal_set_real(halui_data->axis_pos_relative[2], emcStatus->motion.traj.actualPosition.tran.z - emcStatus->task.g5x_offset.tran.z - emcStatus->task.g92_offset.tran.z - emcStatus->task.toolOffset.tran.z); } if (axis_mask & 0x0008) { - *(halui_data->axis_pos_commanded[3]) = emcStatus->motion.traj.position.a; - *(halui_data->axis_pos_feedback[3]) = emcStatus->motion.traj.actualPosition.a; - *(halui_data->axis_pos_relative[3]) = emcStatus->motion.traj.actualPosition.a - emcStatus->task.g5x_offset.a - emcStatus->task.g92_offset.a - emcStatus->task.toolOffset.a; + hal_set_real(halui_data->axis_pos_commanded[3], emcStatus->motion.traj.position.a); + hal_set_real(halui_data->axis_pos_feedback[3], emcStatus->motion.traj.actualPosition.a); + hal_set_real(halui_data->axis_pos_relative[3], emcStatus->motion.traj.actualPosition.a - emcStatus->task.g5x_offset.a - emcStatus->task.g92_offset.a - emcStatus->task.toolOffset.a); } if (axis_mask & 0x0010) { - *(halui_data->axis_pos_commanded[4]) = emcStatus->motion.traj.position.b; - *(halui_data->axis_pos_feedback[4]) = emcStatus->motion.traj.actualPosition.b; - *(halui_data->axis_pos_relative[4]) = emcStatus->motion.traj.actualPosition.b - emcStatus->task.g5x_offset.b - emcStatus->task.g92_offset.b - emcStatus->task.toolOffset.b; + hal_set_real(halui_data->axis_pos_commanded[4], emcStatus->motion.traj.position.b); + hal_set_real(halui_data->axis_pos_feedback[4], emcStatus->motion.traj.actualPosition.b); + hal_set_real(halui_data->axis_pos_relative[4], emcStatus->motion.traj.actualPosition.b - emcStatus->task.g5x_offset.b - emcStatus->task.g92_offset.b - emcStatus->task.toolOffset.b); } if (axis_mask & 0x0020) { - *(halui_data->axis_pos_commanded[5]) = emcStatus->motion.traj.position.c; - *(halui_data->axis_pos_feedback[5]) = emcStatus->motion.traj.actualPosition.c; - *(halui_data->axis_pos_relative[5]) = emcStatus->motion.traj.actualPosition.c - emcStatus->task.g5x_offset.c - emcStatus->task.g92_offset.c - emcStatus->task.toolOffset.c; + hal_set_real(halui_data->axis_pos_commanded[5], emcStatus->motion.traj.position.c); + hal_set_real(halui_data->axis_pos_feedback[5], emcStatus->motion.traj.actualPosition.c); + hal_set_real(halui_data->axis_pos_relative[5], emcStatus->motion.traj.actualPosition.c - emcStatus->task.g5x_offset.c - emcStatus->task.g92_offset.c - emcStatus->task.toolOffset.c); } if (axis_mask & 0x0040) { - *(halui_data->axis_pos_commanded[6]) = emcStatus->motion.traj.position.u; - *(halui_data->axis_pos_feedback[6]) = emcStatus->motion.traj.actualPosition.u; - *(halui_data->axis_pos_relative[6]) = emcStatus->motion.traj.actualPosition.u - emcStatus->task.g5x_offset.u - emcStatus->task.g92_offset.u - emcStatus->task.toolOffset.u; + hal_set_real(halui_data->axis_pos_commanded[6], emcStatus->motion.traj.position.u); + hal_set_real(halui_data->axis_pos_feedback[6], emcStatus->motion.traj.actualPosition.u); + hal_set_real(halui_data->axis_pos_relative[6], emcStatus->motion.traj.actualPosition.u - emcStatus->task.g5x_offset.u - emcStatus->task.g92_offset.u - emcStatus->task.toolOffset.u); } if (axis_mask & 0x0080) { - *(halui_data->axis_pos_commanded[7]) = emcStatus->motion.traj.position.v; - *(halui_data->axis_pos_feedback[7]) = emcStatus->motion.traj.actualPosition.v; - *(halui_data->axis_pos_relative[7]) = emcStatus->motion.traj.actualPosition.v - emcStatus->task.g5x_offset.v - emcStatus->task.g92_offset.v - emcStatus->task.toolOffset.v; + hal_set_real(halui_data->axis_pos_commanded[7], emcStatus->motion.traj.position.v); + hal_set_real(halui_data->axis_pos_feedback[7], emcStatus->motion.traj.actualPosition.v); + hal_set_real(halui_data->axis_pos_relative[7], emcStatus->motion.traj.actualPosition.v - emcStatus->task.g5x_offset.v - emcStatus->task.g92_offset.v - emcStatus->task.toolOffset.v); } if (axis_mask & 0x0100) { - *(halui_data->axis_pos_commanded[8]) = emcStatus->motion.traj.position.w; - *(halui_data->axis_pos_feedback[8]) = emcStatus->motion.traj.actualPosition.w; - *(halui_data->axis_pos_relative[8]) = emcStatus->motion.traj.actualPosition.w - emcStatus->task.g5x_offset.w - emcStatus->task.g92_offset.w - emcStatus->task.toolOffset.w; + hal_set_real(halui_data->axis_pos_commanded[8], emcStatus->motion.traj.position.w); + hal_set_real(halui_data->axis_pos_feedback[8], emcStatus->motion.traj.actualPosition.w); + hal_set_real(halui_data->axis_pos_relative[8], emcStatus->motion.traj.actualPosition.w - emcStatus->task.g5x_offset.w - emcStatus->task.g92_offset.w - emcStatus->task.toolOffset.w); } - *(halui_data->joint_is_homed[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].homed; - *(halui_data->joint_on_soft_min_limit[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].minSoftLimit; - *(halui_data->joint_on_soft_max_limit[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].maxSoftLimit; - *(halui_data->joint_on_hard_min_limit[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].minHardLimit; - *(halui_data->joint_override_limits[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].overrideLimits; - *(halui_data->joint_on_hard_max_limit[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].maxHardLimit; - *(halui_data->joint_has_fault[num_joints]) = emcStatus->motion.joint[*(halui_data->joint_selected)].fault; + rtapi_u32 joint_selected = hal_get_ui32(halui_data->joint_selected); + hal_set_bool(halui_data->joint_is_homed[num_joints], emcStatus->motion.joint[joint_selected].homed); + hal_set_bool(halui_data->joint_on_soft_min_limit[num_joints], emcStatus->motion.joint[joint_selected].minSoftLimit); + hal_set_bool(halui_data->joint_on_soft_max_limit[num_joints], emcStatus->motion.joint[joint_selected].maxSoftLimit); + hal_set_bool(halui_data->joint_on_hard_min_limit[num_joints], emcStatus->motion.joint[joint_selected].minHardLimit); + hal_set_bool(halui_data->joint_override_limits[num_joints], emcStatus->motion.joint[joint_selected].overrideLimits); + hal_set_bool(halui_data->joint_on_hard_max_limit[num_joints], emcStatus->motion.joint[joint_selected].maxHardLimit); + hal_set_bool(halui_data->joint_has_fault[num_joints], emcStatus->motion.joint[joint_selected].fault); } @@ -2340,7 +2167,7 @@ int main(int argc, char *argv[]) // wait for task to establish nonzero linearUnits if (emcStatus->motion.traj.linearUnits != 0) { // set once at startup, no changes are expected: - *(halui_data->units_per_mm) = emcStatus->motion.traj.linearUnits; + hal_set_real(halui_data->units_per_mm, emcStatus->motion.traj.linearUnits); task_start_synced = 1; } } diff --git a/src/hal/Submakefile b/src/hal/Submakefile index 85b4c56f121..a4144a67820 100644 --- a/src/hal/Submakefile +++ b/src/hal/Submakefile @@ -3,7 +3,7 @@ ../include/hal.h: ./hal/hal.h cp $^ $@ -HALLIBSRCS := hal/hal_lib.c $(ULAPISRCS) +HALLIBSRCS := hal/hal_lib.c hal/hal_lib_query.c hal/hal_lib_extra.c $(ULAPISRCS) $(call TOOBJSDEPS, $(HALLIBSRCS)): EXTRAFLAGS += -fPIC $(ULAPI_CFLAGS) USERSRCS += $(HALLIBSRCS) ifeq ($(BUILD_SYS),uspace) @@ -20,7 +20,7 @@ $(HALLIB).0: $(call TOOBJS, $(HALLIBSRCS)) @rm -f $@ $(Q)$(CC) $(LDFLAGS) -Wl,-soname,$(notdir $@) -shared -o $@ $^ $(HALLIB_LIBS) $(ULAPI_LDFLAGS) -HALMODULESRCS := hal/halmodule.cc +HALMODULESRCS := hal/halmodule.cc hal/utils/setps_util.c PYSRCS += $(HALMODULESRCS) HALMODULE := ../lib/python/_hal.so @@ -28,5 +28,14 @@ $(HALMODULE): $(call TOOBJS, $(HALMODULESRCS)) $(HALLIB) $(ECHO) Linking python module $(notdir $@) $(Q)$(CXX) $(LDFLAGS) -shared -o $@ $^ +HALQUERYSRCS := hal/halquery.c hal/utils/setps_util.c +PYSRCS += $(HALQUERYSRCS) + +HALQUERY := ../lib/python/halquery.so +$(HALQUERY): $(call TOOBJS, $(HALQUERYSRCS)) $(HALLIB) + $(ECHO) Linking python module $(notdir $@) + $(Q)$(CC) $(LDFLAGS) -shared -o $@ $^ + TARGETS += $(HALLIB) ../lib/liblinuxcnchal.so.0 PYTARGETS += $(HALMODULE) +PYTARGETS += $(HALQUERY) diff --git a/src/hal/classicladder/emc_mods.c b/src/hal/classicladder/emc_mods.c index 0a32528d69a..27e903e39d6 100644 --- a/src/hal/classicladder/emc_mods.c +++ b/src/hal/classicladder/emc_mods.c @@ -22,7 +22,6 @@ #include #define _(x) gettext(x) #include -#include "hal/hal_priv.h" #include #include @@ -134,24 +133,27 @@ char * ConvVarNameToHalSigName(char * VarNameParam) } if(*pin_name) { - hal_pin_t *pin = halpr_find_pin_by_name(pin_name); - if(pin && pin->signal) { - hal_sig_t *sig = SHMPTR(pin->signal); - if(0 != sig->name[0]) { + hal_query_t q = {}; + q.name = pin_name; + q.qtype = HAL_QTYPE_PIN; + int rv = hal_getref_p(&q); + // 'signal' is signal name if connected + if(0 == rv && q.pp.signal) { + if(0 != q.pp.signal[0]) { static char sig_name[100]; // char *arrow = "\xe2\x86\x90"; char *arrow = "\xe2\x87\x92"; if(arrowside == 0) { - snprintf(sig_name, 100, "%s%s", sig->name, arrow); + snprintf(sig_name, 100, "%s%s", q.pp.signal, arrow); } else { - snprintf(sig_name, 100, "%s%s", arrow, sig->name); + snprintf(sig_name, 100, "%s%s", arrow, q.pp.signal); } return sig_name; } } - if (pin && !pin->signal) {return _("no signal connected"); } + if (0 == rv && !q.pp.signal) {return _("no signal connected"); } } } diff --git a/src/hal/classicladder/module_hal.c b/src/hal/classicladder/module_hal.c index c0f0f5384af..d3ac7495548 100644 --- a/src/hal/classicladder/module_hal.c +++ b/src/hal/classicladder/module_hal.c @@ -66,14 +66,14 @@ RTAPI_MP_INT(numFloatOut,"i"); #define numWords InfosGene->SizesInfos.nbr_words #endif -hal_bit_t **hal_inputs; -hal_bit_t **hide_gui; -hal_bit_t **hal_outputs; -hal_s32_t **hal_s32_inputs; -hal_s32_t **hal_s32_outputs; -hal_s32_t *hal_state; -hal_float_t **hal_float_inputs; -hal_float_t **hal_float_outputs; +hal_bool_t *hal_inputs; +hal_bool_t *hide_gui; +hal_bool_t *hal_outputs; +hal_sint_t *hal_s32_inputs; +hal_sint_t *hal_s32_outputs; +hal_sint_t *hal_state; +hal_real_t *hal_float_inputs; +hal_real_t *hal_float_outputs; extern StrGeneralParams GeneralParamsMirror; @@ -82,39 +82,39 @@ extern StrGeneralParams GeneralParamsMirror; void HalReadPhysicalInputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_inputs; i++) { - WriteVar(VAR_PHYS_INPUT, i, *hal_inputs[i]); + WriteVar(VAR_PHYS_INPUT, i, hal_get_bool(hal_inputs[i])); } } void HalWritePhysicalOutputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_outputs; i++) { - *(hal_outputs[i]) = ReadVar(VAR_PHYS_OUTPUT, i); + hal_set_bool(hal_outputs[i], ReadVar(VAR_PHYS_OUTPUT, i)); } } void HalReads32Inputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_words_inputs; i++) { - WriteVar(VAR_PHYS_WORD_INPUT, i, *hal_s32_inputs[i]); + WriteVar(VAR_PHYS_WORD_INPUT, i, hal_get_si32(hal_s32_inputs[i])); } } void HalWrites32Outputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_words_outputs; i++) { - *(hal_s32_outputs[i]) = ReadVar(VAR_PHYS_WORD_OUTPUT, i); + hal_set_si32(hal_s32_outputs[i], ReadVar(VAR_PHYS_WORD_OUTPUT, i)); } } void HalReadFloatInputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_float_inputs; i++) { - WriteVar(VAR_PHYS_FLOAT_INPUT, i, *hal_float_inputs[i]); + WriteVar(VAR_PHYS_FLOAT_INPUT, i, hal_get_real(hal_float_inputs[i])); } } void HalWriteFloatOutputs(void) { int i; for( i=0; iGeneralParams.SizesInfos.nbr_phys_float_outputs; i++) { - *(hal_float_outputs[i]) = ReadVar(VAR_PHYS_FLOAT_OUTPUT, i); + hal_set_real(hal_float_outputs[i], ReadVar(VAR_PHYS_FLOAT_OUTPUT, i)); } } // This actually does the magic of periodic refresh of pins and @@ -142,7 +142,7 @@ static void hal_task(void *arg, long period) { if (milliseconds >= 1) { InfosGene->GeneralParams.PeriodicRefreshMilliSecs=milliseconds; - *hal_state = InfosGene->LadderState; + hal_set_si32(*hal_state, InfosGene->LadderState); t0 = rtapi_get_time(); if (InfosGene->LadderState==STATE_RUN) { @@ -152,7 +152,7 @@ static void hal_task(void *arg, long period) { HalReadFloatInputs(); - InfosGene->HideGuiState = *hide_gui[0]; + InfosGene->HideGuiState = hal_get_bool(hide_gui[0]); ClassicLadder_RefreshAllSections(); @@ -185,63 +185,63 @@ int rtapi_app_main(void) { return result; } - hal_state = hal_malloc(sizeof(hal_s32_t)); - result = hal_param_s32_new("classicladder.ladder-state", HAL_RO, hal_state, compId); + hal_state = hal_malloc(sizeof(*hal_state)); + result = hal_param_new_si32(compId, HAL_RO, hal_state, 0, "classicladder.ladder-state"); if(result < 0) { hal_exit(compId); return result; } - hal_inputs = hal_malloc(sizeof(hal_bit_t*) * numPhysInputs); + hal_inputs = hal_malloc(sizeof(*hal_inputs) * numPhysInputs); if(!hal_inputs) { result = -ENOMEM; goto error; } - hide_gui = hal_malloc(sizeof(hal_bit_t*)); + hide_gui = hal_malloc(sizeof(*hide_gui)); if(!hide_gui) { result = -ENOMEM; goto error; } - hal_s32_inputs = hal_malloc(sizeof(hal_s32_t*) * numS32in); + hal_s32_inputs = hal_malloc(sizeof(*hal_s32_inputs) * numS32in); if(!hal_s32_inputs) { result = -ENOMEM; goto error; } - hal_float_inputs = hal_malloc(sizeof(hal_float_t*) * numFloatIn); + hal_float_inputs = hal_malloc(sizeof(*hal_float_inputs) * numFloatIn); if(!hal_float_inputs) { result = -ENOMEM; goto error; } - hal_outputs = hal_malloc(sizeof(hal_bit_t*) * numPhysOutputs); + hal_outputs = hal_malloc(sizeof(*hal_outputs) * numPhysOutputs); if(!hal_outputs) { result = -ENOMEM; goto error; } - hal_s32_outputs = hal_malloc(sizeof(hal_s32_t*) * numS32out); + hal_s32_outputs = hal_malloc(sizeof(*hal_s32_outputs) * numS32out); if(!hal_s32_outputs) { result = -ENOMEM; goto error; } - hal_float_outputs = hal_malloc(sizeof(hal_float_t*) * numFloatOut); + hal_float_outputs = hal_malloc(sizeof(*hal_float_outputs) * numFloatOut); if(!hal_float_outputs) { result = -ENOMEM; goto error; } for(i=0; i= 0.0 ) { - sign = 0; - out = tmp; + sign_set(0); + out_set(tmp); } else { - sign = 1; - out = -tmp; + sign_set(1); + out_set(-tmp); } - if (tmp > 0.000001) is_positive = 1; - else is_positive = 0; - - if (tmp < -0.000001) is_negative = 1; - else is_negative = 0; + is_positive__set(tmp > 0.000001); + is_negative__set(tmp < -0.000001); } diff --git a/src/hal/components/abs_s32.comp b/src/hal/components/abs_s32.comp index 5939acd9918..4ee33a9cf4e 100644 --- a/src/hal/components/abs_s32.comp +++ b/src/hal/components/abs_s32.comp @@ -15,11 +15,11 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. component abs_s32 "Compute the absolute value and sign of a integer input signal"; -pin in s32 in "input value" ; -pin out s32 out "output value, always non-negative"; -pin out bit sign "Sign of input, false for positive, true for negative" ; -pin out bit is_positive "TRUE if input is positive, FALSE if input is 0 or negative"; -pin out bit is_negative "TRUE if input is negative, FALSE if input is 0 or positive"; +pin in si32 in "input value" ; +pin out si32 out "output value, always non-negative"; +pin out bool sign "Sign of input, false for positive, true for negative" ; +pin out bool is_positive_ "TRUE if input is positive, FALSE if input is 0 or negative"; +pin out bool is_negative_ "TRUE if input is negative, FALSE if input is 0 or positive"; option period no; function _; @@ -27,21 +27,15 @@ license "GPL"; author "Sebastian Kuzminsky"; ;; FUNCTION(_) { - if ( in >= 0 ) { - sign = false; - out = in; + rtapi_s32 i = in; + if ( i >= 0 ) { + sign_set(false); + out_set(i); } else { - sign = true; - out = -in; + sign_set(true); + out_set(-i); } - if (in > 0) - is_positive = true; - else - is_positive = false; - - if (in < 0) - is_negative = true; - else - is_negative = false; + is_positive__set(i > 0); + is_negative__set(i < 0); } diff --git a/src/hal/components/abs_s64.comp b/src/hal/components/abs_s64.comp index ef864d8e3ab..012552b83c6 100644 --- a/src/hal/components/abs_s64.comp +++ b/src/hal/components/abs_s64.comp @@ -17,11 +17,11 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA component abs_s64 "Computes the absolute value and sign of a 64 bit integer input signal"; -pin in s64 in "input value" ; -pin out s64 out "output value, always non-negative"; -pin out bit sign "Sign of input, false for positive, true for negative" ; -pin out bit is_positive "true if input is positive, false if input is 0 or negative"; -pin out bit is_negative "true if input is negative, false if input is 0 or positive"; +pin in sint in "input value" ; +pin out sint out "output value, always non-negative"; +pin out bool sign "Sign of input, false for positive, true for negative" ; +pin out bool is_positive_ "true if input is positive, false if input is 0 or negative"; +pin out bool is_negative_ "true if input is negative, false if input is 0 or positive"; option period no; function _; @@ -30,21 +30,15 @@ author "ArcEye based on code from Sebastian Kuzminsky"; ;; FUNCTION(_) { - if ( in >= 0 ) { - sign = false; - out = in; + rtapi_sint i = in; + if ( i >= 0 ) { + sign_set(false); + out_set(i); } else { - sign = true; - out = -in; + sign_set(true); + out_set(-i); } - if (in > 0) - is_positive = true; - else - is_positive = false; - - if (in < 0) - is_negative = true; - else - is_negative = false; + is_positive__set(i > 0); + is_negative__set(i < 0); } diff --git a/src/hal/components/and2.comp b/src/hal/components/and2.comp index a4f5c6a3f2b..7d5463cc609 100644 --- a/src/hal/components/and2.comp +++ b/src/hal/components/and2.comp @@ -1,7 +1,7 @@ component and2 "Two-input AND gate"; -pin in bit in0 "First input"; -pin in bit in1 "Second input"; -pin out bit out "Output"; +pin in bool in0 "First input"; +pin in bool in1 "Second input"; +pin out bool out "Output"; description """ The *out* pin is computed from the value of the *in0* and *in1* pins according @@ -33,4 +33,4 @@ see_also """ license "GPL"; author "Jeff Epler"; ;; -FUNCTION(_) { out = in0 && in1; } +FUNCTION(_) { out_set(in0 && in1); } diff --git a/src/hal/components/anglejog.comp b/src/hal/components/anglejog.comp index d1bddc2bb18..876d04bf66a 100644 --- a/src/hal/components/anglejog.comp +++ b/src/hal/components/anglejog.comp @@ -36,28 +36,28 @@ pin is current-scale-out as it depends on the iscale-factor setting. Simulation Config: `configs/sim/axis/anglejog/anglejog.in` """; -pin in bit enable_in "enables motion (disables alteration of angle and scale)"; -pin in s32 counts_in "MPG (wheel) counts"; -pin in float angle_degrees_in "vector angle"; -pin in s32 iscale_factor = 10000 "integer scaling factor (>1)"; -pin in float scale_in "magnitude units/count (mag = counts * scale)"; -pin in float max_vel "vector max velocity magnitude"; -pin in float max_accel "vector max acceleration magnitude"; -pin in float accel_fraction_in = 1 "acceleration fraction input"; +pin in bool enable_in "enables motion (disables alteration of angle and scale)"; +pin in si32 counts_in "MPG (wheel) counts"; +pin in real angle_degrees_in "vector angle"; +pin in si32 iscale_factor = 10000 "integer scaling factor (>1)"; +pin in real scale_in "magnitude units/count (mag = counts * scale)"; +pin in real max_vel "vector max velocity magnitude"; +pin in real max_accel "vector max acceleration magnitude"; +pin in real accel_fraction_in = 1 "acceleration fraction input"; -pin out bit enable_out "to: axis.M.jog-enable AND axis.N.jog-enable"; -pin out float current_scale "effective scale (informational)"; -pin out float current_scale_out "to: axis.M.jog-scale AND axis.N.jog-scale"; -pin out s32 coscounts "to: axis.M.jog-counts (cosine counts)"; -pin out s32 sincounts "to: axis.N.jog-counts (sine counts)"; -pin out float cos_accel_fraction "to: axis.M.jog-accel-fraction"; -pin out float sin_accel_fraction "to: axis.N.jog-accel-fraction"; +pin out bool enable_out "to: axis.M.jog-enable AND axis.N.jog-enable"; +pin out real current_scale "effective scale (informational)"; +pin out real current_scale_out "to: axis.M.jog-scale AND axis.N.jog-scale"; +pin out si32 coscounts "to: axis.M.jog-counts (cosine counts)"; +pin out si32 sincounts "to: axis.N.jog-counts (sine counts)"; +pin out real cos_accel_fraction "to: axis.M.jog-accel-fraction"; +pin out real sin_accel_fraction "to: axis.N.jog-accel-fraction"; // output monitor pins: -pin out bit active "angle jog move in progress"; -pin out float current_angle_degrees "current angle"; -pin out float current_mag "current vector magnitude"; -pin out float current_vel "current vector speed"; +pin out bool active "angle jog move in progress"; +pin out real current_angle_degrees "current angle"; +pin out real current_mag "current vector magnitude"; +pin out real current_vel "current vector speed"; function _; license "GPL"; @@ -66,7 +66,7 @@ author "Dewey Garrett"; #include #define TO_RAD M_PI/180 // replicate simple_tp.h define for tiny magnitude delta: -#define TINY_DP(max_accel,period) (max_accel*period*period*0.001) +#define TINY_DP(_max_accel,_period) ((_max_accel)*(_period)*(_period)*0.001) #define MIN_ISCALE_FACTOR 10 #define MAX_ISCALE_FACTOR 100000 @@ -83,9 +83,9 @@ static int ifactor = 0; int newcounts; if (once) { - current_angle_degrees = angle_degrees_in; - current_scale = scale_in; - current_scale_out = scale_in/iscale_factor; + current_angle_degrees_set(angle_degrees_in); + current_scale_set(scale_in); + current_scale_out_set(scale_in/iscale_factor); ifactor = iscale_factor; once = 0; } @@ -100,13 +100,13 @@ static int ifactor = 0; delta_counts = newcounts - old_counts_in; old_enable_in = enable_in; old_counts_in = newcounts; - enable_out = enable_in; + enable_out_set(enable_in); if (delta_counts!=0) {wait_for_count_change = 0;} if (enable_in) { tot_counts = tot_counts + delta_counts;} mag_cmd = tot_counts * current_scale_out; - active = 0; + active_set(0); /* compute max change in velocity per servo period */ max_dv = max_accel * fperiod; /* compute a tiny magnitude range, to be treated as zero */ @@ -123,12 +123,12 @@ static int ifactor = 0; vel_req = -max_dv + sqrt(2.0 * max_accel * mag_err + max_dv * max_dv); /* mark planner as active */ - active = 1; + active_set(1); } else if (mag_err < -tiny_dp) { vel_req = max_dv - sqrt(-2.0 * max_accel * mag_err + max_dv * max_dv); /* mark planner as active */ - active = 1; + active_set(1); } else { /* within 'tiny_dp' of desired mag, no need to move */ vel_req = 0.0; @@ -158,11 +158,11 @@ static int ifactor = 0; } } } - current_angle_degrees = angle_degrees_in; + current_angle_degrees_set(angle_degrees_in); if ( current_scale_out != scale_in || new_ifactor) { - current_scale = scale_in; - current_scale_out = scale_in/ifactor; + current_scale_set(scale_in); + current_scale_out_set(scale_in/ifactor); tot_counts = current_mag/current_scale_out; } } @@ -176,24 +176,24 @@ static int ifactor = 0; } /* ramp velocity toward request at accel limit */ if (vel_req > current_vel + max_dv) { - current_vel += max_dv; + current_vel_set(current_vel + max_dv); } else if (vel_req < current_vel - max_dv) { - current_vel -= max_dv; + current_vel_set(current_vel - max_dv); } else { - current_vel = vel_req; + current_vel_set(vel_req); } /* check for still moving */ if (current_vel != 0.0) { /* yes, mark planner active */ - active = 1; + active_set(1); } /* integrate velocity to get new magnitude */ - current_mag += current_vel * fperiod; + current_mag_set(current_mag + current_vel * fperiod); double cos_angle,sin_angle; cos_angle = cos(current_angle_degrees * TO_RAD); sin_angle = sin(current_angle_degrees * TO_RAD); - coscounts = current_mag * cos_angle/current_scale_out; - sincounts = current_mag * sin_angle/current_scale_out; - cos_accel_fraction = accel_fraction_in * cos_angle; - sin_accel_fraction = accel_fraction_in * sin_angle; + coscounts_set(current_mag * cos_angle/current_scale_out); + sincounts_set(current_mag * sin_angle/current_scale_out); + cos_accel_fraction_set(accel_fraction_in * cos_angle); + sin_accel_fraction_set(accel_fraction_in * sin_angle); } diff --git a/src/hal/components/axistest.comp b/src/hal/components/axistest.comp index 2e09c35207a..a66f091e1e3 100644 --- a/src/hal/components/axistest.comp +++ b/src/hal/components/axistest.comp @@ -1,22 +1,22 @@ component axistest """\ Used to allow testing of an axis. Used IN PnCconf."""; -pin in bit jog-minus "Drive TRUE to jog the axis in its negative ('minus') direction."; -pin in bit jog-plus "Drive TRUE to jog the axis in its positive direction."; -pin in bit run "Drive TRUE to run the axis near its current position_fb with a trapezoidal velocity profile."; -pin in float maxvel "Maximum velocity"; -pin in float amplitude "Approximate amplitude of positions to command during 'run'"; -pin in s32 dir "Direction from central point to test: 0 = both, 1 = positive, 2 = negative"; -pin out float position-cmd; -pin in float position-fb; -pin out bit running; -pin out float run-target; -pin out float run-start; -pin out float run-low; -pin out float run-high; -pin in s32 pause = 0 "Pause time for each end of run in seconds"; -param rw float epsilon = .001; +pin in bool jog-minus "Drive TRUE to jog the axis in its negative ('minus') direction."; +pin in bool jog-plus "Drive TRUE to jog the axis in its positive direction."; +pin in bool run "Drive TRUE to run the axis near its current position_fb with a trapezoidal velocity profile."; +pin in real maxvel "Maximum velocity"; +pin in real amplitude "Approximate amplitude of positions to command during 'run'"; +pin in si32 dir "Direction from central point to test: 0 = both, 1 = positive, 2 = negative"; +pin in real position-fb; +pin out real position-cmd; +pin out bool running; +pin out real run-target; +pin out real run-start; +pin out real run-low; +pin out real run-high; +pin in si32 pause = 0 "Pause time for each end of run in seconds"; +param rw real epsilon = .001; variable double timer; -param r float elapsed "Current value of the internal timer"; +param r real elapsed "Current value of the internal timer"; variable int timer_on; function update; license "GPL"; @@ -27,19 +27,19 @@ extern double fabs(double); if (timer_on) { timer += fperiod; } -elapsed = timer; +elapsed_set(timer); if(run) { if(!running) { - running = 1; - run_start = position_fb; + running_set(1); + run_start_set(position_fb); - if(dir == 2) run_high = run_start; - else run_high = run_start + amplitude; + if(dir == 2) run_high_set(run_start); + else run_high_set(run_start + amplitude); - if(dir == 1) run_low = run_start; - else run_low = run_start - amplitude; + if(dir == 1) run_low_set(run_start); + else run_low_set(run_start - amplitude); - position_cmd = run_low; + position_cmd_set(run_low); } if(fabs(position_fb - position_cmd) < epsilon) { @@ -50,26 +50,26 @@ if(run) { } else if (timer >= pause) { timer_on = false; if(position_cmd == run_low) { - position_cmd = run_high; + position_cmd_set(run_high); } else { - position_cmd = run_low; + position_cmd_set(run_low); } } } } } else if(running) { - position_cmd = run_start; + position_cmd_set(run_start); if(fabs(position_fb - run_start) < epsilon) { - running = 0; + running_set(0); timer_on = false; } } else { if(jog_minus) { - position_cmd = position_fb - 10; + position_cmd_set(position_fb - 10); } else if(jog_plus) { - position_cmd = position_fb + 10; + position_cmd_set(position_fb + 10); } else { - position_cmd = position_fb; + position_cmd_set(position_fb); } } diff --git a/src/hal/components/bin2gray.comp b/src/hal/components/bin2gray.comp index b8331963a4a..10c47d0c90f 100644 --- a/src/hal/components/bin2gray.comp +++ b/src/hal/components/bin2gray.comp @@ -1,10 +1,11 @@ component bin2gray "convert a number to the gray-code representation"; description """Converts a number into gray-code"""; -pin in unsigned in "binary code in"; -pin out unsigned out "gray code out"; +pin in ui32 in "binary code in"; +pin out ui32 out "gray code out"; license "GPL"; author "Andy Pugh"; option period no; function _; ;; -out = (in >> 1) ^ in; +rtapi_u32 i = in; +out_set((i >> 1) ^ i); diff --git a/src/hal/components/biquad.comp b/src/hal/components/biquad.comp index e793642f38e..a72e5807b1e 100644 --- a/src/hal/components/biquad.comp +++ b/src/hal/components/biquad.comp @@ -38,31 +38,31 @@ component biquad "Biquad IIR filter"; description """Biquad IIR filter. Implements the following transfer function: H(z) = (n~0~ + n~1~z^-1^ + n~2~z^-2^) / (1 + d~1~z^-1^ + d~2~z^-2^)"""; -pin in float in "Filter input."; -pin out float out "Filter output."; -pin in bit enable = 0 "Filter enable. When false, the *in* pin \ +pin in real in "Filter input."; +pin out real out "Filter output."; +pin in bool enable = 0 "Filter enable. When false, the *in* pin \ is passed to the *out* pin without any filtering. \ A *transition from false to true* causes filter \ coefficients to be calculated according to the current \ *type* and the describing pin and parameter settings"; -pin out bit valid = 0 "When false, indicates an error occurred when calculating \ +pin out bool valid = 0 "When false, indicates an error occurred when calculating \ filter coefficients (require 2>**Q**>0.5 and *f0*>sampleRate/2)"; -pin in u32 type_ = 0 "Filter type determines the type of filter \ +pin in ui32 type_ = 0 "Filter type determines the type of filter \ coefficients calculated. When 0, coefficients must be loaded directly \ from the *n0,n1,n2,d1* params. When 1, \ a low pass filter is created specified by the *f0,Q* pins. \ When 2, a notch filter is created specified by the *f0,Q* pins."; -pin in float f0 = 250.0 "The corner frequency of the filter."; -pin in float Q = 0.7071 "The Q of the filter."; +pin in real f0 = 250.0 "The corner frequency of the filter."; +pin in real Q = 0.7071 "The Q of the filter."; -param rw float d1 = 0.0 "1st-delayed denominator coef"; -param rw float d2 = 0.0 "2nd-delayed denominator coef"; -param rw float n0 = 1.0 "non-delayed numerator coef"; -param rw float n1 = 0.0 "1st-delayed numerator coef"; -param rw float n2 = 0.0 "2nd-delayed numerator coef"; -pin out float s1 = 0.0 "1st-delayed internal state (for debug only)"; -pin out float s2 = 0.0 "2nd-delayed internal state (for debug only)"; +param rw real d1 = 0.0 "1st-delayed denominator coef"; +param rw real d2 = 0.0 "2nd-delayed denominator coef"; +param rw real n0 = 1.0 "non-delayed numerator coef"; +param rw real n1 = 0.0 "1st-delayed numerator coef"; +param rw real n2 = 0.0 "2nd-delayed numerator coef"; +pin out real s1 = 0.0 "1st-delayed internal state (for debug only)"; +pin out real s2 = 0.0 "2nd-delayed internal state (for debug only)"; option data Internal; option extra_setup; @@ -92,7 +92,7 @@ typedef enum { typedef struct { - hal_bit_t lastEnable; + rtapi_bool lastEnable; } Internal; @@ -117,7 +117,7 @@ FUNCTION(_) // If not direct coefficient loading. if(type_ != TYPE_DIRECT){ - valid = 0; + valid_set(0); sampleRate = 1.0 / (period * 1e-9); @@ -145,25 +145,25 @@ FUNCTION(_) break; } - n0 = b0 / a0; - n1 = b1 / a0; - n2 = b2 / a0; - d1 = a1 / a0; - d2 = a2 / a0; - s1 = s2 = 0.0; + n0_set(b0 / a0); + n1_set(b1 / a0); + n2_set(b2 / a0); + d1_set(a1 / a0); + d2_set(a2 / a0); + s1_set(s2_set(0.0)); } - valid = 1; + valid_set(1); } while(0); } if(!enable || !valid){ - out = in; + out_set(in); }else{ // Transposed direct form II. - out = in * n0 + s1; - s1 = in * n1 - out * d1 + s2; - s2 = in * n2 - out * d2; + out_set(in * n0 + s1); + s1_set(in * n1 - out * d1 + s2); + s2_set(in * n2 - out * d2); } } diff --git a/src/hal/components/bitmerge.comp b/src/hal/components/bitmerge.comp index 4d9a1cbcadb..11760d35ce5 100644 --- a/src/hal/components/bitmerge.comp +++ b/src/hal/components/bitmerge.comp @@ -3,8 +3,8 @@ description """This component creates a compound unsigned-32 from individual bit-inputs for each bit of an unsigned-32 output. The number of bits can be limited by the "personality" modparam. The inverse process can be performed by the bitslice HAL component."""; -pin out u32 out "The output value"; -pin in bit in-##[32:personality]; +pin out ui32 out "The output value"; +pin in bool in-##[32:personality]; author "Andy Pugh"; license "GPL2+"; function _; @@ -17,4 +17,4 @@ for (int i = personality; i > 0;) { if (in(--i)) v |= 1; } -out = v; +out_set(v); diff --git a/src/hal/components/bitslice.comp b/src/hal/components/bitslice.comp index d6c805f49c9..11c440aae43 100644 --- a/src/hal/components/bitslice.comp +++ b/src/hal/components/bitslice.comp @@ -3,8 +3,8 @@ description """This component creates individual bit-outputs for each bit of an unsigned-32 input. The number of bits can be limited by the "personality" modparam. The inverse process can be performed by the bitmerge HAL component."""; -pin in u32 in "The input value"; -pin out bit out-##[32:personality]; +pin in ui32 in "The input value"; +pin out bool out-##[32:personality]; author "Andy Pugh"; license "GPL2+"; function _; @@ -13,6 +13,6 @@ option period no; ;; rtapi_u32 v = in; for (int i = 0; i < personality; i++) { - out(i) = v & 1; + out_set(i, v & 1); v >>= 1; } diff --git a/src/hal/components/bitwise.comp b/src/hal/components/bitwise.comp index 42b14169a91..38a0b6791be 100644 --- a/src/hal/components/bitwise.comp +++ b/src/hal/components/bitwise.comp @@ -1,12 +1,12 @@ component bitwise "Computes various bitwise operations on the two input values"; -pin in u32 in0 "First input value"; -pin in u32 in1 "Second input value"; -pin out u32 out-and "The bitwise AND of the two inputs"; -pin out u32 out-or "The bitwise OR of the two inputs"; -pin out u32 out-xor "The bitwise XOR of the two inputs"; -pin out u32 out-nand "The inverse of the bitwise AND"; -pin out u32 out-nor "The inverse of the bitwise OR"; -pin out u32 out-xnor "The inverse of the bitwise XOR"; +pin in ui32 in0 "First input value"; +pin in ui32 in1 "Second input value"; +pin out ui32 out-and "The bitwise AND of the two inputs"; +pin out ui32 out-or "The bitwise OR of the two inputs"; +pin out ui32 out-xor "The bitwise XOR of the two inputs"; +pin out ui32 out-nand "The inverse of the bitwise AND"; +pin out ui32 out-nor "The inverse of the bitwise OR"; +pin out ui32 out-xnor "The inverse of the bitwise XOR"; author "Andy Pugh"; license "GPL 2+"; @@ -14,9 +14,8 @@ function _; option period no; ;; -out_and = (in0 & in1); -out_nand = ~out_and; -out_or = (in0 | in1); -out_nor = ~out_or; -out_xor = (in0 ^ in1); -out_xnor = ~out_xor; +rtapi_u32 i0 = in0; +rtapi_u32 i1 = in1; +out_nand_set(~out_and_set(i0 & i1)); +out_nor_set( ~out_or_set( i0 | i1)); +out_xnor_set(~out_xor_set(i0 ^ i1)); diff --git a/src/hal/components/bldc.comp b/src/hal/components/bldc.comp index 5eaddc42b8f..ed7884ee238 100644 --- a/src/hal/components/bldc.comp +++ b/src/hal/components/bldc.comp @@ -1,37 +1,37 @@ component bldc """BLDC and AC-servo control component *loadrt* *bldc* *cfg*=_qi6,aH_"""; -pin in bit hall1 if personality & 0x01 "Hall sensor signal 1"; -pin in bit hall2 if personality & 0x01 "Hall sensor signal 2"; -pin in bit hall3 if personality & 0x01 "Hall sensor signal 3"; -pin out bit hall_error if personality & 0x01 """Indicates that the selected hall pattern gives inconsistent rotor position data. +pin in bool hall1 if personality & 0x01 "Hall sensor signal 1"; +pin in bool hall2 if personality & 0x01 "Hall sensor signal 2"; +pin in bool hall3 if personality & 0x01 "Hall sensor signal 3"; +pin out bool hall_error if personality & 0x01 """Indicates that the selected hall pattern gives inconsistent rotor position data. This can be due to the pattern being wrong for the motor, or one or more sensors being unconnected or broken. A consistent pattern is not neceesarily valid, but an inconsistent one can never be valid."""; -pin in bit C1 if (personality & 0x10) "Fanuc Gray-code bit 0 input"; -pin in bit C2 if (personality & 0x10) "Fanuc Gray-code bit 1 input"; -pin in bit C4 if (personality & 0x10) "Fanuc Gray-code bit 2 input"; -pin in bit C8 if (personality & 0x10) "Fanuc Gray-code bit 3 input"; +pin in bool C1 if (personality & 0x10) "Fanuc Gray-code bit 0 input"; +pin in bool C2 if (personality & 0x10) "Fanuc Gray-code bit 1 input"; +pin in bool C4 if (personality & 0x10) "Fanuc Gray-code bit 2 input"; +pin in bool C8 if (personality & 0x10) "Fanuc Gray-code bit 3 input"; -pin in float value "PWM master amplitude input"; +pin in real value "PWM master amplitude input"; -pin in float lead-angle = 90 if personality & 0x06 +pin in real lead-angle = 90 if personality & 0x06 "The phase lead between the electrical vector and the rotor position in degrees"; -pin in bit rev +pin in bool rev """Set this pin true to reverse the motor. Negative PWM amplitudes will alsoreverse the motor and there will generally be a Hall pattern that runs the motor in each direction too."""; -pin in float frequency if (personality & 0x0F)==0 """Frequency input for motors with no feedback at all, or those with only an index (which is ignored)"""; +pin in real frequency if (personality & 0x0F)==0 """Frequency input for motors with no feedback at all, or those with only an index (which is ignored)"""; -pin in float initvalue = 0.2 if personality & 0x04 """The current to be used for the homing sequence in applications where an incremental encoder is used with no hall-sensor feedback"""; +pin in real initvalue = 0.2 if personality & 0x04 """The current to be used for the homing sequence in applications where an incremental encoder is used with no hall-sensor feedback"""; -pin in signed rawcounts = 0 if personality & 0x06 +pin in si32 rawcounts = 0 if personality & 0x06 """Encoder counts input. This must be linked to the encoder rawcounts pin or encoder index resets will cause the motor commutation to fail."""; -pin io bit index-enable if personality & 0x08 """This pin should be connected to the associated encoder index-enable pin to zero the encoder when it passes index. +pin io bool index-enable if personality & 0x08 """This pin should be connected to the associated encoder index-enable pin to zero the encoder when it passes index. This is only used indicate to the bldc control component that an index has been seen."""; -pin in bit init if (personality & 0x05) == 4 +pin in bool init if (personality & 0x05) == 4 """A rising edge on this pin starts the motor alignment sequence. This pin should be connected in such a way that the motors re-align any time that encoder monitoring has been interrupted. Typically this will only be at machine power-off. + @@ -42,77 +42,77 @@ The complementary *init-done* pin can be used to handle the required sequencing. Both pins can be ignored if the encoder offset is known explicitly, such as is the case with an absolute encoder. In that case the *offset* parameter can be set directly in the HAL file."""; -pin out bit init-done = 0 if (personality & 0x05) == 4 +pin out bool init-done = 0 if (personality & 0x05) == 4 "Indicates homing sequence complete."; -pin out float A-value if (personality & 0xF00)==0 "Output amplitude for phase A"; -pin out float B-value if (personality & 0xF00)==0 "Output amplitude for phase B"; -pin out float C-value if (personality & 0xF00)==0 "Output amplitude for phase C"; -pin out bit A-on if (personality & 0xF00)==0x100 "Output bit for phase A"; -pin out bit B-on if (personality & 0xF00)==0x100 "Output bit for phase B"; -pin out bit C-on if (personality & 0xF00)==0x100 "Output bit for phase C"; -pin out float A-high if (personality & 0xF00)==0x200 "High-side driver for phase A"; -pin out float B-high if (personality & 0xF00)==0x200 "High-side driver for phase B"; -pin out float C-high if (personality & 0xF00)==0x200 "High-side driver for phase C"; -pin out float A-low if (personality & 0xF00)==0x200 "Low-side driver for phase A"; -pin out float B-low if (personality & 0xF00)==0x200 "Low-side driver for phase B"; -pin out float C-low if (personality & 0xF00)==0x200 "Low-side driver for phase C"; -pin out bit A-high-on if (personality & 0xF00)==0x300 "High-side driver for phase A"; -pin out bit B-high-on if (personality & 0xF00)==0x300 "High-side driver for phase B"; -pin out bit C-high-on if (personality & 0xF00)==0x300 "High-side driver for phase C"; -pin out bit A-low-on if (personality & 0xF00)==0x300 "Low-side driver for phase A"; -pin out bit B-low-on if (personality & 0xF00)==0x300 "Low-side driver for phase B"; -pin out bit C-low-on if (personality & 0xF00)==0x300"Low-side driver for phase C"; - -pin out bit hall1-out if (personality & 0x400) "Hall 1 output"; -pin out bit hall2-out if (personality & 0x400) "Hall 2 output"; -pin out bit hall3-out if (personality & 0x400) "Hall 3 output"; - -pin out bit C1-out if (personality & 0x800) "Fanuc Gray-code bit 0 output"; -pin out bit C2-out if (personality & 0x800) "Fanuc Gray-code bit 1 output"; -pin out bit C4-out if (personality & 0x800) "Fanuc Gray-code bit 2 output"; -pin out bit C8-out if (personality & 0x800) "Fanuc Gray-code bit 3 output"; - -pin out float phase-angle = 0 +pin out real A-value if (personality & 0xF00)==0 "Output amplitude for phase A"; +pin out real B-value if (personality & 0xF00)==0 "Output amplitude for phase B"; +pin out real C-value if (personality & 0xF00)==0 "Output amplitude for phase C"; +pin out bool A-on if (personality & 0xF00)==0x100 "Output bit for phase A"; +pin out bool B-on if (personality & 0xF00)==0x100 "Output bit for phase B"; +pin out bool C-on if (personality & 0xF00)==0x100 "Output bit for phase C"; +pin out real A-high if (personality & 0xF00)==0x200 "High-side driver for phase A"; +pin out real B-high if (personality & 0xF00)==0x200 "High-side driver for phase B"; +pin out real C-high if (personality & 0xF00)==0x200 "High-side driver for phase C"; +pin out real A-low if (personality & 0xF00)==0x200 "Low-side driver for phase A"; +pin out real B-low if (personality & 0xF00)==0x200 "Low-side driver for phase B"; +pin out real C-low if (personality & 0xF00)==0x200 "Low-side driver for phase C"; +pin out bool A-high-on if (personality & 0xF00)==0x300 "High-side driver for phase A"; +pin out bool B-high-on if (personality & 0xF00)==0x300 "High-side driver for phase B"; +pin out bool C-high-on if (personality & 0xF00)==0x300 "High-side driver for phase C"; +pin out bool A-low-on if (personality & 0xF00)==0x300 "Low-side driver for phase A"; +pin out bool B-low-on if (personality & 0xF00)==0x300 "Low-side driver for phase B"; +pin out bool C-low-on if (personality & 0xF00)==0x300"Low-side driver for phase C"; + +pin out bool hall1-out if (personality & 0x400) "Hall 1 output"; +pin out bool hall2-out if (personality & 0x400) "Hall 2 output"; +pin out bool hall3-out if (personality & 0x400) "Hall 3 output"; + +pin out bool C1-out if (personality & 0x800) "Fanuc Gray-code bit 0 output"; +pin out bool C2-out if (personality & 0x800) "Fanuc Gray-code bit 1 output"; +pin out bool C4-out if (personality & 0x800) "Fanuc Gray-code bit 2 output"; +pin out bool C8-out if (personality & 0x800) "Fanuc Gray-code bit 3 output"; + +pin out real phase-angle = 0 """Phase angle including lead/lag angle after encoder zeroing, etc. Useful for angle/current drives. This value has a range of 0 to 1 and measures electrical revolutions. It will have two zeros for a 4 pole motor, three for a 6-pole, etc."""; -pin out float rotor-angle = 0 +pin out real rotor-angle = 0 """Rotor angle after encoder zeroing etc. Useful for angle/current drives which add their own phase offset such as the 8I20. This value has a range of 0 to 1 and measures electrical revolutions. It will have two zeros for a 4 pole motor, three for a 6-pole, etc."""; -pin out float out +pin out real out "Current output, including the effect of the dir pin and the alignment sequence."; -pin out bit out-dir +pin out bool out-dir "Direction output, high if *value* is negative XOR *rev* is true."; -pin out float out-abs +pin out real out-abs "Absolute value of the input value"; -param r signed in_type = -1 "state machine output, will probably hide after debug"; -param r signed out_type = -1 "state machine output, will probably hide after debug"; +param r si32 in_type = -1 "state machine output, will probably hide after debug"; +param r si32 out_type = -1 "state machine output, will probably hide after debug"; -param rw signed scale = 512 if personality & 0x06 +param rw si32 scale = 512 if personality & 0x06 "The number of encoder counts per rotor revolution."; -param rw signed poles = 4 if personality & 0x06 +param rw si32 poles = 4 if personality & 0x06 """The number of motor poles. The encoder scale will be divided by this value to determine the number of encoder counts per electrical revolution."""; -param rw signed encoder-offset = 0 if personality & 0x0A +param rw si32 encoder-offset = 0 if personality & 0x0A """The offset, in encoder counts, between the motor electrical zero and the encoder zero modulo the number of counts per electrical revolution"""; -param r signed offset_measured = 0 if personality & 0x04 +param r si32 offset_measured = 0 if personality & 0x04 """The encoder offset measured by the homing sequence (in certain modes)"""; -param rw float drive-offset = 0 """The angle, in degrees, applied to the commanded angle by the drive in degrees. +param rw real drive-offset = 0 """The angle, in degrees, applied to the commanded angle by the drive in degrees. This value is only used during the homing sequence of drives with incremental encoder feedback. It is used to back-calculate from commanded angle to actual phase angle. It is only relevant to drives which expect rotor-angle input rather than phase-angle demand. Should be 0 for most drives."""; -param rw unsigned output-pattern=25 if personality & 0x400 +param rw ui32 output-pattern=25 if personality & 0x400 """Commutation pattern to be output in Hall Signal translation mode. See the description of *pattern* for details."""; -param rw unsigned pattern=25 if personality & 0x01 +param rw ui32 pattern=25 if personality & 0x01 """Commutation pattern to use, from 0 to 47. Default is type 25. Every plausible combination is included. The table below shows the excitation pattern along the top, and the pattern code on the left hand side. @@ -382,14 +382,14 @@ FUNCTION(_) { if (rev) V = -value; else V = value; - out_dir = (V < 0); - out_abs = fabs(V); + out_dir_set((V < 0)); + out_abs_set(fabs(V)); // Would expect to set "out" here too, but some modes need to over-ride it. if ((personality & 0x05) == 4){ if (init && !old_init && init_done) { - init_done = 0; - in_type = -1; + init_done_set(0); + in_type_set(-1); } else { old_init = init; @@ -409,17 +409,17 @@ FUNCTION(_) { case -2: // Error type, simply to suppress error messages return; case -1: // Initialisation - in_type = personality & 0xFF; - if (in_type & 0x08) index_enable = 1; + in_type_set(personality & 0xFF); + if (in_type & 0x08) index_enable_set(1); counter = absc[0]; - out_type = personality & 0x7F00; + out_type_set(personality & 0x7F00); force_trap = (personality & 0x8000); return; case 0x00: // Dumb VFD mode, just set the angle with no feedback - phase_angle += (frequency * period / 1000000000.0); - phase_angle -= floor(phase_angle); - rotor_angle = phase_angle; + phase_angle_set(phase_angle + (frequency * period / 1000000000.0)); + phase_angle_set(phase_angle - floor(phase_angle)); + rotor_angle_set(phase_angle); break; case 0x01: // Trapezoidal Hall Commutation. @@ -432,7 +432,7 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR, "Only `Hall patterns 0-47 are allowed, you have" " requested pattern %i\n", pattern); - pattern = 0; + pattern_set(0); return; } @@ -448,36 +448,36 @@ FUNCTION(_) { // angle lookup table. for (i = 0 ; phases[i] != ph && i<8 ; i++) {} - rotor_angle = angles[i]; - rotor_angle -= floor(rotor_angle); - if (out_dir) phase_angle = rotor_angle + 0.25; - else phase_angle = rotor_angle - 0.25; - phase_angle -= floor(phase_angle); + rotor_angle_set(angles[i]); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + if (out_dir) phase_angle_set(rotor_angle + 0.25); + else phase_angle_set(rotor_angle - 0.25); + phase_angle_set(phase_angle - floor(phase_angle)); - if (! (ph & old_ph)){ hall_error = 1;} - if (pattern != (unsigned)old_pattern){hall_error = 0;} + if (! (ph & old_ph)){ hall_error_set(1);} + if (pattern != (unsigned)old_pattern){hall_error_set(0);} if (force_trap) break; if (in_type == 0x05 && old_ph && ph != old_ph) { // Homing to hall edges for (i = 1 ; phases[i] != ph && i<8 ; i++) {} if (phases[i - 1] == old_ph) { - rotor_angle = (angles[i] + angles[i - 1])/2;} + rotor_angle_set((angles[i] + angles[i - 1])/2);} else{ - rotor_angle = (angles[i] + angles[i + 1])/2; + rotor_angle_set((angles[i] + angles[i + 1])/2); } - rotor_angle -= floor(rotor_angle); - if (out_dir) phase_angle = rotor_angle - 0.25; - else phase_angle = rotor_angle + 0.25; - phase_angle -= floor(phase_angle); - offset_measured = long_rawcounts - rotor_angle * ( 2 * scale/poles); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + if (out_dir) phase_angle_set(rotor_angle - 0.25); + else phase_angle_set(rotor_angle + 0.25); + phase_angle_set(phase_angle - floor(phase_angle)); + offset_measured_set(long_rawcounts - rotor_angle * ( 2 * scale/poles)); // And now we are homed, switch to sinusoidal drive - in_type = 0x02; + in_type_set(0x02); } else if (in_type == 0x0D) { // homing to encoder index if (!index_enable){ // index has reset - offset_measured = long_rawcounts; - in_type = 0x02; + offset_measured_set(long_rawcounts); + in_type_set(0x02); } } old_ph = ph; @@ -491,34 +491,34 @@ FUNCTION(_) { | ((C4 != 0) << 2) | ((C8 != 0) << 3); for (i = 0 ; gray_b[i] != ph && i<16 ; i++) {} - rotor_angle = gray_a[i] + 0.03125; - rotor_angle -= floor(rotor_angle); - if (out_dir) phase_angle = rotor_angle - 0.25; - else phase_angle = rotor_angle + 0.25; - phase_angle -= floor(phase_angle); + rotor_angle_set(gray_a[i] + 0.03125); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + if (out_dir) phase_angle_set(rotor_angle - 0.25); + else phase_angle_set(rotor_angle + 0.25); + phase_angle_set(phase_angle - floor(phase_angle)); if (force_trap) break; if (in_type == 0x14 && old_ph && ph != old_ph) { // Homing to Gray edges for (i = 1 ; gray_b[i] != ph && i<15 ; i++) {} if (phases[i - 1] == old_ph) { - rotor_angle = gray_a[i]; + rotor_angle_set(gray_a[i]); } else{ - rotor_angle = gray_a[i + 1]; + rotor_angle_set(gray_a[i + 1]); } - rotor_angle -= floor(rotor_angle); - if (out_dir) phase_angle = rotor_angle - 0.25; - else phase_angle = rotor_angle + 0.25; - phase_angle -= floor(phase_angle); - offset_measured = long_rawcounts - rotor_angle * ( 2 * scale/poles); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + if (out_dir) phase_angle_set(rotor_angle - 0.25); + else phase_angle_set(rotor_angle + 0.25); + phase_angle_set(phase_angle - floor(phase_angle)); + offset_measured_set(long_rawcounts - rotor_angle * ( 2 * scale/poles)); // And now we are homed, switch to sinusoidal drive - in_type = 0x02; + in_type_set(0x02); } else if (in_type == 0x1C) { // homing to encoder index if (!index_enable){ // index has reset - offset_measured = long_rawcounts; - in_type = 0x02; + offset_measured_set(long_rawcounts); + in_type_set(0x02); } } old_ph = ph; @@ -533,23 +533,23 @@ FUNCTION(_) { } if (! init_done) { if (counter <= 0) { - offset_measured = long_rawcounts - phase_angle * ( 2 * scale/poles); + offset_measured_set(long_rawcounts - phase_angle * ( 2 * scale/poles)); counter = absc[0]; old_init = 1; - init_done = 1; - in_type = 0x02; // switch to sinusoidal commutation + init_done_set(1); + in_type_set(0x02); // switch to sinusoidal commutation return; } - init_done = 0; + init_done_set(0); for (i = 0 ; absc[i] >= counter && i < 6 ; i++ ) {} V = initvalue * (V_a[i-1] + (V_a[i] - V_a[i-1]) * (counter - absc[i-1]) / (absc[i] - absc[i-1])); - phase_angle = (th_a[i-1] + (th_a[i] - th_a[i-1]) + phase_angle_set(th_a[i-1] + (th_a[i] - th_a[i-1]) * (counter - absc[i-1]) / (absc[i] - absc[i-1])); - phase_angle -= floor(phase_angle); + phase_angle_set(phase_angle - floor(phase_angle)); counter -= fperiod; - rotor_angle = phase_angle - (drive_offset/360.0); - rotor_angle -= floor(rotor_angle); + rotor_angle_set(phase_angle - (drive_offset/360.0)); + rotor_angle_set(rotor_angle - floor(rotor_angle)); } else { rtapi_print_msg(RTAPI_MSG_ERR, "An error has occurred in the " @@ -560,18 +560,18 @@ FUNCTION(_) { case 0x0C: // Incremental encoder homing to index. if (! init) return; if (!index_enable){ // index has reset - offset_measured = long_rawcounts; + offset_measured_set(long_rawcounts); counter = absc[0]; old_init = 1; - init_done = 1; - in_type = 0x02; + init_done_set(1); + in_type_set(0x02); break; } if (! init_done){ - if (initvalue < 0) rotor_angle -= period / 1000000000.0; - else rotor_angle += period / 1000000000.0; - rotor_angle -= floor(rotor_angle); - phase_angle = rotor_angle; + if (initvalue < 0) rotor_angle_set(rotor_angle - period / 1000000000.0); + else rotor_angle_set(rotor_angle + period / 1000000000.0); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + phase_angle_set(rotor_angle); V = fabs(initvalue); } break; @@ -583,11 +583,11 @@ FUNCTION(_) { lead = lead_angle / 360.0; } lagcomped_counts = long_rawcounts + ((long_rawcounts - old_long_rawcounts)/2); - rotor_angle = (double)((lagcomped_counts - offset_measured - - encoder_offset)* poles/2)/scale; - rotor_angle -= floor(rotor_angle); - phase_angle = rotor_angle + lead; - phase_angle -= floor(phase_angle); + rotor_angle_set((double)((lagcomped_counts - offset_measured + - encoder_offset)* poles/2)/scale); + rotor_angle_set(rotor_angle - floor(rotor_angle)); + phase_angle_set(rotor_angle + lead); + phase_angle_set(phase_angle - floor(phase_angle)); break; case 0x03: @@ -595,7 +595,7 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR, "Both Hall Sensors and Absolute " "encoder specified on the same motor. Only the" "Encoder will be used\n"); - in_type = 0x02; + in_type_set(0x02); return; case 0x06: case 0x07: @@ -604,29 +604,29 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR, "Specifying the use of both absolute " "and incremental encoders on the same motor is an " "error. Motor disabled\n"); - in_type = -2; + in_type_set(-2); return; case 0x08: rtapi_print_msg(RTAPI_MSG_ERR, "Driving an electronically commutated" "motor with only an index for feedback is not" "possible. Motor Disabled\n" ); - in_type = -2; + in_type_set(-2); return; case 0x09: rtapi_print_msg(RTAPI_MSG_ERR, "The use of an encoder Index with " "Hall sensors is not supported. Defaulting to " "trapezoidal commutation\n"); - in_type = 0x01; + in_type_set(0x01); return; case 0x0A: rtapi_print_msg(RTAPI_MSG_ERR, "Index is not needed with an Absolute" "encoder and will be ignored\n"); - in_type = 0x02; + in_type_set(0x02); return; default: rtapi_print_msg(RTAPI_MSG_ERR, "Unknown input type pattern (%X) in " "bldc\n", in_type); - in_type = -2; + in_type_set(-2); return; } @@ -642,130 +642,130 @@ FUNCTION(_) { if (force_trap) {trap = 1;} // forced trapezoidal mode - out = V; - out_abs = fabs(V); + out_set(V); + out_abs_set(fabs(V)); switch (out_type){ case 0: // Default; 3-wire sinusoidal or trapezoidal if (trap){ - if (ph & 040) A_value =V; - else if (ph & 004) A_value = -V; - else A_value = 0; + if (ph & 040) A_value_set(V); + else if (ph & 004) A_value_set(-V); + else A_value_set(0); - if (ph & 020) B_value = V; - else if (ph & 002) B_value = -V; - else B_value = 0; + if (ph & 020) B_value_set(V); + else if (ph & 002) B_value_set(-V); + else B_value_set(0); - if (ph & 010) C_value = V; - else if (ph & 001) C_value = -V; - else C_value = 0; + if (ph & 010) C_value_set(V); + else if (ph & 001) C_value_set(-V); + else C_value_set(0); } else { sintheta = sin(phase_angle * pi2); costheta = cos(phase_angle * pi2); - A_value = out_abs * costheta; - B_value = out_abs * (costheta * cos120 + sintheta * sin120); - C_value = out_abs * (costheta * cos120 - sintheta * sin120); + A_value_set(out_abs * costheta); + B_value_set(out_abs * (costheta * cos120 + sintheta * sin120)); + C_value_set(out_abs * (costheta * cos120 - sintheta * sin120)); } return; case 0x100: // bit outputs, 3-wire. Dubious utility if (out_dir){ ph = (ph & 070) >> 3 | (ph & 007) << 3;} - if (ph & 040) {A_on = 1;} - else if (ph & 020) {B_on = 1;} - else if (ph & 010) {C_on = 1;} - else {A_on = 0 ; B_on = 0 ; C_on = 0;} - if (ph & 004) {A_on = 0;} - else if (ph & 002) {B_on = 0;} - else if (ph & 001) {C_on = 0;} - else {A_on = 0 ; B_on = 0 ; C_on = 0;} + if (ph & 040) {A_on_set(1);} + else if (ph & 020) {B_on_set(1);} + else if (ph & 010) {C_on_set(1);} + else {A_on_set(0 ); B_on_set(0 ); C_on_set(0);} + if (ph & 004) {A_on_set(0);} + else if (ph & 002) {B_on_set(0);} + else if (ph & 001) {C_on_set(0);} + else {A_on_set(0 ); B_on_set(0 ); C_on_set(0);} return; case 0x200: // 6-wire modes if (trap){ if (out_dir){ ph = (ph & 070) >> 3 | (ph & 007) << 3;} - if (ph & 040) { A_high = out_abs; A_low = 0;} - else if (ph & 004) {A_high = 0; A_low = out_abs;} - else {A_high = 0; A_low = 0;} + if (ph & 040) { A_high_set(out_abs); A_low_set(0);} + else if (ph & 004) {A_high_set(0); A_low_set(out_abs);} + else {A_high_set(0); A_low_set(0);} - if (ph & 020) {B_high = out_abs; B_low = 0;} - else if (ph & 002) {B_high = 0; B_low = out_abs;} - else {B_high = 0; B_low = 0;} + if (ph & 020) {B_high_set(out_abs); B_low_set(0);} + else if (ph & 002) {B_high_set(0); B_low_set(out_abs);} + else {B_high_set(0); B_low_set(0);} - if (ph & 010) {C_high = out_abs; C_low = 0;} - else if (ph & 001) {C_high = 0; C_low = out_abs;} - else {C_high = 0; C_low=0;} + if (ph & 010) {C_high_set(out_abs); C_low_set(0);} + else if (ph & 001) {C_high_set(0); C_low_set(out_abs);} + else {C_high_set(0); C_low_set(0);} } else { sintheta = sin(phase_angle * pi2); costheta = cos(phase_angle * pi2); if (costheta >=0){ - A_high = out_abs * costheta; A_low = 0;} + A_high_set(out_abs * costheta); A_low_set(0);} else { - A_high = 0; A_low = -out_abs * costheta;} + A_high_set(0); A_low_set(-out_abs * costheta);} if ((costheta * cos120 + sintheta * sin120) >= 0){ - B_high = out_abs * (costheta * cos120 + sintheta * sin120); - B_low = 0;} + B_high_set(out_abs * (costheta * cos120 + sintheta * sin120)); + B_low_set(0);} else { - B_high = 0; - B_low = -out_abs * (costheta * cos120 + sintheta * sin120);} + B_high_set(0); + B_low_set(-out_abs * (costheta * cos120 + sintheta * sin120));} if ((costheta * cos120 - sintheta * sin120) >= 0) { - C_high = out_abs * (costheta * cos120 - sintheta * sin120); - C_low = 0;} + C_high_set(out_abs * (costheta * cos120 - sintheta * sin120)); + C_low_set(0);} else { - C_high = 0; - C_low = -out_abs * (costheta * cos120 - sintheta * sin120);} + C_high_set(0); + C_low_set(-out_abs * (costheta * cos120 - sintheta * sin120));} } return; case 0x300: // 6-wire bit mode if (out_dir) { - A_high_on = (ph & 004) ; A_low_on = (ph & 040); - B_high_on = (ph & 002) ; B_low_on = (ph & 020); - C_high_on = (ph & 001) ; C_low_on = (ph & 010); + A_high_on_set((ph & 004) ); A_low_on_set((ph & 040)); + B_high_on_set((ph & 002) ); B_low_on_set((ph & 020)); + C_high_on_set((ph & 001) ); C_low_on_set((ph & 010)); } else { - A_high_on = (ph & 040) ; A_low_on = (ph & 004); - B_high_on = (ph & 020) ; B_low_on = (ph & 002); - C_high_on = (ph & 010) ; C_low_on = (ph & 001); + A_high_on_set((ph & 040) ); A_low_on_set((ph & 004)); + B_high_on_set((ph & 020) ); B_low_on_set((ph & 002)); + C_high_on_set((ph & 010) ); C_low_on_set((ph & 001)); } return; case 0x400: // Hall Output for (i = 0; P[(output_pattern << 3) + i] != ((unsigned)ph & 0xff) && i < 8 ; i++) {} - hall1_out = (i & 0x04); - hall2_out = (i & 0x02); - hall3_out = (i & 0x01); + hall1_out_set((i & 0x04)); + hall2_out_set((i & 0x02)); + hall3_out_set((i & 0x01)); return; case 0x800: // Fanuc Red Cap style Gray-Code emulation for (i = 0; (gray_a[i] + 0.0625) < rotor_angle && i < 16 ; i++) {} - C1_out = (gray_b[i] & 001); - C2_out = (gray_b[i] & 002); - C4_out = (gray_b[i] & 004); - C8_out = (gray_b[i] & 010); + C1_out_set((gray_b[i] & 001)); + C2_out_set((gray_b[i] & 002)); + C4_out_set((gray_b[i] & 004)); + C8_out_set((gray_b[i] & 010)); return; case 0x500: rtapi_print_msg(RTAPI_MSG_ERR, "Combinations of Hall Pattern and Bit" " outputs are not supported. Defaulting to Hall"); - out_type = 0x400; + out_type_set(0x400); return; case 0x600: rtapi_print_msg(RTAPI_MSG_ERR, "6-Wire Hall patterns outputs are " "not supported. Defaulting to 3-wire"); - out_type = 0x400; + out_type_set(0x400); return; case 0x700: rtapi_print_msg(RTAPI_MSG_ERR, "6-wire combinations of Hall and Bit" " outputs can't be supported. Defaulting to 3-wire" " Hall pattern"); - out_type = 0x400; + out_type_set(0x400); return; case 0x900: case 0xB00: @@ -773,17 +773,17 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR, "Combinations of bit level and " " Gray Code outputs are not supported. Defaulting" " to Gray Code"); - out_type = 0x800; + out_type_set(0x800); return; case 0xC00: rtapi_print_msg(RTAPI_MSG_ERR, "Hall Sensor and Gray-code outputs" " can not be combined. defaulting to Hall"); - out_type = 0x400; + out_type_set(0x400); return; default: rtapi_print_msg(RTAPI_MSG_ERR, "Unsupported output type (%X) in bldc" , out_type); - in_type = -2; + in_type_set(-2); return; } } diff --git a/src/hal/components/blend.comp b/src/hal/components/blend.comp index 4c1461f9ac7..9429b13ca21 100644 --- a/src/hal/components/blend.comp +++ b/src/hal/components/blend.comp @@ -17,12 +17,12 @@ component blend "Perform linear interpolation between two values"; -pin in float in1 "First input. If select is equal to 1.0, the output is equal to in1"; -pin in float in2 "Second input. If select is equal to 0.0, the output is equal to in2"; -pin in float select "Select input. For values between 0.0 and 1.0, the output changes linearly from in2 to in1"; -pin out float out "Output value."; +pin in real in1 "First input. If select is equal to 1.0, the output is equal to in1"; +pin in real in2 "Second input. If select is equal to 0.0, the output is equal to in2"; +pin in real select "Select input. For values between 0.0 and 1.0, the output changes linearly from in2 to in1"; +pin out real out "Output value."; -param rw bit open "If true, select values outside the range 0.0 to 1.0 give values outside the range in2 to in1. If false, outputs are clamped to the the range in2 to in1"; +param rw bool open "If true, select values outside the range 0.0 to 1.0 give values outside the range in2 to in1. If false, outputs are clamped to the the range in2 to in1"; option period no; function _; @@ -32,7 +32,7 @@ author "Jeff Epler"; ;; FUNCTION(_) { - double select_ = select; + rtapi_real select_ = select; if(!open) { if(select_ < 0) select_ = 0; if(select_ > 1) select_ = 1; } - out = in1 * select_ + in2 * (1 - select_); + out_set(in1 * select_ + in2 * (1 - select_)); } diff --git a/src/hal/components/boss_plc.c b/src/hal/components/boss_plc.c index 49f06889ea8..afa1d7cc37f 100644 --- a/src/hal/components/boss_plc.c +++ b/src/hal/components/boss_plc.c @@ -152,9 +152,9 @@ typedef void (*TIMER_ROUTINE)(void *pArgs); typedef struct { // Private data. BOOL enabled; - hal_u32_t nSec; - hal_u32_t count; - hal_u32_t timeout; + rtapi_u32 nSec; + rtapi_u32 count; + rtapi_u32 timeout; TIMER_ROUTINE pTimeout; void *pArgs; TimerMode mode; @@ -165,7 +165,7 @@ static void Timer_Enable(Timer *this, TimerMode mode); static void Timer_Disable(Timer *this); static BOOL Timer_IsEnabled(Timer *this); static void Timer_Update(Timer *this, long period); -static void Timer_SetTimeout(Timer *this, hal_u32_t timeout); +static void Timer_SetTimeout(Timer *this, rtapi_u32 timeout); #if 0 static void Timer_SetCallback(Timer *this, TIMER_ROUTINE pCallback, void *pArgs); #endif @@ -188,23 +188,25 @@ typedef enum { typedef struct { // Exported pins. - hal_float_t *pPositionIn; - hal_bit_t *pJogEnIn; - hal_bit_t *pIn; - hal_bit_t *pPosOut; - hal_bit_t *pNegOut; + hal_real_t pPositionIn; + hal_bool_t pJogEnIn; + hal_bool_t pIn; + hal_bool_t pPosOut; + hal_bool_t pNegOut; + + hal_uint_t stateDebug; // Only available when debug is on // Internal data. LimitState state; - hal_float_t position; - hal_bit_t limitPos; - hal_bit_t limitNeg; + rtapi_real position; + rtapi_bool limitPos; + rtapi_bool limitNeg; } Limit; static int Limit_Export(Limit *this, int compId, int id, char axis); static void Limit_Init(Limit *this); static BOOL Limit_IsActive(Limit *this); -static void Limit_Refresh(Limit *this, hal_bit_t override); +static void Limit_Refresh(Limit *this, rtapi_bool override); /****************************************************************************** @@ -216,18 +218,18 @@ static void Limit_Refresh(Limit *this, hal_bit_t override); typedef struct { // Exported pins. - hal_bit_t *pEnableIn; - hal_bit_t *pReadyIn; - hal_bit_t *pFaultOut; + hal_bool_t pEnableIn; + hal_bool_t pReadyIn; + hal_bool_t pFaultOut; // Internal data. Timer timer; - hal_bit_t lastEnable; + rtapi_bool lastEnable; } Amp; static int Amp_Export(Amp *this, int compId, int id, char axis); static void Amp_Init(Amp *this); -static void Amp_Refresh(Amp *this, long period, hal_u32_t readyDelay); +static void Amp_Refresh(Amp *this, long period, rtapi_u32 readyDelay); /****************************************************************************** @@ -256,57 +258,59 @@ typedef enum { typedef struct { // Pins. (former parameters) - hal_u32_t *ampReadyDelay; - hal_u32_t *brakeOnDelay; - hal_u32_t *brakeOffDelay; - hal_float_t *spindleLoToHi; - hal_float_t *jogScale[NUM_JOG_SEL]; + hal_uint_t ampReadyDelay; + hal_uint_t brakeOnDelay; + hal_uint_t brakeOffDelay; + hal_real_t spindleLoToHi; + hal_real_t jogScale[NUM_JOG_SEL]; // Pins. - hal_bit_t *pCycleStartIn; - hal_bit_t *pCycleHoldIn; - hal_bit_t *pFeedHoldOut; - hal_float_t *pAdaptiveFeedIn; - hal_float_t *pAdaptiveFeedOut; - hal_bit_t *pToolChangeIn; - hal_bit_t *pToolChangedOut; - hal_bit_t *pWaitUserOut; - hal_bit_t *pMistOnIn; - hal_bit_t *pMistOnOut; - hal_bit_t *pFloodOnIn; - hal_bit_t *pFloodOnOut; - - hal_bit_t *pLimitOverrideIn; - hal_bit_t *pLimitActiveOut; + hal_bool_t pCycleStartIn; + hal_bool_t pCycleHoldIn; + hal_bool_t pFeedHoldOut; + hal_real_t pAdaptiveFeedIn; + hal_real_t pAdaptiveFeedOut; + hal_bool_t pToolChangeIn; + hal_bool_t pToolChangedOut; + hal_bool_t pWaitUserOut; + hal_bool_t pMistOnIn; + hal_bool_t pMistOnOut; + hal_bool_t pFloodOnIn; + hal_bool_t pFloodOnOut; + + hal_bool_t pLimitOverrideIn; + hal_bool_t pLimitActiveOut; Limit xLimit; Limit yLimit; - hal_bit_t *pZJogEnIn; - hal_bit_t *pZLimitPosIn; - hal_bit_t *pZLimitNegIn; - hal_bit_t *pZLimitPosOut; - hal_bit_t *pZLimitNegOut; + hal_bool_t pZJogEnIn; + hal_bool_t pZLimitPosIn; + hal_bool_t pZLimitNegIn; + hal_bool_t pZLimitPosOut; + hal_bool_t pZLimitNegOut; Amp amps[NUM_AXIS]; - hal_float_t *pSpindleSpeedIn; - hal_bit_t *pSpindleIsOnIn; - hal_bit_t *pSpindleFwdOut; - hal_bit_t *pSpindleRevOut; - hal_bit_t *pSpindleIncIn; - hal_bit_t *pSpindleDecIn; - hal_bit_t *pSpindleIncOut; - hal_bit_t *pSpindleDecOut; - hal_bit_t *pBrakeEnIn; - hal_bit_t *pBrakeEnOut; + hal_real_t pSpindleSpeedIn; + hal_bool_t pSpindleIsOnIn; + hal_bool_t pSpindleFwdOut; + hal_bool_t pSpindleRevOut; + hal_bool_t pSpindleIncIn; + hal_bool_t pSpindleDecIn; + hal_bool_t pSpindleIncOut; + hal_bool_t pSpindleDecOut; + hal_bool_t pBrakeEnIn; + hal_bool_t pBrakeEnOut; + + hal_bool_t pJogSelIn[NUM_JOG_SEL]; + hal_real_t pJogScaleOut; - hal_bit_t *pJogSelIn[NUM_JOG_SEL]; - hal_float_t *pJogScaleOut; + hal_uint_t spindleStateDebug; // Only available when debug is on // Private data. SpindleState spindleState; Timer spindleTimer; - hal_float_t lastSpindleSpeed; - hal_bit_t lastCycleStart; + rtapi_real lastSpindleSpeed; + rtapi_bool lastCycleStart; } Plc; @@ -438,14 +442,9 @@ Plc_Init(Plc *this) this->lastCycleStart = 1; // Initialize parameters. - *(this->brakeOffDelay) = 500; - *(this->brakeOnDelay) = 300; - *(this->ampReadyDelay) = 50; - *(this->spindleLoToHi) = 500; - - *(this->jogScale[0]) = 0.0001; + hal_set_real(this->jogScale[0], 0.0001); for(i = 1; i < NUM_JOG_SEL; i++){ - *(this->jogScale[i]) = *(this->jogScale[i-1]) * 10; + hal_set_real(this->jogScale[i], hal_get_real(this->jogScale[i-1]) * 10); } // Initialize timer. @@ -512,62 +511,61 @@ Plc_ExportFeed(Plc *this, int compId, int id) int error; // Export pins. - error = hal_pin_bit_newf(HAL_IN, &this->pCycleStartIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pCycleStartIn, 0, "boss_plc.%d.cycle-start-in", id); if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pCycleHoldIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pCycleHoldIn, 0, "boss_plc.%d.cycle-hold-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pFeedHoldOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pFeedHoldOut, 0, "boss_plc.%d.feed-hold-out", id); } if(!error){ - error = hal_pin_float_newf(HAL_IN, &this->pAdaptiveFeedIn, compId, + error = hal_pin_new_real(compId, HAL_IN, &this->pAdaptiveFeedIn, 1.0, "boss_plc.%d.adaptive-feed-in", id); } if(!error){ - *this->pAdaptiveFeedIn = 1.0; - error = hal_pin_float_newf(HAL_OUT, &this->pAdaptiveFeedOut, compId, + error = hal_pin_new_real(compId, HAL_OUT, &this->pAdaptiveFeedOut, 0.0, "boss_plc.%d.adaptive-feed-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pToolChangeIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pToolChangeIn, 0, "boss_plc.%d.tool-change-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pToolChangedOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pToolChangedOut, 0, "boss_plc.%d.tool-changed-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pWaitUserOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pWaitUserOut, 0, "boss_plc.%d.wait-user-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pMistOnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pMistOnIn, 0, "boss_plc.%d.mist-on-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pMistOnOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pMistOnOut, 0, "boss_plc.%d.mist-on-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pFloodOnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pFloodOnIn, 0, "boss_plc.%d.flood-on-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pFloodOnOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pFloodOnOut, 0, "boss_plc.%d.flood-on-out", id); } @@ -581,11 +579,11 @@ Plc_ExportLimits(Plc *this, int compId, int id) int error; // Export pins. - error = hal_pin_bit_newf(HAL_IN, &this->pLimitOverrideIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pLimitOverrideIn, 0, "boss_plc.%d.limit-override-in", id); if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pLimitActiveOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pLimitActiveOut, 0, "boss_plc.%d.limit-active-out", id); } @@ -598,39 +596,39 @@ Plc_ExportLimits(Plc *this, int compId, int id) } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pZLimitPosIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pZLimitPosIn, 0, "boss_plc.%d.%c-limit-pos-in", id, axisNames[2]); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pZJogEnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pZJogEnIn, 0, "boss_plc.%d.%c-jog-en-in", id, axisNames[2]); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pZLimitNegIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pZLimitNegIn, 0, "boss_plc.%d.%c-limit-neg-in", id, axisNames[2]); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pZLimitPosOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pZLimitPosOut, 0, "boss_plc.%d.%c-limit-pos-out", id, axisNames[2]); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pZLimitNegOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pZLimitNegOut, 0, "boss_plc.%d.%c-limit-neg-out", id, axisNames[2]); } // Export optional parameters. if(debug > 0){ if(!error){ - error = hal_param_u32_newf(HAL_RO, &this->xLimit.state, compId, + error = hal_param_new_ui32(compId, HAL_RO, &this->xLimit.stateDebug, 0, "boss_plc.%d.%c-limit-state", id, axisNames[0]); } if(!error){ - error = hal_param_u32_newf(HAL_RO, &this->yLimit.state, compId, + error = hal_param_new_ui32(compId, HAL_RO, &this->yLimit.stateDebug, 0, "boss_plc.%d.%c-limit-state", id, axisNames[1]); } } @@ -645,7 +643,7 @@ Plc_ExportAmps(Plc *this, int compId, int id) int error, i; Amp *pAmp; - error = hal_pin_u32_newf(HAL_IO, &this->ampReadyDelay, compId, + error = hal_pin_new_ui32(compId, HAL_IO, &this->ampReadyDelay, 50, "boss_plc.%d.amp-ready-delay", id); pAmp = this->amps; @@ -663,75 +661,75 @@ Plc_ExportSpindle(Plc *this, int compId, int id) int error; // Export parameters. - error = hal_pin_u32_newf(HAL_IO, &this->brakeOnDelay, compId, + error = hal_pin_new_ui32(compId, HAL_IO, &this->brakeOnDelay, 300, "boss_plc.%d.brake-on-delay", id); if(!error){ - error = hal_pin_u32_newf(HAL_IO, &this->brakeOffDelay, compId, + error = hal_pin_new_ui32(compId, HAL_IO, &this->brakeOffDelay, 500, "boss_plc.%d.brake-off-delay", id); } if(!error){ - error = hal_pin_float_newf(HAL_IO, &this->spindleLoToHi, compId, + error = hal_pin_new_real(compId, HAL_IO, &this->spindleLoToHi, 500, "boss_plc.%d.spindle-lo-to-hi", id); } // Export optional parameters. if(debug > 0){ if(!error){ - error = hal_param_u32_newf(HAL_RO, &this->spindleState, compId, + error = hal_param_new_ui32(compId, HAL_RO, &this->spindleStateDebug, 0, "boss_plc.%d.spindle-state", id); } } // Export pins. if(!error){ - error = hal_pin_float_newf(HAL_IN, &this->pSpindleSpeedIn, compId, + error = hal_pin_new_real(compId, HAL_IN, &this->pSpindleSpeedIn, 0.0, "boss_plc.%d.spindle-speed-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pSpindleIsOnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pSpindleIsOnIn, 0, "boss_plc.%d.spindle-is-on-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pSpindleFwdOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pSpindleFwdOut, 0, "boss_plc.%d.spindle-fwd-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pSpindleRevOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pSpindleRevOut, 0, "boss_plc.%d.spindle-rev-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pSpindleIncIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pSpindleIncIn, 0, "boss_plc.%d.spindle-inc-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pSpindleDecIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pSpindleDecIn, 0, "boss_plc.%d.spindle-dec-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pSpindleIncOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pSpindleIncOut, 0, "boss_plc.%d.spindle-inc-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pSpindleDecOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pSpindleDecOut, 0, "boss_plc.%d.spindle-dec-out", id); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pBrakeEnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pBrakeEnIn, 0, "boss_plc.%d.brake-en-in", id); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pBrakeEnOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pBrakeEnOut, 0, "boss_plc.%d.brake-en-out", id); } @@ -746,20 +744,20 @@ Plc_ExportJog(Plc *this, int compId, int id) // Export parameters. for(i = 0, error = 0; i < NUM_JOG_SEL && !error; i++){ - error = hal_pin_float_newf(HAL_IO, &this->jogScale[i], compId, + error = hal_pin_new_real(compId, HAL_IO, &this->jogScale[i], 0.0, "boss_plc.%d.jog-scale-%d", id, i); } if(!error){ for(i = 0; i < NUM_JOG_SEL && !error; i++){ - error = hal_pin_bit_newf(HAL_IN, &this->pJogSelIn[i], compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pJogSelIn[i], 0, "boss_plc.%d.jog-sel-in-%d", id, i); } } // Export pins. if(!error){ - error = hal_pin_float_newf(HAL_OUT, &this->pJogScaleOut, compId, + error = hal_pin_new_real(compId, HAL_OUT, &this->pJogScaleOut, 0.0, "boss_plc.%d.jog-scale-out", id); } @@ -781,6 +779,12 @@ Plc_Refresh(void *arg, long period) Plc_RefreshAmps(this, period); Plc_RefreshSpindle(this, period); Plc_RefreshJog(this, period); + + if(debug > 0) { + hal_set_ui32(this->spindleStateDebug, this->spindleState); + hal_set_ui32(this->xLimit.stateDebug, this->xLimit.state); + hal_set_ui32(this->yLimit.stateDebug, this->yLimit.state); + } } @@ -790,35 +794,35 @@ Plc_RefreshFeed(Plc *this, long period) (void)period; BOOL riseCycleStart; - riseCycleStart = !this->lastCycleStart && *this->pCycleStartIn; - this->lastCycleStart = *this->pCycleStartIn; + riseCycleStart = !this->lastCycleStart && hal_get_bool(this->pCycleStartIn); + this->lastCycleStart = hal_get_bool(this->pCycleStartIn); // Condition feed hold so machine waits for cycle start and spindle to be // running if it is enabled. - *this->pFeedHoldOut = *this->pCycleHoldIn - || (*this->pSpindleSpeedIn && !*this->pSpindleIsOnIn) - || (*this->pSpindleIsOnIn - && (this->lastSpindleSpeed != *this->pSpindleSpeedIn)) - || (*this->pFeedHoldOut && !riseCycleStart); - this->lastSpindleSpeed = *this->pSpindleSpeedIn; + hal_set_bool(this->pFeedHoldOut, hal_get_bool(this->pCycleHoldIn) + || (hal_get_real(this->pSpindleSpeedIn) && !hal_get_bool(this->pSpindleIsOnIn)) + || (hal_get_bool(this->pSpindleIsOnIn) + && (this->lastSpindleSpeed != hal_get_real(this->pSpindleSpeedIn))) + || (hal_get_bool(this->pFeedHoldOut) && !riseCycleStart)); + this->lastSpindleSpeed = hal_get_real(this->pSpindleSpeedIn); // Limit rapid/feed to 1% when limits are being overridden. - if(*this->pLimitOverrideIn && (*this->pAdaptiveFeedIn > 0.01)) - *this->pAdaptiveFeedOut = 0.01; + if(hal_get_bool(this->pLimitOverrideIn) && (hal_get_real(this->pAdaptiveFeedIn) > 0.01)) + hal_set_real(this->pAdaptiveFeedOut, 0.01); else - *this->pAdaptiveFeedOut = *this->pAdaptiveFeedIn; + hal_set_real(this->pAdaptiveFeedOut, hal_get_real(this->pAdaptiveFeedIn)); // Wait for cycle start to acknowledge tool change. - *this->pToolChangedOut = (*this->pToolChangeIn && riseCycleStart) - || (*this->pToolChangedOut && *this->pToolChangeIn); + hal_set_bool(this->pToolChangedOut, (hal_get_bool(this->pToolChangeIn) && riseCycleStart) + || (hal_get_bool(this->pToolChangedOut) && hal_get_bool(this->pToolChangeIn))); // Indicates waiting for user to press cycle start. - *this->pWaitUserOut = *this->pFeedHoldOut - || (*this->pToolChangeIn && !*this->pToolChangedOut); + hal_set_bool(this->pWaitUserOut, hal_get_bool(this->pFeedHoldOut) + || (hal_get_bool(this->pToolChangeIn) && !hal_get_bool(this->pToolChangedOut))); // Turn coolant off during tool changes. - *this->pMistOnOut = *this->pMistOnIn && !*this->pToolChangeIn; - *this->pFloodOnOut = *this->pFloodOnIn && !*this->pToolChangeIn; + hal_set_bool(this->pMistOnOut, hal_get_bool(this->pMistOnIn) && !hal_get_bool(this->pToolChangeIn)); + hal_set_bool(this->pFloodOnOut, hal_get_bool(this->pFloodOnIn) && !hal_get_bool(this->pToolChangeIn)); } @@ -826,19 +830,19 @@ static void Plc_RefreshLimits(Plc *this, long period) { (void)period; - Limit_Refresh(&this->xLimit, *this->pLimitOverrideIn); - Limit_Refresh(&this->yLimit, *this->pLimitOverrideIn); + Limit_Refresh(&this->xLimit, hal_get_bool(this->pLimitOverrideIn)); + Limit_Refresh(&this->yLimit, hal_get_bool(this->pLimitOverrideIn)); // Condition Z limits with override in manual mode. - *this->pZLimitPosOut = *this->pZLimitPosIn - && !(*this->pZJogEnIn && *this->pLimitOverrideIn); - *this->pZLimitNegOut = *this->pZLimitNegIn - && !(*this->pZJogEnIn && *this->pLimitOverrideIn); + hal_set_bool(this->pZLimitPosOut, hal_get_bool(this->pZLimitPosIn) + && !(hal_get_bool(this->pZJogEnIn) && hal_get_bool(this->pLimitOverrideIn))); + hal_set_bool(this->pZLimitNegOut, hal_get_bool(this->pZLimitNegIn) + && !(hal_get_bool(this->pZJogEnIn) && hal_get_bool(this->pLimitOverrideIn))); // Generate limit active signal for pilot lamp. - *this->pLimitActiveOut = Limit_IsActive(&this->xLimit) + hal_set_bool(this->pLimitActiveOut, Limit_IsActive(&this->xLimit) || Limit_IsActive(&this->yLimit) - || *this->pZLimitPosIn || *this->pZLimitNegIn; + || hal_get_bool(this->pZLimitPosIn) || hal_get_bool(this->pZLimitNegIn)); } @@ -850,7 +854,7 @@ Plc_RefreshAmps(Plc *this, long period) pAmp = this->amps; for(i = 0; i < NUM_AXIS; i++, pAmp++){ - Amp_Refresh(pAmp, period, *(this->ampReadyDelay)); + Amp_Refresh(pAmp, period, hal_get_ui32(this->ampReadyDelay)); } } @@ -862,10 +866,10 @@ Plc_RefreshSpindle(Plc *this, long period) switch(this->spindleState){ // Spindle is off, brake is on. case SS_OFF: - if(!*this->pBrakeEnIn){ + if(!hal_get_bool(this->pBrakeEnIn)){ this->spindleState = SS_WAIT_BRAKE_OFF; - *this->pBrakeEnOut = 0; - Timer_SetTimeout(&this->spindleTimer, *(this->brakeOffDelay)); + hal_set_bool(this->pBrakeEnOut, 0); + Timer_SetTimeout(&this->spindleTimer, hal_get_ui32(this->brakeOffDelay)); Timer_Enable(&this->spindleTimer, TM_ONE_SHOT); } break; @@ -873,56 +877,56 @@ Plc_RefreshSpindle(Plc *this, long period) // Spindle is off, brake has been turned off. Wait at least a brake off // delay before turning spindle on. case SS_WAIT_BRAKE_OFF: - if(*this->pBrakeEnIn){ + if(hal_get_bool(this->pBrakeEnIn)){ this->spindleState = SS_OFF; - *this->pBrakeEnOut = 1; + hal_set_bool(this->pBrakeEnOut, 1); Timer_Disable(&this->spindleTimer); - }else if((*this->pSpindleSpeedIn != 0.0) + }else if((hal_get_real(this->pSpindleSpeedIn) != 0.0) && !Timer_IsEnabled(&this->spindleTimer)){ this->spindleState = SS_WAIT_ON; - if(*this->pSpindleSpeedIn > *(this->spindleLoToHi) - || (*this->pSpindleSpeedIn < 0.0 - && *this->pSpindleSpeedIn >= -*(this->spindleLoToHi))){ + if(hal_get_real(this->pSpindleSpeedIn) > hal_get_real(this->spindleLoToHi) + || (hal_get_real(this->pSpindleSpeedIn) < 0.0 + && hal_get_real(this->pSpindleSpeedIn) >= -hal_get_real(this->spindleLoToHi))){ - *this->pSpindleFwdOut = 1; + hal_set_bool(this->pSpindleFwdOut, 1); }else{ - *this->pSpindleRevOut = 1; + hal_set_bool(this->pSpindleRevOut, 1); } } break; // Spindle has been turned on. Wait for confirmation that it is running. case SS_WAIT_ON: - if(*this->pSpindleIsOnIn){ + if(hal_get_bool(this->pSpindleIsOnIn)){ this->spindleState = SS_ON; - }else if(*this->pSpindleSpeedIn == 0.0){ + }else if(hal_get_real(this->pSpindleSpeedIn) == 0.0){ this->spindleState = SS_WAIT_BRAKE_OFF; - *this->pSpindleFwdOut = 0; - *this->pSpindleRevOut = 0; + hal_set_bool(this->pSpindleFwdOut, 0); + hal_set_bool(this->pSpindleRevOut, 0); } break; // Spindle is running. case SS_ON: - if(*this->pSpindleSpeedIn == 0.0){ + if(hal_get_real(this->pSpindleSpeedIn) == 0.0){ this->spindleState = SS_WAIT_OFF; - *this->pSpindleFwdOut = 0; - *this->pSpindleRevOut = 0; + hal_set_bool(this->pSpindleFwdOut, 0); + hal_set_bool(this->pSpindleRevOut, 0); } break; // Spindle has been turned off. Wait for confirmation. case SS_WAIT_OFF: - if(!*this->pSpindleIsOnIn){ + if(!hal_get_bool(this->pSpindleIsOnIn)){ this->spindleState = SS_WAIT_BRAKE_ON; - Timer_SetTimeout(&this->spindleTimer, *(this->brakeOnDelay)); + Timer_SetTimeout(&this->spindleTimer, hal_get_ui32(this->brakeOnDelay)); Timer_Enable(&this->spindleTimer, TM_ONE_SHOT); } break; @@ -936,16 +940,16 @@ Plc_RefreshSpindle(Plc *this, long period) default: this->spindleState = SS_WAIT_OFF; - *this->pSpindleFwdOut = 0; - *this->pSpindleRevOut = 0; + hal_set_bool(this->pSpindleFwdOut, 0); + hal_set_bool(this->pSpindleRevOut, 0); } // Condition spindle increase and decrease so they are disabled when // spindle is not running and both cannot be enabled at the same time. - *this->pSpindleIncOut = *this->pSpindleIncIn && !*this->pSpindleDecIn - && *this->pSpindleIsOnIn; - *this->pSpindleDecOut = *this->pSpindleDecIn && !*this->pSpindleIncIn - && *this->pSpindleIsOnIn; + hal_set_bool(this->pSpindleIncOut, hal_get_bool(this->pSpindleIncIn) && !hal_get_bool(this->pSpindleDecIn) + && hal_get_bool(this->pSpindleIsOnIn)); + hal_set_bool(this->pSpindleDecOut, hal_get_bool(this->pSpindleDecIn) && !hal_get_bool(this->pSpindleIncIn) + && hal_get_bool(this->pSpindleIsOnIn)); } @@ -957,8 +961,8 @@ Plc_RefreshJog(Plc *this, long period) // Jog scale. for(i = 0; i < NUM_JOG_SEL; i++){ - if(*this->pJogSelIn[i]){ - *this->pJogScaleOut = *(this->jogScale[i]); + if(hal_get_bool(this->pJogSelIn[i])){ + hal_set_real(this->pJogScaleOut, hal_get_real(this->jogScale[i])); break; } } @@ -974,26 +978,26 @@ Limit_Export(Limit *this, int compId, int id, char axis) { int error; - error = hal_pin_float_newf(HAL_IN, &this->pPositionIn, compId, + error = hal_pin_new_real(compId, HAL_IN, &this->pPositionIn, 0.0, "boss_plc.%d.%c-position-in", id, axis); if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pJogEnIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pJogEnIn, 0, "boss_plc.%d.%c-jog-en-in", id, axis); } if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pIn, 0, "boss_plc.%d.%c-limit-in", id, axis); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pPosOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pPosOut, 0, "boss_plc.%d.%c-limit-pos-out", id, axis); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pNegOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pNegOut, 0, "boss_plc.%d.%c-limit-neg-out", id, axis); } @@ -1011,72 +1015,72 @@ Limit_Init(Limit *this) static BOOL Limit_IsActive(Limit *this) { - return(*this->pIn); + return hal_get_bool(this->pIn); } static void -Limit_Refresh(Limit *this, hal_bit_t override) +Limit_Refresh(Limit *this, rtapi_bool override) { switch(this->state){ case LS_INIT: default: this->state = LS_ON_LIMIT; this->limitNeg = this->limitPos = 1; - this->position = *this->pPositionIn; + this->position = hal_get_real(this->pPositionIn); // Fall through. case LS_ON_LIMIT: - if(*this->pIn == 0){ + if(hal_get_bool(this->pIn) == 0){ this->limitNeg = this->limitPos = 0; - if(*this->pPositionIn == this->position) + if(hal_get_real(this->pPositionIn) == this->position) this->state = LS_NO_MOTION; - else if(*this->pPositionIn > this->position) + else if(hal_get_real(this->pPositionIn) > this->position) this->state = LS_POS_MOTION; - else if(*this->pPositionIn < this->position) + else if(hal_get_real(this->pPositionIn) < this->position) this->state = LS_NEG_MOTION; } break; case LS_NO_MOTION: - if(*this->pIn){ + if(hal_get_bool(this->pIn)){ this->state = LS_ON_LIMIT; this->limitNeg = this->limitPos = 1; - }else if(*this->pPositionIn > this->position){ + }else if(hal_get_real(this->pPositionIn) > this->position){ this->state = LS_POS_MOTION; - }else if(*this->pPositionIn < this->position){ + }else if(hal_get_real(this->pPositionIn) < this->position){ this->state = LS_NEG_MOTION; } break; case LS_POS_MOTION: - if(*this->pIn){ + if(hal_get_bool(this->pIn)){ this->state = LS_ON_LIMIT; this->limitPos = 1; - }else if(*this->pPositionIn == this->position){ + }else if(hal_get_real(this->pPositionIn) == this->position){ this->state = LS_NO_MOTION; - }else if(*this->pPositionIn < this->position){ + }else if(hal_get_real(this->pPositionIn) < this->position){ this->state = LS_NEG_MOTION; } break; case LS_NEG_MOTION: - if(*this->pIn){ + if(hal_get_bool(this->pIn)){ this->state = LS_ON_LIMIT; this->limitNeg = 1; - }else if(*this->pPositionIn == this->position){ + }else if(hal_get_real(this->pPositionIn) == this->position){ this->state = LS_NO_MOTION; - }else if(*this->pPositionIn > this->position){ + }else if(hal_get_real(this->pPositionIn) > this->position){ this->state = LS_POS_MOTION; } break; } - this->position = *this->pPositionIn; + this->position = hal_get_real(this->pPositionIn); // Condition limits with override in manual mode. - *this->pPosOut = this->limitPos && !(*this->pJogEnIn && override); - *this->pNegOut = this->limitNeg && !(*this->pJogEnIn && override); + hal_set_bool(this->pPosOut, this->limitPos && !(hal_get_bool(this->pJogEnIn) && override)); + hal_set_bool(this->pNegOut, this->limitNeg && !(hal_get_bool(this->pJogEnIn) && override)); } @@ -1089,16 +1093,16 @@ Amp_Export(Amp *this, int compId, int id, char axis) { int error; - error = hal_pin_bit_newf(HAL_IN, &this->pEnableIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pEnableIn, 0, "boss_plc.%d.%c-amp-enable-in", id, axis); if(!error){ - error = hal_pin_bit_newf(HAL_IN, &this->pReadyIn, compId, + error = hal_pin_new_bool(compId, HAL_IN, &this->pReadyIn, 0, "boss_plc.%d.%c-amp-ready-in", id, axis); } if(!error){ - error = hal_pin_bit_newf(HAL_OUT, &this->pFaultOut, compId, + error = hal_pin_new_bool(compId, HAL_OUT, &this->pFaultOut, 0, "boss_plc.%d.%c-amp-fault-out", id, axis); } @@ -1118,11 +1122,11 @@ Amp_Init(Amp *this) static void -Amp_Refresh(Amp *this, long period, hal_u32_t readyDelay) +Amp_Refresh(Amp *this, long period, rtapi_u32 readyDelay) { Timer_Update(&this->timer, period); - if(*this->pEnableIn){ + if(hal_get_bool(this->pEnableIn)){ if(!this->lastEnable){ Timer_SetTimeout(&this->timer, readyDelay); Timer_Enable(&this->timer, TM_ONE_SHOT); @@ -1131,10 +1135,10 @@ Amp_Refresh(Amp *this, long period, hal_u32_t readyDelay) Timer_Disable(&this->timer); } - *this->pFaultOut = *this->pEnableIn && !*this->pReadyIn - && !Timer_IsEnabled(&this->timer); + hal_set_bool(this->pFaultOut, hal_get_bool(this->pEnableIn) && !hal_get_bool(this->pReadyIn) + && !Timer_IsEnabled(&this->timer)); - this->lastEnable = *this->pEnableIn; + this->lastEnable = hal_get_bool(this->pEnableIn); } @@ -1199,7 +1203,7 @@ Timer_Update(Timer *this, long period) static void -Timer_SetTimeout(Timer *this, hal_u32_t timeout) +Timer_SetTimeout(Timer *this, rtapi_u32 timeout) { this->count = 0; this->timeout = timeout; diff --git a/src/hal/components/carousel.comp b/src/hal/components/carousel.comp index 06de3ee31d4..354605f1d1f 100644 --- a/src/hal/components/carousel.comp +++ b/src/hal/components/carousel.comp @@ -101,52 +101,52 @@ at the completion of the tool search and at the same time the reverse duty/cycle velocity value will be sent to the motor-vel pin. """; -pin in signed pocket-number """The pocket to move to when the .enable pin goes high. If the value +pin in si32 pocket-number """The pocket to move to when the .enable pin goes high. If the value passed is higher than the number of pockets specified in the "pockets" modparam then modulo arithmetic is used. This is intended to allow the use of multiple tools in the same holder, as is sometimes useful with lathes."""; -pin in bit enable "Set this pin high to start movement. Setting it low will stop movement"; -pin out bit active "indicates that the component is active"; -pin out bit ready "This pin goes high when the carousel is in-position"; -pin in bit strobe = 1 """Use this pin to indicate that the position feedback is valid. Often +pin in bool enable "Set this pin high to start movement. Setting it low will stop movement"; +pin out bool active "indicates that the component is active"; +pin out bool ready "This pin goes high when the carousel is in-position"; +pin in bool strobe = 1 """Use this pin to indicate that the position feedback is valid. Often provided by binary encoders"""; -pin in bit parity_ """Some encoders supply a parity bit, if this is connected then the -parity-error output bit will indicate parity errors"""; -pin in bit sense-# [32:personality] """Carousel position feedback pins. In 'index' mode there +pin in bool parity_ """Some encoders supply a parity bit, if this is connected then the +parity-error output bool will indicate parity errors"""; +pin in bool sense-# [32:personality] """Carousel position feedback pins. In 'index' mode there will be only 2 pins. sense-0 is the index and sense-1 is the pocket sensor."""; -pin in float rev-pulse """The duration in seconds for which a ratchet changer (Boxford, Emco) +pin in real rev-pulse """The duration in seconds for which a ratchet changer (Boxford, Emco) should pulse the reverse pin to lock the holder"""; -pin in float fwd-dc "Velocity or duty cycle when forwards rotation is desired"; -pin in float rev-dc "Velocity or duty cycle when reverse rotation is desired"; -pin in float hold-dc "Duty cycle when carousel is in-position (to hold against stop)"; -pin in float align-dc """Use this pin to set the speed of a slower alignment move once the changer is in position. Such a system almost +pin in real fwd-dc "Velocity or duty cycle when forwards rotation is desired"; +pin in real rev-dc "Velocity or duty cycle when reverse rotation is desired"; +pin in real hold-dc "Duty cycle when carousel is in-position (to hold against stop)"; +pin in real align-dc """Use this pin to set the speed of a slower alignment move once the changer is in position. Such a system almost certainly needs decel-time setting too"""; -pin in float decel-time "Time to wait for carousel to stop before final alignment and position check"; -pin in signed counts "Connect to the rawcounts of an encoder or a stepgen in 'counts' mode"; -pin in signed scale = 100 "The number of stepgen or encoder counts between successive pockets"; -pin in signed width = 10 "How far each side of the exact scale to signal a new pocket"; -pin in signed home-offset = 0 "The offset (in counts) between the index and pocket 1"; -pin io bit index-enable "Used to home to an encoder index"; -pin in bit jog-fwd "Jog the carousel forwards one tool position"; -pin in bit jog-rev """Jog the carousel in reverse (only if dir = 2). +pin in real decel-time "Time to wait for carousel to stop before final alignment and position check"; +pin in si32 counts "Connect to the rawcounts of an encoder or a stepgen in 'counts' mode"; +pin in si32 scale = 100 "The number of stepgen or encoder counts between successive pockets"; +pin in si32 width = 10 "How far each side of the exact scale to signal a new pocket"; +pin in si32 home-offset = 0 "The offset (in counts) between the index and pocket 1"; +pin io bool index-enable "Used to home to an encoder index"; +pin in bool jog-fwd "Jog the carousel forwards one tool position"; +pin in bool jog-rev """Jog the carousel in reverse (only if dir = 2). It is very important that these pins should be debounced and should probably also be interlocked to only operate when the machine is idle."""; -pin out bit motor-fwd "Indicates the motor should run forwards (bigger numbers)"; -pin out bit motor-rev "Indicates the motor should run reverse."; -pin out bit parity-error "Indicates a parity error"; -pin out signed current-position "This pin indicates the current position feedback"; -pin out float motor-vel "The duty-cycle or velocity to drive a DC motor or stepgen"; -pin out bit homed = 0 "Shows that homing is complete. Only used in index and edge modes"; -pin in bit unhome = 0 "Should only really be necessary for testing"; -pin out float counts-target "Target position for a stepgen or external PID controller"; - -param r signed state = 0 "Current component state"; -param r bit homing = 0 "Shows that homing is in progress. Only used for index mode"; -param r float timer "Shows the value of the internal timer"; -param r signed motor-dir "Internal tag for search direction"; -param r signed counts-offset "Internal offset of index pin"; -param rw unsigned debounce "How many thread cycles to wait for the position to stabilise"; -param r signed target "Current target pocket, debug"; +pin out bool motor-fwd "Indicates the motor should run forwards (bigger numbers)"; +pin out bool motor-rev "Indicates the motor should run reverse."; +pin out bool parity-error "Indicates a parity error"; +pin out si32 current-position "This pin indicates the current position feedback"; +pin out real motor-vel "The duty-cycle or velocity to drive a DC motor or stepgen"; +pin out bool homed = 0 "Shows that homing is complete. Only used in index and edge modes"; +pin in bool unhome = 0 "Should only really be necessary for testing"; +pin out real counts-target "Target position for a stepgen or external PID controller"; + +param r si32 state = 0 "Current component state"; +param r bool homing = 0 "Shows that homing is in progress. Only used for index mode"; +param r real timer "Shows the value of the internal timer"; +param r si32 motor-dir "Internal tag for search direction"; +param r si32 counts-offset "Internal offset of index pin"; +param rw ui32 debounce "How many thread cycles to wait for the position to stabilise"; +param r si32 target "Current target pocket, debug"; option count_function; option extra_setup; @@ -160,7 +160,7 @@ variable int inst_pockets; variable int inst_code; variable int inst_parity; variable int old_index = 0; -param r signed base_counts = 0; +param r si32 base_counts = 0; variable int old_unhome = 0; function _ ; @@ -294,15 +294,15 @@ FUNCTION(_){ } if (strobe) { - current_position = new_pos; - parity_error = (pcalc != (inst_parity ^ parity_)); + current_position_set(new_pos); + parity_error_set(pcalc != (inst_parity ^ parity_)); } mod_pocket = ((pocket_number - 1) % inst_pockets) + 1; // mod is odd with negatives, so just in case if (mod_pocket < 1) mod_pocket = 1; if (mod_pocket > inst_pockets) mod_pocket = inst_pockets; - if (unhome && ! old_unhome) homed = 0; + if (unhome && ! old_unhome) homed_set(0); old_unhome = unhome; enum State { @@ -321,88 +321,88 @@ FUNCTION(_){ }; switch (state){ case WAITING: // waiting at start - motor_dir = 0; + motor_dir_set(0); if (jog_fwd || (jog_rev && inst_dir == 2)) { if ((inst_code == 'I' || inst_code == 'E' || inst_code == 'C') && ! homed){ - state = HOME_START; + state_set(HOME_START); break; } - target = current_position + jog_fwd - jog_rev; - counts_target += scale * (target - current_position); - if (target > inst_pockets ) target = 1; - if (target < 1) target = inst_pockets; + target_set(current_position + jog_fwd - jog_rev); + counts_target_set(counts_target + scale * (target - current_position)); + if (target > inst_pockets ) target_set(1); + if (target < 1) target_set(inst_pockets); if (jog_fwd){ - motor_fwd = 1; - motor_rev = 0; - motor_vel = fwd_dc; - motor_dir = 1; + motor_fwd_set(1); + motor_rev_set(0); + motor_vel_set(fwd_dc); + motor_dir_set(1); } if (jog_rev){ - motor_fwd = 0; - motor_rev = 1; - motor_vel = rev_dc; - motor_dir = -1; + motor_fwd_set(0); + motor_rev_set(1); + motor_vel_set(rev_dc); + motor_dir_set(-1); } - active = 1; - state = JOG; + active_set(1); + state_set(JOG); break; } - motor_vel = hold_dc; + motor_vel_set(hold_dc); if (! enable) return ; - active = 1; + active_set(1); if ((inst_code == 'I' || inst_code == 'E' || inst_code == 'C') && ! homed){ - state = HOME_START; + state_set(HOME_START); break; } - state = DIR_CHOOSE; - ready = 0; + state_set(DIR_CHOOSE); + ready_set(0); /* Fallthrough */ case DIR_CHOOSE: // choose direction if (mod_pocket < 1 || mod_pocket > inst_pockets) { - state = WAITING; + state_set(WAITING); return; } if (inst_dir == 2){ if (current_position < mod_pocket){ if (mod_pocket - current_position > (inst_pockets / 2)) { - motor_fwd = 0; - motor_rev = 1; - motor_vel = rev_dc; - motor_dir = -1; - counts_target += (mod_pocket - current_position - inst_pockets) * scale; + motor_fwd_set(0); + motor_rev_set(1); + motor_vel_set(rev_dc); + motor_dir_set(-1); + counts_target_set(counts_target + (mod_pocket - current_position - inst_pockets) * scale); } else { - motor_fwd = 1; - motor_rev = 0; - motor_vel = fwd_dc; - motor_dir = 1; - counts_target += (mod_pocket - current_position ) * scale; + motor_fwd_set(1); + motor_rev_set(0); + motor_vel_set(fwd_dc); + motor_dir_set(1); + counts_target_set(counts_target + (mod_pocket - current_position ) * scale); } } else { if (current_position - mod_pocket > (inst_pockets / 2)) { - motor_fwd = 1; - motor_rev = 0; - motor_vel = fwd_dc; - motor_dir = 1; - counts_target += (mod_pocket - current_position + inst_pockets) * scale; + motor_fwd_set(1); + motor_rev_set(0); + motor_vel_set(fwd_dc); + motor_dir_set(1); + counts_target_set(counts_target + (mod_pocket - current_position + inst_pockets) * scale); } else { - motor_fwd = 0; - motor_rev = 1; - motor_vel = rev_dc; - motor_dir = -1; - counts_target += (mod_pocket - current_position) * scale; + motor_fwd_set(0); + motor_rev_set(1); + motor_vel_set(rev_dc); + motor_dir_set(-1); + counts_target_set(counts_target + (mod_pocket - current_position) * scale); } } } else { - counts_target += (mod_pocket - current_position) * scale; + counts_target_set(counts_target + (mod_pocket - current_position) * scale); if (counts_target < counts ) { - counts_target += scale * inst_pockets; + counts_target_set(counts_target + scale * inst_pockets); } - motor_fwd = 1; - motor_rev = 0; - motor_vel = fwd_dc; - motor_dir = 1; + motor_fwd_set(1); + motor_rev_set(0); + motor_vel_set(fwd_dc); + motor_dir_set(1); } - state = MOVE; + state_set(MOVE); /* Fallthrough */ case MOVE: // moving if ((current_position != mod_pocket) && enable){ @@ -412,67 +412,67 @@ FUNCTION(_){ return; } if (rev_pulse > 0){ - motor_fwd = 0; - motor_rev = 1; - motor_vel = rev_dc; - timer = rev_pulse; - state = REV_TIME; + motor_fwd_set(0); + motor_rev_set(1); + motor_vel_set(rev_dc); + timer_set(rev_pulse); + state_set(REV_TIME); } else if (decel_time > 0) { // stop and prepare for alignment - motor_vel = 0; - timer = decel_time; - state = WAIT_STOP; + motor_vel_set(0); + timer_set(decel_time); + state_set(WAIT_STOP); } else { - motor_fwd = 0; - motor_rev = 0; - motor_vel = hold_dc; - active = 0; - if (enable && current_position == mod_pocket) ready = 1; - state = WAIT_ENABLE_FALSE; + motor_fwd_set(0); + motor_rev_set(0); + motor_vel_set(hold_dc); + active_set(0); + if (enable && current_position == mod_pocket) ready_set(1); + state_set(WAIT_ENABLE_FALSE); } break; case REV_TIME: // timed reverse pulse - timer -= fperiod; + timer_set(timer - fperiod); if (timer > 0) return; - state = WAIT_ENABLE_FALSE; - motor_fwd = 0; - motor_rev = 0; - motor_vel = hold_dc; - active = 0; - if (enable) ready = 1; + state_set(WAIT_ENABLE_FALSE); + motor_fwd_set(0); + motor_rev_set(0); + motor_vel_set(hold_dc); + active_set(0); + if (enable) ready_set(1); break; case WAIT_STOP: //Waiting for carousel to stop - timer -= fperiod; + timer_set(timer - fperiod); if (timer > 0) return; if (align_dc == 0){ - state = FINAL_MOVE_BACK; + state_set(FINAL_MOVE_BACK); break; } - motor_vel = -align_dc; + motor_vel_set(-align_dc); if (motor_dir == 1) { - state = BACK_UP_INDEX; + state_set(BACK_UP_INDEX); } else { - state = BACK_OFF_INDEX; + state_set(BACK_OFF_INDEX); } break; case BACK_UP_INDEX: //backing up to index if ( align_pin == 0 ) return; - state = BACK_OFF_INDEX; + state_set(BACK_OFF_INDEX); break; case BACK_OFF_INDEX: //backing back off of index if ( align_pin != 0 ) return; - motor_vel = align_dc; - state = FINAL_MOVE_BACK; + motor_vel_set(align_dc); + state_set(FINAL_MOVE_BACK); break; case FINAL_MOVE_BACK: // final move back to index if ( align_pin == 0 ) return; - motor_fwd = 0; - motor_rev = 0; - motor_vel = hold_dc; - active = 0; + motor_fwd_set(0); + motor_rev_set(0); + motor_vel_set(hold_dc); + active_set(0); // final safety check for in-position - if (enable && current_position == mod_pocket) ready = 1; - state = WAIT_ENABLE_FALSE; + if (enable && current_position == mod_pocket) ready_set(1); + state_set(WAIT_ENABLE_FALSE); break; case WAIT_ENABLE_FALSE: //waiting for enable to go false if (! ready && ! err_once){ @@ -481,19 +481,19 @@ FUNCTION(_){ } if (enable) return; err_once = 0; - state = WAITING; + state_set(WAITING); break; case HOME_START: // start of homing - homed = 0; - homing = 1; - motor_fwd = 1; - motor_rev = 0; - motor_vel = fwd_dc; - motor_dir = 1; - index_enable = 1; - counts_target += scale * inst_pockets; + homed_set(0); + homing_set(1); + motor_fwd_set(1); + motor_rev_set(0); + motor_vel_set(fwd_dc); + motor_dir_set(1); + index_enable_set(1); + counts_target_set(counts_target + scale * inst_pockets); old_index = 1; // ensure 0->1 cycle of home sensor - state = HOME_WAIT; + state_set(HOME_WAIT); /* Fallthrough */ case HOME_WAIT: ;// waiting for index & pulse int ind = 0; @@ -503,20 +503,20 @@ FUNCTION(_){ ind = (sense(0) && sense(1)); } if ( ! index_enable || ((! old_index) && ind)){ // index found - current_position = 1; - homed = 1; - homing = 0; - active = 0; - motor_fwd = 0; - motor_rev = 0; - motor_vel = 0; - base_counts = counts - home_offset; - counts_target = base_counts; + current_position_set(1); + homed_set(1); + homing_set(0); + active_set(0); + motor_fwd_set(0); + motor_rev_set(0); + motor_vel_set(0); + base_counts_set(counts - home_offset); + counts_target_set(base_counts); if ( align_dc == 0) { - state = WAITING; + state_set(WAITING); } else { - timer = decel_time; - state = WAIT_STOP; + timer_set(decel_time); + state_set(WAIT_STOP); } } old_index = ind; @@ -529,17 +529,17 @@ FUNCTION(_){ return; } if (align_dc != 0 && ! align_pin) return; - motor_fwd = 0; - motor_rev = 0; - motor_vel = hold_dc; - active = 0; + motor_fwd_set(0); + motor_rev_set(0); + motor_vel_set(hold_dc); + active_set(0); if (jog_fwd || jog_rev) return; // require button release to jog again if (align_dc != 0) { - motor_vel = -align_dc; - timer = decel_time; - state = WAIT_STOP; + motor_vel_set(-align_dc); + timer_set(decel_time); + state_set(WAIT_STOP); } else { - state = WAITING; + state_set(WAITING); } break; } diff --git a/src/hal/components/charge_pump.comp b/src/hal/components/charge_pump.comp index 0593fdba7b9..d5690106f9d 100644 --- a/src/hal/components/charge_pump.comp +++ b/src/hal/components/charge_pump.comp @@ -17,10 +17,10 @@ component charge_pump "Create a square-wave for the 'charge pump' input of some controller boards"; option singleton yes; -pin out bit out "Square wave if 'enable' is TRUE or unconnected, low if 'enable' is FALSE"; -pin out bit out-2 "Square wave at half the frequency of 'out'"; -pin out bit out-4 "Square wave at a quarter of the frequency of 'out'"; -pin in bit enable = TRUE "If FALSE, forces all 'out' pins to be low"; +pin out bool out "Square wave if 'enable' is TRUE or unconnected, low if 'enable' is FALSE"; +pin out bool out-2 "Square wave at half the frequency of 'out'"; +pin out bool out-4 "Square wave at a quarter of the frequency of 'out'"; +pin in bool enable = TRUE "If FALSE, forces all 'out' pins to be low"; function _ "Toggle the output bit (if enabled)"; description """ The 'Charge Pump' should be added to the base thread function. @@ -37,12 +37,12 @@ FUNCTION(_) { static int acc; if ( enable ) { acc++; - out = (acc & 0x1); - out_2 = (acc & 0x2); - out_4 = (acc & 0x4); + out_set((acc & 0x1)); + out_2_set((acc & 0x2)); + out_4_set((acc & 0x4)); } else { - out = 0; - out_2 = 0; - out_4 = 0; + out_set(0); + out_2_set(0); + out_4_set(0); } } diff --git a/src/hal/components/clarke2.comp b/src/hal/components/clarke2.comp index 0c2bc9e665f..f86a8fdae01 100644 --- a/src/hal/components/clarke2.comp +++ b/src/hal/components/clarke2.comp @@ -12,10 +12,10 @@ B of the input. Since the H (homopolar) output will always be zero in this case, it is not generated."""; see_also """*clarke3*(9) for the general case, *clarkeinv*(9) for the inverse transform."""; -pin in float a; -pin in float b "first two phases of three phase input"; -pin out float x; -pin out float y "cartesian components of output"; +pin in real a; +pin in real b "first two phases of three phase input"; +pin out real x; +pin out real y "cartesian components of output"; option period no; function _; license "GPL"; @@ -31,6 +31,6 @@ author "John Kasunich"; #define K2 (1.154700538379250) /* 2/sqrt(3) */ FUNCTION(_) { - x = a; - y = K1*a + K2*b; + rtapi_real a_ = x_set(a); + y_set(K1*a_ + K2*b); } diff --git a/src/hal/components/clarke3.comp b/src/hal/components/clarke3.comp index 76efd7beed5..b2842f6e0a7 100644 --- a/src/hal/components/clarke3.comp +++ b/src/hal/components/clarke3.comp @@ -9,12 +9,12 @@ three phases are known to sum to zero, see *clarke2* for a simpler version."""; see_also """*clarke2*(9) for the 'a+b+c=0' case, *clarkeinv*(9) for the inverse transform."""; -pin in float a; -pin in float b; -pin in float c "three phase input vector"; -pin out float x; -pin out float y "cartesian components of output"; -pin out float h "homopolar component of output"; +pin in real a; +pin in real b; +pin in real c "three phase input vector"; +pin out real x; +pin out real y "cartesian components of output"; +pin out real h "homopolar component of output"; option period no; function _; license "GPL"; @@ -32,9 +32,12 @@ author "John Kasunich"; #define K4 (0.471404520791032) /* sqrt(2)/3 */ FUNCTION(_) { - x = K1*a - K2*(b+c); - y = K3*(b-c); - h = K4*(a+b+c); + rtapi_real a_ = a; + rtapi_real b_ = b; + rtapi_real c_ = c; + x_set(K1*a_ - K2*(b_+c_)); + y_set(K3*(b_-c_)); + h_set(K4*(a_+b_+c_)); } diff --git a/src/hal/components/clarkeinv.comp b/src/hal/components/clarkeinv.comp index 0592b00ea70..6d6107eadb5 100644 --- a/src/hal/components/clarkeinv.comp +++ b/src/hal/components/clarkeinv.comp @@ -3,13 +3,13 @@ description """The inverse Clarke transform can be used rotate a vector quantity and then translate it from Cartesian coordinate system to a three phase system (three components 120 degrees apart)."""; see_also """*clarke2*(9) and *clarke3*(9) for the forward transform."""; -pin in float x; -pin in float y "cartesian components of input"; -pin in float h "homopolar component of input (usually zero)"; -pin in float theta "rotation angle: 0.00 to 1.00 = 0 to 360 degrees"; -pin out float a; -pin out float b; -pin out float c "three phase output vector"; +pin in real x; +pin in real y "cartesian components of input"; +pin in real h "homopolar component of input (usually zero)"; +pin in real theta "rotation angle: 0.00 to 1.00 = 0 to 360 degrees"; +pin out real a; +pin out real b; +pin out real c "three phase output vector"; option period no; function _; license "GPL"; @@ -28,7 +28,7 @@ author "John Kasunich"; #define rev2rad (6.283185308) /* 2 * pi */ FUNCTION(_) { - double xr, yr, rads, costheta, sintheta; + rtapi_real xr, yr, rads, costheta, sintheta; // rotate it rads = theta * rev2rad; @@ -38,7 +38,8 @@ FUNCTION(_) { yr = x * sintheta + y * costheta; /* transform to three phase */ - a = xr + K3*h; - b = -K1*xr + K2*yr + K3*h; - c = -K1*xr - K2*yr + K3*h; + rtapi_real h_ = h; + a_set(xr + K3*h_); + b_set(-K1*xr + K2*yr + K3*h_); + c_set(-K1*xr - K2*yr + K3*h_); } diff --git a/src/hal/components/comp.comp b/src/hal/components/comp.comp index 4ab496b293b..cf27ca469e0 100644 --- a/src/hal/components/comp.comp +++ b/src/hal/components/comp.comp @@ -1,10 +1,10 @@ component comp "Two input comparator with hysteresis"; -pin in float in0 "Inverting input to the comparator"; -pin in float in1 "Non-inverting input to the comparator"; -pin out bit out "Normal output. True when *in1* > *in0* (see parameter *hyst* for details)"; -pin out bit equal "Match output. True when difference between *in1* and *in0* is less than *hyst*/2"; +pin in real in0 "Inverting input to the comparator"; +pin in real in1 "Non-inverting input to the comparator"; +pin out bool out "Normal output. True when *in1* > *in0* (see parameter *hyst* for details)"; +pin out bool equal "Match output. True when difference between *in1* and *in0* is less than *hyst*/2"; -param rw float hyst=0.0 """Hysteresis of the comparator (default 0.0) +param rw real hyst=0.0 """Hysteresis of the comparator (default 0.0) With zero hysteresis, the output is true when *in1* > *in0*. With nonzero hysteresis, the output switches on and off at two different values, @@ -18,16 +18,16 @@ license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - double tmp = in1 - in0; - double halfhyst = 0.5 * hyst; + rtapi_real tmp = in1 - in0; + rtapi_real halfhyst = 0.5 * hyst; if(tmp < -halfhyst) { - out = 0; - equal = 0; + out_set(0); + equal_set(0); } else if(tmp > halfhyst){ - out = 1; - equal = 0; + out_set(1); + equal_set(0); } else { - equal = 1; + equal_set(1); } } diff --git a/src/hal/components/conv.comp.in b/src/hal/components/conv.comp.in index 4e2d3adf592..cd0068f46c3 100644 --- a/src/hal/components/conv.comp.in +++ b/src/hal/components/conv.comp.in @@ -1,8 +1,8 @@ -component conv_@IN@_@OUT@ "Convert a value from @IN@ to @OUT@"; +component conv_@XIN@_@XOUT@ "Convert a value from @IN@ to @OUT@"; pin in @IN@ in; pin out @OUT@ out; -@CC@pin out bit out_of_range "TRUE when 'in' is not in the range of @OUT@"; -@CC@param rw bit clamp """If TRUE, then clamp to the range of @OUT@. If FALSE, then allow the value to "wrap around"."""; +@CC@pin out bool out_of_range "TRUE when 'in' is not in the range of @OUT@"; +@CC@param rw bool clamp_ """If TRUE, then clamp to the range of @OUT@. If FALSE, then allow the value to "wrap around"."""; option period no; function _ "Update 'out' based on 'in'"; license "GPL"; @@ -12,17 +12,17 @@ author "Jeff Epler"; #include FUNCTION(_) { @TYPI@ val = in; -@CC@ if(clamp) { +@CC@ if(clamp_) { #if @MAXEN@ == 0 -@CC@ if(val > (@TYPI@)@MAX@) { out = @MAX@; out_of_range = 1; return; } +@CC@ if(val > (@TYPI@)@MAX@) { out_set(@MAX@); out_of_range_set(1); return; } #endif #if @MINEN@ == 0 -@CC@ if(val < (@TYPI@)@MIN@) { out = @MIN@; out_of_range = 1; return; } +@CC@ if(val < (@TYPI@)@MIN@) { out_set(@MIN@); out_of_range_set(1); return; } #endif -@CC@ out = (@TYPO@)val; -@CC@ out_of_range = 0; +@CC@ out_set((@TYPO@)val); +@CC@ out_of_range_set(0); @CC@ } else { - out = (@TYPO@)val; -@CC@ if((@TYPI@)out != val) out_of_range = 1; + out_set((@TYPO@)val); +@CC@ if((@TYPI@)out != val) out_of_range_set(1); @CC@ } } diff --git a/src/hal/components/corexy_by_hal.comp b/src/hal/components/corexy_by_hal.comp index bde7d7b620d..50e8517c7b8 100644 --- a/src/hal/components/corexy_by_hal.comp +++ b/src/hal/components/corexy_by_hal.comp @@ -1,17 +1,17 @@ // Based on a forum posting by nbremond component corexy_by_hal "CoreXY kinematics"; -pin in float alpha_fb"typ: feedback from alpha motor controller"; -pin in float beta_fb "typ: feedback from beta motor controller"; +pin in real alpha_fb"typ: feedback from alpha motor controller"; +pin in real beta_fb "typ: feedback from beta motor controller"; -pin in float j0_motor_pos_cmd"typ: from joint.0.motor-pos-cmd"; -pin in float j1_motor_pos_cmd"typ: from joint.1.motor-pos-cmd"; +pin in real j0_motor_pos_cmd"typ: from joint.0.motor-pos-cmd"; +pin in real j1_motor_pos_cmd"typ: from joint.1.motor-pos-cmd"; -pin out float j0_motor_pos_fb"typ: to joint.0.motor-pos-fb"; -pin out float j1_motor_pos_fb"typ: to joint.1.motor-pos-fb"; +pin out real j0_motor_pos_fb"typ: to joint.0.motor-pos-fb"; +pin out real j1_motor_pos_fb"typ: to joint.1.motor-pos-fb"; -pin out float alpha_cmd"typ: command to alpha motor"; -pin out float beta_cmd "typ: command to beta ts motor"; +pin out real alpha_cmd"typ: command to alpha motor"; +pin out real beta_cmd "typ: command to beta ts motor"; function _; description """ @@ -57,10 +57,10 @@ author "Dewey Garrett based on forum post from nbremond"; FUNCTION(_) { // forward kinematics (j0==x,j1==y from motor positions): - j0_motor_pos_fb = alpha_fb + beta_fb; - j1_motor_pos_fb = alpha_fb - beta_fb; + j0_motor_pos_fb_set(alpha_fb + beta_fb); + j1_motor_pos_fb_set(alpha_fb - beta_fb); // inverse kinematics (motor positions from j0==x,j1==y): - alpha_cmd = 0.5*(j0_motor_pos_cmd + j1_motor_pos_cmd); - beta_cmd = 0.5*(j0_motor_pos_cmd - j1_motor_pos_cmd); + alpha_cmd_set(0.5*(j0_motor_pos_cmd + j1_motor_pos_cmd)); + beta_cmd_set(0.5*(j0_motor_pos_cmd - j1_motor_pos_cmd)); } diff --git a/src/hal/components/counter.c b/src/hal/components/counter.c index 54e3adfa288..d279c88db33 100644 --- a/src/hal/components/counter.c +++ b/src/hal/components/counter.c @@ -65,19 +65,19 @@ typedef struct { unsigned char oldA; /* previous value of phase A */ unsigned char reset_on_index; unsigned char pad; /* padding for alignment */ - hal_s32_t *raw_count; /* pin: raw binary count value */ - hal_bit_t *phaseA; /* quadrature input */ - hal_bit_t *phaseZ; /* index pulse input */ - hal_bit_t *index_ena; /* index enable input */ - hal_bit_t *reset; /* counter reset input */ - hal_s32_t *count; /* captured binary count value */ - hal_float_t *pos; /* scaled position (floating point) */ - hal_float_t *vel; /* scaled velocity (floating point) */ - hal_float_t *pos_scale; /* pin: scaling factor for pos */ + hal_sint_t raw_count; /* pin: raw binary count value */ + hal_bool_t phaseA; /* quadrature input */ + hal_bool_t phaseZ; /* index pulse input */ + hal_bool_t index_ena; /* index enable input */ + hal_bool_t reset; /* counter reset input */ + hal_sint_t count; /* captured binary count value */ + hal_real_t pos; /* scaled position (floating point) */ + hal_real_t vel; /* scaled velocity (floating point) */ + hal_real_t pos_scale; /* pin: scaling factor for pos */ double old_scale; /* stored scale value */ double scale; /* reciprocal value used for scaling */ - hal_s32_t last_count; - hal_s32_t last_index_count; + rtapi_s32 last_count; + rtapi_s32 last_index_count; } counter_t; /* pointer to array of counter_t structs in shmem, 1 per counter */ @@ -138,10 +138,10 @@ int rtapi_app_main(void) counter_array[n].oldZ = 0; counter_array[n].oldA = 0; counter_array[n].reset_on_index = 0; - *(counter_array[n].raw_count) = 0; - *(counter_array[n].count) = 0; - *(counter_array[n].pos) = 0.0; - *(counter_array[n].pos_scale) = 1.0; + hal_set_si32(counter_array[n].raw_count, 0); + hal_set_si32(counter_array[n].count, 0); + hal_set_real(counter_array[n].pos, 0.0); + hal_set_real(counter_array[n].pos_scale, 1.0); counter_array[n].old_scale = 1.0; counter_array[n].scale = 1.0; } @@ -185,16 +185,16 @@ static void update(void *arg, long period) for (cntr = arg, n = 0; n < num_chan; cntr++, n++) { // count on rising edge - if(!cntr->oldA && *cntr->phaseA) - (*cntr->raw_count)++; - cntr->oldA = *cntr->phaseA; + if(!cntr->oldA && hal_get_bool(cntr->phaseA)) + hal_set_si32(cntr->raw_count, hal_get_si32(cntr->raw_count) + 1); + cntr->oldA = hal_get_bool(cntr->phaseA); // reset on rising edge - if(cntr->reset_on_index && !cntr->oldZ && *cntr->phaseZ) { - cntr->last_index_count = *(cntr->raw_count); - *(cntr->index_ena) = 0; + if(cntr->reset_on_index && !cntr->oldZ && hal_get_bool(cntr->phaseZ)) { + cntr->last_index_count = hal_get_si32(cntr->raw_count); + hal_set_bool(cntr->index_ena, 0); } - cntr->oldZ = *cntr->phaseZ; + cntr->oldZ = hal_get_bool(cntr->phaseZ); } } @@ -207,37 +207,37 @@ static void capture(void *arg, long period) /* check reset input */ int raw_count; int counts; - if (*(cntr->reset)) { + if (hal_get_bool(cntr->reset)) { /* reset is active, reset the counter */ - *(cntr->raw_count) = 0; + hal_set_si32(cntr->raw_count, 0); cntr->last_index_count = 0; cntr->last_count = 0; } /* capture raw counts to latches */ - raw_count = *(cntr->raw_count); - *(cntr->count) = raw_count - cntr->last_index_count; + raw_count = hal_get_si32(cntr->raw_count); + hal_set_si32(cntr->count, raw_count - cntr->last_index_count); counts = (raw_count - cntr->last_count); cntr->last_count = raw_count; /* check for change in scale value */ - if ( *(cntr->pos_scale) != cntr->old_scale ) { + if ( hal_get_real(cntr->pos_scale) != cntr->old_scale ) { /* save new scale to detect future changes */ - cntr->old_scale = *(cntr->pos_scale); + cntr->old_scale = hal_get_real(cntr->pos_scale); /* scale value has changed, test and update it */ - if ((*(cntr->pos_scale) < 1e-20) && (*(cntr->pos_scale) > -1e-20)) { + if ((hal_get_real(cntr->pos_scale) < 1e-20) && (hal_get_real(cntr->pos_scale) > -1e-20)) { /* value too small, divide by zero is a bad thing */ - *(cntr->pos_scale) = 1.0; + hal_set_real(cntr->pos_scale, 1.0); } /* we actually want the reciprocal */ - cntr->scale = 1.0 / *(cntr->pos_scale); + cntr->scale = 1.0 / hal_get_real(cntr->pos_scale); } /* scale count to make floating point position */ - *(cntr->pos) = *(cntr->count) * cntr->scale; + hal_set_real(cntr->pos, hal_get_si32(cntr->count) * cntr->scale); /* scale counts to make floating point velocity */ - *(cntr->vel) = counts * cntr->scale * 1e9 / period; + hal_set_real(cntr->vel, counts * cntr->scale * 1e9 / period); /* update reset_on_index based on index_ena */ - cntr->reset_on_index = *(cntr->index_ena); + cntr->reset_on_index = hal_get_bool(cntr->index_ena); } } @@ -245,9 +245,17 @@ static void capture(void *arg, long period) * LOCAL FUNCTION DEFINITIONS * ************************************************************************/ +#define CHK(v) do { \ + int _rv = (v); \ + if(0 != _rv) { \ + rtapi_set_msg_level(msg); \ + return _rv; \ + } \ + } while(0) + static int export_counter(int num, counter_t * addr) { - int retval, msg; + int msg; /* This function exports a lot of stuff, which results in a lot of logging if msg_level is at INFO or ALL. So we save the current value @@ -257,50 +265,23 @@ static int export_counter(int num, counter_t * addr) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pins for the quadrature inputs */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->phaseA), comp_id, "counter.%d.phase-A", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_bool(comp_id, HAL_IN, &addr->phaseA, 0, "counter.%d.phase-A", num)); /* export pin for the index input */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->phaseZ), comp_id, "counter.%d.phase-Z", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_bool(comp_id, HAL_IN, &addr->phaseZ, 0, "counter.%d.phase-Z", num)); /* export pin for the index enable input */ - retval = hal_pin_bit_newf(HAL_IO, &(addr->index_ena), comp_id, "counter.%d.index-enable", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_bool(comp_id, HAL_IO, &addr->index_ena, 0, "counter.%d.index-enable", num)); /* export pin for the reset input */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->reset), comp_id, "counter.%d.reset", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_bool(comp_id, HAL_IN, &addr->reset, 0, "counter.%d.reset", num)); /* export parameter for raw counts */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->raw_count), comp_id, "counter.%d.rawcounts", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &addr->raw_count, 0, "counter.%d.rawcounts", num)); /* export pin for counts captured by capture() */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->count), comp_id, "counter.%d.counts", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &addr->count, 0, "counter.%d.counts", num)); /* export pin for scaled position captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos), comp_id, "counter.%d.position", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_OUT, &addr->pos, 0.0, "counter.%d.position", num)); /* export pin for scaled velocity captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->vel), comp_id, "counter.%d.velocity", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_OUT, &addr->vel, 0.0, "counter.%d.velocity", num)); /* export parameter for scaling */ - retval = hal_pin_float_newf(HAL_IO, &(addr->pos_scale), comp_id, "counter.%d.position-scale", num); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_IO, &addr->pos_scale, 0.0, "counter.%d.position-scale", num)); /* restore saved message level */ rtapi_set_msg_level(msg); return 0; diff --git a/src/hal/components/dbounce.comp b/src/hal/components/dbounce.comp index 4256aa2ff97..f45355afe58 100644 --- a/src/hal/components/dbounce.comp +++ b/src/hal/components/dbounce.comp @@ -5,9 +5,9 @@ delay pins for each instance and supports *count*= or *names*= parameters (groups are not used) """; -pin in bit in; -pin out bit out; -pin in u32 delay = 5; +pin in bool in; +pin out bool out; +pin in ui32 delay = 5; variable unsigned state; option period no; @@ -24,7 +24,7 @@ FUNCTION(_) { state++; } else { /* yes, set output */ - out = 1; + out_set(1); } } else { /* input false, is state at zero? */ @@ -33,7 +33,7 @@ FUNCTION(_) { state--; } else { /* yes, clear output */ - out = 0; + out_set(0); } } } diff --git a/src/hal/components/ddt.comp b/src/hal/components/ddt.comp index 92ce48e3a7c..ee9d463f776 100644 --- a/src/hal/components/ddt.comp +++ b/src/hal/components/ddt.comp @@ -33,14 +33,14 @@ every time the real time function is called. """; -pin in float in; -pin out float out; +pin in real in; +pin out real out; -variable double old; +variable rtapi_real old; function _; license "GPL"; ;; -double tmp = in; -out = (tmp - old) / (period * 1e-9); +rtapi_real tmp = in; +out_set((tmp - old) / (period * 1e-9)); old = tmp; diff --git a/src/hal/components/deadzone.comp b/src/hal/components/deadzone.comp index 759a097048d..44938e76ee0 100644 --- a/src/hal/components/deadzone.comp +++ b/src/hal/components/deadzone.comp @@ -1,8 +1,8 @@ component deadzone "Return the center if within the threshold"; -param rw float center = 0.0 "The center of the dead zone"; -param rw float threshold = 1.0 "The dead zone is *center* ±(*threshold*/2)"; -pin in float in; -pin out float out; +param rw real center = 0.0 "The center of the dead zone"; +param rw real threshold = 1.0 "The dead zone is *center* ±(*threshold*/2)"; +pin in real in; +pin out real out; option period no; function _ "Update *out* based on *in* and the parameters."; @@ -11,12 +11,12 @@ license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - double th2 = threshold / 2; - double lo = center - th2; - double hi = center + th2; - double in_ = in; + rtapi_real th2 = threshold / 2; + rtapi_real lo = center - th2; + rtapi_real hi = center + th2; + rtapi_real in_ = in; - if(in_ < lo) out = in_ + th2; - else if(in_ > hi) out = in_ - th2; - else out = center; + if(in_ < lo) out_set(in_ + th2); + else if(in_ > hi) out_set(in_ - th2); + else out_set(center); } diff --git a/src/hal/components/debounce.c b/src/hal/components/debounce.c index 0edc0be1a26..8aecf78dcff 100644 --- a/src/hal/components/debounce.c +++ b/src/hal/components/debounce.c @@ -65,9 +65,13 @@ RTAPI_MP_ARRAY_INT(cfg,MAX_GROUP,"Group size for up to "MAX_GROUP_STR" groups"); /** This structure contains the runtime data for a single filter. */ typedef struct { - hal_bit_t *in; /* pin: input */ - hal_bit_t *out; /* pin: output */ - hal_s32_t state; /* parameter*: internal state */ + hal_bool_t in; /* pin: input */ + hal_bool_t out; /* pin: output */ +#ifdef EXPORT_STATE + hal_sint_t state; /* parameter*: internal state */ +#else + rtapi_s32 state; /* parameter*: internal state */ +#endif } debounce_t; /* *note - this parameter is only exported if EXPORT_STATE is defined */ @@ -75,9 +79,9 @@ typedef struct { /** This structure contains the runtime data for a group of filters */ typedef struct { - int channels; /* number of channels in group */ - hal_s32_t delay; /* parameter: delay for this group */ - debounce_t *filter_array; /* pointer to individual filter data */ + int channels; /* number of channels in group */ + hal_sint_t delay; /* parameter: delay for this group */ + debounce_t *filter_array; /* pointer to individual filter data */ } debounce_group_t; /* ptr to array of debounce_group_t structs in shmem, 1 per group */ @@ -168,6 +172,14 @@ void rtapi_app_exit(void) * REALTIME DEBOUNCE FUNCTION * ************************************************************************/ +#ifdef EXPORT_STATE +static inline rtapi_s32 get_state(hal_sint_t *s) { return hal_get_si32(*s); } +static inline rtapi_s32 set_state(hal_sint_t *s, rtapi_s32 v) { return hal_set_si32(*s, v); } +#else +static inline rtapi_s32 get_state(rtapi_s32 *s) { return *s; } +static inline rtapi_s32 set_state(rtapi_s32 *s, rtapi_s32 v) { return (*s = v); } +#endif + /** The debounce filter works by incrementing a counter whenever the input is true, and decrementing the counter when it is false. If the counter decrements to zero, the output is set false and @@ -193,33 +205,33 @@ static void debounce(void *arg, long period) /* point to filter group */ group = (debounce_group_t *) arg; /* first make sure delay is sane */ - if (group->delay < 0) { - group->delay = 1; + if (hal_get_si32(group->delay) < 0) { + hal_set_si32(group->delay, 1); } /* loop thru filters */ for (n = 0; n < group->channels; n++) { - /* point at a filter */ - filter = &(group->filter_array[n]); - /* update this filter */ - if (*(filter->in)) { - /* input true, is state at threshold? */ - if (filter->state < group->delay) { - /* no, increment */ - filter->state++; - } else { - /* yes, set output */ - *(filter->out) = 1; - } - } else { - /* input false, is state at zero? */ - if (filter->state > 0) { - /* no, decrement */ - filter->state--; - } else { - /* yes, clear output */ - *(filter->out) = 0; - } - } + /* point at a filter */ + filter = &(group->filter_array[n]); + /* update this filter */ + if (hal_get_bool(filter->in)) { + /* input true, is state at threshold? */ + if (get_state(&filter->state) < hal_get_si32(group->delay)) { + /* no, increment */ + set_state(&filter->state, get_state(&filter->state) + 1); + } else { + /* yes, set output */ + hal_set_bool(filter->out, 1); + } + } else { + /* input false, is state at zero? */ + if (get_state(&filter->state) > 0) { + /* no, decrement */ + set_state(&filter->state, get_state(&filter->state) - 1); + } else { + /* yes, clear output */ + hal_set_bool(filter->out, 0); + } + } } } @@ -241,36 +253,31 @@ static int export_group(int num, debounce_group_t * addr, int group_size) /* allocate shared memory for this filter group */ addr->filter_array = hal_malloc(group_size * sizeof(debounce_t)); if (addr->filter_array == 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: hal_malloc() failed\n"); - return -1; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: hal_malloc() failed\n"); + return -1; } /* export param variable for delay */ - retval = hal_param_s32_newf(HAL_RW, &(addr->delay), comp_id, "debounce.%d.delay", num); + retval = hal_param_new_si32(comp_id, HAL_RW, &addr->delay, 5, "debounce.%d.delay", num); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: 'debounce.%d.delay' param export failed\n", num); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: 'debounce.%d.delay' param export failed\n", num); + return retval; } /* export function */ retval = hal_export_functf(debounce, addr, 0, 0, comp_id, "debounce.%d", num); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: 'debounce.%d' funct export failed\n", num); - return -1; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: 'debounce.%d' funct export failed\n", num); + return -1; } /* set default parameter values */ - addr->delay = 5; addr->channels = group_size; /* loop to export each filter in group */ for (n = 0; n < group_size; n++) { - retval = export_filter(n, &(addr->filter_array[n]), num); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: filter %d export failed\n", n); - return -1; - } + retval = export_filter(n, &(addr->filter_array[n]), num); + if (retval != 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: filter %d export failed\n", n); + return -1; + } } /* restore saved message level */ rtapi_set_msg_level(msg); @@ -281,35 +288,31 @@ static int export_filter(int num, debounce_t * addr, int group_num) { int retval; char buf[HAL_NAME_LEN + 1]; + rtapi_snprintf(buf, sizeof(buf), "debounce.%d.%d", group_num, num); /* export pin for input */ - rtapi_snprintf(buf, sizeof(buf), "debounce.%d.%d.in", group_num, num); - retval = hal_pin_bit_new(buf, HAL_IN, &(addr->in), comp_id); + retval = hal_pin_new_bool(comp_id, HAL_IN, &addr->in, 0, "%s.in", buf); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: '%s' pin export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: '%s.in' pin export failed\n", buf); + return retval; } /* export pin for output */ - rtapi_snprintf(buf, sizeof(buf), "debounce.%d.%d.out", group_num, num); - retval = hal_pin_bit_new(buf, HAL_OUT, &(addr->out), comp_id); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &addr->out, 0, "%s.out", buf); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: '%s' pin export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: '%s.out' pin export failed\n", buf); + return retval; } #ifdef EXPORT_STATE /* export parameter containing internal state */ - rtapi_snprintf(buf, sizeof(buf), "debounce.%d.%d.state", group_num, num); - retval = hal_param_s32_new(buf, HAL_RO, &(addr->state), comp_id); + retval = hal_param_new_si32(comp_id, HAL_RO, &addr->state, 0, "%s.state", buf); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "DEBOUNCE: ERROR: '%s' param export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "DEBOUNCE: ERROR: '%s.state' param export failed\n", buf); + return retval; } +#else + // Param is init to zero. + // When no param is exported, we need to be sure too. + set_state(&addr->state, 0); #endif - /* set initial parameter and pin values */ - addr->state = 0; - *(addr->out) = 0; return 0; } diff --git a/src/hal/components/demux.comp b/src/hal/components/demux.comp index d2a78610479..7d4c8d19067 100644 --- a/src/hal/components/demux.comp +++ b/src/hal/components/demux.comp @@ -10,12 +10,12 @@ An optional operating mode is enabled by setting the "bargraph" parameter to true, in this case all bits up to the selected bit will be set, as might be required for an LED bargraph display."""; -pin in bit sel-bit-## [5] "Binary-number bit selectors"; -pin in unsigned sel-u32 "Integer selection input"; -pin out bit out-## [32:personality] "The set of output bits"; +pin in bool sel-bit-## [5] "Binary-number bit selectors"; +pin in ui32 sel-u32 "Integer selection input"; +pin out bool out-## [32:personality] "The set of output bits"; option default_personality 32; -param rw bit bargraph = 0; +param rw bool bargraph = 0; see_also "*select8*(9)"; license "GPL 2+"; @@ -32,7 +32,8 @@ FUNCTION(_){ bit = sel_u32 + sel_bit(0) + (sel_bit(1) << 1) + (sel_bit(2) << 2) + (sel_bit(3) << 3) + (sel_bit(4) << 4); if (bit >= personality) bit = personality - 1; + rtapi_bool bg = bargraph; for (i = 0; i < personality ; i++) { - out(i) = (bargraph) ? (bit > i) : (bit == i); + out_set(i, bg ? (bit > i) : (bit == i)); } } diff --git a/src/hal/components/demux_generic.c b/src/hal/components/demux_generic.c index fd72759f711..c759b2f30ad 100644 --- a/src/hal/components/demux_generic.c +++ b/src/hal/components/demux_generic.c @@ -19,6 +19,7 @@ #include #include +#include #include @@ -30,18 +31,16 @@ MODULE_LICENSE("GPL"); #define MAX_CHAN 100 #define MAX_SIZE 1024 #define EPS 2e-7 -#define MAX_S32 0x7FFFFFFF -#define MAX_U32 0xFFFFFFFF typedef struct { - hal_data_u *input; - hal_data_u **outputs; - hal_u32_t *sel_int; - hal_bit_t **sel_bit; - unsigned int selection; - hal_u32_t *debounce; - unsigned int timer; - hal_bit_t *suppress; + hal_refs_u input; + hal_refs_u *outputs; + hal_uint_t sel_int; + hal_bool_t *sel_bit; + hal_uint_t selection; // (param) + hal_uint_t debounce; + hal_uint_t timer; // (param) + hal_bool_t suppress; int in_type; int out_type; int size; @@ -56,7 +55,6 @@ typedef struct { static int comp_id; static demux_t *demux; static void write_fp(void *arg, long period); -static void write_nofp(void *arg, long period); char *config[MAX_CHAN]; RTAPI_MP_ARRAY_STRING(config, MAX_CHAN, "demux specifiers inNUMout"); @@ -79,7 +77,7 @@ int rtapi_app_main(void){ } // allocate shared memory for the base struct - demux = hal_malloc(sizeof(demux_t)); + demux = hal_malloc(sizeof(*demux)); if (demux == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "demux_generic component: Out of Memory\n"); @@ -89,7 +87,7 @@ int rtapi_app_main(void){ // Count the instances. for (demux->num_insts = 0; config[demux->num_insts];demux->num_insts++) {} - demux->insts = hal_malloc(demux->num_insts * sizeof(demux_inst_t)); + demux->insts = hal_malloc(demux->num_insts * sizeof(*demux->insts)); // Parse the config string for (i = 0; i < demux->num_insts; i++) { char c; @@ -168,22 +166,13 @@ int rtapi_app_main(void){ inst->out_type = inst->in_type; } - if (inst->in_type == HAL_FLOAT || inst->out_type == HAL_FLOAT) { - retval = hal_export_functf(write_fp, inst, 1, 0, comp_id, "demux-gen.%02i", i); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "demux_generic: ERROR: function export" - " failed\n"); - goto fail0; - } - } - else - { - retval = hal_export_functf(write_nofp, inst, 0, 0, comp_id, "demux-gen.%02i", i); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "demux_generic: ERROR: function export" - " failed\n"); - goto fail0; - } + // We did away with the no-fp thread. + // Always export the float case. It can do any-to-any. + retval = hal_export_functf(write_fp, inst, 1, 0, comp_id, "demux-gen.%02i", i); + if (retval < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "demux_generic: ERROR: function export" + " failed\n"); + goto fail0; } // Input pins @@ -193,9 +182,9 @@ int rtapi_app_main(void){ if (s !=1){ inst->num_bits = 0; } else { //make the bit pins - inst->sel_bit = hal_malloc(inst->num_bits * sizeof(hal_bit_t*)); + inst->sel_bit = hal_malloc(inst->num_bits * sizeof(*inst->sel_bit)); for (p = 0; p < inst->num_bits; p++) { - retval = hal_pin_bit_newf(HAL_IN, &inst->sel_bit[p], comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->sel_bit[p], 0, "demux-gen.%02i.sel-bit-%02i", i, p); if (retval != 0) { goto fail0; @@ -203,7 +192,7 @@ int rtapi_app_main(void){ } } - retval = hal_pin_u32_newf(HAL_IN, &(inst->sel_int), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &(inst->sel_int), 0, "demux-gen.%02i.sel-int", i); if (retval != 0) { goto fail0; @@ -214,44 +203,60 @@ int rtapi_app_main(void){ if (retval >= HAL_NAME_LEN) { goto fail0; } - retval = hal_pin_new(hal_name, inst->in_type, HAL_IN, - (void**)&(inst->input), comp_id); + switch(inst->in_type) { + case HAL_BOOL: retval = hal_pin_new_bool(comp_id, HAL_OUT, &inst->input.b, 0, "%s", hal_name); break; + case HAL_REAL: retval = hal_pin_new_real(comp_id, HAL_OUT, &inst->input.r, 0, "%s", hal_name); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_OUT, &inst->input.s, 0, "%s", hal_name); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_OUT, &inst->input.u, 0, "%s", hal_name); break; + // FIXME: Future...when we switch types + case HAL_SINT: retval = hal_pin_new_sint(comp_id, HAL_OUT, &inst->input.s, 0, "%s", hal_name); break; + case HAL_UINT: retval = hal_pin_new_uint(comp_id, HAL_OUT, &inst->input.u, 0, "%s", hal_name); break; + default: retval = -ENOENT; break; + } if (retval != 0) { goto fail0; } // Behaviour-modifiers - retval = hal_pin_bit_newf(HAL_IN, &inst->suppress, comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->suppress, 0, "demux-gen.%02i.suppress-no-input", i); if (retval != 0) { goto fail0; } - retval = hal_pin_u32_newf(HAL_IN, &inst->debounce, comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &inst->debounce, 0, "demux-gen.%02i.debounce-us", i); if (retval != 0) { goto fail0; } - retval = hal_param_u32_newf(HAL_RO, &inst->timer, comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RO, &inst->timer, 0, "demux-gen.%02i.elapsed", i); if (retval != 0) { goto fail0; } - retval = hal_param_u32_newf(HAL_RO, &inst->selection, comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RO, &inst->selection, 0, "demux-gen.%02i.selected", i); if (retval != 0) { goto fail0; } //output pins - inst->outputs = hal_malloc(inst->size * sizeof(hal_data_u*)); + inst->outputs = hal_malloc(inst->size * sizeof(*inst->outputs)); for (p = 0; p < inst->size; p++) { retval = rtapi_snprintf(hal_name, HAL_NAME_LEN, "demux-gen.%02i.out-%s-%02i", i, types[inst->out_type], p); if (retval >= HAL_NAME_LEN) { goto fail0; } - retval = hal_pin_new(hal_name, inst->out_type, HAL_OUT, - (void**)&(inst->outputs[p]), comp_id); + switch(inst->out_type) { + case HAL_BOOL: retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->outputs[p].b, 0, "%s", hal_name); break; + case HAL_REAL: retval = hal_pin_new_real(comp_id, HAL_IN, &inst->outputs[p].r, 0, "%s", hal_name); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_IN, &inst->outputs[p].s, 0, "%s", hal_name); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_IN, &inst->outputs[p].u, 0, "%s", hal_name); break; + // FIXME: Future...when we switch types + case HAL_SINT: retval = hal_pin_new_sint(comp_id, HAL_IN, &inst->outputs[p].s, 0, "%s", hal_name); break; + case HAL_UINT: retval = hal_pin_new_uint(comp_id, HAL_IN, &inst->outputs[p].u, 0, "%s", hal_name); break; + default: retval = -ENOENT; break; + } if (retval != 0) { goto fail0; } @@ -268,124 +273,103 @@ int rtapi_app_main(void){ } +// From 'f' to 't' conversion +#define FT(f,t) ((((f) & 0x0f) << 4) + ((t) & 0x0f)) + void write_fp(void *arg, long period) { demux_inst_t *inst = arg; int i = 0; unsigned s = 0; if (inst->num_bits > 0) { while (i < inst->num_bits) { - s += (*inst->sel_bit[i] != 0) << i; + s += (hal_get_bool(inst->sel_bit[i]) != 0) << i; i++; } } // if you document it, it's not a bug, it's a feature. Might even be useful - s += *inst->sel_int; + s += hal_get_ui32(inst->sel_int); - if (*inst->suppress && s == 0) + if (hal_get_bool(inst->suppress) && s == 0) return; - if (s != inst->selection && inst->timer < *inst->debounce) { - inst->timer += period / 1000; + rtapi_u32 timer = hal_get_ui32(inst->timer); + if (s != hal_get_ui32(inst->selection) && timer < hal_get_ui32(inst->debounce)) { + hal_set_ui32(inst->timer, timer + period / 1000); return; } - inst->selection = s; - inst->timer = 0; + hal_set_ui32(inst->selection, s); + hal_set_ui32(inst->timer, 0); if ((int)s >= inst->size) s = inst->size - 1; - switch (inst->in_type * 8 + inst->out_type) { - case 012: //HAL_BIT => HAL_FLOAT - inst->outputs[s]->f = inst->input->b ? 1.0 : 0.0; // - break; - case 021: //HAL_FLOAT => HAL_BIT - inst->outputs[s]->b = - (inst->input->f > EPS || inst->input->f < -EPS) ? 1 : 0; + switch (FT(inst->in_type, inst->out_type)) { + case FT(HAL_BOOL, HAL_BOOL): //HAL_BIT => HAL_BIT + hal_set_bool(inst->outputs[s].b, hal_get_bool(inst->input.b)); break; - case 022: //HAL_FLOAT => HAL_FLOAT - inst->outputs[s]->f = inst->input->f; + case FT(HAL_BOOL, HAL_S32): //HAL_BIT => HAL_S32 + hal_set_si32(inst->outputs[s].s, hal_get_bool(inst->input.b)); break; - case 023: //HAL_FLOAT => HAL_S32 - if (inst->input->f > MAX_S32) { - inst->outputs[s]->s = MAX_S32; - } else if (inst->input->f < -MAX_S32) { - inst->outputs[s]->s = -MAX_S32; - } else { - inst->outputs[s]->s = inst->input->f; - } + case FT(HAL_BOOL, HAL_U32): //HAL_BIT => HAL_U32 + hal_set_ui32(inst->outputs[s].u, hal_get_bool(inst->input.b)); break; - case 024: //HAL_FLOAT => HAL_U32 - if (inst->input->f > MAX_U32) { - inst->outputs[s]->u = MAX_U32; - } else if (inst->input->f < 0) { - inst->outputs[s]->u = 0; - } else { - inst->outputs[s]->u = inst->input->f; - } + case FT(HAL_BOOL, HAL_REAL): //HAL_BIT => HAL_FLOAT + hal_set_real(inst->outputs[s].r, hal_get_bool(inst->input.b) ? 1.0 : 0.0); break; - case 032: //HAL_S32 => HAL_FLOAT - inst->outputs[s]->f = inst->input->s; + + case FT(HAL_REAL, HAL_BOOL): //HAL_FLOAT => HAL_BIT + hal_set_bool(inst->outputs[s].b, fabs(hal_get_real(inst->input.r)) > EPS); break; - case 042: //HAL_U32 => HAL_FLOAT - inst->outputs[s]->f = (unsigned int) inst->input->u; + case FT(HAL_REAL, HAL_REAL): //HAL_FLOAT => HAL_FLOAT + hal_set_real(inst->outputs[s].r, hal_get_real(inst->input.r)); break; - } -} - -void write_nofp(void *arg, long period) { - demux_inst_t *inst = arg; - int i = 0; - unsigned s = 0; - if (inst->num_bits > 0) { - while (i < inst->num_bits) { - s += (*inst->sel_bit[i] != 0) << i; - i++; + case FT(HAL_REAL, HAL_S32): { //HAL_FLOAT => HAL_S32 + rtapi_real v = hal_get_real(inst->input.r); + if (v > RTAPI_INT32_MAX) { + hal_set_si32(inst->outputs[s].s, RTAPI_INT32_MAX); + } else if (v < RTAPI_INT32_MIN) { + hal_set_si32(inst->outputs[s].s, RTAPI_INT32_MIN); + } else { + hal_set_si32(inst->outputs[s].s, v); } - } - - s += *inst->sel_int; - - if (*inst->suppress && s == 0) - return; - if (s != inst->selection && inst->timer < *inst->debounce) { - inst->timer += period / 1000; - return; - } - - inst->selection = s; - inst->timer = 0; + break; } + case FT(HAL_REAL, HAL_U32): { //HAL_FLOAT => HAL_U32 + rtapi_real v = hal_get_real(inst->input.r); + if (v > RTAPI_UINT32_MAX) { + hal_set_ui32(inst->outputs[s].u, RTAPI_UINT32_MAX); + } else if (v < 0) { + hal_set_ui32(inst->outputs[s].u, 0); + } else { + hal_set_ui32(inst->outputs[s].u, v); + } + break; } - if ((int)s >= inst->size) - s = inst->size - 1; - switch (inst->in_type * 8 + inst->out_type) { - case 011: //HAL_BIT => HAL_BIT - inst->outputs[s]->b = inst->input->b; - break; - case 013: //HAL_BIT => HAL_S32 - inst->outputs[s]->s = inst->input->b; - break; - case 014: //HAL_BIT => HAL_U32 - inst->outputs[s]->u = inst->input->b; + case FT(HAL_S32, HAL_BOOL): //HAL_S32 => HAL_BIT + hal_set_bool(inst->outputs[s].b, hal_get_si32(inst->input.s) != 0); break; - case 031: //HAL_S32 => HAL_BIT - inst->outputs[s]->b = inst->input->s == 0 ? 0 : 1; + case FT(HAL_S32, HAL_S32): //HAL_S32 => HAL_S32 + hal_set_si32(inst->outputs[s].s, hal_get_si32(inst->input.s)); break; - case 033: //HAL_S32 => HAL_S32 - inst->outputs[s]->s = inst->input->s; + case FT(HAL_S32, HAL_U32): { //HAL_S32 => HAL_U32 + rtapi_s32 v = hal_get_si32(inst->input.s); + hal_set_ui32(inst->outputs[s].u, v > 0 ? v : 0); + break; } + case FT(HAL_S32, HAL_REAL): //HAL_S32 => HAL_FLOAT + hal_set_real(inst->outputs[s].r, hal_get_si32(inst->input.s)); break; - case 034: //HAL_S32 => HAL_U32 - inst->outputs[s]->u = (inst->input->s > 0) ? inst->input->s : 0; - break; - case 041: //HAL_U32 => HAL_BIT - inst->outputs[s]->b = inst->input->u == 0 ? 0 : 1; + + case FT(HAL_U32, HAL_BIT): //HAL_U32 => HAL_BIT + hal_set_bool(inst->outputs[s].b, hal_get_ui32(inst->input.u) != 0); break; - case 043: //HAL_U32 => HAL_S32 - inst->outputs[s]->s = - ((unsigned int) inst->input->u > MAX_S32) ? - MAX_S32 : inst->input->u; + case FT(HAL_U32, HAL_S32): { //HAL_U32 => HAL_S32 + rtapi_u32 v = hal_get_ui32(inst->input.u); + hal_set_si32(inst->outputs[s].s, v > (rtapi_u32)RTAPI_INT32_MAX ? RTAPI_INT32_MAX : (rtapi_s32)v); + break; } + case FT(HAL_U32, HAL_U32): //HAL_U32 => HAL_U32 + hal_set_ui32(inst->outputs[s].u, hal_get_ui32(inst->input.u)); break; - case 044: //HAL_U32 => HAL_U32 - inst->outputs[s]->u = inst->input->u; + case FT(HAL_U32, HAL_REAL): //HAL_U32 => HAL_FLOAT + hal_set_real(inst->outputs[s].r, hal_get_ui32(inst->input.u)); break; } } diff --git a/src/hal/components/differential.comp b/src/hal/components/differential.comp index ec986495d02..c81f360a7ae 100644 --- a/src/hal/components/differential.comp +++ b/src/hal/components/differential.comp @@ -17,17 +17,17 @@ component differential "kinematics for a differential transmission"; -pin in float roll-cmd "position command for roll (in degrees)"; -pin in float pitch-cmd "position command for pitch (in degrees)"; +pin in real roll-cmd "position command for roll (in degrees)"; +pin in real pitch-cmd "position command for pitch (in degrees)"; -pin out float roll-fb "position feedback for roll (in degrees)"; -pin out float pitch-fb "position feedback for pitch (in degrees)"; +pin out real roll-fb "position feedback for roll (in degrees)"; +pin out real pitch-fb "position feedback for pitch (in degrees)"; -pin out float motor0-cmd "position command to motor0 (based on roll & pitch inputs)"; -pin out float motor1-cmd "position command to motor1 (based on roll & pitch inputs)"; +pin out real motor0-cmd "position command to motor0 (based on roll & pitch inputs)"; +pin out real motor1-cmd "position command to motor1 (based on roll & pitch inputs)"; -pin in float motor0-fb "position feedback from motor0"; -pin in float motor1-fb "position feedback from motor1"; +pin in real motor0-fb "position feedback from motor0"; +pin in real motor1-fb "position feedback from motor1"; option period no; function _; @@ -37,9 +37,9 @@ author "Sebastian Kuzminsky"; ;; FUNCTION(_) { - motor0_cmd = roll_cmd + pitch_cmd; - motor1_cmd = roll_cmd - pitch_cmd; + motor0_cmd_set(roll_cmd + pitch_cmd); + motor1_cmd_set(roll_cmd - pitch_cmd); - roll_fb = (motor0_fb + motor1_fb)/2; - pitch_fb = (motor0_fb - motor1_fb)/2; + roll_fb_set((motor0_fb + motor1_fb)/2); + pitch_fb_set((motor0_fb - motor1_fb)/2); } diff --git a/src/hal/components/div2.comp b/src/hal/components/div2.comp index 636a9becd19..5e3ec3e53b2 100644 --- a/src/hal/components/div2.comp +++ b/src/hal/components/div2.comp @@ -20,10 +20,10 @@ // component div2 "Quotient of two floating point inputs"; -pin in float in0 "the Dividend"; -pin in float in1 "the Divisor"; -pin out float out "the Quotient out = in0 / in1"; -param rw float deadband "The *out* will be zero if *in* is between -*deadband* and +*deadband*" ; +pin in real in0 "the Dividend"; +pin in real in1 "the Divisor"; +pin out real out "the Quotient out = in0 / in1"; +param rw real deadband "The *out* will be zero if *in* is between -*deadband* and +*deadband*" ; description """ A very simple comp to divide a floating point number @@ -45,23 +45,26 @@ function _; static bool error_msg = 0; FUNCTION(_) { - double dividend = in0; - double divisor = in1; - if ( deadband < 1e-12 ) deadband = 1e-12; - if ( divisor > -deadband && divisor < 0 ) { - out = ( dividend / -deadband ); + rtapi_real dividend = in0; + rtapi_real divisor = in1; + rtapi_real ddbd = deadband; + if ( ddbd < 1e-12 ) { + ddbd = deadband_set(1e-12); + } + if ( divisor > -ddbd && divisor < 0 ) { + out_set(dividend / -ddbd); if (!error_msg) rtapi_print_msg(RTAPI_MSG_ERR, "\n \n DIV2 DIVISOR IS TOO CLOSE TO -ZERO,\n THEREFORE -DEADBAND IS USED.\n INCREASE THE DIVISOR, in1.\n \n \n"); error_msg = 1; - } else if (divisor >= 0 && divisor < deadband) { - out = ( dividend / deadband ); + } else if (divisor >= 0 && divisor < ddbd) { + out_set(dividend / ddbd); if (!error_msg) rtapi_print_msg(RTAPI_MSG_ERR, "\n \n DIV2 DIVISOR IS TOO CLOSE TO +ZERO,\n THEREFORE +DEADBAND IS USED.\n INCREASE THE DIVISOR, in1.\n \n \n"); error_msg = 1; } else { - out = ( dividend / divisor ); + out_set(dividend / divisor); error_msg = 0; } } diff --git a/src/hal/components/edge.comp b/src/hal/components/edge.comp index 341d62a7135..42656188be9 100644 --- a/src/hal/components/edge.comp +++ b/src/hal/components/edge.comp @@ -16,16 +16,16 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. component edge "Edge detector"; -pin in bit in; -pin out bit out "Goes high when the desired edge is seen on 'in'"; -pin out bit out_invert "Goes low when the desired edge is seen on 'in'"; +pin in bool in; +pin out bool out "Goes high when the desired edge is seen on 'in'"; +pin out bool out_invert "Goes low when the desired edge is seen on 'in'"; -param rw bit both=FALSE "If TRUE, selects both edges. Otherwise, selects one edge according to in-edge"; -param rw bit in_edge=TRUE "If both is FALSE, selects the one desired edge: TRUE means falling, FALSE means rising"; -param rw signed out_width_ns=0 "Time in nanoseconds of the output pulse"; +param rw bool both=FALSE "If TRUE, selects both edges. Otherwise, selects one edge according to in-edge"; +param rw bool in_edge=TRUE "If both is FALSE, selects the one desired edge: TRUE means falling, FALSE means rising"; +param rw si32 out_width_ns=0 "Time in nanoseconds of the output pulse"; -param r signed time_left_ns "Time left in this output pulse"; -param r bit last_in "Previous input value"; +param r si32 time_left_ns "Time left in this output pulse"; +param r bool last_in "Previous input value"; variable int first = 1; function _ "Produce output pulses from input edges"; @@ -35,8 +35,9 @@ author "Jeff Epler"; FUNCTION(_){ int new_in = in; - if (time_left_ns > 0) { - time_left_ns -= period; + rtapi_s32 tlns = time_left_ns; + if (tlns > 0) { + time_left_ns_set(tlns -= period); } if ( !first ) { int rise = new_in && !last_in; @@ -45,18 +46,18 @@ FUNCTION(_){ both ? rise || fall : in_edge ? fall : rise; if(desired_edge) { - time_left_ns = out_width_ns; - out = 1; - } else if(time_left_ns > 0) { - out = 1; + time_left_ns_set(out_width_ns); + out_set(1); + } else if(tlns > 0) { + out_set(1); } else { - time_left_ns = 0; - out = 0; + time_left_ns_set(0); + out_set(0); } } else { first = 0; } - last_in = new_in; - out_invert = !out; + last_in_set(new_in); + out_invert_set(!out); } diff --git a/src/hal/components/encoder.c b/src/hal/components/encoder.c index 82d72449de9..2b9f2f34537 100644 --- a/src/hal/components/encoder.c +++ b/src/hal/components/encoder.c @@ -88,6 +88,7 @@ typedef struct { char count_detected; char index_detected; char latch_detected; + char reserved[1+4]; // Align on 8-byte boundary rtapi_s32 raw_count; rtapi_u32 timestamp; rtapi_s32 index_count; @@ -104,36 +105,36 @@ typedef struct { unsigned char state; /* u:rw quad decode state machine state */ unsigned char oldZ; /* u:rw previous value of phase Z */ unsigned char Zmask; /* u:rc c:s mask for oldZ, from index-ena */ - hal_bit_t *x4_mode; /* u:r enables x4 counting (default) */ - hal_bit_t *counter_mode; /* u:r enables counter mode */ - hal_s32_t *missing_teeth; /* u:r non-zero enables missing-teeth index */ - hal_s32_t dt; /* u:w most recent tooth space */ - hal_s32_t limit_dt; /* u:r c:w inter-count gap (nS) to define index */ + hal_bool_t x4_mode; /* u:r enables x4 counting (default) */ + hal_bool_t counter_mode; /* u:r enables counter mode */ + hal_sint_t missing_teeth; /* u:r non-zero enables missing-teeth index */ + hal_sint_t dt; /* u:w (param) most recent tooth space */ + hal_sint_t limit_dt; /* u:r c:w (param) inter-count gap (nS) to define index */ atomic buf[2]; /* u:w c:r double buffer for atomic data */ volatile atomic *bp; /* u:r c:w ptr to in-use buffer */ - hal_s32_t *raw_counts; /* u:rw raw count value, in update() only */ - hal_bit_t *phaseA; /* u:r quadrature input */ - hal_bit_t *phaseB; /* u:r quadrature input */ - hal_bit_t *phaseZ; /* u:r index pulse input */ - hal_bit_t *index_ena; /* c:rw index enable input */ - hal_bit_t *reset; /* c:r counter reset input */ - hal_bit_t *latch_in; /* c:r counter latch input */ - hal_bit_t *latch_rising; /* u:r latch on rising edge? */ - hal_bit_t *latch_falling; /* u:r latch on falling edge? */ - rtapi_s32 raw_count; /* c:rw captured raw_count */ - rtapi_u32 timestamp; /* c:rw captured timestamp */ - rtapi_s32 index_count; /* c:rw captured index count */ - rtapi_s32 latch_count; /* c:rw captured index count */ - hal_s32_t *count; /* c:w captured binary count value */ - hal_s32_t *count_latch; /* c:w captured binary count value */ - hal_float_t *min_speed; /* c:r minimum velocity to estimate nonzero */ - hal_float_t *pos; /* c:w scaled position (floating point) */ - hal_float_t *pos_interp; /* c:w scaled and interpolated position (float) */ - hal_float_t *pos_latch; /* c:w scaled latched position (floating point) */ - hal_float_t *vel; /* c:w scaled velocity (floating point) */ - hal_float_t *vel_rpm; /* rps * 60 for convenience */ - hal_float_t *pos_scale; /* c:r pin: scaling factor for pos */ - hal_bit_t old_latch; /* value of latch on previous cycle */ + hal_sint_t raw_counts; /* u:rw raw count value, in update() only */ + hal_bool_t phaseA; /* u:r quadrature input */ + hal_bool_t phaseB; /* u:r quadrature input */ + hal_bool_t phaseZ; /* u:r index pulse input */ + hal_bool_t index_ena; /* c:rw index enable input */ + hal_bool_t reset; /* c:r counter reset input */ + hal_bool_t latch_in; /* c:r counter latch input */ + hal_bool_t latch_rising; /* u:r latch on rising edge? */ + hal_bool_t latch_falling; /* u:r latch on falling edge? */ + rtapi_s32 raw_count; /* c:rw captured raw_count */ + rtapi_u32 timestamp; /* c:rw captured timestamp */ + rtapi_s32 index_count; /* c:rw captured index count */ + rtapi_s32 latch_count; /* c:rw captured index count */ + hal_sint_t count; /* c:w captured binary count value */ + hal_sint_t count_latch; /* c:w captured binary count value */ + hal_real_t min_speed; /* c:r minimum velocity to estimate nonzero */ + hal_real_t pos; /* c:w scaled position (floating point) */ + hal_real_t pos_interp; /* c:w scaled and interpolated position (float) */ + hal_real_t pos_latch; /* c:w scaled latched position (floating point) */ + hal_real_t vel; /* c:w scaled velocity (floating point) */ + hal_real_t vel_rpm; /* rps * 60 for convenience */ + hal_real_t pos_scale; /* c:r pin: scaling factor for pos */ + rtapi_bool old_latch; /* value of latch on previous cycle */ double old_scale; /* c:rw stored scale value */ double scale; /* c:rw reciprocal value used for scaling */ int counts_since_timeout; /* c:rw used for velocity calcs */ @@ -231,7 +232,7 @@ int rtapi_app_main(void) return -1; } /* allocate shared memory for counter data */ - counter_array = hal_malloc(howmany * sizeof(counter_t)); + counter_array = hal_malloc(howmany * sizeof(*counter_array)); if (counter_array == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "ENCODER: ERROR: hal_malloc() failed\n"); @@ -264,27 +265,27 @@ int rtapi_app_main(void) cntr->oldZ = 0; cntr->Zmask = 0; cntr->gaps = 0; - *(cntr->x4_mode) = 1; - *(cntr->counter_mode) = 0; - *(cntr->latch_rising) = 1; - *(cntr->latch_falling) = 1; + hal_set_bool(cntr->x4_mode, 1); + hal_set_bool(cntr->counter_mode, 0); + hal_set_bool(cntr->latch_rising, 1); + hal_set_bool(cntr->latch_falling, 1); cntr->buf[0].count_detected = 0; cntr->buf[1].count_detected = 0; cntr->buf[0].index_detected = 0; cntr->buf[1].index_detected = 0; cntr->bp = &(cntr->buf[0]); - *(cntr->raw_counts) = 0; + hal_set_si32(cntr->raw_counts, 0); cntr->raw_count = 0; cntr->timestamp = 0; cntr->index_count = 0; cntr->latch_count = 0; - *(cntr->count) = 0; - *(cntr->min_speed) = 1.0; - *(cntr->pos) = 0.0; - *(cntr->pos_latch) = 0.0; - *(cntr->vel) = 0.0; - *(cntr->vel_rpm) = 0.0; - *(cntr->pos_scale) = 1.0; + hal_set_si32(cntr->count, 0); + hal_set_real(cntr->min_speed, 1.0); + hal_set_real(cntr->pos, 0.0); + hal_set_real(cntr->pos_latch, 0.0); + hal_set_real(cntr->vel, 0.0); + hal_set_real(cntr->vel_rpm, 0.0); + hal_set_real(cntr->pos_scale, 1.0); cntr->old_scale = 1.0; cntr->scale = 1.0; cntr->counts_since_timeout = 0; @@ -332,37 +333,35 @@ static void update(void *arg, long period) cntr = arg; for (n = 0; n < howmany; n++) { buf = (atomic *) cntr->bp; - cntr->dt += period; + hal_set_si32(cntr->dt, hal_get_si32(cntr->dt) + period); /* get state machine current state */ state = cntr->state; /* add input bits to state code */ - if (*(cntr->phaseA)) { + if (hal_get_bool(cntr->phaseA)) { state |= SM_PHASE_A_MASK; } - if (*(cntr->phaseB)) { + if (hal_get_bool(cntr->phaseB)) { state |= SM_PHASE_B_MASK; } /* look up new state */ - if ( *(cntr->counter_mode) ) { + if ( hal_get_bool(cntr->counter_mode) ) { state = lut_ctr[state & (SM_LOOKUP_MASK & ~SM_PHASE_B_MASK)]; - } else if ( *(cntr->x4_mode) ) { + } else if ( hal_get_bool(cntr->x4_mode) ) { state = lut_x4[state & SM_LOOKUP_MASK]; } else { state = lut_x1[state & SM_LOOKUP_MASK]; } /* should we count? */ if (state & SM_CNT_UP_MASK) { - if (*(cntr->missing_teeth) && cntr->dt > cntr->limit_dt){ + if (hal_get_si32(cntr->missing_teeth) && hal_get_si32(cntr->dt) > hal_get_si32(cntr->limit_dt)){ cntr->gaps++; } - (*cntr->raw_counts)++; - buf->raw_count = *(cntr->raw_counts); + buf->raw_count = hal_set_si32(cntr->raw_counts, hal_get_si32(cntr->raw_counts) + 1); buf->timestamp = timebase; buf->count_detected = 1; - cntr->dt = 0; + hal_set_si32(cntr->dt, 0); } else if (state & SM_CNT_DN_MASK) { - (*cntr->raw_counts)--; - buf->raw_count = *(cntr->raw_counts); + buf->raw_count = hal_set_si32(cntr->raw_counts, hal_get_si32(cntr->raw_counts) - 1); buf->timestamp = timebase; buf->count_detected = 1; } @@ -371,26 +370,26 @@ static void update(void *arg, long period) /* get old phase Z state, make room for new bit value */ state = cntr->oldZ << 1; /* add new value of phase Z */ - if (*(cntr->phaseZ) || cntr->gaps) { + if (hal_get_bool(cntr->phaseZ) || cntr->gaps) { state |= 1; } cntr->oldZ = state & 3; /* test for index enabled and rising edge on phase Z */ if ((state & cntr->Zmask) == 1) { /* capture counts, reset Zmask */ - buf->index_count = *(cntr->raw_counts); + buf->index_count = hal_get_si32(cntr->raw_counts); buf->index_detected = 1; cntr->Zmask = 0; } /* test for latch enabled and desired edge on latch-in */ - latch = *(cntr->latch_in), old_latch = cntr->old_latch; + latch = hal_get_bool(cntr->latch_in), old_latch = cntr->old_latch; rising = latch && !old_latch; falling = !latch && old_latch; - if((rising && *(cntr->latch_rising)) - || (falling && *(cntr->latch_falling))) { + if((rising && hal_get_bool(cntr->latch_rising)) + || (falling && hal_get_bool(cntr->latch_falling))) { buf->latch_detected = 1; - buf->latch_count = *(cntr->raw_counts); + buf->latch_count = hal_get_si32(cntr->raw_counts); } cntr->old_latch = latch; @@ -427,7 +426,7 @@ static void capture(void *arg, long period) if ( buf->index_detected ) { buf->index_detected = 0; cntr->index_count = buf->index_count; - *(cntr->index_ena) = 0; + hal_set_bool(cntr->index_ena, 0); } /* handle latch */ if ( buf->latch_detected ) { @@ -436,41 +435,42 @@ static void capture(void *arg, long period) } /* update Zmask based on index_ena */ - if (*(cntr->index_ena)) { + if (hal_get_bool(cntr->index_ena)) { cntr->Zmask = 3; } else { cntr->Zmask = 0; } /* done interacting with update() */ /* check for change in scale value */ - if ( *(cntr->pos_scale) != cntr->old_scale ) { + if ( hal_get_real(cntr->pos_scale) != cntr->old_scale ) { /* save new scale to detect future changes */ - cntr->old_scale = *(cntr->pos_scale); + cntr->old_scale = hal_get_real(cntr->pos_scale); /* scale value has changed, test and update it */ - if ((*(cntr->pos_scale) < 1e-20) && (*(cntr->pos_scale) > -1e-20)) { + if ((hal_get_real(cntr->pos_scale) < 1e-20) && (hal_get_real(cntr->pos_scale) > -1e-20)) { /* value too small, divide by zero is a bad thing */ - *(cntr->pos_scale) = 1.0; + hal_set_real(cntr->pos_scale, 1.0); } /* we actually want the reciprocal */ - cntr->scale = 1.0 / *(cntr->pos_scale); + cntr->scale = 1.0 / hal_get_real(cntr->pos_scale); } /* check for valid min_speed */ - if ( *(cntr->min_speed) == 0 ) { - *(cntr->min_speed) = 1; + if ( hal_get_real(cntr->min_speed) == 0 ) { + hal_set_real(cntr->min_speed, 1); } /* check reset input */ - if (*(cntr->reset)) { + if (hal_get_bool(cntr->reset)) { /* reset is active, reset the counter */ /* note: we NEVER reset raw_counts, that is always a running count of edges seen since startup. The public "count" is the difference between raw_count and index_count, so it will become zero. */ - cntr->raw_count = *(cntr->raw_counts); + cntr->raw_count = hal_get_si32(cntr->raw_counts); cntr->index_count = cntr->raw_count; } /* process data from update() */ if ( buf->count_detected ) { + rtapi_s32 missing_teeth = hal_get_si32(cntr->missing_teeth); /* one or more counts in the last period */ buf->count_detected = 0; delta_time = buf->timestamp - cntr->timestamp; @@ -478,62 +478,64 @@ static void capture(void *arg, long period) // lowpass the gap detector deliberately ignoring missing teeth // see https://github.com/LinuxCNC/linuxcnc/issues/2635 if (delta_counts != 0){ - cntr->limit_dt *= 0.9; - cntr->limit_dt += 0.1 * ((*(cntr->missing_teeth) + 0.5) * (delta_time / delta_counts)); + rtapi_s32 limit_dt = hal_get_si32(cntr->limit_dt); + limit_dt *= 0.9; + limit_dt += 0.1 * ((missing_teeth + 0.5) * (delta_time / delta_counts)); + hal_set_si32(cntr->limit_dt, limit_dt); } // correct counts for tooth gap - *cntr->raw_counts += *(cntr->missing_teeth) * cntr->gaps; - cntr->raw_count = buf->raw_count + *(cntr->missing_teeth) * cntr->gaps; - delta_counts += *(cntr->missing_teeth) * cntr->gaps; + hal_set_si32(cntr->raw_counts, hal_get_si32(cntr->raw_counts) + missing_teeth * cntr->gaps); + cntr->raw_count = buf->raw_count + missing_teeth * cntr->gaps; + delta_counts += missing_teeth * cntr->gaps; cntr->gaps = 0; cntr->timestamp = buf->timestamp; if ( cntr->counts_since_timeout < 2 ) { cntr->counts_since_timeout++; } else { vel = (delta_counts * cntr->scale ) / (delta_time * 1e-9); - *(cntr->vel) = vel; + hal_set_real(cntr->vel, vel); } } else { /* no count */ if ( cntr->counts_since_timeout ) { /* calc time since last count */ delta_time = timebase - cntr->timestamp; - if (*(cntr->missing_teeth) && delta_time > 1.5 * cntr->limit_dt){ + if (hal_get_si32(cntr->missing_teeth) && delta_time > 1.5 * hal_get_si32(cntr->limit_dt)){ // dont update the velocity in the tooth gap - } else if ( delta_time < 1e9 / ( *(cntr->min_speed) * cntr->scale )) { + } else if ( delta_time < 1e9 / ( hal_get_real(cntr->min_speed) * cntr->scale )) { /* not to long, estimate vel if a count arrived now */ vel = ( cntr->scale ) / (delta_time * 1e-9); /* make vel positive, even if scale is negative */ if ( vel < 0.0 ) vel = -vel; /* use lesser of estimate and previous value */ /* use sign of previous value, magnitude of estimate */ - if ( vel < *(cntr->vel) ) { - *(cntr->vel) = vel; + if ( vel < hal_get_real(cntr->vel) ) { + hal_set_real(cntr->vel, vel); } - if ( -vel > *(cntr->vel) ) { - *(cntr->vel) = -vel; + if ( -vel > hal_get_real(cntr->vel) ) { + hal_set_real(cntr->vel, -vel); } } else { /* its been a long time, stop estimating */ cntr->counts_since_timeout = 0; - *(cntr->vel) = 0; + hal_set_real(cntr->vel, 0); } } else { /* we already stopped estimating */ - *(cntr->vel) = 0; + hal_set_real(cntr->vel, 0); } } - *(cntr->vel_rpm) = *(cntr->vel) * 60.0; + hal_set_real(cntr->vel_rpm, hal_get_real(cntr->vel) * 60.0); /* compute net counts */ - *(cntr->count) = cntr->raw_count - cntr->index_count; - *(cntr->count_latch) = cntr->latch_count - cntr->index_count; + hal_set_si32(cntr->count, cntr->raw_count - cntr->index_count); + hal_set_si32(cntr->count_latch, cntr->latch_count - cntr->index_count); /* scale count to make floating point position */ - *(cntr->pos) = *(cntr->count) * cntr->scale; - *(cntr->pos_latch) = *(cntr->count_latch) * cntr->scale; + hal_set_real(cntr->pos, hal_get_si32(cntr->count) * cntr->scale); + hal_set_real(cntr->pos_latch, hal_get_si32(cntr->count_latch) * cntr->scale); /* add interpolation value */ delta_time = timebase - cntr->timestamp; - interp = *(cntr->vel) * (delta_time * 1e-9); - *(cntr->pos_interp) = *(cntr->pos) + interp; + interp = hal_get_real(cntr->vel) * (delta_time * 1e-9); + hal_set_real(cntr->pos_interp, hal_get_real(cntr->pos) + interp); /* move on to next channel */ cntr++; } @@ -556,143 +558,145 @@ static int export_encoder(counter_t * addr,char * prefix) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pins for the quadrature inputs */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->phaseA), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->phaseA), 0, "%s.phase-A", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->phaseB), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->phaseB), 0, "%s.phase-B", prefix); if (retval != 0) { return retval; } /* export pin for the index input */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->phaseZ), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->phaseZ), 0, "%s.phase-Z", prefix); if (retval != 0) { return retval; } /* export pin for the index enable input */ - retval = hal_pin_bit_newf(HAL_IO, &(addr->index_ena), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IO, &(addr->index_ena), 0, "%s.index-enable", prefix); if (retval != 0) { return retval; } /* export pin for the reset input */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->reset), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->reset), 0, "%s.reset", prefix); if (retval != 0) { return retval; } /* export pins for position latching */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->latch_in), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->latch_in), 0, "%s.latch-input", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->latch_rising), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->latch_rising), 0, "%s.latch-rising", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->latch_falling), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->latch_falling), 0, "%s.latch-falling", prefix); if (retval != 0) { return retval; } /* export parameter for raw counts */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->raw_counts), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->raw_counts), 0, "%s.rawcounts", prefix); if (retval != 0) { return retval; } /* export pin for counts captured by capture() */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->count), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->count), 0, "%s.counts", prefix); if (retval != 0) { return retval; } /* export pin for counts latched by capture() */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->count_latch), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->count_latch), 0, "%s.counts-latched", prefix); if (retval != 0) { return retval; } /* export pin for minimum speed estimated by capture() */ - retval = hal_pin_float_newf(HAL_IN, &(addr->min_speed), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->min_speed), 0.0, "%s.min-speed-estimate", prefix); if (retval != 0) { return retval; } /* export pin for scaled position captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->pos), 0.0, "%s.position", prefix); if (retval != 0) { return retval; } /* export pin for scaled and interpolated position captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos_interp), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->pos_interp), 0.0, "%s.position-interpolated", prefix); if (retval != 0) { return retval; } /* export pin for latched position captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos_latch), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->pos_latch), 0.0, "%s.position-latched", prefix); if (retval != 0) { return retval; } /* export pin for scaled velocity captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->vel), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->vel), 0.0, "%s.velocity", prefix); if (retval != 0) { return retval; } /* export pin for scaled velocity captured by capture() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->vel_rpm), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->vel_rpm), 0.0, "%s.velocity-rpm", prefix); if (retval != 0) { return retval; } /* export pin for scaling */ - retval = hal_pin_float_newf(HAL_IO, &(addr->pos_scale), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->pos_scale), 0.0, "%s.position-scale", prefix); if (retval != 0) { return retval; } /* export pin for x4 mode */ - retval = hal_pin_bit_newf(HAL_IO, &(addr->x4_mode), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IO, &(addr->x4_mode), 0, "%s.x4-mode", prefix); if (retval != 0) { return retval; } /* export pin for counter mode */ - retval = hal_pin_bit_newf(HAL_IO, &(addr->counter_mode), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IO, &(addr->counter_mode), 0, "%s.counter-mode", prefix); if (retval != 0) { return retval; } /* export pin for missing-tooth index */ - retval = hal_pin_s32_newf(HAL_IN, &(addr->missing_teeth), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_IN, &(addr->missing_teeth), 0, "%s.missing-teeth", prefix); if (retval != 0) { return retval; } -/* uncomment to debug missing tooth - retval = hal_param_s32_newf(HAL_RO, &(addr->dt), comp_id, + // These two, 'dt' and 'limit_dt' were commented out. However, they are + // used in the code and if they can be parameters, them they must be + // created. Parameters and pins work the same now and you can no longer + // abuse parameters as (very expensive) variables. + retval = hal_param_new_si32(comp_id, HAL_RO, &(addr->dt), 0, "%s.dt", prefix); if (retval != 0) { return retval; } - retval = hal_param_s32_newf(HAL_RO, &(addr->limit_dt), comp_id, + retval = hal_param_new_si32(comp_id, HAL_RO, &(addr->limit_dt), 0, "%s.limit_dt", prefix); if (retval != 0) { return retval; } -*/ /* restore saved message level */ rtapi_set_msg_level(msg); diff --git a/src/hal/components/encoder_ratio.c b/src/hal/components/encoder_ratio.c index 9a17ea26e18..3adf5c0ce07 100644 --- a/src/hal/components/encoder_ratio.c +++ b/src/hal/components/encoder_ratio.c @@ -116,22 +116,22 @@ RTAPI_MP_ARRAY_STRING(names,MAX_CHAN,"encoder_ratio names"); /* this structure contains the runtime data for a single counter */ typedef struct { - hal_bit_t *master_A; /* quadrature input */ - hal_bit_t *master_B; /* quadrature input */ - hal_bit_t *slave_A; /* quadrature input */ - hal_bit_t *slave_B; /* quadrature input */ - hal_bit_t *enable; /* enable input */ - unsigned char master_state; /* quad decode state machine state */ - unsigned char slave_state; /* quad decode state machine state */ + hal_bool_t master_A; /* quadrature input */ + hal_bool_t master_B; /* quadrature input */ + hal_bool_t slave_A; /* quadrature input */ + hal_bool_t slave_B; /* quadrature input */ + hal_bool_t enable; /* enable input */ + unsigned master_state; /* quad decode state machine state */ + unsigned slave_state; /* quad decode state machine state */ int raw_error; /* internal data */ int master_increment; /* internal data */ int slave_increment; /* internal data */ double output_scale; /* internal data */ - hal_float_t *error; /* error output */ - hal_u32_t *master_ppr; /* parameter: master encoder PPR */ - hal_u32_t *slave_ppr; /* parameter: slave encoder PPR */ - hal_u32_t *master_teeth; /* parameter: master "gear" tooth count */ - hal_u32_t *slave_teeth; /* parameter: slave "gear" tooth count */ + hal_real_t error; /* error output */ + hal_uint_t master_ppr; /* parameter: master encoder PPR */ + hal_uint_t slave_ppr; /* parameter: slave encoder PPR */ + hal_uint_t master_teeth; /* parameter: master "gear" tooth count */ + hal_uint_t slave_teeth; /* parameter: slave "gear" tooth count */ } encoder_pair_t; /* pointer to array of counter_t structs in shmem, 1 per counter */ @@ -240,7 +240,7 @@ int rtapi_app_main(void) encoder_pair_array[n].slave_increment = 0; encoder_pair_array[n].raw_error = 0; encoder_pair_array[n].output_scale = 1.0; - *(encoder_pair_array[n].error) = 0.0; + hal_set_real(encoder_pair_array[n].error, 0.0); } /* export functions */ retval = hal_export_funct("encoder-ratio.sample", sample, @@ -279,7 +279,7 @@ static void sample(void *arg, long period) (void)period; encoder_pair_t *pair; int n; - unsigned char state; + unsigned state; pair = arg; for (n = 0; n < howmany; n++) { @@ -287,16 +287,16 @@ static void sample(void *arg, long period) /* get state machine current state */ state = pair->master_state; /* add input bits to state code */ - if (*(pair->master_A)) { + if (hal_get_bool(pair->master_A)) { state |= SM_PHASE_A_MASK; } - if (*(pair->master_B)) { + if (hal_get_bool(pair->master_B)) { state |= SM_PHASE_B_MASK; } /* look up new state */ state = lut[state & SM_LOOKUP_MASK]; /* are we enabled? */ - if ( *(pair->enable) != 0 ) { + if ( hal_get_bool(pair->enable) != 0 ) { /* has an edge been detected? */ if (state & SM_CNT_UP_MASK) { pair->raw_error -= pair->master_increment; @@ -310,10 +310,10 @@ static void sample(void *arg, long period) /* get state machine current state */ state = pair->slave_state; /* add input bits to state code */ - if (*(pair->slave_A)) { + if (hal_get_bool(pair->slave_A)) { state |= SM_PHASE_A_MASK; } - if (*(pair->slave_B)) { + if (hal_get_bool(pair->slave_B)) { state |= SM_PHASE_B_MASK; } /* look up new state */ @@ -342,13 +342,13 @@ static void update(void *arg, long period) for (n = 0; n < howmany; n++) { /* scale raw error to output pin */ if ( pair->output_scale > 0 ) { - *(pair->error) = pair->raw_error / pair->output_scale; + hal_set_real(pair->error, pair->raw_error / pair->output_scale); } /* update scale factors (only needed if params change, but it's faster to do it every time than to detect changes.) */ - pair->master_increment = *(pair->master_teeth) * *(pair->slave_ppr); - pair->slave_increment = *(pair->slave_teeth) * *(pair->master_ppr); - pair->output_scale = *(pair->master_ppr) * *(pair->slave_ppr) * *(pair->slave_teeth); + pair->master_increment = hal_get_ui32(pair->master_teeth) * hal_get_ui32(pair->slave_ppr); + pair->slave_increment = hal_get_ui32(pair->slave_teeth) * hal_get_ui32(pair->master_ppr); + pair->output_scale = hal_get_ui32(pair->master_ppr) * hal_get_ui32(pair->slave_ppr) * hal_get_ui32(pair->slave_teeth); /* move on to next pair */ pair++; } @@ -372,55 +372,55 @@ static int export_encoder_pair(int num, encoder_pair_t * addr, char* prefix) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pins for the quadrature inputs */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->master_A), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->master_A), 0, "%s.master-A", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->master_B), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->master_B), 0, "%s.master-B", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->slave_A), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->slave_A), 0, "%s.slave-A", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->slave_B), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->slave_B), 0, "%s.slave-B", prefix); if (retval != 0) { return retval; } /* export pin for the enable input */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->enable), 0, "%s.enable", prefix); if (retval != 0) { return retval; } /* export pin for output */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->error), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->error), 0.0, "%s.error", prefix); if (retval != 0) { return retval; } /* export pins for config info() */ - retval = hal_pin_u32_newf(HAL_IO, &(addr->master_ppr), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IO, &(addr->master_ppr), 0, "%s.master-ppr", prefix); if (retval != 0) { return retval; } - retval = hal_pin_u32_newf(HAL_IO, &(addr->slave_ppr), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IO, &(addr->slave_ppr), 0, "%s.slave-ppr", prefix); if (retval != 0) { return retval; } - retval = hal_pin_u32_newf(HAL_IO, &(addr->master_teeth), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IO, &(addr->master_teeth), 0, "%s.master-teeth", prefix); if (retval != 0) { return retval; } - retval = hal_pin_u32_newf(HAL_IO, &(addr->slave_teeth), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IO, &(addr->slave_teeth), 0, "%s.slave-teeth", prefix); if (retval != 0) { return retval; diff --git a/src/hal/components/enum.c b/src/hal/components/enum.c index 061d4271d20..e6ecf728779 100644 --- a/src/hal/components/enum.c +++ b/src/hal/components/enum.c @@ -36,8 +36,8 @@ MODULE_LICENSE("GPL"); #define MAX_CHAN 256 typedef struct { - hal_bit_t *bit; - hal_u32_t *en; // note use index 0 differently + hal_bool_t bit; + hal_uint_t en; // note use index 0 differently } enum_hal_t; typedef struct{ @@ -137,10 +137,10 @@ int rtapi_app_main(void){ // create single per-instance int pin in index 0 if (inst->dir == HAL_OUT) { - retval = hal_pin_u32_newf(HAL_IN, &(inst->hal[0].en), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &(inst->hal[0].en), 0, "%s.input", this); } else { - retval = hal_pin_u32_newf(HAL_OUT, &(inst->hal[0].en), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal[0].en), 0, "%s.output", this); } v = 0; @@ -150,12 +150,11 @@ int rtapi_app_main(void){ //increment for skipped enumerations while (*(++token) == 0) v++; - retval = hal_pin_bit_newf(inst->dir, &(inst->hal[j].bit), - comp_id, "%s.%s-%s",this, token, + retval = hal_pin_new_bool(comp_id, inst->dir, &(inst->hal[j].bit), + 0, "%s.%s-%s",this, token, (inst->dir == HAL_IN)?"in":"out"); - retval += hal_pin_u32_newf(HAL_IN, &(inst->hal[j].en), - comp_id, "%s.%s-val",this, token); - *(inst->hal[j].en) = v++; + retval += hal_pin_new_ui32(comp_id, HAL_IN, &(inst->hal[j].en), + v++, "%s.%s-val",this, token); if (retval < 0){ rtapi_print_msg(RTAPI_MSG_ERR, "Failed to create HAL pins\n"); @@ -191,10 +190,10 @@ static void decode(void *v_inst, long period){ int i; enum_inst_t *inst = v_inst; for (i = 1; i <= inst->num_pins; i++){ - if (*(inst->hal[0].en) == *(inst->hal[i].en)){ - *(inst->hal[i].bit) = 1; + if (hal_get_ui32(inst->hal[0].en) == hal_get_ui32(inst->hal[i].en)){ + hal_set_bool(inst->hal[i].bit, 1); } else { - *(inst->hal[i].bit) = 0; + hal_set_bool(inst->hal[i].bit, 0); } } } @@ -202,10 +201,10 @@ static void encode(void *v_inst, long period){ (void)period; int i; enum_inst_t *inst = v_inst; - *(inst->hal[0].en) = 0; + hal_set_ui32(inst->hal[0].en, 0); for (i = 1; i <= inst->num_pins; i++){ - if (*(inst->hal[i].bit)){ - *(inst->hal[0].en) = *(inst->hal[i].en); + if (hal_get_bool(inst->hal[i].bit)){ + hal_set_ui32(inst->hal[0].en, hal_get_ui32(inst->hal[i].en)); } } } diff --git a/src/hal/components/eoffset_per_angle.comp b/src/hal/components/eoffset_per_angle.comp index 69f00e2153a..aa0922c148b 100644 --- a/src/hal/components/eoffset_per_angle.comp +++ b/src/hal/components/eoffset_per_angle.comp @@ -61,27 +61,27 @@ transverse *X* coordinate according to the selected *fnum* function. //" quote char for vim highlighting -pin in bit active = 0 "From: motion.eoffset-active"; -pin in bit is_on = 0 "From: halui.machine.is-on"; +pin in bool active = 0 "From: motion.eoffset-active"; +pin in bool is_on = 0 "From: halui.machine.is-on"; -pin in bit enable_in = 0 "Enable Input"; -pin in float radius_ref = 1 "Radius reference (see notes)"; -pin in float angle = 0 "Input angle (in degrees)"; -pin in float start_angle = 0 "Start angle (in degrees)"; -pin in s32 fnum = 0 "Function selector (default 0)"; -pin in float rfraction = 0.1 "Offset amplitude (+/- fraction of radius_ref)"; -pin in float fmult = 6 "Offset frequency multiplier"; -pin in u32 k = 10000 "Scaling Factor (if 0, use 10000)"; +pin in bool enable_in = 0 "Enable Input"; +pin in real radius_ref = 1 "Radius reference (see notes)"; +pin in real angle = 0 "Input angle (in degrees)"; +pin in real start_angle = 0 "Start angle (in degrees)"; +pin in si32 fnum = 0 "Function selector (default 0)"; +pin in real rfraction = 0.1 "Offset amplitude (+/- fraction of radius_ref)"; +pin in real fmult = 6 "Offset frequency multiplier"; +pin in ui32 k = 10000 "Scaling Factor (if 0, use 10000)"; -pin out bit is_off "invert is_on (for convenience)"; +pin out bool is_off "invert is_on (for convenience)"; -pin out bit enable_out "To: axis.L.eoffset-enable"; -pin out bit clear "To: axis.L.eoffset-clear"; -pin out s32 kcounts "To: axis.L.eoffset-counts"; -pin out float kreciprocal "To: axis.L.eoffset-scale (1/k)"; +pin out bool enable_out "To: axis.L.eoffset-enable"; +pin out bool clear "To: axis.L.eoffset-clear"; +pin out si32 kcounts "To: axis.L.eoffset-counts"; +pin out real kreciprocal "To: axis.L.eoffset-scale (1/k)"; -pin out float eoffset_dbg "offset (debug pin--use kcounts & kreciprocal)"; -pin out u32 state_dbg "state (debug pin)"; +pin out real eoffset_dbg "offset (debug pin--use kcounts & kreciprocal)"; +pin out ui32 state_dbg "state (debug pin)"; //--------------------------------------------------------------------- // per-instance items: @@ -151,19 +151,20 @@ FUNCTION(_) { ofunc* thefunc; run_ct++; - state_dbg = STATE; + state_dbg_set(STATE); kfactor = k; if (k == 0) {kfactor = 10000;} - kreciprocal = 1/((float)kfactor); + kreciprocal_set(1/((rtapi_real)kfactor)); - is_off = !is_on; // convenience pin + is_off_set(!is_on); // convenience pin if (is_off) { // note: the external_offsets implementation defines // axis.L.eoffset as zero when machine is off err_stop = 0; - enable_out = 0; - kcounts = 0; eoffset_dbg = 0; + enable_out_set(0); + kcounts_set(0); + eoffset_dbg_set(0); messaged = 0; STATE = OFF; return; @@ -182,15 +183,16 @@ FUNCTION(_) { } err_stop = 0; messaged = 1; - kcounts = 0; + kcounts_set(0); STATE = READY; dprint("OFF->READY",kcounts); return; break; case READY: if (!enable_in) {return;} - kcounts = 0; eoffset_dbg = 0; - enable_out = 0; + kcounts_set(0); + eoffset_dbg_set(0); + enable_out_set(0); delay_ct = 0; STATE = RUNNING; dprint("READY->RUNNING",kcounts); @@ -198,7 +200,7 @@ FUNCTION(_) { break; case RUNNING: if (enable_in) { - enable_out = 1; + enable_out_set(1); STATE = RUNNING; } else { /* @@ -210,8 +212,9 @@ FUNCTION(_) { ** to zero to remove any residual with no modifications to ** simple_tp.c */ - clear = 1; - kcounts = 0; eoffset_dbg = 0; + clear_set(1); + kcounts_set(0); + eoffset_dbg_set(0); STATE = STOPPING; delay_ct = run_ct; dprint("RUNNING->STOPPING",kcounts); @@ -234,7 +237,7 @@ FUNCTION(_) { if (run_ct < (FINISH_DELAY + delay_ct) ) { STATE = FINISH; } else { - enable_out = 0; + enable_out_set(0); if (err_stop) { STATE = OFF; dprint("FINISH->OFF",kcounts); @@ -243,7 +246,7 @@ FUNCTION(_) { dprint("FINISH->READY",kcounts); } } - clear = 0; + clear_set(0); return; break; } //switch (STATE) @@ -265,15 +268,16 @@ FUNCTION(_) { // thefunc returned nonzero (problem) err_stop = 1; dptr->ovalue = 0; - kcounts = 0; eoffset_dbg = 0; + kcounts_set(0); + eoffset_dbg_set(0); STATE = STOPPING; rtapi_print_msg(RTAPI_MSG_ERR, "eoffset_per_angle stopping:func%d problem\n",fnum); return; } - kcounts = kfactor * dptr->ovalue; - eoffset_dbg = kcounts * kreciprocal; // debug pin + kcounts_set(kfactor * dptr->ovalue); + eoffset_dbg_set(kcounts * kreciprocal); // debug pin return; } diff --git a/src/hal/components/estop_latch.comp b/src/hal/components/estop_latch.comp index a97fd002c2c..09db1319f7f 100644 --- a/src/hal/components/estop_latch.comp +++ b/src/hal/components/estop_latch.comp @@ -36,12 +36,12 @@ In more complex systems, it may be more appropriate to use classicladder to manage the software portion of the estop chain. """; -pin in bit ok_in = true; -pin in bit fault_in = false; -pin in bit reset; -pin out bit ok_out = false; -pin out bit fault_out = true; -pin out bit watchdog; +pin in bool ok_in = true; +pin in bool fault_in = false; +pin in bool reset; +pin out bool ok_out = false; +pin out bool fault_out = true; +pin out bool watchdog; option period no; function _; option data estop_data; @@ -57,17 +57,17 @@ FUNCTION(_) { /* no fault conditions, check for reset edge */ if ( reset && !data.old_reset ) { /* got a rising edge, indicate "OK" on outputs */ - ok_out = 1; - fault_out = 0; + ok_out_set(1); + fault_out_set(0); } if( ok_out ) { /* toggle watchdog */ - watchdog = !watchdog; + watchdog_set(!watchdog); } } else { /* fault condition exists, trip */ - ok_out = 0; - fault_out = 1; + ok_out_set(0); + fault_out_set(1); } /* store state of reset input for next pass (for edge detect) */ data.old_reset = reset; diff --git a/src/hal/components/feedcomp.comp b/src/hal/components/feedcomp.comp index 12cafd9fae7..6ce146b100d 100644 --- a/src/hal/components/feedcomp.comp +++ b/src/hal/components/feedcomp.comp @@ -15,11 +15,11 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. component feedcomp "Multiply the input by the ratio of current velocity to the feed rate."; -pin out float out "Proportionate output value"; -pin in float in "Reference value"; -pin in bit enable "Turn compensation on or off."; -pin in float vel "Current velocity"; -param rw float feed "Feed rate reference value"; +pin out real out "Proportionate output value"; +pin in real in "Reference value"; +pin in bool enable "Turn compensation on or off."; +pin in real vel "Current velocity"; +param rw real feed "Feed rate reference value"; notes "Note that if enable is false, out = in."; option period no; @@ -28,6 +28,6 @@ license "GPL"; author "Eric H. Johnson"; ;; FUNCTION(_) { - if (enable) out = in * (vel / feed); - else out = in; + if (enable) out_set(in * (vel / feed)); + else out_set(in); } diff --git a/src/hal/components/filter_kalman.comp b/src/hal/components/filter_kalman.comp index ad0c522d4b2..db96f69d4f2 100644 --- a/src/hal/components/filter_kalman.comp +++ b/src/hal/components/filter_kalman.comp @@ -44,23 +44,23 @@ Common practice is also to conservatively set *Rk* and *Qk* slightly larger then ones to get robustness. """; -pin in bit debug = FALSE "When asserted, prints out measured and estimated values."; -pin in bit passthrough = FALSE "When asserted, copies measured value into estimated value."; -pin in bit reset = FALSE +pin in bool debug = FALSE "When asserted, prints out measured and estimated values."; +pin in bool passthrough = FALSE "When asserted, copies measured value into estimated value."; +pin in bool reset = FALSE """When asserted, resets filter to its initial state and returns 0 as an estimated value (*reset* pin has higher priority than *passthrough* pin)."""; -pin in float zk "Measured value."; -pin out float xk_out "Estimated value."; -param rw float Rk = 1.17549e-38 "Estimation of the noise covariances (process)."; -param rw float Qk = 1.17549e-38 "Estimation of the noise covariances (observation)."; +pin in real zk "Measured value."; +pin out real xk_out "Estimated value."; +param rw real Rk = 1.17549e-38 "Estimation of the noise covariances (process)."; +param rw real Qk = 1.17549e-38 "Estimation of the noise covariances (observation)."; option extra_setup yes; option period no; function _ "Update *xk-out* based on *zk* input."; -variable float xk_last; -variable float Pk_last; +variable rtapi_real xk_last; +variable rtapi_real Pk_last; variable bool initialized = FALSE; variable int cidx = 0; @@ -68,7 +68,7 @@ variable int cidx = 0; ;; #include -typedef hal_float_t D; // to Keep code synchronized with C++ based TrivialKalmanFilter implementation. +typedef rtapi_real D; // to Keep code synchronized with C++ based TrivialKalmanFilter implementation. // Based on: https://github.com/dwrobel/TrivialKalmanFilter/blob/master/src/TrivialKalmanFilter.h // Assumes simplified model @@ -101,7 +101,7 @@ FUNCTION(_) { initialized = TRUE; if (reset) { - xk_out = 0; + xk_out_set(0); if (debug) { print_info(cidx, zk, xk_out); @@ -112,7 +112,7 @@ FUNCTION(_) { } if (passthrough) { - xk_out = zk; + xk_out_set(zk); if (debug) { print_info(cidx, zk, xk_out); @@ -136,7 +136,7 @@ FUNCTION(_) { xk_last = xk; Pk_last = Pk; - xk_out = xk; + xk_out_set(xk); if (debug) { print_info(cidx, zk, xk_out); diff --git a/src/hal/components/flipflop.comp b/src/hal/components/flipflop.comp index 3cc6b5cfed6..6aaf27ad4f2 100644 --- a/src/hal/components/flipflop.comp +++ b/src/hal/components/flipflop.comp @@ -1,10 +1,10 @@ component flipflop "D type flip-flop"; -pin in bit data_ "data input"; -pin in bit clk "clock, rising edge writes data to out"; -pin in bit set "when true, force out true"; -pin in bit reset "when true, force out false; overrides set"; -pin io bit out "output"; -pin io bit out-not "inverted output"; +pin in bool data_ "data input"; +pin in bool clk "clock, rising edge writes data to out"; +pin in bool set "when true, force out true"; +pin in bool reset "when true, force out false; overrides set"; +pin io bool out "output"; +pin io bool out-not "inverted output"; option data flipflop_data; option period no; @@ -20,12 +20,13 @@ FUNCTION(_) { c = clk; if ( reset ) { - out = 0; + out_set(0); + out_not_set(1); } else if ( set ) { - out = 1; + out_set(1); + out_not_set(0); } else if ( c && ! data.oldclk ) { - out = data_; + out_not_set(!out_set(data_)); } - out_not = !out; data.oldclk = c; } diff --git a/src/hal/components/gantry.comp b/src/hal/components/gantry.comp index cbb12bb4d02..9a53e4e8d2d 100644 --- a/src/hal/components/gantry.comp +++ b/src/hal/components/gantry.comp @@ -39,15 +39,15 @@ ******************************************************************************/ component gantry "LinuxCNC HAL component for driving multiple joints from a single axis."; -pin out float joint.##.pos-cmd [7 : personality] "Per-joint commanded position"; -pin in float joint.##.pos-fb [7 : personality] "Per-joint position feedback"; -pin in bit joint.##.home [7 : personality] "Per-joint home switch"; -pin out float joint.##.offset [7 : personality] "(debugging) Per-joint offset value, updated when homing."; -pin in float position-cmd "Commanded position from motion"; -pin out float position-fb "Position feedback to motion"; -pin out bit home "Combined home signal, true if all joint home inputs are true."; -pin out bit limit "Combined limit signal, true if any joint home input is true."; -pin in float search-vel "HOME_SEARCH_VEL from INI file"; +pin out real joint.##.pos-cmd [7 : personality] "Per-joint commanded position"; +pin in real joint.##.pos-fb [7 : personality] "Per-joint position feedback"; +pin in bool joint.##.home [7 : personality] "Per-joint home switch"; +pin out real joint.##.offset [7 : personality] "(debugging) Per-joint offset value, updated when homing."; +pin in real position-cmd "Commanded position from motion"; +pin out real position-fb "Position feedback to motion"; +pin out bool home "Combined home signal, true if all joint home inputs are true."; +pin out bool limit "Combined limit signal, true if any joint home input is true."; +pin in real search-vel "HOME_SEARCH_VEL from INI file"; function read "Update position-fb and home/limit outputs based on joint values."; function write "Update joint pos-cmd outputs based on position-cmd in."; description """ @@ -81,8 +81,8 @@ When a joint home switch trips, the commanded velocity will drop immediately fro license "GPL"; author "Charles Steinkuehler"; option period no; -variable float offset[7] = 0.0; -variable float prev_cmd = 0.0; +variable rtapi_real offset[7] = 0.0; +variable rtapi_real prev_cmd = 0.0; variable int fb_joint = 0; variable int latching = 0; ;; @@ -90,8 +90,8 @@ FUNCTION(read) { int i=1; // First (or only) joint - home=joint_home(0); - limit=joint_home(0); + home_set(joint_home(0)); + limit_set(joint_home(0)); // All other joints, if configured while (i < personality) { @@ -99,20 +99,20 @@ FUNCTION(read) { if(latching==0) { // Don't assert home until all joints hit their home switches - home &= joint_home(i); + home_set(home && joint_home(i)); } else { // Don't release home until all joints have backed off their // home switches - home |= joint_home(i); + home_set(home || joint_home(i)); } // Remember the home state for next time latching=home; // Limit is always asserted if any home switch is asserted - limit |= joint_home(i); + limit_set(limit || joint_home(i)); i++; } @@ -123,19 +123,19 @@ FUNCTION(read) { if ((joint_home(fb_joint) == 1) && (home == 0)) { for (i=0; i < personality; i++) { if (joint_home(i) == 0) { - position_fb = joint_pos_fb(i) + offset[i]; + position_fb_set(joint_pos_fb(i) + offset[i]); fb_joint = i; break; } } } else { - position_fb = joint_pos_fb(fb_joint) + offset[fb_joint]; + position_fb_set(joint_pos_fb(fb_joint) + offset[fb_joint]); } } FUNCTION(write) { int i; - float delta; + rtapi_real delta; // Determine if we're moving in the same direction as home search @@ -164,8 +164,8 @@ FUNCTION(write) { // Update each joint's commanded position for (i=0; i < personality; i++) { - joint_pos_cmd(i) = position_cmd - offset[i]; - joint_offset(i) = offset[i]; + joint_pos_cmd_set(i, position_cmd - offset[i]); + joint_offset_set(i, offset[i]); } } diff --git a/src/hal/components/gearchange.comp b/src/hal/components/gearchange.comp index ddbb75c94b7..adc4ae99a55 100644 --- a/src/hal/components/gearchange.comp +++ b/src/hal/components/gearchange.comp @@ -5,19 +5,19 @@ The scale of gear 1 is assumed to be 1, so the output device scale should be chosen accordingly. The scale of gear 2 is relative to gear 1, so if gear 2 runs the spindle 2.5 times as fast as gear 1, scale2 should be set to 2.5."""; -pin in bit sel "Gear selection input"; -pin in float speed_in "Speed command input"; -pin out float speed_out "Speed command to DAC/PWM"; -pin in bit dir_in "Direction command input"; -pin out bit dir_out "Direction output - possibly inverted for second gear"; -param rw float min1 = 0 "Minimum allowed speed in gear range 1"; -param rw float max1 = 100000 "Maximum allowed speed in gear range 1"; -param rw float min2 = 0 "Minimum allowed speed in gear range 2"; -param rw float max2 = 100000 "Maximum allowed speed in gear range 2"; -param rw float scale2 = 1.0 """Relative scale of gear 2 vs. gear 1. +pin in bool sel "Gear selection input"; +pin in real speed_in "Speed command input"; +pin out real speed_out "Speed command to DAC/PWM"; +pin in bool dir_in "Direction command input"; +pin out bool dir_out "Direction output - possibly inverted for second gear"; +param rw real min1 = 0 "Minimum allowed speed in gear range 1"; +param rw real max1 = 100000 "Maximum allowed speed in gear range 1"; +param rw real min2 = 0 "Minimum allowed speed in gear range 2"; +param rw real max2 = 100000 "Maximum allowed speed in gear range 2"; +param rw real scale2 = 1.0 """Relative scale of gear 2 vs. gear 1. Since it is assumed that gear 2 is "high gear", *scale2* must be greater than 1, and will be reset to 1 if set lower."""; -param rw bit reverse = 0 "Set to 1 to reverse the spindle in second gear."; +param rw bool reverse = 0 "Set to 1 to reverse the spindle in second gear."; option period no; function _; @@ -25,11 +25,11 @@ license "GPL"; author "Stephen Wille Padnos"; ;; FUNCTION(_) { - hal_float_t temp_in = speed_in; - hal_float_t sign=1; + rtapi_real temp_in = speed_in; + rtapi_real sign=1; /* Assume that the output device is scaled so that gear 1 is "Pass-through" */ /* the other gear(s) need to be scaled by the relative scale for that gear */ - if (scale2 < 1) scale2 = 1; + if (scale2 < 1) scale2_set(1); if (temp_in < 0) { sign = -1; temp_in = -temp_in; @@ -38,11 +38,11 @@ FUNCTION(_) { if (temp_in < min2) temp_in = min2; else if (temp_in > max2) temp_in = max2; temp_in /= scale2; /* scale up to second gear output range */ - dir_out = dir_in ^ reverse; + dir_out_set(dir_in ^ reverse); } else { if (temp_in < min1) temp_in = min1; else if (temp_in > max1) temp_in = max1; - dir_out = dir_in; + dir_out_set(dir_in); } - speed_out = sign*temp_in; + speed_out_set(sign*temp_in); } diff --git a/src/hal/components/gray2bin.comp b/src/hal/components/gray2bin.comp index c73c5c02d03..f5590fa02cb 100644 --- a/src/hal/components/gray2bin.comp +++ b/src/hal/components/gray2bin.comp @@ -1,14 +1,15 @@ component gray2bin "convert a gray-code input to binary"; description """Converts a gray-coded number into the corresponding binary value"""; -pin in unsigned in "gray code in"; -pin out unsigned out "binary code out"; +pin in ui32 in "gray code in"; +pin out ui32 out "binary code out"; license "GPL"; author "Andy Pugh"; function _; option period no; ;; -unsigned int mask; -out = in; -for(mask = in >> 1 ; mask != 0 ; mask = mask >> 1){ - out ^= mask; +rtapi_u32 mask; +rtapi_u32 val = in; +for(mask = val >> 1 ; mask != 0 ; mask = mask >> 1){ + val ^= mask; } +out_set(val); diff --git a/src/hal/components/histobins.comp b/src/hal/components/histobins.comp index 2b708ec2bcb..2163467490b 100644 --- a/src/hal/components/histobins.comp +++ b/src/hal/components/histobins.comp @@ -42,36 +42,36 @@ Additional output statistics pins: The method input pin selects an alternate variance calculation. Maintainers note: hardcoded for MAXBINNUMBER==200 -"""; - -pin in u32 pintype; -pin in float input; -pin in s32 input_s32; -pin in u32 input_u32; -pin in bit input_bit; - -pin in u32 nbins = 20; // must be < MAXBINNUMBER -pin in float binsize = 1; -pin in float minvalue = 0; - -pin in s32 index; // use s32 to avoid 0x hex display in hal -pin out s32 check; // use s32 to avoid 0x hex display in hal -pin in bit reset; -pin in bit method; - -pin out bit input_error; -pin out float binvalue; -pin out float pextra; -pin out float nextra; -pin out float input_min; -pin out float input_max; - -pin out u32 nsamples; -pin out float variance; -pin out float mean; +"""; //" To make vim happy in syntax=c mode + +pin in ui32 pintype; +pin in real input; +pin in si32 input_s32; +pin in ui32 input_u32; +pin in bool input_bit; + +pin in ui32 nbins = 20; // must be < MAXBINNUMBER +pin in real binsize = 1; +pin in real minvalue = 0; + +pin in si32 index; // use s32 to avoid 0x hex display in hal +pin out si32 check; // use s32 to avoid 0x hex display in hal +pin in bool reset; +pin in bool method; + +pin out bool input_error; +pin out real binvalue; +pin out real pextra; +pin out real nextra; +pin out real input_min; +pin out real input_max; + +pin out ui32 nsamples; +pin out real variance; +pin out real mean; // user may interrogate availablebins to determine this compiled-in limit -pin out s32 availablebins = 200; //MAXBINNUMBER +pin out si32 availablebins = 200; //MAXBINNUMBER option period no; function _; @@ -80,31 +80,31 @@ variable int bin[200]; // MAXBINNUMBER variable int first = 1; variable unsigned last_nbins = 0; -variable hal_float_t maxvalue; +variable rtapi_real maxvalue; -variable hal_float_t last_binsize = 0; -variable hal_float_t last_minvalue = 0; +variable rtapi_real last_binsize = 0; +variable rtapi_real last_minvalue = 0; -variable hal_float_t sum; -variable hal_float_t sq_sum; -variable hal_float_t m2; +variable rtapi_real sum; +variable rtapi_real sq_sum; +variable rtapi_real m2; license "GPL"; author "Dewey Garrett"; ;; -hal_float_t invalue; +rtapi_real invalue; unsigned i; int idx; -check = index; +check_set(index); if ( (nbins > (unsigned)availablebins) || (nbins < 1) ) { - input_error = 1; - check = index; // allow continue with no updates + input_error_set(1); + check_set(index); // allow continue with no updates return; } -input_error = 0; +input_error_set(0); if (reset) {first = 1;} //pintype "0:float, 1:s32, 2:u32 3:bit"; @@ -123,56 +123,57 @@ if ( first ) { maxvalue = minvalue + nbins * binsize; first = 0; - pextra = 0; nextra = 0; + pextra_set(0); + nextra_set(0); for (i = 0; i < nbins; i++) { bin[i] = 0; } - nsamples = 0; - mean = 0; + nsamples_set(0); + mean_set(0); sum = 0; sq_sum = 0; - variance = 0; - input_min = 1e99; //dng - input_max = -1e99; //dng + variance_set(0); + input_min_set(1e99); //dng + input_max_set(-1e99); //dng m2 = 0; } else { if (invalue < minvalue) { - nextra++; + nextra_set(nextra + 1); } else if (invalue > maxvalue) { - pextra++; + pextra_set(pextra + 1); } else { idx = (invalue - minvalue)/binsize; bin[idx]++; } } -check = index; // user should verify check==index for reading values +check_set(index); // user should verify check==index for reading values // -1 value indicates illegal index if (index < 0) { - binvalue = -1; + binvalue_set(-1); } else if (index < (int)nbins) { - binvalue = bin[index]; + binvalue_set(bin[index]); } else { - binvalue = -1; + binvalue_set(-1); } -if (invalue < input_min) input_min = invalue; -if (invalue > input_max) input_max = invalue; +if (invalue < input_min) input_min_set(invalue); +if (invalue > input_max) input_max_set(invalue); -nsamples++; +nsamples_set(nsamples + 1); if (nsamples >= 2) { if (method == 0 ) { - hal_float_t delta; + rtapi_real delta; delta = invalue - mean; - mean = mean + delta / nsamples; + mean_set(mean + delta / nsamples); m2 = m2 + delta * (invalue - mean); - variance = m2/(nsamples - 1); + variance_set(m2/(nsamples - 1)); } else { sum += invalue; sq_sum += invalue * invalue; - variance = (sq_sum - (sum * sum)/nsamples)/(nsamples -1); - mean = sum/nsamples; + variance_set((sq_sum - (sum * sum)/nsamples)/(nsamples -1)); + mean_set(sum/nsamples); } } diff --git a/src/hal/components/histobinstream.comp b/src/hal/components/histobinstream.comp index b1deeaa40fe..98cda872767 100644 --- a/src/hal/components/histobinstream.comp +++ b/src/hal/components/histobinstream.comp @@ -46,32 +46,32 @@ Maintainers note: hardcoded for MAXBINNUMBER==200 """; // "} make vim syntax highligting happy -pin in u32 pintype "Select the input pin (0:input 1:input-s32 2:input-u32 3:input-bit)."; -pin in float input "Floating point input value (pintype 0)."; -pin in s32 input_s32 "Signed input value (pintype 1)."; -pin in u32 input_u32 "Unsigned input value (pintype 2)."; -pin in bit input_bit "Bit input value (pintype 3)."; - -pin in u32 nbins = 20 "Number of active bins N (0 ... N-1)."; -pin in float binsize = 1 "Width of one bin in input units."; -pin in float minvalue = 0 "Lower edge of bin 0."; - -pin in bit reset = 1 "Reset state and bins."; -pin in bit stream = 0 "Set to high to stream all bins and tails on rising edge."; -pin in bit method = 0 "Variance method (0:Welford incremental, 1:sum of squares)."; - -pin out bit stream_error "Set if the data stream did not fit and was never sent."; -pin out bit input_error "Set when input rules are violated; updates are invalid until fixed and a reset."; - -pin out float input_min "Minimum input value seen (latched on stream rising edge)."; -pin out float input_max "Maximum input value seen (latched on stream rising edge)."; -pin out u32 nsamples "Number of samples accumulated (latched on stream rising edge)."; -pin out float variance "Variance of the input (latched on stream rising edge)."; -pin out float mean "Mean of the input (latched on stream rising edge)."; -pin out s64 stream_time "The time it took for the stream data to be pushed out in nanoseconds (ns)."; +pin in ui32 pintype "Select the input pin (0:input 1:input-si322:input-u32 3:input-bit)."; +pin in real input "Floating point input value (pintype 0)."; +pin in si32 input_s32 "Signed input value (pintype 1)."; +pin in ui32 input_u32 "Unsigned input value (pintype 2)."; +pin in bool input_bit "Bit input value (pintype 3)."; + +pin in ui32 nbins = 20 "Number of active bins N (0 ... N-1)."; +pin in real binsize = 1 "Width of one bin in input units."; +pin in real minvalue = 0 "Lower edge of bin 0."; + +pin in bool reset = 1 "Reset state and bins."; +pin in bool stream = 0 "Set to high to stream all bins and tails on rising edge."; +pin in bool method = 0 "Variance method (0:Welford incremental, 1:sum of squares)."; + +pin out bool stream_error "Set if the data stream did not fit and was never sent."; +pin out bool input_error "Set when input rules are violated; updates are invalid until fixed and a reset."; + +pin out real input_min "Minimum input value seen (latched on stream rising edge)."; +pin out real input_max "Maximum input value seen (latched on stream rising edge)."; +pin out ui32 nsamples "Number of samples accumulated (latched on stream rising edge)."; +pin out real variance "Variance of the input (latched on stream rising edge)."; +pin out real mean "Mean of the input (latched on stream rising edge)."; +pin out sint stream_time "The time it took for the stream data to be pushed out in nanoseconds (ns)."; // user may interrogate availablebins to determine this compiled-in limit -pin out s32 availablebins = 200; //MAXBINNUMBER +pin out si32 availablebins = 200; //MAXBINNUMBER option period no; function _; @@ -83,22 +83,22 @@ include ; variable int first = 1; variable unsigned last_nbins = 0; -variable real_t last_binsize = 0; -variable real_t last_minvalue = 0; -variable real_t maxvalue = 0; +variable rtapi_real last_binsize = 0; +variable rtapi_real last_minvalue = 0; +variable rtapi_real maxvalue = 0; variable hal_stream_data_u bins[200]; // MAXBINNUMBER variable hal_stream_data_u ptail; // count of inputs >= upper edge variable hal_stream_data_u ntail; // count of inputs < minvalue variable rtapi_u64 run_nsamples = 0; -variable real_t run_min = 1e99; -variable real_t run_max = -1e99; -variable real_t run_mean = 0; -variable real_t run_variance = 0; -variable real_t sum = 0; -variable real_t sq_sum = 0; -variable real_t m2 = 0; +variable rtapi_real run_min = 1e99; +variable rtapi_real run_max = -1e99; +variable rtapi_real run_mean = 0; +variable rtapi_real run_variance = 0; +variable rtapi_real sum = 0; +variable rtapi_real sq_sum = 0; +variable rtapi_real m2 = 0; variable bool last_stream = 0; variable hal_stream_t fifo; @@ -135,11 +135,11 @@ FUNCTION(_) { // Cache some pins rtapi_u32 c_nbins= nbins; - real_t c_binsize = binsize; - real_t c_minvalue = minvalue; + rtapi_real c_binsize = binsize; + rtapi_real c_minvalue = minvalue; // Select the input according to pintype. - real_t invalue; + rtapi_real invalue; switch (pintype) { case 0: invalue = input; break; case 1: invalue = input_s32; break; @@ -151,14 +151,14 @@ FUNCTION(_) { // Validate the requested bin geometry. binsize must be > 0 to avoid a // divide by zero and to keep the bin index monotonic. if (c_nbins < 1 || c_nbins > (unsigned)availablebins || c_binsize <= 0.0) { - input_error = 1; + input_error_set(1); last_stream = stream; // do not act on a stream edge while in error return; } if (reset) { first = 1; - input_error = 0; + input_error_set(0); } if ( first @@ -166,7 +166,7 @@ FUNCTION(_) { || c_binsize != last_binsize || c_minvalue != last_minvalue) { first = 0; - maxvalue = c_minvalue + (real_t)c_nbins * c_binsize; + maxvalue = c_minvalue + (rtapi_real)c_nbins * c_binsize; for (unsigned i = 0; i < c_nbins; i++) bins[i].u = 0; ptail.u = 0; @@ -201,7 +201,7 @@ FUNCTION(_) { ++run_nsamples; if (run_nsamples >= 2) { if (method == 0) { - real_t delta = invalue - run_mean; + rtapi_real delta = invalue - run_mean; run_mean += delta / run_nsamples; m2 += delta * (invalue - run_mean); run_variance = m2 / (run_nsamples - 1); @@ -227,11 +227,11 @@ FUNCTION(_) { bool b = stream; // On the low-to-high transition latch the statistics and push the bins. if (b && !last_stream) { - nsamples = (hal_u32_t)run_nsamples; - mean = run_mean; - variance = run_variance; - input_min = run_nsamples ? run_min : 0; - input_max = run_nsamples ? run_max : 0; + nsamples_set(run_nsamples); + mean_set(run_mean); + variance_set(run_variance); + input_min_set(run_nsamples ? run_min : 0); + input_max_set(run_nsamples ? run_max : 0); unsigned need = c_nbins + 2; int avail = hal_stream_maxdepth(&fifo) - hal_stream_depth(&fifo); @@ -243,12 +243,12 @@ FUNCTION(_) { hal_stream_write(&fifo, &bins[i]); // Positive overflow hal_stream_write(&fifo, &ptail); - stream_error = 0; - stream_time = rtapi_get_time() - now; + stream_error_set(0); + stream_time_set(rtapi_get_time() - now); } else { // Not enough room to stream an entire set; never stream an // incomplete data set. - stream_error = 1; + stream_error_set(1); } } last_stream = b; diff --git a/src/hal/components/homecomp.comp b/src/hal/components/homecomp.comp index 79c4691787f..f073114f0de 100644 --- a/src/hal/components/homecomp.comp +++ b/src/hal/components/homecomp.comp @@ -111,8 +111,8 @@ static custom_home_local_data customH[EMCMOT_MAX_JOINTS]; // data for per-joint custom-homing-specific hal pins: typedef struct { - hal_bit_t *request_custom_homing; // input requests custom homing - hal_bit_t *is_custom_homing; // output verifies custom homing + hal_bool_t request_custom_homing; // input requests custom homing + hal_bool_t is_custom_homing; // output verifies custom homing } custom_one_joint_home_data_t; typedef struct { @@ -126,7 +126,7 @@ static int custom_makepins(int id,int njoints) int jno,retval; custom_one_joint_home_data_t *addr; - custom_joint_home_data = hal_malloc(sizeof(custom_all_joints_home_data_t)); + custom_joint_home_data = hal_malloc(sizeof(*custom_joint_home_data)); if (custom_joint_home_data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HOMING: custom_all_joints_home_data_t malloc failed\n"); return -1; @@ -136,9 +136,9 @@ static int custom_makepins(int id,int njoints) for (jno = 0; jno < njoints; jno++) { addr = &(custom_joint_home_data->custom_jhd[jno]); - retval += hal_pin_bit_newf(HAL_IN, &(addr->request_custom_homing), id, + retval += hal_pin_new_bool(id, HAL_IN, &(addr->request_custom_homing), 0, "joint.%d.request-custom-homing", jno); - retval += hal_pin_bit_newf(HAL_OUT, &(addr->is_custom_homing), id, + retval += hal_pin_new_bool(id, HAL_OUT, &(addr->is_custom_homing), 0, "joint.%d.is-custom-homing", jno); } return retval; @@ -150,7 +150,7 @@ static void custom_read_homing_in_pins(int njoints) custom_one_joint_home_data_t *addr; for (jno = 0; jno < njoints; jno++) { addr = &(custom_joint_home_data->custom_jhd[jno]); - customH[jno].request_custom_homing = *(addr->request_custom_homing); // IN + customH[jno].request_custom_homing = hal_get_bool(addr->request_custom_homing); // IN // echo for verification: customH[jno].is_custom_homing = customH[jno].request_custom_homing; @@ -163,7 +163,7 @@ static void custom_write_homing_out_pins(int njoints) custom_one_joint_home_data_t *addr; for (jno = 0; jno < njoints; jno++) { addr = &(custom_joint_home_data->custom_jhd[jno]); - *(addr->is_custom_homing) = customH[jno].is_custom_homing; // OUT + hal_set_bool(addr->is_custom_homing, customH[jno].is_custom_homing); // OUT } } @@ -344,12 +344,12 @@ static emcmot_joint_t *joints; // data for per-joint homing-specific hal pins: typedef struct { - hal_bit_t *home_sw; // home switch input - hal_bit_t *homing; // joint is homing - hal_bit_t *homed; // joint was homed - hal_bit_t *index_enable; // motmod sets: request reset on index + hal_bool_t home_sw; // home switch input + hal_bool_t homing; // joint is homing + hal_bool_t homed; // joint was homed + hal_bool_t index_enable; // motmod sets: request reset on index // encoder clears: index arrived - hal_s32_t *home_state; // homing state machine state + hal_sint_t home_state; // homing state machine state } one_joint_home_data_t; typedef struct { @@ -374,15 +374,15 @@ static int makepins(int id,int njoints) for (jno = 0; jno < njoints; jno++) { addr = &(joint_home_data->jhd[jno]); - retval += hal_pin_bit_newf(HAL_IN, &(addr->home_sw), id, + retval += hal_pin_new_bool(id, HAL_IN, &(addr->home_sw), 0, "joint.%d.home-sw-in", jno); - retval += hal_pin_bit_newf(HAL_OUT, &(addr->homing), id, + retval += hal_pin_new_bool(id, HAL_OUT, &(addr->homing), 0, "joint.%d.homing", jno); - retval += hal_pin_bit_newf(HAL_OUT, &(addr->homed), id, + retval += hal_pin_new_bool(id, HAL_OUT, &(addr->homed), 0, "joint.%d.homed", jno); - retval += hal_pin_s32_newf(HAL_OUT, &(addr->home_state), id, + retval += hal_pin_new_si32(id, HAL_OUT, &(addr->home_state), 0, "joint.%d.home-state", jno); - retval += hal_pin_bit_newf(HAL_IO, &(addr->index_enable), id, + retval += hal_pin_new_bool(id, HAL_IO, &(addr->index_enable), 0, "joint.%d.index-enable", jno); } return retval; diff --git a/src/hal/components/hypot.comp b/src/hal/components/hypot.comp index 22132618770..93a338e9335 100644 --- a/src/hal/components/hypot.comp +++ b/src/hal/components/hypot.comp @@ -1,8 +1,8 @@ component hypot "Three-input hypotenuse (Euclidean distance) calculator"; -pin in float in0; -pin in float in1; -pin in float in2; -pin out float out "out = sqrt(*in0*^2^ + *in1*^2^ + *in2*^2^)"; +pin in real in0; +pin in real in1; +pin in real in2; +pin out real out "out = sqrt(*in0*^2^ + *in1*^2^ + *in2*^2^)"; option period no; function _; license "GPL"; @@ -10,6 +10,6 @@ author "Jeff Epler"; ;; #include FUNCTION(_) { - double a = in0, b = in1, c = in2; - out = sqrt(a*a + b*b + c*c); + rtapi_real a = in0, b = in1, c = in2; + out_set(sqrt(a*a + b*b + c*c)); } diff --git a/src/hal/components/ilowpass.comp b/src/hal/components/ilowpass.comp index 5722f3bd941..79f4fe9c540 100644 --- a/src/hal/components/ilowpass.comp +++ b/src/hal/components/ilowpass.comp @@ -13,21 +13,21 @@ on the MPG. Choose *gain* according to the smoothing level desired. Divide the **axis**.__N__.**jog-scale** values by *scale*."""; -pin in s32 in; +pin in si32 in; -pin out s32 out """*out* tracks *in* * *scale* through a low-pass +pin out si32 out """*out* tracks *in* * *scale* through a low-pass filter of *gain* per period."""; -param rw float scale = 1024 """A scale factor applied to the output +param rw real scale = 1024 """A scale factor applied to the output value of the low-pass filter."""; -param rw float gain = .5 """Together with the period, sets the rate at +param rw real gain = .5 """Together with the period, sets the rate at which the output changes. Useful range is between 0 and 1, with higher values causing the input value to be tracked more quickly. For instance, a setting of 0.9 causes the output value to go 90% of the way towards the input value in each period."""; -variable double value; +variable rtapi_real value; option period no; function _ "Update the output based on the input and parameters."; @@ -39,5 +39,5 @@ author "Jeff Epler"; FUNCTION(_) { value += (in - value) * gain; - out = (int)(rtapi_s64)floor((value * scale) + 0.5); + out_set((rtapi_s64)floor((value * scale) + 0.5)); } diff --git a/src/hal/components/integ.comp b/src/hal/components/integ.comp index 8a6f68888fb..f83735fa4e6 100644 --- a/src/hal/components/integ.comp +++ b/src/hal/components/integ.comp @@ -1,18 +1,19 @@ component integ "Integrator with gain pin and windup limits"; -pin in float in; -pin in float gain = 1.0; -pin out float out "The discrete integral of 'gain * in' since 'reset' was deasserted"; -pin in bit reset "When asserted, set out to 0"; -pin in float max_ = 1e20; +pin in real in; +pin in real gain = 1.0; +pin out real out "The discrete integral of 'gain * in' since 'reset' was deasserted"; +pin in bool reset "When asserted, set out to 0"; +pin in real max_ = 1e20; -pin in float min_ = -1e20; +pin in real min_ = -1e20; function _; license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - if(reset) out = 0; - else out = out + gain * in * fperiod; - if (out > max_) out = max_; - if (out < min_) out = min_; + rtapi_real val = out; + if(reset) out_set(val = 0); + else out_set(val + gain * in * fperiod); + if (val > max_) out_set(max_); + if (val < min_) out_set(min_); } diff --git a/src/hal/components/invert.comp b/src/hal/components/invert.comp index 4f7712655d9..91d55b7e1a7 100644 --- a/src/hal/components/invert.comp +++ b/src/hal/components/invert.comp @@ -18,9 +18,9 @@ The output will be the mathematical inverse of the input, ie *out* = 1 / *in*. The parameter *deadband* can be used to control how close to 0 the denominator can be before the output is clamped to 0. *deadband* must be at least 1e-8, and must be positive."""; -pin in float in "Analog input value"; -pin out float out "Analog output value"; -param rw float deadband "The *out* will be zero if *in* is between -*deadband* and +*deadband*."; +pin in real in "Analog input value"; +pin out real out "Analog output value"; +param rw real deadband "The *out* will be zero if *in* is between -*deadband* and +*deadband*."; option period no; function _; @@ -32,12 +32,13 @@ see_also " invert(9), div2(9) "; #include FUNCTION(_) { - double tmp = in; - if (deadband < 1e-12) deadband = 1e-12; - if ( tmp > -deadband && tmp <0) - out = -1/deadband; - else if (tmp >= 0 && tmp -ddbd && tmp < 0) + out_set(-1.0/ddbd); + else if (tmp >= 0 && tmp < ddbd) + out_set(1.0/ddbd); else - out = 1/tmp; + out_set(1.0/tmp); } diff --git a/src/hal/components/joint_axis_mapper.comp b/src/hal/components/joint_axis_mapper.comp index a8b51c72d93..ac581eeaee0 100644 --- a/src/hal/components/joint_axis_mapper.comp +++ b/src/hal/components/joint_axis_mapper.comp @@ -18,7 +18,7 @@ net z-fault joint.2.faulted => jam.z-fault license "GPL"; -pin out bit dummy "halcompile requires at least one halpin"; +pin out bool dummy "halcompile requires at least one halpin"; function _; option period no; @@ -34,8 +34,8 @@ int number_joints = 9; static int axis_counts[9]; typedef struct{ - hal_bit_t *fault_in[16]; - hal_bit_t *fault_out[16]; + hal_bool_t fault_in[16]; + hal_bool_t fault_out[16]; } faults_in_t; static faults_in_t *faults_in; @@ -46,7 +46,7 @@ int rtapi_app_main(void) { if(comp_id < 0) return comp_id; number_joints = strlen(coord); - faults_in = hal_malloc(sizeof(faults_in_t)); + faults_in = hal_malloc(sizeof(*faults_in)); rtapi_print_msg(RTAPI_MSG_INFO, "Joint Axis Mapper - Initializing with coords %s\n", coord); @@ -77,12 +77,12 @@ int rtapi_app_main(void) { if(coord[i] == 'W' || coord[i] == 'w'){ axis_counts[8]++; this_count = axis_counts[8]; } if(this_count == 1){ - hal_pin_bit_newf(HAL_IN, &(faults_in->fault_in[i]), comp_id, "jam.%c-fault", coord[i]); - hal_pin_bit_newf(HAL_OUT, &(faults_in->fault_out[i]), comp_id, "jam.%c-fault-latched", coord[i]); + hal_pin_new_bool(comp_id, HAL_IN, &faults_in->fault_in[i], 0, "jam.%c-fault", coord[i]); + hal_pin_new_bool(comp_id, HAL_OUT, &faults_in->fault_out[i], 0, "jam.%c-fault-latched", coord[i]); } else if(this_count > 1){ - hal_pin_bit_newf(HAL_IN, &(faults_in->fault_in[i]), comp_id, "jam.%c%d-fault", coord[i], this_count); - hal_pin_bit_newf(HAL_OUT, &(faults_in->fault_out[i]), comp_id, "jam.%c%d-fault-latched", coord[i], this_count); + hal_pin_new_bool(comp_id, HAL_IN, &faults_in->fault_in[i], 0, "jam.%c%d-fault", coord[i], this_count); + hal_pin_new_bool(comp_id, HAL_OUT, &faults_in->fault_out[i], 0, "jam.%c%d-fault-latched", coord[i], this_count); } else { rtapi_print_msg(RTAPI_MSG_ERR, "Joint Axis Mapper - %c axis not found in coord string\n", coord[i]); @@ -100,11 +100,11 @@ void rtapi_app_exit(void) { FUNCTION(_) { - dummy=0; // if we don't use at least one halpin in FUNCTION we get a compiler warning + (void)__comp_inst; // We don't have any pins or anything else that is referenced in the instance for(int i = 0; i < number_joints; i++) { - if(*faults_in->fault_in[i] && ! *faults_in->fault_out[i]){ + if(hal_get_bool(faults_in->fault_in[i]) && ! hal_get_bool(faults_in->fault_out[i])){ rtapi_print_msg(RTAPI_MSG_ERR, "%c Axis fault detected\n", fault_letter[i]); } - *(faults_in->fault_out[i]) = *(faults_in->fault_in[i]); + hal_set_bool(faults_in->fault_out[i], hal_get_bool(faults_in->fault_in[i])); } } diff --git a/src/hal/components/joyhandle.comp b/src/hal/components/joyhandle.comp index dd64fa0fa90..b86ed789997 100644 --- a/src/hal/components/joyhandle.comp +++ b/src/hal/components/joyhandle.comp @@ -15,13 +15,13 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. component joyhandle "sets nonlinear joypad movements, deadbands and scales"; -pin in float in; -pin out float out; -param rw float power = 2.0; -param rw float deadband = 0.; -param rw float scale = 1.; -param rw float offset = 0.; -param rw bit inverse = 0; +pin in real in; +pin out real out; +param rw real power = 2.0; +param rw real deadband = 0.; +param rw real scale = 1.; +param rw real offset = 0.; +param rw bool inverse = 0; description """ The component *joyhandle* uses the following formula for a non linear joypad movements: @@ -51,51 +51,49 @@ author "Paul Willutzki"; #include FUNCTION(_) { -double p,a,b,alin,clin,xm,ym,xinv,yinv; - -if (power < 1.0) power =1.0; - -if (deadband >= 0.99) deadband = 0.99; -else if (deadband <= 0.) deadband = 0.; - -p = power - 1.; -a = -1./(pow(deadband,p)-1.); -b = 1. - a; -alin = -scale/(deadband-1); -clin = 1.*(scale+offset-alin); - -if (in >= 1.) out = scale + offset; -else if ((in <= deadband) && (in >= (-1*deadband))) out = 0.; -else if (in <= -1.) out = -scale - offset; -else if ((in > deadband) && (in < 1.)) - { - if (power == 1.) out=alin*in + clin; - else { - if (inverse == 0) out = scale*(a*pow(in,power) + b*in) + offset; +rtapi_real p,a,b,alin,clin,xm,ym,xinv,yinv; + +rtapi_real pwr = power; +if (pwr < 1.0) power_set(pwr = 1.0); + +rtapi_real ddbd = deadband; +if (ddbd >= 0.99) deadband_set(ddbd = 0.99); +else if (ddbd <= 0.0) deadband_set(ddbd = 0.0); + +p = pwr - 1.0; +a = -1.0/(pow(ddbd,p)-1.0); +b = 1.0 - a; +alin = -scale/(ddbd-1); +clin = 1.0*(scale+offset-alin); + +if (in >= 1.0) out_set(scale + offset); +else if ((in <= ddbd) && (in >= (-1*ddbd))) out_set(0.0); +else if (in <= -1.0) out_set(-scale - offset); +else if ((in > ddbd) && (in < 1.0)) { + if (pwr == 1.0) out_set(alin*in + clin); + else { + if (inverse == 0) out_set(scale*(a*pow(in,pwr) + b*in) + offset); else { - xm = (deadband+1)/2; - ym = alin*xm + clin; - xinv = 2*xm-in; - yinv = scale*(a*pow(xinv,power) + b*xinv) + offset; - out =2*ym-yinv; - } - } - } -else if ((in < (-1.*deadband)) && (in > -1.)) - { - if (power == 1.) out=-1.*(alin*-1.*in + clin); - else { - if (inverse == 0) out = -1*(scale*(a*pow((-1.*in),power) - b*in) + offset); + xm = (ddbd+1)/2; + ym = alin*xm + clin; + xinv = 2*xm-in; + yinv = scale*(a*pow(xinv,pwr) + b*xinv) + offset; + out_set(2*ym-yinv); + } + } +} else if ((in < (-1.0*ddbd)) && (in > -1.0)) { + if (pwr == 1.0) out_set(-1.0*(alin*-1.0*in + clin)); + else { + if (inverse == 0) out_set(-1*(scale*(a*pow((-1.0*in),pwr) - b*in) + offset)); else { - xm = (deadband+1)/2; - ym = alin*xm + clin; - xinv = 2*xm+in; - yinv = scale*(a*pow(xinv,power) + b*xinv) + offset; - out =-2*ym-yinv; - } - } - } -else out = 0.; - -// out = scale*(a*pow(in,power) + b*in) + offset; + xm = (ddbd+1)/2; + ym = alin*xm + clin; + xinv = 2*xm+in; + yinv = scale*(a*pow(xinv,pwr) + b*xinv) + offset; + out_set(-2*ym-yinv); + } + } +} else out_set(0.0); + +// out = scale*(a*pow(in,pwr) + b*in) + offset; } diff --git a/src/hal/components/knob2float.comp b/src/hal/components/knob2float.comp index 37771a1db3a..1e19f38503c 100644 --- a/src/hal/components/knob2float.comp +++ b/src/hal/components/knob2float.comp @@ -17,13 +17,13 @@ component knob2float "Convert counts (probably from an encoder) to a float value"; -pin in s32 counts "Counts"; -pin in bit enable "When TRUE, output is controlled by count, when FALSE, output is fixed"; -pin in float scale "Amount of output change per count"; -pin out float out "Output value"; +pin in si32 counts "Counts"; +pin in bool enable "When TRUE, output is controlled by count, when FALSE, output is fixed"; +pin in real scale "Amount of output change per count"; +pin out real out "Output value"; -param rw float max_out=1.0 "Maximum output value, further increases in count will be ignored"; -param rw float min_out=0.0 "Minimum output value, further decreases in count will be ignored"; +param rw real max_out=1.0 "Maximum output value, further increases in count will be ignored"; +param rw real min_out=0.0 "Minimum output value, further decreases in count will be ignored"; option data knob2float_data; @@ -35,27 +35,27 @@ author "John Kasunich"; typedef struct { long old_counts; - double old_out; + rtapi_real old_out; } knob2float_data; FUNCTION(_) { long delta_counts; - double tmp_out; + rtapi_real tmp_out; if ( min_out > max_out ) { - min_out = max_out; + min_out_set(max_out); } delta_counts = counts - data.old_counts; if ( enable ) { - tmp_out = data.old_out + delta_counts * scale; - if ( tmp_out > max_out ) { - data.old_out = max_out; - } else if ( tmp_out < min_out ) { - data.old_out = min_out; - } else { - data.old_out = tmp_out; - } + tmp_out = data.old_out + delta_counts * scale; + if ( tmp_out > max_out ) { + data.old_out = max_out; + } else if ( tmp_out < min_out ) { + data.old_out = min_out; + } else { + data.old_out = tmp_out; + } } - out = data.old_out; + out_set(data.old_out); data.old_counts += delta_counts; } diff --git a/src/hal/components/laserpower.comp b/src/hal/components/laserpower.comp index 8baf122041c..ee885d069ea 100644 --- a/src/hal/components/laserpower.comp +++ b/src/hal/components/laserpower.comp @@ -1,22 +1,22 @@ component laserpower "Scales laser power output based upon velocity input power and distance to go"; -pin in float min_power "Minimum allowed power level. "; -pin in float max_power "Maximum allowed power level"; -pin in float req_velocity "Requested motion velocity"; -pin in float cur_velocity "Current motion velocity"; -pin in bit enabled "True when laser output enabled"; +pin in real min_power "Minimum allowed power level. "; +pin in real max_power "Maximum allowed power level"; +pin in real req_velocity "Requested motion velocity"; +pin in real cur_velocity "Current motion velocity"; +pin in bool enabled "True when laser output enabled"; -pin in bit raster_mode "false for vector mode, true for raster mode"; -pin in float raster_power "Requested power level during raster operations"; +pin in bool raster_mode "false for vector mode, true for raster mode"; +pin in real raster_power "Requested power level during raster operations"; -pin in float vector_power "Requested power level during vector operations"; -pin in float distance_to_go "Distance to go of current move"; +pin in real vector_power "Requested power level during vector operations"; +pin in real distance_to_go "Distance to go of current move"; -pin out float power "Current power level command"; +pin out real power "Current power level command"; -pin out float command_power "Commanded power before normalization and velocity scaling"; -pin out float start_power "Power level when reqPower last changed"; -pin out float start_distance "Distance amount when reqPower last changed"; -pin out float vel_scale "Velocity related scaling component."; +pin out real command_power "Commanded power before normalization and velocity scaling"; +pin out real start_power "Power level when reqPower last changed"; +pin out real start_distance "Distance amount when reqPower last changed"; +pin out real vel_scale "Velocity related scaling component."; description """ During operation laserpower must be scaled proportionally to actual velocity vs @@ -40,49 +40,49 @@ include ; ;; -const hal_float_t zero = 0.00005; +const rtapi_real zero = 0.00005; -bool float_zero(hal_float_t a) { +bool float_zero(rtapi_real a) { return fabs(a) < zero; } FUNCTION(_) { - static float previous_vector_power = 0; - static float previous_distance_to_go = 0; + static rtapi_real previous_vector_power = 0; + static rtapi_real previous_distance_to_go = 0; //velocity gain is proportional to current velocity and requested velocity //if the machine slows down around a corner, we lower the laser power proportionally //if the machine is not moving, we want vel scale to be 0 if(float_zero(req_velocity) || float_zero(cur_velocity)) { - vel_scale = 0; + vel_scale_set(0); } else { - vel_scale = (fabs(cur_velocity) / fabs(req_velocity)); + vel_scale_set((fabs(cur_velocity) / fabs(req_velocity))); } if (raster_mode) { - command_power = raster_power; + command_power_set(raster_power); } else { if((previous_distance_to_go < distance_to_go) || !float_zero(vector_power - previous_vector_power)) { //if vector power changes during a move we begin scaling from the previously //commanded vector power to the new power during the move - start_power = previous_vector_power; - start_distance = distance_to_go; + start_power_set(previous_vector_power); + start_distance_set(distance_to_go); } previous_vector_power = vector_power; previous_distance_to_go = distance_to_go; - command_power = start_power + ((vector_power-start_power) * (1 - (distance_to_go / start_distance))); + command_power_set(start_power + ((vector_power-start_power) * (1 - (distance_to_go / start_distance)))); } if(!enabled || command_power < 0.0) { //if we aren't performing a feed move or // command power is less than 0 we don't output any power no matter what given min and max are - power = 0.0; + power_set(0.0); } else { - power = ((max_power-min_power) * vel_scale * (command_power / 100)) + min_power; + power_set(((max_power-min_power) * vel_scale * (command_power / 100)) + min_power); } } diff --git a/src/hal/components/latencybins.comp b/src/hal/components/latencybins.comp index 1304a854f33..78a75e104ee 100644 --- a/src/hal/components/latencybins.comp +++ b/src/hal/components/latencybins.comp @@ -34,23 +34,23 @@ The latency pin outputs the instantaneous latency. Maintainers note: hardcoded for MAXBINNUMBER==1000 """; -pin in s32 maxbinnumber = 1000; // MAXBINNUMBER -pin in s32 index; //use s32 to avoid 0x hex display in hal -pin in bit reset; -pin in s32 nsbinsize; - -pin out s32 check; -pin out s32 latency; -pin out s32 latency_max; -pin out s32 latency_min; -pin out s32 pbinvalue; -pin out s32 nbinvalue; -pin out s32 pextra; -pin out s32 nextra; -pin out s32 variance; +pin in si32 maxbinnumber = 1000; // MAXBINNUMBER +pin in si32 index; //use s32 to avoid 0x hex display in hal +pin in bool reset; +pin in si32 nsbinsize; + +pin out si32 check; +pin out si32 latency; +pin out si32 latency_max; +pin out si32 latency_min; +pin out si32 pbinvalue; +pin out si32 nbinvalue; +pin out si32 pextra; +pin out si32 nextra; +pin out si32 variance; // user may interrogate available bins to determine this compiled-in limit -pin out s32 availablebins = 1000; // MAXBINNUMBER +pin out si32 availablebins = 1000; // MAXBINNUMBER function _; variable rtapi_s64 last_timer = 0; @@ -87,10 +87,11 @@ if ( first || nsbinsize == 0 // important to avoid divide by zero ) { first = 0; - latency = 0; - latency_min = 0x7FFFFFFF; - latency_max = 0x80000000; - pextra = 0; nextra = 0; + latency_set(0); + latency_min_set(0x7FFFFFFF); + latency_max_set(0x80000000); + pextra_set(0); + nextra_set(0); for (i = 0; i <= binmax; i++) { pbins[i] = 0; nbins[i] = 0; } @@ -98,20 +99,20 @@ if ( first sum = 0; sq_sum = 0; } else { - latency = lat32; + latency_set(lat32); i = lat32/nsbinsize; - if (lat32 > latency_max) latency_max = lat32; - if (lat32 < latency_min) latency_min = lat32; + if (lat32 > latency_max) latency_max_set(lat32); + if (lat32 < latency_min) latency_min_set(lat32); if (i >= 0) { if (i > binmax) { - pextra++; + pextra_set(pextra + 1); } else { pbins[i]++; } } else { i = -i; if (i > binmax) { - nextra++; + nextra_set(nextra + 1); } else { nbins[i]++; } @@ -125,19 +126,19 @@ if ( first rtapi_u64 divisor; dividend = sq_sum - rtapi_div_u64(sum * sum,nsamples); divisor = nsamples -1; - variance = rtapi_div_u64(dividend,divisor); + variance_set(rtapi_div_u64(dividend,divisor)); } } -check = index; // user should verify check==index for reading values +check_set(index); // user should verify check==index for reading values // -1 value indicates illegal index if (index < 0) { - pbinvalue = -1; - nbinvalue = -1; + pbinvalue_set(-1); + nbinvalue_set(-1); } else if (index <=binmax) { - pbinvalue = pbins[index]; - nbinvalue = nbins[index]; + pbinvalue_set(pbins[index]); + nbinvalue_set(nbins[index]); } else { - pbinvalue = -1; - nbinvalue = -1; + pbinvalue_set(-1); + nbinvalue_set(-1); } diff --git a/src/hal/components/latencybinstream.comp b/src/hal/components/latencybinstream.comp index a496d81b292..1dbf725c565 100644 --- a/src/hal/components/latencybinstream.comp +++ b/src/hal/components/latencybinstream.comp @@ -41,22 +41,22 @@ of the *stream* pin. Maintainers note: hardcoded for MAXBINNUMBER==1000 """; -pin in s64 maxbinnumber = 1000 "Number of active bins N on each side (-N...0...N)."; // MAXBINNUMBER -pin in s64 nsbinsize "Time interval for one bin in nanoseconds (ns)."; -pin in bit reset = 1 "Reset state and bins."; -pin in bit stream = 0 "Set to high to stream all bins and tails on rising edge."; - -pin out bit stream_error "Set if the data stream did not fit and was never sent."; -pin out s64 latency "Last measured latency."; -pin out s64 latency_avg "Average latency (when stream pin is asserted)."; -pin out s64 latency_max "Maximum latency (when stream pin is asserted)."; -pin out s64 latency_min "Minimum latency (when stream pin is asserted)."; -pin out s64 variance "Variance of the latency (when stream pin is asserted)."; -pin out s64 stream_time "The time it took for the stream data to be pushed out in nanoseconds (ns)."; +pin in sint maxbinnumber = 1000 "Number of active bins N on each side (-N...0...N)."; // MAXBINNUMBER +pin in sint nsbinsize "Time interval for one bin in nanoseconds (ns)."; +pin in bool reset = 1 "Reset state and bins."; +pin in bool stream = 0 "Set to high to stream all bins and tails on rising edge."; + +pin out bool stream_error "Set if the data stream did not fit and was never sent."; +pin out sint latency "Last measured latency."; +pin out sint latency_avg "Average latency (when stream pin is asserted)."; +pin out sint latency_max "Maximum latency (when stream pin is asserted)."; +pin out sint latency_min "Minimum latency (when stream pin is asserted)."; +pin out sint variance "Variance of the latency (when stream pin is asserted)."; +pin out sint stream_time "The time it took for the stream data to be pushed out in nanoseconds (ns)."; // user may interrogate available bins to determine this compiled-in limit // MAXBINNUMBER -pin out s64 availablebins = 1000 """ +pin out sint availablebins = 1000 """ Hard-coded maximum number of bins. You need to change the source code if you need more bins. """; @@ -68,7 +68,7 @@ modparam dummy keys "Stream shmem unique key for each instance"; include ; include ; -variable rtapi_s64 last_time = 0; +variable rtapi_sint last_time = 0; variable int last_binmax = 0; variable int first = 1; variable hal_stream_data_u ptail; // Positive overflow count @@ -78,11 +78,11 @@ variable hal_stream_data_u nbins[1001]; // MAXBINNUMBER+1 variable bool last_stream = 0; variable hal_stream_t fifo; -variable rtapi_u64 nsamples; -variable rtapi_u64 sum; -variable rtapi_u64 sq_sum; -variable rtapi_s64 lat_min = RTAPI_INT64_MAX; -variable rtapi_s64 lat_max = RTAPI_INT64_MIN; +variable rtapi_uint nsamples; +variable rtapi_uint sum; +variable rtapi_uint sq_sum; +variable rtapi_sint lat_min = RTAPI_INT64_MAX; +variable rtapi_sint lat_max = RTAPI_INT64_MIN; license "GPL"; author "B.Stultiens"; @@ -110,11 +110,11 @@ EXTRA_SETUP() { } FUNCTION(_) { - rtapi_s64 now = rtapi_get_time(); - rtapi_s64 lat = now - last_time - period; + rtapi_sint now = rtapi_get_time(); + rtapi_sint lat = now - last_time - period; last_time = now; - rtapi_s64 binmax = maxbinnumber; + rtapi_sint binmax = maxbinnumber; if (binmax > MAXBINNUMBER) { binmax = MAXBINNUMBER; } @@ -124,7 +124,7 @@ FUNCTION(_) { first = 1; } - rtapi_s64 nsbs = nsbinsize; // May not be zero, important to avoid divide by zero + rtapi_sint nsbs = nsbinsize; // May not be zero, important to avoid divide by zero if (first || binmax != last_binmax || !nsbs) { first = 0; lat_min = RTAPI_INT64_MAX; @@ -135,13 +135,13 @@ FUNCTION(_) { nsamples = 0; sum = 0; sq_sum = 0; - latency = 0; - variance = 0; - latency_avg = 0; - latency_min = 0; - latency_max = 0; + latency_set(0); + variance_set(0); + latency_avg_set(0); + latency_min_set(0); + latency_max_set(0); } else { - latency = lat; + latency_set(lat); int i = lat/nsbs; if (lat > lat_max) lat_max = lat; if (lat < lat_min) lat_min = lat; @@ -170,10 +170,10 @@ FUNCTION(_) { // 1 ( sum^2 ) // s^2 = ----- * ( sq_sum - ----- ) // n - 1 ( n ) - variance = (sq_sum - (sum * sum / nsamples)) / (nsamples - 1); - latency_avg = sum / nsamples; - latency_min = lat_min; - latency_max = lat_max; + variance_set((sq_sum - (sum * sum / nsamples)) / (nsamples - 1)); + latency_avg_set(sum / nsamples); + latency_min_set(lat_min); + latency_max_set(lat_max); } int avail = hal_stream_maxdepth(&fifo) - hal_stream_depth(&fifo); if (avail >= 2 * binmax + 1 + 2) { @@ -187,12 +187,12 @@ FUNCTION(_) { hal_stream_write(&fifo, &pbins[i]); // Positive overflow hal_stream_write(&fifo, &ptail); - stream_error = 0; - stream_time = rtapi_get_time() - now; + stream_error_set(0); + stream_time_set(rtapi_get_time() - now); } else { // Else we have not enough room to stream an entire set and // will not stream incomplete data sets. - stream_error = 1; + stream_error_set(1); } } last_stream = b; diff --git a/src/hal/components/lcd.c b/src/hal/components/lcd.c index 01cd8540242..11db13bc279 100644 --- a/src/hal/components/lcd.c +++ b/src/hal/components/lcd.c @@ -39,7 +39,7 @@ MODULE_LICENSE("GPL"); #define MAX_ENTRY 20 typedef struct { - void **args; + hal_refs_u *args; int num_args; char *fmt; int length; @@ -48,16 +48,16 @@ typedef struct { typedef struct { lcd_page_t *pages; unsigned num_pages; - hal_u32_t *page_num; - hal_u32_t last_page; - hal_u32_t *out; - hal_float_t *contrast; - hal_float_t last_contrast; + hal_uint_t page_num; + hal_uint_t out; + hal_real_t contrast; + rtapi_u32 last_page; + rtapi_real last_contrast; char buff[MAX_ENTRY + 1]; int c_ptr; int f_ptr; int a_ptr; - unsigned int dp; + hal_uint_t dp; }lcd_inst_t; typedef struct { @@ -70,7 +70,7 @@ static lcd_t *lcd; static void write(void *arg, long period); static void write_one(lcd_inst_t *inst); -static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp); +static int parse_fmt(char *in, int *ptr, char *out, hal_refs_u *val, char dp); char *digits = "0123456789ABCDEF"; @@ -142,7 +142,7 @@ int rtapi_app_main(void){ fmt_strings[i] + f1); inst->pages[p].length = f - f1 + 2; inst->pages[p].args = hal_malloc(inst->pages[p].num_args - * sizeof(hal_float_t)); + * sizeof(*inst->pages[p].args)); f1 = f + 2; { int a = -1, s = -1; @@ -155,8 +155,8 @@ int rtapi_app_main(void){ a++; switch (type){ case 'f': - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->pages[p].args[a]), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->pages[p].args[a].r), 0.0, "lcd.%02i.page.%02i.arg.%02i", i, p, a); if (retval != 0) { @@ -165,8 +165,8 @@ int rtapi_app_main(void){ break; case 'u': case 'c': - retval = hal_pin_u32_newf(HAL_IN, - (hal_u32_t **)&(inst->pages[p].args[a]), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, + &(inst->pages[p].args[a].u), 0, "lcd.%02i.page.%02i.arg.%02i", i, p, a); if (retval != 0) { @@ -175,8 +175,8 @@ int rtapi_app_main(void){ break; case 's': - retval = hal_pin_s32_newf(HAL_IN, - (hal_s32_t **)&(inst->pages[p].args[a]), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_IN, + &(inst->pages[p].args[a].s), 0, "lcd.%02i.page.%02i.arg.%02i", i, p, a); if (retval != 0) { @@ -184,8 +184,8 @@ int rtapi_app_main(void){ } break; case 'b': - retval = hal_pin_bit_newf(HAL_IN, - (hal_bit_t **)&(inst->pages[p].args[a]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, + &(inst->pages[p].args[a].b), 0, "lcd.%02i.page.%02i.arg.%02i", i, p, a); if (retval != 0) { @@ -207,25 +207,24 @@ int rtapi_app_main(void){ } for (i = 0; i < lcd->num_insts; i++){ - retval = hal_pin_u32_newf(HAL_IN, &(lcd->insts[i].page_num), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &(lcd->insts[i].page_num), 0, "lcd.%02i.page_num", i); if (retval != 0) { return retval; } lcd->insts[i].last_page = -1; // force screen refresh - retval = hal_pin_u32_newf(HAL_OUT, &(lcd->insts[i].out), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_OUT, &(lcd->insts[i].out), 0, "lcd.%02i.out",i); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IN, &(lcd->insts[i].contrast), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(lcd->insts[i].contrast), 0.0, "lcd.%02i.contrast",i); if (retval != 0) { return retval; } - retval = hal_param_u32_newf(HAL_RW, &(lcd->insts[i].dp), comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RW, &(lcd->insts[i].dp), '.', "lcd.%02i.decimal-separator",i); - lcd->insts[i].dp = '.'; if (retval != 0) { return retval; } @@ -277,18 +276,18 @@ static void write_one(lcd_inst_t *inst){ return;} if (inst->buff[inst->c_ptr] != 0){ - *inst->out = inst->buff[inst->c_ptr++]; + hal_set_ui32(inst->out, inst->buff[inst->c_ptr++]); return; } inst->c_ptr = 0; inst->buff[0] = 0; - if (*inst->page_num >= inst->num_pages) return; // should this error? + if (hal_get_ui32(inst->page_num) >= inst->num_pages) return; // should this error? - if (*inst->page_num != inst->last_page){ - inst->last_page = *inst->page_num; - *inst->out = 0x11; //cursor off + if (hal_get_ui32(inst->page_num) != inst->last_page){ + inst->last_page = hal_get_ui32(inst->page_num); + hal_set_ui32(inst->out, 0x11); //cursor off inst->buff[0] = 0x1E; //cursor home inst->buff[1] = 0x1A; //clear screen inst->buff[2] = 0; // end @@ -298,8 +297,8 @@ static void write_one(lcd_inst_t *inst){ return; } - if (inst->f_ptr >= inst->pages[*inst->page_num].length){ - *inst->out = 0x1B; // ESC + if (inst->f_ptr >= inst->pages[hal_get_ui32(inst->page_num)].length){ + hal_set_ui32(inst->out, 0x1B); // ESC inst->buff[0] = 0x3D; // = inst->buff[1] = 0x20; // Line 0 inst->buff[2] = 0x20; // Column 0 @@ -310,12 +309,12 @@ static void write_one(lcd_inst_t *inst){ return; } - if (*inst->contrast != inst->last_contrast){ - int c = *inst->contrast * 159.0 + 0x20; + if (hal_get_real(inst->contrast) != inst->last_contrast){ + int c = hal_get_real(inst->contrast) * 159.0 + 0x20; if (c > 0xBF) c = 0xBF; if (c < 0x20) c = 0x20; - inst->last_contrast = *inst->contrast; - *inst->out = 0x1B; + inst->last_contrast = hal_get_real(inst->contrast); + hal_set_ui32(inst->out, 0x1B); inst->buff[0] = 'C'; inst->buff[1] = c; inst->buff[2] = 0; @@ -323,9 +322,9 @@ static void write_one(lcd_inst_t *inst){ return; } - switch (inst->pages[*inst->page_num].fmt[inst->f_ptr]){ + switch (inst->pages[hal_get_ui32(inst->page_num)].fmt[inst->f_ptr]){ case '\\': //escape chars - c1 = inst->pages[*inst->page_num].fmt[++inst->f_ptr]; + c1 = inst->pages[hal_get_ui32(inst->page_num)].fmt[++inst->f_ptr]; switch (c1){ case 'n': case 'N': @@ -351,7 +350,7 @@ static void write_one(lcd_inst_t *inst){ /* Fallthrough */ default: //check for hex - c2 = inst->pages[*inst->page_num].fmt[++inst->f_ptr]; + c2 = inst->pages[hal_get_ui32(inst->page_num)].fmt[++inst->f_ptr]; inst->f_ptr++; if (c1 > '9') c1 &= 0xDF; //upper case if (c2 > '9') c2 &= 0xDF; @@ -363,24 +362,24 @@ static void write_one(lcd_inst_t *inst){ inst->buff[0] = 0; } } - *inst->out = inst->buff[0]; + hal_set_ui32(inst->out, inst->buff[0]); inst->c_ptr = 1; return; case '%': - retval = parse_fmt(inst->pages[*inst->page_num].fmt, + retval = parse_fmt(inst->pages[hal_get_ui32(inst->page_num)].fmt, &inst->f_ptr, inst->buff, - inst->pages[*inst->page_num].args[inst->a_ptr++], - (char)inst->dp); + &(inst->pages[hal_get_ui32(inst->page_num)].args[inst->a_ptr++]), + (char)hal_get_ui32(inst->dp)); if (retval >= 0) { - *inst->out = inst->buff[0]; + hal_set_ui32(inst->out, inst->buff[0]); inst->c_ptr = 1; inst->f_ptr++; return; } /* Fallthrough */ default: - *inst->out = inst->pages[*inst->page_num].fmt[inst->f_ptr++]; + hal_set_ui32(inst->out, inst->pages[hal_get_ui32(inst->page_num)].fmt[inst->f_ptr++]); } } @@ -393,7 +392,7 @@ int num_digits_baseN(rtapi_u64 val, int base){ return n; } -static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ +static int parse_fmt(char *in, int *ptr, char *out, hal_refs_u *val, char dp){ /*parse val into the format in in pointed to by ptr. if out is null, then simply return the type of the format as u, s or f. a return value of -1 indicates an invalid pointer @@ -476,7 +475,7 @@ static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ { unsigned int tmp; int i; - unsigned int v = *((hal_u32_t*)val); + unsigned int v = hal_get_ui32(val->u); if (c < 1) c = num_digits_baseN(v, base); @@ -504,7 +503,7 @@ static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ { int tmp, s = 0; int i; - int v = *((hal_s32_t*)val); + int v = hal_get_si32(val->s); if (sgn == '+') s = 1; if (v < 0) {s = 1; sgn = '-'; v = -v;} @@ -543,7 +542,7 @@ static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ if (out == NULL || val == NULL) return 'f'; { int i; - double v = *((hal_float_t*)val); + double v = hal_get_real(val->r); rtapi_u64 tmp = 0; //enough bits for 9 decimal digits. int s = 0; @@ -608,7 +607,7 @@ static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ if (out == NULL || val == NULL) return 'c'; { int i; - unsigned char v = *((hal_u32_t*)val); + unsigned char v = hal_get_ui32(val->u); if (c == 0) c = 1; for (i = 0; i < c; i++){ @@ -622,7 +621,7 @@ static int parse_fmt(char *in, int *ptr, char *out, void *val, char dp){ { char c1, c2; char bt = 'E', bf = 'E'; // a hint that there is a format error - int v = *((hal_bit_t*)val); + int v = hal_get_bool(val->b); if (in[++(*ptr)] == '\\'){ c1 = in[++(*ptr)]; if (c1 > '9') c1 &= 0xDF; diff --git a/src/hal/components/led_dim.comp b/src/hal/components/led_dim.comp index 6db977e5e9e..e197088c518 100644 --- a/src/hal/components/led_dim.comp +++ b/src/hal/components/led_dim.comp @@ -36,8 +36,8 @@ * ******************************************************************************/ component led_dim "HAL component for dimming LEDs"; -pin in float in "Brightness input value -> 0 to 1"; -pin out float out "Luminance output value -> 0 to 1"; +pin in real in "Brightness input value -> 0 to 1"; +pin out real out "Luminance output value -> 0 to 1"; function _ "Update the output value"; description """ Component for LED dimming according to human perception of brightness of light. @@ -47,7 +47,7 @@ The output is calculated using the CIE 1931 formula. license "GPL"; author "Alexander Rössler"; option period no; -variable hal_float_t last_in = 0.0; +variable rtapi_real last_in = 0.0; ;; #include #define MIN(x,y) (x < y ? x : y) @@ -56,17 +56,17 @@ variable hal_float_t last_in = 0.0; FUNCTION(_) { if (last_in != in) { - hal_float_t input = MIN(MAX(in, 0.0), 1.0); // clamp to 0.0, 1.0 + rtapi_real input = MIN(MAX(in, 0.0), 1.0); // clamp to 0.0, 1.0 // luminance calculation based on CIE 1931 formula // see http://forum.arduino.cc/index.php/topic,147810.0.html if (input < 0.079996) { - out = input / 9.033; + out_set(input / 9.033); } else { - out = pow((input + 0.16) / 1.16, 3.0); + out_set(pow((input + 0.16) / 1.16, 3.0)); } last_in = in; diff --git a/src/hal/components/limit1.comp b/src/hal/components/limit1.comp index a0cf417de7d..ddb76ada8ca 100644 --- a/src/hal/components/limit1.comp +++ b/src/hal/components/limit1.comp @@ -1,16 +1,16 @@ component limit1 "Limit the output signal to fall between min and max"; -pin in float in; -pin out float out; -pin in float min_=-1e20; -pin in float max_=1e20; +pin in real in; +pin out real out; +pin in real min_=-1e20; +pin in real max_=1e20; option period no; function _; license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - double tmp = in; + rtapi_real tmp = in; if(tmp < min_) tmp = min_; if(tmp > max_) tmp = max_; - out = tmp; + out_set(tmp); } diff --git a/src/hal/components/limit2.comp b/src/hal/components/limit2.comp index 2ce275101cb..d7174ec72c1 100644 --- a/src/hal/components/limit2.comp +++ b/src/hal/components/limit2.comp @@ -1,20 +1,20 @@ component limit2 "Limit the output signal to fall between min and max and limit its slew rate to less than maxv per second. When the signal is a position, this means that position and velocity are limited."; -pin in float in; -pin out float out; -pin in bit load "When TRUE, immediately set *out* to *in*, ignoring maxv"; -pin in float min_=-1e20; -pin in float max_=1e20; -pin in float maxv=1e20; +pin in real in; +pin out real out; +pin in bool load "When TRUE, immediately set *out* to *in*, ignoring maxv"; +pin in real min_=-1e20; +pin in real max_=1e20; +pin in real maxv=1e20; option data limit2_data; function _; license "GPL"; author "Jeff Epler"; ;; -typedef struct { double old_out; } limit2_data; +typedef struct { rtapi_real old_out; } limit2_data; #ifndef clamp -static inline double clamp(double v, double sub, double sup) { +static inline rtapi_real clamp(rtapi_real v, rtapi_real sub, rtapi_real sup) { if(v < sub) return sub; if(v > sup) return sup; return v; @@ -22,11 +22,11 @@ static inline double clamp(double v, double sub, double sup) { #endif FUNCTION(_) { - double tmp = in; - double maxdelta = maxv * fperiod; + rtapi_real tmp = in; + rtapi_real maxdelta = maxv * fperiod; tmp = clamp(tmp, min_, max_); - if(load) { out = data.old_out = tmp; return; } + if(load) { out_set(data.old_out = tmp); return; } tmp = clamp(tmp, data.old_out - maxdelta, data.old_out + maxdelta); data.old_out = tmp; - out = tmp; + out_set(tmp); } diff --git a/src/hal/components/limit3.comp b/src/hal/components/limit3.comp index daa82939931..c1ea302eb5e 100644 --- a/src/hal/components/limit3.comp +++ b/src/hal/components/limit3.comp @@ -3,23 +3,23 @@ Limit the output signal to fall between min and max, limit its slew rate to less than maxv per second, and limit its second derivative to less than maxa per second squared. When the signal is a position, this means that the position, velocity, and acceleration are limited."""; -pin in float in; -pin in bit enable = 1 "1: out follows in, 0: out returns to 0 (always per constraints)"; -pin out float out; -pin in bit load=0 +pin in real in; +pin in bool enable = 1 "1: out follows in, 0: out returns to 0 (always per constraints)"; +pin out real out; +pin in bool load=0 """When TRUE, immediately set *out* to *in*, ignoring maxv and maxa"""; -pin in float min_=-1e20; -pin in float max_=1e20; -pin in float maxv=1e20; -pin in float maxa=1e7 """Max Acceleration. Note that the component becomes +pin in real min_=-1e20; +pin in real max_=1e20; +pin in real maxv=1e20; +pin in real maxa=1e7 """Max Acceleration. Note that the component becomes unstable with maxa greater than about 1e7 in a 1kHz thread"""; -pin in u32 smooth_steps=2 +pin in ui32 smooth_steps=2 """Smooth out acceleration this many periods before reaching input or max/min limit. Higher values avoid oscillation, but will accelerate slightly more slowly."""; -variable double in_pos_old; -variable double out_old; +variable rtapi_real in_pos_old; +variable rtapi_real out_old; function _; license "GPL"; author "John Kasunich"; @@ -30,7 +30,7 @@ author "John Kasunich"; #define SET_NEXT_STATE(_out, _in) \ do { \ out_old = out; \ - out = _out; \ + out_set(_out); \ in_pos_old = _in; \ return; \ } while (0) @@ -47,19 +47,19 @@ author "John Kasunich"; #define EPSILON 1e-9 FUNCTION(_) { - double invalue; - double in_pos_lim, in_vel; - double min_vel, max_vel, min_pos, max_pos; - double stop_pos_max, stop_pos_min; - double stop_time_max, stop_time_min; - double in_vel_time_max, in_vel_time_min; - double out_pos_max, out_pos_min, in_pos_max, in_pos_min; - double ach_pos_min, ach_pos_max; - - double out_vel = (out-out_old)/fperiod; - double goal_pos_min, goal_pos_max, goal_pos_cur; - double pos_diff, vel_diff, goal_pos_prev; - double t, ti, a, v, s; + rtapi_real invalue; + rtapi_real in_pos_lim, in_vel; + rtapi_real min_vel, max_vel, min_pos, max_pos; + rtapi_real stop_pos_max, stop_pos_min; + rtapi_real stop_time_max, stop_time_min; + rtapi_real in_vel_time_max, in_vel_time_min; + rtapi_real out_pos_max, out_pos_min, in_pos_max, in_pos_min; + rtapi_real ach_pos_min, ach_pos_max; + + rtapi_real out_vel = (out-out_old)/fperiod; + rtapi_real goal_pos_min, goal_pos_max, goal_pos_cur; + rtapi_real pos_diff, vel_diff, goal_pos_prev; + rtapi_real t, ti, a, v, s; if (enable) { invalue = in; // out pin follows in pin per limits diff --git a/src/hal/components/limit_axis.comp b/src/hal/components/limit_axis.comp index 223f9973673..f2458264799 100644 --- a/src/hal/components/limit_axis.comp +++ b/src/hal/components/limit_axis.comp @@ -42,19 +42,19 @@ option extra_setup 1; option period no; function _; -pin out bit error-no-range "error pin indicating that no range matches the fb"; -pin out float min-output "Minimum limit output"; -pin out float max-output "Maximum limit output"; -pin in float fb "Feedback pin, the value of this pin determines which range is active"; -pin out unsigned current-range "Indicates which range is currently active"; -pin in float min-limit-## [10:personality] "The array of minimum limits to select from"; -pin in float max-limit-## [10:personality] "The array of macimum limits"; -pin in float min-range-## [10:personality] "Defines the range of values with which the fb is compared to set the range"; -pin in float max-range-## [10:personality] "Defines the range of values with which the fb is compared to set the range"; -pin in bit enable-## [10:personality] "Used to enable and disable a specific range"; -pin in bit sticky-## [10:personality] "Used to make specific range 'sticky' or not"; -pin out bit error-range-## [10:personality] = 1 "Error bit indicating that the fb pin falls outside all ranges"; -pin out bit error-limit-## [10:personality] = 1 "Error bit indicating that the max limit is not larger than the min limit"; +pin out bool error-no-range "error pin indicating that no range matches the fb"; +pin out real min-output "Minimum limit output"; +pin out real max-output "Maximum limit output"; +pin in real fb "Feedback pin, the value of this pin determines which range is active"; +pin out ui32 current-range "Indicates which range is currently active"; +pin in real min-limit-## [10:personality] "The array of minimum limits to select from"; +pin in real max-limit-## [10:personality] "The array of macimum limits"; +pin in real min-range-## [10:personality] "Defines the range of values with which the fb is compared to set the range"; +pin in real max-range-## [10:personality] "Defines the range of values with which the fb is compared to set the range"; +pin in bool enable-## [10:personality] "Used to enable and disable a specific range"; +pin in bool sticky-## [10:personality] "Used to make specific range 'sticky' or not"; +pin out bool error-range-## [10:personality] = 1 "Error bit indicating that the fb pin falls outside all ranges"; +pin out bool error-limit-## [10:personality] = 1 "Error bit indicating that the max limit is not larger than the min limit"; ;; @@ -66,8 +66,8 @@ FUNCTION(_){ fb <= max_range(current_range) && enable(current_range)) { - max_output = max_limit(current_range); - min_output = min_limit(current_range); + max_output_set(max_limit(current_range)); + min_output_set(min_limit(current_range)); return; } @@ -87,12 +87,12 @@ FUNCTION(_){ i, max_range(i), min_range(i)); - error_range(i) = 1; + error_range_set(i, 1); } continue; } // If we made it to here clear the error - error_range(i) = 0; + error_range_set(i, 0); if (max_limit(i) < min_limit(i)){ // Throw Error and skip this range @@ -102,22 +102,22 @@ FUNCTION(_){ i, max_limit(i), min_limit(i)); - error_limit(i) = 1; + error_limit_set(i, 1); } continue; } // If we made it to here clear the error - error_limit(i) = 0; + error_limit_set(i, 0); // Check position, take first range that it fits in. if(min_range(i) <= fb && fb <= max_range(i)) { - max_output = max_limit(i); - min_output = min_limit(i); + max_output_set(max_limit(i)); + min_output_set(min_limit(i)); // Found our limits, stop looking - error_no_range = 0; + error_no_range_set(0); if (i != (int)current_range){ rtapi_print_msg(RTAPI_MSG_INFO, "limit_axis: Switching to Range %d\n", i); - current_range = i; + current_range_set(i); } return; } @@ -125,7 +125,7 @@ FUNCTION(_){ // If we've looked through all our ranges, then it's not there if (!error_no_range){ - error_no_range = 1; + error_no_range_set(1); rtapi_print_msg(RTAPI_MSG_ERR, "limit_axis: No Range found corresponding to feedback"); diff --git a/src/hal/components/lincurve.comp b/src/hal/components/lincurve.comp index a3d120632ad..46ce4a46c2e 100644 --- a/src/hal/components/lincurve.comp +++ b/src/hal/components/lincurve.comp @@ -23,12 +23,12 @@ Sample usage: loadrt lincurve count=3 personality=4,4,4 for a set of three 4-element graphs. """; -param rw float x-val-##[16 : personality] "axis breakpoints"; -param rw float y-val-##[16 : personality] "output values to be interpolated"; +param rw real x-val-##[16 : personality] "axis breakpoints"; +param rw real y-val-##[16 : personality] "output values to be interpolated"; -pin in float in_ "The input value"; -pin out float out_ "The output value"; -pin io float out-io "The output value, compatible with PID gains"; +pin in real in_ "The input value"; +pin out real out_ "The output value"; +pin io real out-io "The output value, compatible with PID gains"; variable unsigned i = 0; @@ -43,24 +43,22 @@ function _; ;; FUNCTION(_){ - double f, x; + rtapi_real f, x; x = in_; if (x >= x_val(personality-1)) { - out_ = y_val(personality-1); - out_io = out_; + out_io_set(out__set(y_val(personality-1))); return; } if (x <= x_val(0)) { - out_ = y_val(0); - out_io = out_; + out_io_set(out__set(y_val(0))); return; } + // FIXME: potential buffer overflow read while (x > x_val(i+1)) { i++;} while (x < (x_val(i))) { i--;} f = (x - x_val(i))/(x_val(i+1)-x_val(i)); - out_ = y_val(i) + f * (y_val(i+1) - y_val(i)); - out_io = out_; + out_io_set(out__set(y_val(i) + f * (y_val(i+1) - y_val(i)))); } EXTRA_SETUP(){ diff --git a/src/hal/components/logic.comp b/src/hal/components/logic.comp index 72afe58b146..a8f6be929de 100644 --- a/src/hal/components/logic.comp +++ b/src/hal/components/logic.comp @@ -13,12 +13,12 @@ Each number defines the behaviour of the individual logic gate. The list must have the same number of personalities as the N count. """; -pin in bit in-##[16 : personality & 0xff]; -pin out bit and if personality & 0x100; -pin out bit or if personality & 0x200; -pin out bit xor if personality & 0x400; -pin out bit nand if personality & 0x800; -pin out bit nor if personality & 0x1000; +pin in bool in-##[16 : personality & 0xff]; +pin out bool and if personality & 0x100; +pin out bool or if personality & 0x200; +pin out bool xor if personality & 0x400; +pin out bool nand if personality & 0x800; +pin out bool nor if personality & 0x1000; function _ "Read the inputs and toggle the output bit."; description """ General `logic function' component. Can perform `and', `or', @@ -82,9 +82,9 @@ FUNCTION(_) { if(in(i)) { o = 1; x = !x; } else { a = 0; } } - if(personality & 0x100) and = a; - if(personality & 0x200) or = o; - if(personality & 0x400) xor = x; - if(personality & 0x800) nand = !a; - if(personality & 0x1000) nor = !o; + if(personality & 0x100) and_set(a); + if(personality & 0x200) or_set(o); + if(personality & 0x400) xor_set(x); + if(personality & 0x800) nand_set(!a); + if(personality & 0x1000) nor_set(!o); } diff --git a/src/hal/components/lowpass.comp b/src/hal/components/lowpass.comp index 2dbdeec6fc8..f7a288d129b 100644 --- a/src/hal/components/lowpass.comp +++ b/src/hal/components/lowpass.comp @@ -30,10 +30,10 @@ Examples: a = (2 * pi * 1) ( *1Hz* bandwidth single pole) gain = *0.0063* """; -pin in float in; -pin out float out " out += (in - out) * gain "; -pin in bit load "When TRUE, copy *in* to *out* instead of applying the filter equation."; -param rw float gain; +pin in real in; +pin out real out " out += (in - out) * gain "; +pin in bool load "When TRUE, copy *in* to *out* instead of applying the filter equation."; +param rw real gain; option period no; function _; license "GPL"; @@ -42,7 +42,9 @@ notes "The effect of a specific *gain* value is dependent on the period of the f ;; FUNCTION(_) { if(load) - out = in; - else - out += (in - out) * gain; + out_set(in); + else { + rtapi_real val = out; + out_set(val + (in - val) * gain); + } } diff --git a/src/hal/components/lut5.comp b/src/hal/components/lut5.comp index 755fd763134..20720893c53 100644 --- a/src/hal/components/lut5.comp +++ b/src/hal/components/lut5.comp @@ -1,11 +1,11 @@ component lut5 """Arbitrary 5-input logic function based on a look-up table"""; -pin in bit in_0; -pin in bit in_1; -pin in bit in_2; -pin in bit in_3; -pin in bit in_4; -pin out bit out; -param rw u32 function; +pin in bool in_0; +pin in bool in_1; +pin in bool in_2; +pin in bool in_3; +pin in bool in_4; +pin out bool out; +param rw ui32 function; function _; description """ *lut5* @@ -103,5 +103,5 @@ FUNCTION(_) { if(in_3) shift += 8; if(in_4) shift += 16; - out = (function & (1<= 2; + out_set(sum >= 2); } diff --git a/src/hal/components/match8.comp b/src/hal/components/match8.comp index 7cb8fdf337d..bcc6f29a33f 100644 --- a/src/hal/components/match8.comp +++ b/src/hal/components/match8.comp @@ -1,22 +1,22 @@ component match8 "8-bit binary match detector"; -pin in bit in = TRUE "cascade input - if false, output is false regardless of other inputs"; -pin in bit a0; -pin in bit a1; -pin in bit a2; -pin in bit a3; -pin in bit a4; -pin in bit a5; -pin in bit a6; -pin in bit a7; -pin in bit b0; -pin in bit b1; -pin in bit b2; -pin in bit b3; -pin in bit b4; -pin in bit b5; -pin in bit b6; -pin in bit b7; -pin out bit out "true only if in is true and a[m] matches b[m] for m = 0 thru 7"; +pin in bool in = TRUE "cascade input - if false, output is false regardless of other inputs"; +pin in bool a0; +pin in bool a1; +pin in bool a2; +pin in bool a3; +pin in bool a4; +pin in bool a5; +pin in bool a6; +pin in bool a7; +pin in bool b0; +pin in bool b1; +pin in bool b2; +pin in bool b3; +pin in bool b4; +pin in bool b5; +pin in bool b6; +pin in bool b7; +pin out bool out "true only if in is true and a[m] matches b[m] for m = 0 thru 7"; option period no; function _; license "GPL"; @@ -36,5 +36,5 @@ FUNCTION(_) { if (( a7 && !b7 ) || ( !a7 && b7 )) goto nomatch; tmp = 1; nomatch: - out = tmp; + out_set(tmp); } diff --git a/src/hal/components/matrix_kb.c b/src/hal/components/matrix_kb.c index c737464d1c5..4f27d1914b4 100644 --- a/src/hal/components/matrix_kb.c +++ b/src/hal/components/matrix_kb.c @@ -29,30 +29,29 @@ MODULE_LICENSE("GPL"); typedef struct { struct { - hal_bit_t **key; - hal_bit_t **rows; - hal_bit_t **cols; - hal_u32_t *keycode; + hal_bool_t *key; + hal_bool_t *rows; + hal_bool_t *cols; + hal_uint_t keycode; } hal; struct { - hal_u32_t rollover; - hal_bit_t invert; + hal_uint_t rollover; + hal_bool_t invert; } param; - hal_u32_t ncols; - hal_u32_t nrows; - hal_u32_t *now; - hal_u32_t *then; - hal_bit_t invert; + rtapi_u32 ncols; + rtapi_u32 nrows; + rtapi_u32 *now; + rtapi_u32 *then; char name[HAL_NAME_LEN + 1]; struct input_dev *key_dev; - hal_u32_t index; + rtapi_u32 index; unsigned keydown; unsigned keyup; unsigned rowshift; unsigned row; unsigned num_keys; - hal_bit_t scan; - hal_bit_t keystroke; + rtapi_bool scan; + rtapi_bool keystroke; }kb_inst_t; typedef struct { @@ -70,7 +69,7 @@ RTAPI_MP_ARRAY_STRING(names, MAX_CHAN, "component names"); void keyup(kb_inst_t *inst){ unsigned r, c; - unsigned keycode = *inst->hal.keycode & ~(inst->keydown | inst->keyup); + unsigned keycode = hal_get_ui32(inst->hal.keycode) & ~(inst->keydown | inst->keyup); r = keycode >> inst->rowshift; c = keycode & ~(0xFFFFFFFF << inst->rowshift); @@ -83,11 +82,11 @@ void keyup(kb_inst_t *inst){ if (inst->num_keys > 0) inst->num_keys--; - *inst->hal.key[r * inst->ncols + c] = 0; + hal_set_bool(inst->hal.key[r * inst->ncols + c], 0); } void keydown(kb_inst_t *inst){ unsigned r, c; - unsigned keycode = *inst->hal.keycode & ~(inst->keydown | inst->keyup); + unsigned keycode = hal_get_ui32(inst->hal.keycode) & ~(inst->keydown | inst->keyup); r = keycode >> inst->rowshift; c = keycode & ~(0xFFFFFFFF << inst->rowshift); @@ -98,60 +97,61 @@ void keydown(kb_inst_t *inst){ return; } - if (inst->num_keys >= inst->param.rollover) return; + if (inst->num_keys >= hal_get_ui32(inst->param.rollover)) return; inst->num_keys++; - *inst->hal.key[r * inst->ncols + c] = 1; + hal_set_bool(inst->hal.key[r * inst->ncols + c], 1); } void loop(void *arg, long period){ (void)period; unsigned c; - hal_u32_t scan = 0; + rtapi_u32 scan = 0; kb_inst_t *inst = arg; if (inst->scan){ //scanning request for (c = 0; c < inst->ncols; c++){ - scan += ((*inst->hal.cols[c] != inst->param.invert) << c); + scan += ((hal_get_bool(inst->hal.cols[c]) != hal_get_bool(inst->param.invert)) << c); } if (scan == inst->now[inst->row] && scan != inst->then[inst->row]){ // debounced and changed for (c = 0; c < inst->ncols; c++){ int mask = 1 << c; if ((inst->then[inst->row] & mask) && !(scan & mask)){ //keyup - *inst->hal.keycode = inst->keyup + hal_set_ui32(inst->hal.keycode, inst->keyup + (inst->row << inst->rowshift) - + c; + + c); keyup(inst); } else if (!(inst->then[inst->row] & mask) && (scan & mask)){//keydown - *inst->hal.keycode = inst->keydown + hal_set_ui32(inst->hal.keycode, inst->keydown + (inst->row << inst->rowshift) - + c; + + c); keydown(inst); } } } else { - *inst->hal.keycode = 0x40;//nochange + hal_set_ui32(inst->hal.keycode, 0x40);//nochange } inst->then[inst->row] = inst->now[inst->row]; inst->now[inst->row] = scan; - *inst->hal.rows[inst->row] = inst->param.invert; + hal_set_bool(inst->hal.rows[inst->row], hal_get_bool(inst->param.invert)); inst->row++; if (inst->row >= inst->nrows) inst->row = 0; - *inst->hal.rows[inst->row] = !inst->param.invert; + hal_set_bool(inst->hal.rows[inst->row], !hal_get_bool(inst->param.invert)); } else { - if (*inst->hal.keycode == 0x40) return; - if ((*inst->hal.keycode & inst->keydown) == inst->keydown){ + rtapi_u32 keycode = hal_get_ui32(inst->hal.keycode); + if (keycode == 0x40) return; + if ((keycode & inst->keydown) == inst->keydown){ keydown(inst); } - else if ((*inst->hal.keycode & inst->keydown) == inst->keyup) + else if ((keycode & inst->keydown) == inst->keyup) { keyup(inst); } @@ -169,7 +169,7 @@ int rtapi_app_main(void){ } // allocate shared memory for data - kb = hal_malloc(sizeof(kb_t)); + kb = hal_malloc(sizeof(*kb)); if (kb == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "matrix_kb component: Out of Memory\n"); @@ -189,7 +189,7 @@ int rtapi_app_main(void){ return -1; } - kb->insts = hal_malloc(kb->num_insts * sizeof(kb_inst_t)); + kb->insts = hal_malloc(kb->num_insts * sizeof(*kb->insts)); for (i = 0; i < kb->num_insts; i++){ int a = 0; @@ -201,7 +201,7 @@ int rtapi_app_main(void){ inst->ncols = 0; inst->scan = 0; inst->keystroke = 0; - inst->param.invert = 1; + hal_set_bool(inst->param.invert, 1); for(j = 0; config[i][j] !=0; j++){ int n = (config[i][j] | 0x20); //lower case @@ -237,11 +237,11 @@ int rtapi_app_main(void){ ; (inst->nrows << inst->rowshift) > inst->keydown ; inst->keydown <<= 1, inst->keyup <<= 1); - inst->hal.key = (hal_bit_t **)hal_malloc(inst->nrows * inst->ncols * sizeof(hal_bit_t*)); - inst->now = hal_malloc(inst->nrows * sizeof(hal_u32_t)); - inst->then = hal_malloc(inst->nrows * sizeof(hal_u32_t)); + inst->hal.key = hal_malloc(inst->nrows * inst->ncols * sizeof(*inst->hal.key)); + inst->now = hal_malloc(inst->nrows * sizeof(*inst->now)); + inst->then = hal_malloc(inst->nrows * sizeof(*inst->then)); inst->row = 0; - inst->param.rollover = 2; + hal_set_ui32(inst->param.rollover, 2); if (names[i]){ @@ -254,9 +254,9 @@ int rtapi_app_main(void){ for (c = 0; c < inst->ncols; c++){ for (r = 0; r < inst->nrows; r++){ - retval = hal_pin_bit_newf(HAL_OUT, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(inst->hal.key[r * inst->ncols + c]), - comp_id, + 0, "%s.key.r%xc%x", inst->name, r, c); if (retval != 0) { @@ -269,12 +269,12 @@ int rtapi_app_main(void){ } if (inst->scan){ //internally generated scanning - inst->hal.rows = (hal_bit_t **)hal_malloc(inst->nrows * sizeof(hal_bit_t*)); - inst->hal.cols = (hal_bit_t **)hal_malloc(inst->ncols * sizeof(hal_bit_t*)); + inst->hal.rows = hal_malloc(inst->nrows * sizeof(*inst->hal.rows)); + inst->hal.cols = hal_malloc(inst->ncols * sizeof(*inst->hal.cols)); for (r = 0; r < inst->nrows; r++){ - retval = hal_pin_bit_newf(HAL_OUT, - &(inst->hal.rows[r]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, + &(inst->hal.rows[r]), 0, "%s.row-%02i-out",inst->name, r); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -284,8 +284,8 @@ int rtapi_app_main(void){ } } for (c = 0; c < inst->ncols; c++){ - retval = hal_pin_bit_newf(HAL_IN, - &(inst->hal.cols[c]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, + &(inst->hal.cols[c]), 0, "%s.col-%02i-in",inst->name, c); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -295,8 +295,8 @@ int rtapi_app_main(void){ } } - retval = hal_pin_u32_newf(HAL_OUT, - &(inst->hal.keycode), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_OUT, + &(inst->hal.keycode), 0, "%s.keycode",inst->name); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -305,8 +305,8 @@ int rtapi_app_main(void){ return -1; } - retval = hal_param_bit_newf(HAL_RW, - &(inst->param.invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, + &(inst->param.invert), 0, "%s.negative-logic",inst->name); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -316,8 +316,8 @@ int rtapi_app_main(void){ } - retval = hal_param_u32_newf(HAL_RW, - &(inst->param.rollover), comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RW, + &(inst->param.rollover), 0, "%s.key_rollover",inst->name); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -329,8 +329,8 @@ int rtapi_app_main(void){ } else // scanning by 7i73 or similar { - retval = hal_pin_u32_newf(HAL_IN, - &(inst->hal.keycode), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, + &(inst->hal.keycode), 0, "%s.keycode",inst->name); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, diff --git a/src/hal/components/matrixkins.comp b/src/hal/components/matrixkins.comp index 29760d6d795..c63a5e211c1 100644 --- a/src/hal/components/matrixkins.comp +++ b/src/hal/components/matrixkins.comp @@ -175,20 +175,20 @@ the adjustment values should be added to the old values instead of replacing the """; see_also "kins(9)"; -pin out bit dummy=1; // halcompile requires at least one pin +pin out bool dummy=1; // halcompile requires at least one pin license "GPL"; ;; static struct haldata { - hal_float_t C_xx; - hal_float_t C_xy; - hal_float_t C_xz; - hal_float_t C_yx; - hal_float_t C_yy; - hal_float_t C_yz; - hal_float_t C_zx; - hal_float_t C_zy; - hal_float_t C_zz; + hal_real_t C_xx; + hal_real_t C_xy; + hal_real_t C_xz; + hal_real_t C_yx; + hal_real_t C_yy; + hal_real_t C_yz; + hal_real_t C_zx; + hal_real_t C_zy; + hal_real_t C_zz; } *haldata; static int matrixkins_setup(void) { @@ -203,20 +203,15 @@ static int matrixkins_setup(void) { haldata = hal_malloc(sizeof(struct haldata)); if (!haldata) goto error; - res |= hal_param_float_new("matrixkins.C_xx", HAL_RW, &haldata->C_xx, comp_id); - res |= hal_param_float_new("matrixkins.C_xy", HAL_RW, &haldata->C_xy, comp_id); - res |= hal_param_float_new("matrixkins.C_xz", HAL_RW, &haldata->C_xz, comp_id); - res |= hal_param_float_new("matrixkins.C_yx", HAL_RW, &haldata->C_yx, comp_id); - res |= hal_param_float_new("matrixkins.C_yy", HAL_RW, &haldata->C_yy, comp_id); - res |= hal_param_float_new("matrixkins.C_yz", HAL_RW, &haldata->C_yz, comp_id); - res |= hal_param_float_new("matrixkins.C_zx", HAL_RW, &haldata->C_zx, comp_id); - res |= hal_param_float_new("matrixkins.C_zy", HAL_RW, &haldata->C_zy, comp_id); - res |= hal_param_float_new("matrixkins.C_zz", HAL_RW, &haldata->C_zz, comp_id); - - haldata->C_xx = haldata->C_yy = haldata->C_zz = 1.0; - haldata->C_xy = haldata->C_xz = 0.0; - haldata->C_yx = haldata->C_yz = 0.0; - haldata->C_zx = haldata->C_zy = 0.0; + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_xx, 1.0, "matrixkins.C_xx"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_xy, 0.0, "matrixkins.C_xy"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_xz, 0.0, "matrixkins.C_xz"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_yx, 0.0, "matrixkins.C_yx"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_yy, 1.0, "matrixkins.C_yy"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_yz, 0.0, "matrixkins.C_yz"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_zx, 0.0, "matrixkins.C_zx"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_zy, 0.0, "matrixkins.C_zy"); + res |= hal_param_new_real(comp_id, HAL_RW, &haldata->C_zz, 1.0, "matrixkins.C_zz"); if (res) goto error; @@ -259,20 +254,20 @@ int kinematicsForward(const double *j, // https://ardoris.wordpress.com/2008/07/18/general-formula-for-the-inverse-of-a-3x3-matrix/ // https://en.wikipedia.org/wiki/Invertible_matrix#Inversion_of_3_%C3%97_3_matrices - double a = haldata->C_xx; - double b = haldata->C_xy; - double c = haldata->C_xz; - double d = haldata->C_yx; - double e = haldata->C_yy; - double f = haldata->C_yz; - double g = haldata->C_zx; - double h = haldata->C_zy; - double i = haldata->C_zz; - - double det = a * (e * i - f * h) + rtapi_real a = hal_get_real(haldata->C_xx); + rtapi_real b = hal_get_real(haldata->C_xy); + rtapi_real c = hal_get_real(haldata->C_xz); + rtapi_real d = hal_get_real(haldata->C_yx); + rtapi_real e = hal_get_real(haldata->C_yy); + rtapi_real f = hal_get_real(haldata->C_yz); + rtapi_real g = hal_get_real(haldata->C_zx); + rtapi_real h = hal_get_real(haldata->C_zy); + rtapi_real i = hal_get_real(haldata->C_zz); + + rtapi_real det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g); - double invdet = 1.0 / det; + rtapi_real invdet = 1.0 / det; // Apply inverse matrix transform to the 3 cartesian coordinates pos->tran.x = invdet * ( (e * i - f * h) * j[0] @@ -305,15 +300,15 @@ int kinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - double a = haldata->C_xx; - double b = haldata->C_xy; - double c = haldata->C_xz; - double d = haldata->C_yx; - double e = haldata->C_yy; - double f = haldata->C_yz; - double g = haldata->C_zx; - double h = haldata->C_zy; - double i = haldata->C_zz; + rtapi_real a = hal_get_real(haldata->C_xx); + rtapi_real b = hal_get_real(haldata->C_xy); + rtapi_real c = hal_get_real(haldata->C_xz); + rtapi_real d = hal_get_real(haldata->C_yx); + rtapi_real e = hal_get_real(haldata->C_yy); + rtapi_real f = hal_get_real(haldata->C_yz); + rtapi_real g = hal_get_real(haldata->C_zx); + rtapi_real h = hal_get_real(haldata->C_zy); + rtapi_real i = hal_get_real(haldata->C_zz); // Apply matrix transform to the 3 cartesian coordinates j[0] = pos->tran.x * a + pos->tran.y * b + pos->tran.z * c; diff --git a/src/hal/components/max31855.comp b/src/hal/components/max31855.comp index 8fe9421b1eb..c39bb05b83d 100644 --- a/src/hal/components/max31855.comp +++ b/src/hal/components/max31855.comp @@ -28,16 +28,16 @@ A maximum of 15 sensors are supported. """; -pin in bit data.#.in [15 : (personality & 0xf)] "Pin(s) connected to data out."; -pin out bit cs.out "Pin connected to cs, pulled low to shift data, pulled high for data refresh."; -pin out bit clk.out "Pin connected to clk."; +pin in bool data.#.in [15 : (personality & 0xf)] "Pin(s) connected to data out."; +pin out bool cs.out "Pin connected to cs, pulled low to shift data, pulled high for data refresh."; +pin out bool clk.out "Pin connected to clk."; -pin out float temp_celsius.# [15 : (personality & 0xf)] """Temperature output values in Celsius."""; -pin out float temp_fahrenheit.# [15 : (personality & 0xf)] """Temperature in Fahrenheit."""; -pin out float temp_kelvin.# [15 : (personality & 0xf)] """Temperature in Kelvin."""; +pin out real temp_celsius.# [15 : (personality & 0xf)] """Temperature output values in Celsius."""; +pin out real temp_fahrenheit.# [15 : (personality & 0xf)] """Temperature in Fahrenheit."""; +pin out real temp_kelvin.# [15 : (personality & 0xf)] """Temperature in Kelvin."""; -pin out bit fault.# [15 : (personality & 0xf)] "Fault condition detected."; -pin out unsigned fault_flags.# [15 : (personality & 0xf)] "Fault flags: 0x1 = open sensor, 0x2 short to gnd, 0x3 short to vcc."; +pin out bool fault.# [15 : (personality & 0xf)] "Fault condition detected."; +pin out ui32 fault_flags.# [15 : (personality & 0xf)] "Fault flags: 0x1 = open sensor, 0x2 short to gnd, 0x3 short to vcc."; variable unsigned data_frame [15]; variable unsigned state = 1; @@ -51,24 +51,24 @@ author "Joseph Calderon"; #include -static float accpoly(float *v, size_t n, float p) { +static rtapi_real accpoly(rtapi_real *v, size_t n, rtapi_real p) { size_t i; - float ret = 0; + rtapi_real ret = 0; for (i = 0; i < n; i++) { ret += v[i] * pow(p, i); } return ret; } -static float to_kelvin(float celsius) { +static rtapi_real to_kelvin(rtapi_real celsius) { return celsius + 273.15; } -static float to_fahrenheit(float celsius) { +static rtapi_real to_fahrenheit(rtapi_real celsius) { return celsius * 1.80 + 32.0; } -static float read_celsius(int32_t v) { +static rtapi_real read_celsius(int32_t v) { if (v & 0x7) { return nan(""); /* fault bit(s) set */ } @@ -82,7 +82,7 @@ static float read_celsius(int32_t v) { return v / 4.0; /* 0.25 degree resolution */ } -static float read_internal(int32_t v) { +static rtapi_real read_internal(int32_t v) { if (v & 0x7) { return nan(""); /* fault bit(s) set */ } @@ -97,16 +97,16 @@ static float read_internal(int32_t v) { return v / 16.0; /* 0.0625 degree resolution */ } -static float read_celsius_adjusted(int32_t sensor_data) { - float temp_raw = read_celsius(sensor_data); - float temp_internal = read_internal(sensor_data); - float voltage_internal = 0, voltage_thermocouple = 0, temp_corrected = 0; +static rtapi_real read_celsius_adjusted(int32_t sensor_data) { + rtapi_real temp_raw = read_celsius(sensor_data); + rtapi_real temp_internal = read_internal(sensor_data); + rtapi_real voltage_internal = 0, voltage_thermocouple = 0, temp_corrected = 0; if (isnan(temp_raw) || isnan(temp_internal)) return nan(""); /* NIST K-Type table (http://srdata.nist.gov/its90/download/type_k.tab) */ - float coeff[][11] = { + rtapi_real coeff[][11] = { {-0.0176004134, 0.0389212035, 1.85587705e-05, -9.94575942e-08, 3.18409465e-10, -5.60728439e-13, 5.60750581e-16, -3.20207199e-19, 9.71511487e-23, -1.21047216e-26, 0}, @@ -119,14 +119,14 @@ static float read_celsius_adjusted(int32_t sensor_data) { 0.000980403624, -4.41302982e-05, 1.05773404e-06, -1.05275504e-08, 0}, {-131.805801, 48.3022194, -1.64603102, 0.0546473116, -0.000965071493, 8.80219341e-06, -3.1108101e-08, 0, 0, 0, 0}}; - int coeff_cols = sizeof(coeff[0]) / sizeof(float); + int coeff_cols = sizeof(coeff[0]) / sizeof(*coeff[0]); /* determine thermocouple voltage by subtracting internal temp and adjusting * for K-type thermocouple */ voltage_thermocouple = (temp_raw - temp_internal) * 0.041276; if (temp_internal >= 0) { - float a[] = {0.118597597, -0.000118343203, 126.968597}; + rtapi_real a[] = {0.118597597, -0.000118343203, 126.968597}; /* for positive temps additional exponential coefficients are needed */ voltage_internal += accpoly(coeff[0], coeff_cols, temp_internal); voltage_internal += a[0] * exp(a[1] * pow((temp_internal - a[2]), 2)); @@ -134,7 +134,7 @@ static float read_celsius_adjusted(int32_t sensor_data) { voltage_internal += accpoly(coeff[1], coeff_cols, temp_internal); } - float voltage_total = voltage_thermocouple + voltage_internal; + rtapi_real voltage_total = voltage_thermocouple + voltage_internal; /* linearize temperature depending on voltage range */ if (voltage_total < 0) { @@ -159,7 +159,7 @@ FUNCTION(bitbang_spi) { int delay = (state >> 7) & 0x3ff; int cs = state & 0x1; - clk_out ^= 0x1; + clk_out_set(!clk_out); if (cs) { /* data refreshes when cs is pulled high */ delay--; @@ -178,15 +178,15 @@ FUNCTION(bitbang_spi) { } if (nbit < 0) { for (i = 0; i < n; i++) { - float f = read_celsius_adjusted((int32_t)data_frame[i]); - fault(i) = (data_frame[i] & 0x7) ? TRUE : FALSE; - fault_flags(i) = data_frame[i] & 0x7; + rtapi_real f = read_celsius_adjusted((int32_t)data_frame[i]); + fault_set(i, (data_frame[i] & 0x7) ? TRUE : FALSE); + fault_flags_set(i, data_frame[i] & 0x7); if (isnan(f)) { rtapi_print("max31855: sensor %d detected fault %x\n", i, data_frame[i] & 0x7); } else { - temp_celsius(i) = f; - temp_fahrenheit(i) = to_fahrenheit(f); - temp_kelvin(i) = to_kelvin(f); + temp_celsius_set(i, f); + temp_fahrenheit_set(i, to_fahrenheit(f)); + temp_kelvin_set(i, to_kelvin(f)); } data_frame[i] = 0; } @@ -196,5 +196,5 @@ FUNCTION(bitbang_spi) { delay++; } state = (delay << 7) | (nbit << 1) | cs; - cs_out = cs; + cs_out_set(cs); } diff --git a/src/hal/components/mesa_pktgyro_test.comp b/src/hal/components/mesa_pktgyro_test.comp index a918df2ba86..0dffa30f172 100644 --- a/src/hal/components/mesa_pktgyro_test.comp +++ b/src/hal/components/mesa_pktgyro_test.comp @@ -51,7 +51,7 @@ include ; include "hal/drivers/mesa-hostmot2/hostmot2.h"; -pin out s32 rxbytes "Number of Bytes received or negative Error code"; +pin out si32 rxbytes "Number of Bytes received or negative Error code"; variable char *name; // PktUART name @@ -71,7 +71,7 @@ function receive; /* This uses the RTAPI_MP_ARRAY_STRING macro to load the list of PktUART channels into an array. This is copied into the *name string of each */ -char *pktuart_chans[4] = {0,}; +char *pktuart_chans[4] = {}; RTAPI_MP_ARRAY_STRING(pktuart_chans, 2, "PktUART Channel names"); static hostmot2_t* hm2=NULL; @@ -88,8 +88,8 @@ FUNCTION(receive){ #undef NUM_FRAMES rtapi_u16 frame_sizes3[20]; - rxbytes=hm2_pktuart_read(name, Replyd3, &num_frames, &max_frame_length, frame_sizes3); - rtapi_print_msg(RTAPI_MSG_INFO, "PktUART receive: got %d bytes, %d frames\n", rxbytes, num_frames); + rxbytes_set(hm2_pktuart_read(name, Replyd3, &num_frames, &max_frame_length, frame_sizes3)); + rtapi_print_msg(RTAPI_MSG_INFO, "PktUART receive: got %d bytes, %d frames\n", (int)rxbytes, num_frames); //Print out the actual frame sizes int i; diff --git a/src/hal/components/message.comp b/src/hal/components/message.comp index 54e46736be5..6a6579778ce 100644 --- a/src/hal/components/message.comp +++ b/src/hal/components/message.comp @@ -60,11 +60,11 @@ net no-inverter classicladder.0.out-23 inverterfail.trigger When any pin goes active, the corresponding message will be displayed."""; -pin in bit trigger =FALSE "signal that triggers the message"; -pin in bit force =FALSE """A FALSE->TRUE transition forces the message to be +pin in bool trigger =FALSE "signal that triggers the message"; +pin in bool force =FALSE """A FALSE->TRUE transition forces the message to be displayed again if the trigger is active"""; -param rw bit edge =TRUE """Selects the desired edge: FALSE means falling, TRUE +param rw bool edge =TRUE """Selects the desired edge: FALSE means falling, TRUE means rising"""; modparam dummy messages """The messages to display. These should be listed, @@ -75,9 +75,9 @@ ignored. If there are fewer messages than "count" or "names" then an error will be raised and the component will not load."""; variable int myidx; -variable hal_bit_t prev_trigger = FALSE; -variable hal_bit_t prev_force = TRUE; -variable hal_bit_t prev_edge = TRUE; +variable bool prev_trigger = FALSE; +variable bool prev_force = TRUE; +variable bool prev_edge = TRUE; option extra_setup yes; @@ -87,11 +87,11 @@ license "GPL v2"; author "Les Newell"; ;; -char *messages[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; +char *messages[16] = {}; RTAPI_MP_ARRAY_STRING(messages, 16, "Displayed strings"); FUNCTION(_){ - hal_bit_t show = false; + rtapi_bool show = false; if(!!prev_edge != !!edge) /* edge type has changed */ { prev_edge = edge; @@ -113,7 +113,7 @@ FUNCTION(_){ show = true; } } - if(show && (messages[myidx] != 0)) + if(show && (messages[myidx] != NULL)) { rtapi_print_msg(RTAPI_MSG_ERR, "%s\n", messages[myidx]); } @@ -127,7 +127,7 @@ EXTRA_SETUP(){ rtapi_print_msg(RTAPI_MSG_ERR,"Count of names= is outside the allowable range 0..15\n"); return -EINVAL; } - if(messages[myidx] == 0) + if(messages[myidx] == NULL) { rtapi_print_msg(RTAPI_MSG_ERR,"Message string for index %d missing\n", myidx); return -EINVAL; diff --git a/src/hal/components/millturn.comp b/src/hal/components/millturn.comp index 2a9ae56df59..1350d219c61 100644 --- a/src/hal/components/millturn.comp +++ b/src/hal/components/millturn.comp @@ -28,7 +28,7 @@ chapter (docs/src/motion/switchkins.txt) """; // The fpin pin is not accessible in kinematics functions. // Use the *_setup() function for pins and params used by kinematics. -pin out s32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; +pin out si32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; option period no; function fdemo; license "GPL"; @@ -40,15 +40,15 @@ author "David Mueller"; static struct haldata { // Example pin pointers: - hal_u32_t *in; - hal_u32_t *out; + hal_uint_t in; + hal_uint_t out; // Example parameters: - hal_float_t param_rw; - hal_float_t param_ro; + //hal_real_t param_rw; + //hal_real_t param_ro; //Declare hal pin pointers used for switchable kinematics - hal_bit_t *kinstype_is_0; - hal_bit_t *kinstype_is_1; + hal_bool_t kinstype_is_0; + hal_bool_t kinstype_is_1; } *haldata; FUNCTION(fdemo) { @@ -57,7 +57,7 @@ FUNCTION(fdemo) { if (fpin == 0) { rtapi_print("fdemo function added to thread\n"); } - fpin++; + fpin_set(fpin + 1); } static int millturn_setup(void) { @@ -69,23 +69,21 @@ static int millturn_setup(void) { // set unready to allow creation of pins if (hal_set_unready(comp_id)) goto error; - haldata = hal_malloc(sizeof(struct haldata)); + haldata = hal_malloc(sizeof(*haldata)); if (!haldata) goto error; // hal pin examples: - res += hal_pin_u32_newf(HAL_IN ,&(haldata->in) ,comp_id,"%s.in" ,HAL_PREFIX); - res += hal_pin_u32_newf(HAL_OUT,&(haldata->out),comp_id,"%s.out",HAL_PREFIX); + res += hal_pin_new_ui32(comp_id, HAL_IN, &haldata->in, 0, "%s.in", HAL_PREFIX); + res += hal_pin_new_ui32(comp_id, HAL_OUT, &haldata->out, 0, "%s.out", HAL_PREFIX); // hal parameter examples: - res += hal_param_float_newf(HAL_RW, &haldata->param_rw,comp_id,"%s.param-rw",HAL_PREFIX); - res += hal_param_float_newf(HAL_RO, &haldata->param_ro,comp_id,"%s.param-ro",HAL_PREFIX); + //res += hal_param_new_real(comp_id, HAL_RW, &haldata->param_rw, 0.0, "%s.param-rw", HAL_PREFIX); + //res += hal_param_new_real(comp_id, HAL_RO, &haldata->param_ro, 0.0, "%s.param-ro", HAL_PREFIX); // hal pins required for switchable kinematics: - res += hal_pin_bit_new("kinstype.is-0", HAL_OUT, &(haldata->kinstype_is_0), comp_id); - res += hal_pin_bit_new("kinstype.is-1", HAL_OUT, &(haldata->kinstype_is_1), comp_id); - - // define default kinematics at startup for switchable kinematics - *haldata->kinstype_is_0 = 1; //default at startup -> mill configuration - *haldata->kinstype_is_1 = 0; //-> turn configuration + //default at startup -> mill configuration + //-> turn configuration + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_0, 1, "kinstype.is-0"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_1, 0, "kinstype.is-1"); if (res) goto error; hal_ready(comp_id); @@ -103,7 +101,7 @@ EXPORT_SYMBOL(kinematicsSwitch); EXPORT_SYMBOL(kinematicsInverse); EXPORT_SYMBOL(kinematicsForward); -static hal_u32_t switchkins_type; +static rtapi_u32 switchkins_type; int kinematicsSwitchable() {return 1;} @@ -115,19 +113,19 @@ int kinematicsSwitch(int new_switchkins_type) switch (switchkins_type) { case 0: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE0\n"); - *haldata->kinstype_is_0 = 1; - *haldata->kinstype_is_1 = 0; + hal_set_bool(haldata->kinstype_is_0, 1); + hal_set_bool(haldata->kinstype_is_1, 0); break; case 1: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 1; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 1); break; default: rtapi_print_msg(RTAPI_MSG_ERR, "kinematicsSwitch:BAD VALUE <%d>\n", switchkins_type); - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_0 = 0; + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_0, 0); return -1; // FAIL } return 0; // ok @@ -175,7 +173,7 @@ int kinematicsForward(const double *j, pos->v = 0; pos->w = 0; - if (*haldata->in && !is_ready && !gave_msg) { + if (hal_get_ui32(haldata->in) && !is_ready && !gave_msg) { rtapi_print_msg(RTAPI_MSG_ERR, "%s the 'in' pin not echoed until Inverse called\n", __FILE__); @@ -213,8 +211,8 @@ int kinematicsInverse(const EmcPose * pos, } //example hal pin update (homing reqd before kinematicsInverse) - *haldata->out = *haldata->in; //dereference - //read from param example: *haldata->out = haldata->param_rw; + hal_set_ui32(haldata->out, hal_get_ui32(haldata->in)); //dereference + //read from param example: *haldata->out = hal_get_real(haldata->param_rw); return 0; } // kinematicsInverse() diff --git a/src/hal/components/minmax.comp b/src/hal/components/minmax.comp index 51e74b6c454..8af3ad72665 100644 --- a/src/hal/components/minmax.comp +++ b/src/hal/components/minmax.comp @@ -1,17 +1,17 @@ component minmax "Track the minimum and maximum values of the input to the outputs"; -pin in float in; -pin in bit reset "When reset is asserted, 'in' is copied to the outputs"; -pin out float max_; -pin out float min_; +pin in real in; +pin in bool reset "When reset is asserted, 'in' is copied to the outputs"; +pin out real max_; +pin out real min_; option period no; function _; license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - if(reset) { max_ = min_ = in; } + if(reset) { max__set(min__set(in)); } else { - if(in > max_) max_ = in; - if(in < min_) min_ = in; + if(in > max_) max__set(in); + if(in < min_) min__set(in); } } diff --git a/src/hal/components/mkconv.sh b/src/hal/components/mkconv.sh index fae52e76f1d..3d5bf666ba9 100644 --- a/src/hal/components/mkconv.sh +++ b/src/hal/components/mkconv.sh @@ -14,7 +14,7 @@ utype() { "u32") echo "rtapi_u32" ;; "s64") echo "rtapi_s64" ;; "u64") echo "rtapi_u64" ;; - "float") echo "real_t" ;; + "float") echo "rtapi_real" ;; *) echo "This_Will_Generate_An_Error" ;; esac } @@ -45,6 +45,18 @@ minval() { esac } +# New HAL types +_newtype() { + case "$1" in + "bit") echo "bool" ;; + "s32") echo "si32" ;; + "u32") echo "ui32" ;; + "s64") echo "sint" ;; + "u64") echo "uint" ;; + "float") echo "real" ;; + *) echo "This_Will_Generate_An_Error" ;; + esac +} # # Conversions # xxx = unsupported conversion @@ -95,11 +107,13 @@ if test "$2" = 'float' -o \ \( "$1" = 's32' -a "$2" = 's64' \) then CC="s,@CC@,//,g"; else CC="s,@CC@,,g"; fi -IN="s,@IN@,$1,g" -OUT="s,@OUT@,$2,g" +XIN="s,@XIN@,${1},g" +XOUT="s,@XOUT@,${2},g" +IN="s,@IN@,$(_newtype "$1"),g" +OUT="s,@OUT@,$(_newtype "$2"),g" MIN="s,@MIN@,$(minval "$2"),g" MAX="s,@MAX@,$(maxval "$2"),g" TYPI="s,@TYPI@,$(utype "$1"),g" TYPO="s,@TYPO@,$(utype "$2"),g" -exec sed -e "$IN; $OUT; $CC; $MIN; $MAX; $TYPI; $TYPO; $MINEN; $MAXEN;" +exec sed -e "$IN; $OUT; $CC; $MIN; $MAX; $TYPI; $TYPO; $MINEN; $MAXEN; $XIN; $XOUT;" diff --git a/src/hal/components/modmath.c b/src/hal/components/modmath.c index 05cf46f699e..aeb089e49ad 100644 --- a/src/hal/components/modmath.c +++ b/src/hal/components/modmath.c @@ -51,14 +51,14 @@ RTAPI_MP_INT(mod_dir, "Modulo direction blocks"); /** These structures contain the runtime data for a single block. */ typedef struct { - hal_bit_t *up; /* output pin: go up to get to the desired position */ - hal_bit_t *down; /* output pin: go down to get to the desired position */ - hal_bit_t *on_target; /* output pin: go at desired position */ - hal_s32_t *actual; /* input pin: actual position */ - hal_s32_t *desired; /* input pin: desired position */ - hal_s32_t *max_num; /* input/output pin: highest value to allow */ - hal_s32_t *min_num; /* input/output pin: lowest value to allow */ - hal_bit_t *wrap; /* input/output pin: set true if the array is circular, false if linear */ + hal_bool_t up; /* output pin: go up to get to the desired position */ + hal_bool_t down; /* output pin: go down to get to the desired position */ + hal_bool_t on_target; /* output pin: go at desired position */ + hal_sint_t actual; /* input pin: actual position */ + hal_sint_t desired; /* input pin: desired position */ + hal_sint_t max_num; /* input/output pin: highest value to allow */ + hal_sint_t min_num; /* input/output pin: lowest value to allow */ + hal_bool_t wrap; /* input/output pin: set true if the array is circular, false if linear */ } mod_dir_t; /* other globals */ @@ -116,43 +116,43 @@ void rtapi_app_exit(void) static void mod_dir_funct(void *arg, long period) { (void)period; - mod_dir_t *mod; - int range, act, des, to_go; - - /* point to block data */ - mod = (mod_dir_t *) arg; - range = *(mod->max_num) - *(mod->min_num) + 1; - act = *(mod->actual); - if (act > *(mod->max_num) || act < *(mod->min_num)) { - act = *(mod->min_num) + ((act-*(mod->min_num)) % (range)); + mod_dir_t *mod = (mod_dir_t *)arg; /* point to block data */ + + rtapi_s32 min_num = hal_get_si32(mod->min_num); + rtapi_s32 max_num = hal_get_si32(mod->max_num); + + rtapi_s32 range = max_num - min_num + 1; + rtapi_s32 act = hal_get_si32(mod->actual); + if (act > max_num || act < min_num) { + act = min_num + ((act-min_num) % (range)); } - des = *(mod->desired); - if (des > *(mod->max_num) || des < *(mod->min_num)) { - des = *(mod->min_num) + ((des-*(mod->min_num)) % (range)); + rtapi_s32 des = hal_get_si32(mod->desired); + if (des > max_num || des < min_num) { + des = min_num + ((des-min_num) % (range)); } - to_go = des-act; + rtapi_s32 to_go = des-act; - if ((*(mod->wrap)) && (to_go > range/2)) { - to_go -= range; + if ((hal_get_bool(mod->wrap)) && (to_go > range/2)) { + to_go -= range; } - if ((*(mod->wrap)) && (to_go < -range/2)) { - to_go += range; + if ((hal_get_bool(mod->wrap)) && (to_go < -range/2)) { + to_go += range; } /* if (desired-actual) >= (actual+(max-min+1)-desired), output "up" */ if (to_go == 0) { - *(mod->up) = 0; - *(mod->down) = 0; - *(mod->on_target) = 1; + hal_set_bool(mod->up, 0); + hal_set_bool(mod->down, 0); + hal_set_bool(mod->on_target, 1); } else if (to_go > 0 ) { - *(mod->down) = 0; - *(mod->on_target) = 0; - *(mod->up) = 1; + hal_set_bool(mod->down, 0); + hal_set_bool(mod->on_target, 0); + hal_set_bool(mod->up, 1); } else { - *(mod->up) = 0; - *(mod->on_target) = 0; - *(mod->down) = 1; + hal_set_bool(mod->up, 0); + hal_set_bool(mod->on_target, 0); + hal_set_bool(mod->down, 1); } } @@ -160,96 +160,46 @@ static void mod_dir_funct(void *arg, long period) * LOCAL FUNCTION DEFINITIONS * ************************************************************************/ +#define CHK(v,ps) do { \ + int _rv = (v); \ + if(0 != _rv) { \ + rtapi_print_msg(RTAPI_MSG_ERR, "MODMATH: ERROR: '%s.%s' pin export failed\n", base, (ps)); \ + return _rv; \ + } \ + } while(0) + static int export_mod_dir(int num) { int retval; - char buf[HAL_NAME_LEN + 1]; + char base[HAL_NAME_LEN + 1]; mod_dir_t *moddir; /* allocate shared memory for modulo "closest direction finder" */ moddir = hal_malloc(sizeof(mod_dir_t)); if (moddir == 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: hal_malloc() failed\n"); - return -1; + rtapi_print_msg(RTAPI_MSG_ERR, "MODMATH: ERROR: hal_malloc() failed\n"); + return -1; } /* export output pins */ - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.up", num); - retval = hal_pin_bit_new(buf, HAL_OUT, &(moddir->up), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.down", num); - retval = hal_pin_bit_new(buf, HAL_OUT, &(moddir->down), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.on-target", num); - retval = hal_pin_bit_new(buf, HAL_OUT, &(moddir->on_target), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } + rtapi_snprintf(base, sizeof(base), "mod-dir.%d", num); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(moddir->up), 0, "%s.up", base), "up"); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(moddir->down), 0, "%s.down", base), "down"); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(moddir->on_target), 1, "%s.on-target", base), "on-target"); /* export input pins */ - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.actual", num); - retval = hal_pin_s32_new(buf, HAL_IN, &(moddir->actual), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.desired", num); - retval = hal_pin_s32_new(buf, HAL_IN, &(moddir->desired), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } + CHK(hal_pin_new_si32(comp_id, HAL_IN, &(moddir->actual), 0, "%s.actual", base), "actual"); + CHK(hal_pin_new_si32(comp_id, HAL_IN, &(moddir->desired), 0, "%s.desired", base), "desired"); /* export pins for max and min values */ - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.min-num", num); - retval = hal_pin_s32_new(buf, HAL_IO, &(moddir->min_num), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.max-num", num); - retval = hal_pin_s32_new(buf, HAL_IO, &(moddir->max_num), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d.wrap", num); - retval = hal_pin_bit_new(buf, HAL_IO, &(moddir->wrap), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' param export failed\n", buf); - return retval; - } + CHK(hal_pin_new_si32(comp_id, HAL_IO, &(moddir->min_num), 0, "%s.min-num", base), "min-num"); + CHK(hal_pin_new_si32(comp_id, HAL_IO, &(moddir->max_num), 15, "%s.max-num", base), "max-num"); + CHK(hal_pin_new_bool(comp_id, HAL_IO, &(moddir->wrap), 1, "%s.wrap", base), "wrap"); + /* export function */ - rtapi_snprintf(buf, sizeof(buf), "mod-dir.%d", num); - retval = hal_export_funct(buf, mod_dir_funct, moddir, 1, 0, comp_id); + retval = hal_export_funct(base, mod_dir_funct, moddir, 1, 0, comp_id); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "MODMATH: ERROR: '%s' funct export failed\n", buf); - return -1; + rtapi_print_msg(RTAPI_MSG_ERR, "MODMATH: ERROR: '%s' funct export failed\n", base); + return -1; } - /* set default parameter values */ - *(moddir->up) = 0; - *(moddir->down) = 0; - *(moddir->on_target) = 1; - *(moddir->min_num) = 0; - *(moddir->max_num) = 15; - *(moddir->actual) = 0; - *(moddir->desired) = 0; - *(moddir->wrap) = 1; /* wrap by default */ return 0; } diff --git a/src/hal/components/moveoff.comp b/src/hal/components/moveoff.comp index b67bace996a..3f6962d3a1f 100644 --- a/src/hal/components/moveoff.comp +++ b/src/hal/components/moveoff.comp @@ -93,39 +93,39 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -pin in bit power_on "Connect to motion.motion-enabled"; -pin in bit move_enable "Enable offsets (Enabling requires apply-offset TRUE also)"; -pin in bit apply_offsets "Enable offsets (Enabling requires move-enable TRUE also)"; -pin in bit backtrack-enable = 1 "Enable backtrack on auto-return"; - -pin in float epsilon=0.0005 "When enabling pins are deactivated, return to un-offsetted position within epsilon units. Warning: values that are too small in value may cause overshoot. A minimum value of 0.0001 is *silently enforced*."; -pin in float waypoint-threshold = 0.02 "Minimum distance (in a single axis) for a new waypoint"; -pin in float waypoint-sample-secs = 0.02 "Minimum sample interval (in seconds) for a new waypoint"; - -pin out bit warning "Set TRUE if apply-offsets is deasserted while offset-applied is TRUE."; -pin out bit offset_applied "TRUE if one or more offsets are applied."; -pin out bit waypoint-limit = 0 "Indicates waypoint limit reached (motion ceases), an enabling pin must be deasserted to initiate return to original position."; -pin out s32 waypoint-ct "Waypoint count (for debugging)"; -pin out s32 waypoint-percent-used "Percent of available waypoints used"; - -pin in float offset-in-#[9 : personality] "Joint offset input value"; -pin in float pos-#[9 : personality] "Joint position (typ: axis.0.motor-pos-cmd)"; -pin in float fb-#[9 : personality] "Joint feedback (typ from encoder and input to pid controller (pid.feedback))"; - -pin out float offset-current-#[9 : personality]"Joint offset current value"; -pin out float pos-plusoffset-#[9 : personality] "Computed joint position plus offset (typically connect to pid command input)"; -pin out float fb-minusoffset-#[9 : personality] "Computed Joint feedback minus offset (typically connected to axis.0.motor-pos-fb)"; - -pin in float offset-vel-#[9 : personality]=10 "Joint offset velocity limit"; -pin in float offset-accel-#[9 : personality]=100 "Joint offset acceleration limit"; -pin in float offset-min-#[9 : personality] = -1e20 "Minimum limit for applied joint offset (typ negative)"; -pin in float offset-max-#[9 : personality] = 1e20 "Maximum limit for applied offset (typ positive)"; +pin in bool power_on "Connect to motion.motion-enabled"; +pin in bool move_enable "Enable offsets (Enabling requires apply-offset TRUE also)"; +pin in bool apply_offsets "Enable offsets (Enabling requires move-enable TRUE also)"; +pin in bool backtrack-enable = 1 "Enable backtrack on auto-return"; + +pin in real epsilon=0.0005 "When enabling pins are deactivated, return to un-offsetted position within epsilon units. Warning: values that are too small in value may cause overshoot. A minimum value of 0.0001 is *silently enforced*."; +pin in real waypoint-threshold = 0.02 "Minimum distance (in a single axis) for a new waypoint"; +pin in real waypoint-sample-secs = 0.02 "Minimum sample interval (in seconds) for a new waypoint"; + +pin out bool warning "Set TRUE if apply-offsets is deasserted while offset-applied is TRUE."; +pin out bool offset_applied "TRUE if one or more offsets are applied."; +pin out bool waypoint-limit = 0 "Indicates waypoint limit reached (motion ceases), an enabling pin must be deasserted to initiate return to original position."; +pin out si32 waypoint-ct "Waypoint count (for debugging)"; +pin out si32 waypoint-percent-used "Percent of available waypoints used"; + +pin in real offset-in-#[9 : personality] "Joint offset input value"; +pin in real pos-#[9 : personality] "Joint position (typ: axis.0.motor-pos-cmd)"; +pin in real fb-#[9 : personality] "Joint feedback (typ from encoder and input to pid controller (pid.feedback))"; + +pin out real offset-current-#[9 : personality]"Joint offset current value"; +pin out real pos-plusoffset-#[9 : personality] "Computed joint position plus offset (typically connect to pid command input)"; +pin out real fb-minusoffset-#[9 : personality] "Computed Joint feedback minus offset (typically connected to axis.0.motor-pos-fb)"; + +pin in real offset-vel-#[9 : personality]=10 "Joint offset velocity limit"; +pin in real offset-accel-#[9 : personality]=100 "Joint offset acceleration limit"; +pin in real offset-min-#[9 : personality] = -1e20 "Minimum limit for applied joint offset (typ negative)"; +pin in real offset-max-#[9 : personality] = 1e20 "Maximum limit for applied offset (typ positive)"; // inputs for debugging: -pin in bit dbg_waypoint_limit_test "Debug input to test with limited number of waypoints"; +pin in bool dbg_waypoint_limit_test "Debug input to test with limited number of waypoints"; // outputs for debugging: -pin out s32 dbg_state "Debug output for current state of state machine"; +pin out si32 dbg_state "Debug output for current state of state machine"; option personality; option extra_setup; @@ -150,21 +150,21 @@ typedef enum { typedef struct { int state[NCHANNELS]; - hal_float_t old_in[NCHANNELS]; - hal_float_t old_out[NCHANNELS]; - hal_float_t old_v[NCHANNELS]; - hal_float_t old_limited_in[NCHANNELS]; + rtapi_real old_in[NCHANNELS]; + rtapi_real old_out[NCHANNELS]; + rtapi_real old_v[NCHANNELS]; + rtapi_real old_limited_in[NCHANNELS]; } old_values_t; struct lim3_input { - hal_float_t minlimit; - hal_float_t maxlimit; - hal_float_t maxvlimit; - hal_float_t maxalimit; - hal_float_t in; - hal_float_t old_in; - hal_float_t old_out; - hal_float_t old_v; + rtapi_real minlimit; + rtapi_real maxlimit; + rtapi_real maxvlimit; + rtapi_real maxalimit; + rtapi_real in; + rtapi_real old_in; + rtapi_real old_out; + rtapi_real old_v; }; static void reset_old(int nchan, old_values_t* d) { @@ -177,7 +177,7 @@ static void reset_old(int nchan, old_values_t* d) { } } -static int offset_removed(int nchan, old_values_t d, hal_float_t eps) { +static int offset_removed(int nchan, old_values_t d, rtapi_real eps) { int removed = 1; int i; for (i = 0 ; i < nchan ; i++) { @@ -190,8 +190,8 @@ static int offset_removed(int nchan, old_values_t d, hal_float_t eps) { } static int at_waypoint(int nchan, - hal_float_t g[], - hal_float_t p[],hal_float_t eps) { + rtapi_real g[], + rtapi_real p[], rtapi_real eps) { int within_eps = 1; int i; @@ -206,17 +206,17 @@ static int at_waypoint(int nchan, static long theperiod; static void lim3(struct lim3_input input, - hal_float_t* old_in, - hal_float_t* limited_out, - hal_float_t* old_v + rtapi_real* old_in, + rtapi_real* limited_out, + rtapi_real* old_v ) { /* following code is adapted from limit3.comp */ - hal_float_t dt = theperiod * 1e-9; - hal_float_t in_v, min_v, max_v, avg_v; - hal_float_t min_out,max_out; - hal_float_t ramp_a, match_time, est_in, est_out; - hal_float_t err, dv, dp; - hal_float_t limited_in; + rtapi_real dt = theperiod * 1e-9; + rtapi_real in_v, min_v, max_v, avg_v; + rtapi_real min_out,max_out; + rtapi_real ramp_a, match_time, est_in, est_out; + rtapi_real err, dv, dp; + rtapi_real limited_in; /* apply first order limit */ limited_in = input.in; @@ -289,18 +289,18 @@ static the_state state = IDLE; static int next_waypoint_index; static rtapi_s64 last_waypoint_time; static rtapi_s64 now; -static hal_float_t time_since_last_sample; -static hal_float_t move_threshold; -static hal_float_t min_sample_interval; +static rtapi_real time_since_last_sample; +static rtapi_real move_threshold; +static rtapi_real min_sample_interval; static bool backtrack; static bool gave_msg; static int max_waypoints = NWAYPOINTS; static struct lim3_input input; -static hal_float_t goal[NCHANNELS]; -static hal_float_t waypoints[NCHANNELS][NWAYPOINTS]; +static rtapi_real goal[NCHANNELS]; +static rtapi_real waypoints[NCHANNELS][NWAYPOINTS]; static old_values_t data; -static hal_float_t eps_in_use; +static rtapi_real eps_in_use; static bool move_in_progress = 0; static the_state next_state; @@ -313,7 +313,7 @@ static const bool allow_backtrack_enable_change = 1; // (e.g., unlimited no. of offset samples) FUNCTION(read_inputs) { - hal_float_t last,delta; + rtapi_real last,delta; int r; bool all_enables = power_on && move_enable && apply_offsets; @@ -344,7 +344,7 @@ FUNCTION(read_inputs) { int r; bool sufficient_movement_for_new_waypoint = 0; - time_since_last_sample = (hal_float_t)(now - last_waypoint_time)/1e9; + time_since_last_sample = (rtapi_real)(now - last_waypoint_time)/1e9; switch (state) { case IDLE: next_waypoint_index = 0; @@ -369,9 +369,9 @@ FUNCTION(read_inputs) { last_waypoint_time = now; next_waypoint_index++; if (next_waypoint_index > max_waypoints - 1) { - waypoint_limit = 1; + waypoint_limit_set(1); } else { - waypoint_limit = 0; + waypoint_limit_set(0); } break; case MOVE_BACK: break; @@ -404,7 +404,7 @@ FUNCTION(read_inputs) { if (!power_on) { reset_old(personality, &data); move_in_progress = 0; - offset_applied = 0; + offset_applied_set(0); next_state = IDLE; break; } @@ -416,7 +416,7 @@ FUNCTION(read_inputs) { for (r = 0; r < personality; r++) { goal[r] = waypoints[r][next_waypoint_index-1]; } - waypoint_limit = 0; + waypoint_limit_set(0); next_waypoint_index--; } } @@ -426,14 +426,14 @@ FUNCTION(read_inputs) { if (!power_on) { reset_old(personality, &data); move_in_progress = 0; - offset_applied = 0; + offset_applied_set(0); next_state = IDLE; break; } move_in_progress = 1; if (backtrack) { if ( next_waypoint_index > 0 ) { - hal_float_t pcur[NCHANNELS]; + rtapi_real pcur[NCHANNELS]; for (r=0; r < personality; r++) { pcur[r] = offset_current(r); } @@ -462,7 +462,7 @@ FUNCTION(read_inputs) { if ( !apply_offsets && offset_applied ) { - warning = 1; + warning_set(1); if (!gave_msg) { // apply_offsets deasserted while offset_applied // for example: @@ -482,7 +482,7 @@ FUNCTION(read_inputs) { } } else { gave_msg = 0; - warning = 0; + warning_set(0); } //}end state control } //read_inputs @@ -505,35 +505,35 @@ FUNCTION(write_outputs) { if ( waypoint_limit && (state == MOVE_AWAY) ) { // no movement in MOVE_AWAY (require: remove enable) } else { - hal_float_t last_old = data.old_out[r]; + rtapi_real last_old = data.old_out[r]; lim3(input, &data.old_in[r], &data.old_out[r], &data.old_v[r] ); - offset_current(r) = data.old_out[r]; - fb_minusoffset(r) = fb(r) - offset_current(r) - - (last_old - data.old_out[r]); - pos_plusoffset(r) = pos(r) + offset_current(r); + offset_current_set(r, data.old_out[r]); + fb_minusoffset_set(r, fb(r) - offset_current(r) + - (last_old - data.old_out[r])); + pos_plusoffset_set(r, pos(r) + offset_current(r)); } } else { - pos_plusoffset(r) = pos(r); - offset_current(r) = 0; - fb_minusoffset(r) = fb(r); + pos_plusoffset_set(r, pos(r)); + offset_current_set(r, 0); + fb_minusoffset_set(r, fb(r)); } } - offset_applied = ! offset_removed(personality, data, eps_in_use); + offset_applied_set(! offset_removed(personality, data, eps_in_use)); if ( !offset_applied ) { // reset backtrack next_waypoint_index = 0; - waypoint_limit = 0; + waypoint_limit_set(0); } - waypoint_ct = next_waypoint_index; - waypoint_percent_used = 100*next_waypoint_index/max_waypoints; + waypoint_ct_set(next_waypoint_index); + waypoint_percent_used_set(100*next_waypoint_index/max_waypoints); - dbg_state = state; + dbg_state_set(state); state = next_state; } //write_outputs diff --git a/src/hal/components/mult2.comp b/src/hal/components/mult2.comp index bc386c1f2c5..248a4ac48f5 100644 --- a/src/hal/components/mult2.comp +++ b/src/hal/components/mult2.comp @@ -1,7 +1,7 @@ component mult2 "Product of two inputs"; -pin in float in0; -pin in float in1; -pin out float out "out = in0 * in1"; +pin in real in0; +pin in real in1; +pin out real out "out = in0 * in1"; option period no; function _; license "GPL"; @@ -10,5 +10,5 @@ see_also " invert(9), div2(9) "; ;; FUNCTION(_) { - out = in0 * in1; + out_set(in0 * in1); } diff --git a/src/hal/components/multiclick.comp b/src/hal/components/multiclick.comp index 003052046d0..f4de1ab293e 100644 --- a/src/hal/components/multiclick.comp +++ b/src/hal/components/multiclick.comp @@ -24,54 +24,54 @@ component multiclick "Single-, double-, triple-, and quadruple-click detector"; license "GPL"; author "Sebastian Kuzminsky"; -pin in bit in "The input line, this is where we look for clicks."; +pin in bool in "The input line, this is where we look for clicks."; -pin out bit single_click +pin out bool single_click "Goes high briefly when a single-click is detected on the 'in' pin."; -pin out bit single_click_only +pin out bool single_click_only """Goes high briefly when a single-click is detected on the 'in' pin and no second click followed it."""; -pin out bit double_click +pin out bool double_click "Goes high briefly when a double-click is detected on the 'in' pin."; -pin out bit double_click_only +pin out bool double_click_only """Goes high briefly when a double-click is detected on the 'in' pin and no third click followed it."""; -pin out bit triple_click +pin out bool triple_click "Goes high briefly when a triple-click is detected on the 'in' pin."; -pin out bit triple_click_only +pin out bool triple_click_only """Goes high briefly when a triple-click is detected on the 'in' pin and no fourth click followed it."""; -pin out bit quadruple_click +pin out bool quadruple_click "Goes high briefly when a quadruple-click is detected on the 'in' pin."; -pin out bit quadruple_click_only +pin out bool quadruple_click_only """Goes high briefly when a quadruple-click is detected on the 'in' pin and no fifth click followed it."""; // for debugging -pin out s32 state; +pin out si32 state; -param rw bit invert_input = FALSE +param rw bool invert_input = FALSE """If FALSE (the default), clicks start with rising edges. If TRUE, clicks start with falling edges."""; -param rw u32 max_hold_ns = 250000000 +param rw ui32 max_hold_ns = 250000000 """If the input is held down longer than this, it's not part of a multi-click. (Default 250,000,000 ns, 250 ms.)"""; -param rw u32 max_space_ns = 250000000 +param rw ui32 max_space_ns = 250000000 """If the input is released longer than this, it's not part of a multi-click. (Default 250,000,000 ns, 250 ms.)"""; -param rw u32 output_hold_ns = 100000000 +param rw ui32 output_hold_ns = 100000000 """Positive pulses on the output pins last this long. (Default 100,000,000 ns, 100 ms.)"""; @@ -176,7 +176,7 @@ FUNCTION(_) { single_click_hold_timer -= period; } else { single_click_hold_timer = 0; - single_click = 0; + single_click_set(0); } } @@ -185,7 +185,7 @@ FUNCTION(_) { single_click_only_hold_timer -= period; } else { single_click_only_hold_timer = 0; - single_click_only = 0; + single_click_only_set(0); } } @@ -194,7 +194,7 @@ FUNCTION(_) { double_click_hold_timer -= period; } else { double_click_hold_timer = 0; - double_click = 0; + double_click_set(0); } } @@ -203,7 +203,7 @@ FUNCTION(_) { double_click_only_hold_timer -= period; } else { double_click_only_hold_timer = 0; - double_click_only = 0; + double_click_only_set(0); } } @@ -212,7 +212,7 @@ FUNCTION(_) { triple_click_hold_timer -= period; } else { triple_click_hold_timer = 0; - triple_click = 0; + triple_click_set(0); } } @@ -221,7 +221,7 @@ FUNCTION(_) { triple_click_only_hold_timer -= period; } else { triple_click_only_hold_timer = 0; - triple_click_only = 0; + triple_click_only_set(0); } } @@ -230,7 +230,7 @@ FUNCTION(_) { quadruple_click_hold_timer -= period; } else { quadruple_click_hold_timer = 0; - quadruple_click = 0; + quadruple_click_set(0); } } @@ -239,7 +239,7 @@ FUNCTION(_) { quadruple_click_only_hold_timer -= period; } else { quadruple_click_only_hold_timer = 0; - quadruple_click_only = 0; + quadruple_click_only_set(0); } } @@ -263,7 +263,7 @@ FUNCTION(_) { click_state = SAW_FIRST_CLICK; timer = 0; timeout = max_space_ns; - single_click = 1; + single_click_set(1); single_click_hold_timer = output_hold_ns; } break; @@ -283,7 +283,7 @@ FUNCTION(_) { click_state = SAW_SECOND_CLICK; timer = 0; timeout = max_space_ns; - double_click = 1; + double_click_set(1); double_click_hold_timer = output_hold_ns; } break; @@ -303,7 +303,7 @@ FUNCTION(_) { click_state = SAW_THIRD_CLICK; timer = 0; timeout = max_space_ns; - triple_click = 1; + triple_click_set(1); triple_click_hold_timer = output_hold_ns; } break; @@ -325,7 +325,7 @@ FUNCTION(_) { click_state = SAW_FOURTH_CLICK; timer = 0; timeout = max_space_ns; - quadruple_click = 1; + quadruple_click_set(1); quadruple_click_hold_timer = output_hold_ns; } break; @@ -359,22 +359,22 @@ FUNCTION(_) { // of the "only" outputs if appropriate switch (click_state) { case SAW_FIRST_CLICK: { - single_click_only = 1; + single_click_only_set(1); single_click_only_hold_timer = output_hold_ns; break; } case SAW_SECOND_CLICK: { - double_click_only = 1; + double_click_only_set(1); double_click_only_hold_timer = output_hold_ns; break; } case SAW_THIRD_CLICK: { - triple_click_only = 1; + triple_click_only_set(1); triple_click_only_hold_timer = output_hold_ns; break; } case SAW_FOURTH_CLICK: { - quadruple_click_only = 1; + quadruple_click_only_set(1); quadruple_click_only_hold_timer = output_hold_ns; break; } @@ -383,6 +383,6 @@ FUNCTION(_) { } } - state = click_state; + state_set(click_state); } diff --git a/src/hal/components/multiswitch.comp b/src/hal/components/multiswitch.comp index 4a6068635cc..f3c0b2bb1c9 100644 --- a/src/hal/components/multiswitch.comp +++ b/src/hal/components/multiswitch.comp @@ -22,13 +22,13 @@ don't connect the extra pin. component multiswitch """This component toggles between a specified number of output bits."""; -pin in bit up = false "Receives signal to toggle up"; -pin in bit down = false "Receives signal to toggle down"; +pin in bool up = false "Receives signal to toggle up"; +pin in bool down = false "Receives signal to toggle down"; -param rw unsigned top-position "Number of positions"; -param rw signed position "Current state (may be set in the HAL)"; +param rw ui32 top-position "Number of positions"; +param rw si32 position "Current state (may be set in the HAL)"; -pin out bit bit-##[32:personality] = false "Output bits"; +pin out bool bit-##[32:personality] = false "Output bits"; modparam dummy cfg """cfg should be a comma-separated list of sizes, for example cfg=2,4,6 would create 3 instances of 2, 4 and 6 bits respectively. Ignore the "personality" parameter, that is auto-generated."""; @@ -53,16 +53,16 @@ FUNCTION(_) { int i; // debounce - if (up && !old_up) { position++; } - if (down && !old_down) { position--;} + if (up && !old_up) { position_set(position + 1); } + if (down && !old_down) { position_set(position - 1);} old_up = up; old_down = down; - if (position < 0) position = top_position; - if ((unsigned)position > top_position) position = 0; + if (position < 0) position_set(top_position); + if ((unsigned)position > top_position) position_set(0); for (i = 0 ; i < personality; i++){ - bit(i) = (i == position); + bit_set(i, i == position); } } @@ -70,7 +70,7 @@ FUNCTION(_) { EXTRA_SETUP(){ (void)prefix; personality = cfg[extra_arg]; - top_position = personality - 1; + top_position_set(personality - 1); return 0; } diff --git a/src/hal/components/mux16.comp b/src/hal/components/mux16.comp index 5e22dc0a3ba..c62392dee09 100644 --- a/src/hal/components/mux16.comp +++ b/src/hal/components/mux16.comp @@ -1,24 +1,24 @@ component mux16 "Select from one of sixteen input values"; -pin in bit use_graycode"""\ +pin in bool use_graycode"""\ This signifies the input will use Gray code instead of binary. Gray code is a good choice when using physical switches because for each increment only one select input changes at a time. """; -pin in bit suppress_no_input"""\ +pin in bool suppress_no_input"""\ This suppresses changing the output if all select lines are false. This stops unwanted jumps in output between transitions of input. but make in00 unavailable. """; -pin in float debounce_time"""\ +pin in real debounce_time"""\ sets debounce time in seconds. eg. .10 = a tenth of a second input must be stable this long before outputs changes. This helps to ignore 'noisy' switches. """; -pin in bit sel#[4] """\ +pin in bool sel#[4] """\ Together, these determine which **in**__N__ value is copied to *out*. """; -pin out float out_f; -pin out s32 out_s """\ +pin out real out_f; +pin out si32 out_s """\ Follows the value of one of the **in**__N__ values according to the four *sel* values and whether use-graycode is active. The s32 value will be trunuated and limited to the max and min values of signed values. @@ -50,10 +50,10 @@ The s32 value will be trunuated and limited to the max and min values of signed |=== """; -param r float elapsed "Current value of the internal debounce timer for debugging."; -param r s32 selected "Current value of the internal selection variable after conversion for debugging"; -pin in float in##[16] "array of selectable outputs"; -variable double delaytime; +param r real elapsed "Current value of the internal debounce timer for debugging."; +param r si32 selected "Current value of the internal selection variable after conversion for debugging"; +pin in real in##[16] "array of selectable outputs"; +variable rtapi_real delaytime; variable int lastnum; variable int running; function _; @@ -78,9 +78,9 @@ FUNCTION(_) { for(i = 1; i < 4; i++){ internal[i] = internal[i] ^ internal[i - 1]; } - selected = num = internal[3]+(internal[2]*2) + (internal[1]*4) + (internal[0]*8); + selected_set(num = internal[3]+(internal[2]*2) + (internal[1]*4) + (internal[0]*8)); }else{ - selected = num = (sel(0))+(sel(1)*2) + (sel(2)*4) + (sel(3)*8); + selected_set(num = (sel(0))+(sel(1)*2) + (sel(2)*4) + (sel(3)*8)); } if(debounce_time) { if (num != lastnum) { @@ -90,17 +90,17 @@ FUNCTION(_) { } if (delaytime < debounce_time) { delaytime += fperiod; - elapsed = delaytime; + elapsed_set(delaytime); return; }else{ running = 0; lastnum = num; - out_s = out_f = in(num); + out_s_set(out_f_set(in(num))); return; } } } /* select the output */ - out_s = out_f = in(num); + out_s_set(out_f_set(in(num))); } diff --git a/src/hal/components/mux2.comp b/src/hal/components/mux2.comp index 70aeebeea5a..ec842f56e19 100644 --- a/src/hal/components/mux2.comp +++ b/src/hal/components/mux2.comp @@ -1,8 +1,8 @@ component mux2 "Select from one of two input values"; -pin in bit sel; -pin out float out "Follows the value of *in0* if *sel* is FALSE, or *in1* if *sel* is TRUE"; -pin in float in1; -pin in float in0; +pin in bool sel; +pin out real out "Follows the value of *in0* if *sel* is FALSE, or *in1* if *sel* is TRUE"; +pin in real in1; +pin in real in0; option period no; function _; license "GPL"; @@ -10,6 +10,6 @@ author "Jeff Epler"; see_also "mux4(9), mux8(9), mux16(9), mux_generic(9)."; ;; FUNCTION(_) { - if(sel) out = in1; - else out = in0; + if(sel) out_set(in1); + else out_set(in0); } diff --git a/src/hal/components/mux4.comp b/src/hal/components/mux4.comp index be5cc0b02d7..c2495dc6530 100644 --- a/src/hal/components/mux4.comp +++ b/src/hal/components/mux4.comp @@ -1,9 +1,9 @@ component mux4 "Select from one of four input values"; -pin in bit sel0; -pin in bit sel1 """\ +pin in bool sel0; +pin in bool sel1 """\ Together, these determine which **in**__N__ value is copied to *out*. """; -pin out float out """\ +pin out real out """\ Follows the value of one of the **in**__N__ values according to the two *sel* values [cols="^1,^1,1"] @@ -19,10 +19,10 @@ Follows the value of one of the **in**__N__ values according to the two *sel* va |=== """; -pin in float in0; -pin in float in1; -pin in float in2; -pin in float in3; +pin in real in0; +pin in real in1; +pin in real in2; +pin in real in3; option period no; function _; license "GPL"; @@ -31,10 +31,10 @@ see_also "mux2(9), mux8(9), mux16(9), mux_generic(9)."; ;; FUNCTION(_) { if(sel1) { - if(sel0) out = in3; - else out = in2; + if(sel0) out_set(in3); + else out_set(in2); } else { - if(sel0) out = in1; - else out = in0; + if(sel0) out_set(in1); + else out_set(in0); } } diff --git a/src/hal/components/mux8.comp b/src/hal/components/mux8.comp index f7d4cab21d8..0a7f6a6c4bd 100644 --- a/src/hal/components/mux8.comp +++ b/src/hal/components/mux8.comp @@ -1,10 +1,10 @@ component mux8 "Select from one of eight input values"; -pin in bit sel0; -pin in bit sel1; -pin in bit sel2 """\ +pin in bool sel0; +pin in bool sel1; +pin in bool sel2 """\ Together, these determine which **in**__N__ value is copied to *out*. """; -pin out float out """\ +pin out real out """\ Follows the value of one of the **in**__N__ values according to the three *sel* values [cols="^1,^1,^1,1"] @@ -25,14 +25,14 @@ Follows the value of one of the **in**__N__ values according to the three *sel* |=== """; -pin in float in0; -pin in float in1; -pin in float in2; -pin in float in3; -pin in float in4; -pin in float in5; -pin in float in6; -pin in float in7; +pin in real in0; +pin in real in1; +pin in real in2; +pin in real in3; +pin in real in4; +pin in real in5; +pin in real in6; +pin in real in7; option period no; function _; license "GPL"; @@ -42,22 +42,22 @@ see_also "mux2(9), mux4(9), mux16(9), mux_generic(9)."; FUNCTION(_) { if(sel0) { if(sel1) { - if(sel2) out = in7; - else out = in3; + if(sel2) out_set(in7); + else out_set(in3); } else { - if(sel2) out = in5; - else out = in1; + if(sel2) out_set(in5); + else out_set(in1); } } else { if(sel1) { - if(sel2) out = in6; - else out = in2; + if(sel2) out_set(in6); + else out_set(in2); } else { - if(sel2) out = in4; - else out = in0; + if(sel2) out_set(in4); + else out_set(in0); } } } diff --git a/src/hal/components/mux_generic.c b/src/hal/components/mux_generic.c index 94dbc0e4c72..8a1759e1821 100644 --- a/src/hal/components/mux_generic.c +++ b/src/hal/components/mux_generic.c @@ -19,6 +19,7 @@ #include #include +#include #include @@ -30,18 +31,16 @@ MODULE_LICENSE("GPL"); #define MAX_CHAN 100 #define MAX_SIZE 1024 #define EPS 2e-7 -#define MAX_S32 0x7FFFFFFF -#define MAX_U32 0xFFFFFFFF typedef struct { - hal_data_u **inputs; - hal_data_u *output; - hal_u32_t *sel_int; - hal_bit_t **sel_bit; - unsigned int selection; - hal_u32_t *debounce; - unsigned int timer; - hal_bit_t *suppress; + hal_refs_u *inputs; + hal_refs_u output; + hal_uint_t sel_int; + hal_bool_t *sel_bit; + hal_uint_t selection; + hal_uint_t debounce; + hal_uint_t timer; + hal_bool_t suppress; int in_type; int out_type; int size; @@ -56,7 +55,6 @@ typedef struct { static int comp_id; static mux_t *mux; static void write_fp(void *arg, long period); -static void write_nofp(void *arg, long period); char *config[MAX_CHAN]; RTAPI_MP_ARRAY_STRING(config, MAX_CHAN, "mux specifiers inNUMout"); @@ -79,7 +77,7 @@ int rtapi_app_main(void){ } // allocate shared memory for the base struct - mux = hal_malloc(sizeof(mux_t)); + mux = hal_malloc(sizeof(*mux)); if (mux == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "mux_generic component: Out of Memory\n"); @@ -89,7 +87,7 @@ int rtapi_app_main(void){ // Count the instances. for (mux->num_insts = 0; config[mux->num_insts];mux->num_insts++) {} - mux->insts = hal_malloc(mux->num_insts * sizeof(mux_inst_t)); + mux->insts = hal_malloc(mux->num_insts * sizeof(*mux->insts)); // Parse the config string for (i = 0; i < mux->num_insts; i++) { char c; @@ -168,22 +166,13 @@ int rtapi_app_main(void){ inst->out_type = inst->in_type; } - if (inst->in_type == HAL_FLOAT || inst->out_type == HAL_FLOAT) { - retval = hal_export_functf(write_fp, inst, 1, 0, comp_id, "mux-gen.%02i", i); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "mux_generic: ERROR: function export" - " failed\n"); - goto fail0; - } - } - else - { - retval = hal_export_functf(write_nofp, inst, 0, 0, comp_id, "mux-gen.%02i", i); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "mux_generic: ERROR: function export" - " failed\n"); - goto fail0; - } + // We did away with the no-fp thread. + // Always export the float case. It can do any-to-any. + retval = hal_export_functf(write_fp, inst, 1, 0, comp_id, "mux-gen.%02i", i); + if (retval < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "mux_generic: ERROR: function export" + " failed\n"); + goto fail0; } // Input pins @@ -194,9 +183,9 @@ int rtapi_app_main(void){ if (s !=1){ inst->num_bits = 0; } else { //make the bit pins - inst->sel_bit = hal_malloc(inst->num_bits * sizeof(hal_bit_t*)); + inst->sel_bit = hal_malloc(inst->num_bits * sizeof(*inst->sel_bit)); for (p = 0; p < inst->num_bits; p++) { - retval = hal_pin_bit_newf(HAL_IN, &inst->sel_bit[p], comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->sel_bit[p], 0, "mux-gen.%02i.sel-bit-%02i", i, p); if (retval != 0) { goto fail0; @@ -204,43 +193,51 @@ int rtapi_app_main(void){ } } - retval = hal_pin_u32_newf(HAL_IN, &(inst->sel_int), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &(inst->sel_int), 0, "mux-gen.%02i.sel-int", i); if (retval != 0) { goto fail0; } - inst->inputs = hal_malloc(inst->size * sizeof(hal_data_u*)); + inst->inputs = hal_malloc(inst->size * sizeof(*inst->inputs)); for (p = 0; p < inst->size; p++) { retval = rtapi_snprintf(hal_name, HAL_NAME_LEN, "mux-gen.%02i.in-%s-%02i", i, types[inst->in_type], p); if (retval >= HAL_NAME_LEN) { goto fail0; } - retval = hal_pin_new(hal_name, inst->in_type, HAL_IN, - (void**)&(inst->inputs[p]), comp_id); + switch(inst->in_type) { + case HAL_BOOL: retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->inputs[p].b, 0, "%s", hal_name); break; + case HAL_REAL: retval = hal_pin_new_real(comp_id, HAL_IN, &inst->inputs[p].r, 0, "%s", hal_name); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_IN, &inst->inputs[p].s, 0, "%s", hal_name); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_IN, &inst->inputs[p].u, 0, "%s", hal_name); break; + // FIXME: Future...when we switch types + case HAL_SINT: retval = hal_pin_new_sint(comp_id, HAL_IN, &inst->inputs[p].s, 0, "%s", hal_name); break; + case HAL_UINT: retval = hal_pin_new_uint(comp_id, HAL_IN, &inst->inputs[p].u, 0, "%s", hal_name); break; + default: retval = -ENOENT; break; + } if (retval != 0) { goto fail0; } } // Behaviour-modifiers - retval = hal_pin_bit_newf(HAL_IN, &inst->suppress, comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &inst->suppress, 0, "mux-gen.%02i.suppress-no-input", i); if (retval != 0) { goto fail0; } - retval = hal_pin_u32_newf(HAL_IN, &inst->debounce, comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IN, &inst->debounce, 0, "mux-gen.%02i.debounce-us", i); if (retval != 0) { goto fail0; } - retval = hal_param_u32_newf(HAL_RO, &inst->timer, comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RO, &inst->timer, 0, "mux-gen.%02i.elapsed", i); if (retval != 0) { goto fail0; } - retval = hal_param_u32_newf(HAL_RO, &inst->selection, comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RO, &inst->selection, 0, "mux-gen.%02i.selected", i); if (retval != 0) { goto fail0; @@ -252,8 +249,16 @@ int rtapi_app_main(void){ if (retval >= HAL_NAME_LEN) { goto fail0; } - retval = hal_pin_new(hal_name, inst->out_type, HAL_OUT, - (void**)&(inst->output), comp_id); + switch(inst->out_type) { + case HAL_BOOL: retval = hal_pin_new_bool(comp_id, HAL_OUT, &inst->output.b, 0, "%s", hal_name); break; + case HAL_REAL: retval = hal_pin_new_real(comp_id, HAL_OUT, &inst->output.r, 0, "%s", hal_name); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_OUT, &inst->output.s, 0, "%s", hal_name); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_OUT, &inst->output.u, 0, "%s", hal_name); break; + // FIXME: Future...when we switch types + case HAL_SINT: retval = hal_pin_new_sint(comp_id, HAL_OUT, &inst->output.s, 0, "%s", hal_name); break; + case HAL_UINT: retval = hal_pin_new_uint(comp_id, HAL_OUT, &inst->output.u, 0, "%s", hal_name); break; + default: retval = -ENOENT; break; + } if (retval != 0) { goto fail0; } @@ -269,124 +274,102 @@ int rtapi_app_main(void){ } +// From 'f' to 't' conversion +#define FT(f,t) ((((f) & 0x0f) << 4) + ((t) & 0x0f)) + void write_fp(void *arg, long period) { mux_inst_t *inst = arg; int i = 0; unsigned s = 0; if (inst->num_bits > 0) { while (i < inst->num_bits) { - s += (*inst->sel_bit[i] != 0) << i; + s += (hal_get_bool(inst->sel_bit[i]) != 0) << i; i++; } } // if you document it, it's not a bug, it's a feature. Might even be useful - s += *inst->sel_int; + s += hal_get_ui32(inst->sel_int); - if (*inst->suppress && s == 0) + if (hal_get_bool(inst->suppress) && s == 0) return; - if (s != inst->selection && inst->timer < *inst->debounce) { - inst->timer += period / 1000; + if (s != hal_get_ui32(inst->selection) && hal_get_ui32(inst->timer) < hal_get_ui32(inst->debounce)) { + hal_set_ui32(inst->timer, hal_get_ui32(inst->timer) + period / 1000); return; } - inst->selection = s; - inst->timer = 0; + hal_set_ui32(inst->selection, s); + hal_set_ui32(inst->timer, 0); if ((int)s >= inst->size) s = inst->size - 1; - switch (inst->in_type * 8 + inst->out_type) { - case 012: //HAL_BIT => HAL_FLOAT - inst->output->f = inst->inputs[s]->b ? 1.0 : 0.0; // - break; - case 021: //HAL_FLOAT => HAL_BIT - inst->output->b = - (inst->inputs[s]->f > EPS || inst->inputs[s]->f < -EPS) ? 1 : 0; + switch (FT(inst->in_type, inst->out_type)) { + case FT(HAL_BOOL, HAL_BOOL): //HAL_BIT => HAL_BIT + hal_set_bool(inst->output.b, hal_get_bool(inst->inputs[s].b)); break; - case 022: //HAL_FLOAT => HAL_FLOAT - inst->output->f = inst->inputs[s]->f; + case FT(HAL_BOOL, HAL_S32): //HAL_BIT => HAL_S32 + hal_set_si32(inst->output.s, hal_get_bool(inst->inputs[s].b)); break; - case 023: //HAL_FLOAT => HAL_S32 - if (inst->inputs[s]->f > MAX_S32) { - inst->output->s = MAX_S32; - } else if (inst->inputs[s]->f < -MAX_S32) { - inst->output->s = -MAX_S32; - } else { - inst->output->s = inst->inputs[s]->f; - } + case FT(HAL_BOOL, HAL_U32): //HAL_BIT => HAL_U32 + hal_set_ui32(inst->output.u, hal_get_bool(inst->inputs[s].b)); break; - case 024: //HAL_FLOAT => HAL_U32 - if (inst->inputs[s]->f > MAX_U32) { - inst->output->u = MAX_U32; - } else if (inst->inputs[s]->f < 0) { - inst->output->u = 0; - } else { - inst->output->u = inst->inputs[s]->f; - } + case FT(HAL_BOOL, HAL_REAL): //HAL_BIT => HAL_FLOAT + hal_set_real(inst->output.r, hal_get_bool(inst->inputs[s].b) ? 1.0 : 0.0); break; - case 032: //HAL_S32 => HAL_FLOAT - inst->output->f = inst->inputs[s]->s; + + case FT(HAL_REAL, HAL_BOOL): //HAL_FLOAT => HAL_BIT + hal_set_bool(inst->output.b, fabs(hal_get_real(inst->inputs[s].r)) > EPS); break; - case 042: //HAL_U32 => HAL_FLOAT - inst->output->f = (unsigned int) inst->inputs[s]->u; + case FT(HAL_REAL, HAL_REAL): //HAL_FLOAT => HAL_FLOAT + hal_set_real(inst->output.r, hal_get_real(inst->inputs[s].r)); break; - } -} - -void write_nofp(void *arg, long period) { - mux_inst_t *inst = arg; - int i = 0; - unsigned s = 0; - if (inst->num_bits > 0) { - while (i < inst->num_bits) { - s += (*inst->sel_bit[i] != 0) << i; - i++; + case FT(HAL_REAL, HAL_S32): { //HAL_FLOAT => HAL_S32 + rtapi_real v = hal_get_real(inst->inputs[s].r); + if (v > RTAPI_INT32_MAX) { + hal_set_si32(inst->output.s, RTAPI_INT32_MAX); + } else if (v < RTAPI_INT32_MIN) { + hal_set_si32(inst->output.s, RTAPI_INT32_MIN); + } else { + hal_set_si32(inst->output.s, v); } - } - - s += *inst->sel_int; - - if (*inst->suppress && s == 0) - return; - if (s != inst->selection && inst->timer < *inst->debounce) { - inst->timer += period / 1000; - return; - } - - inst->selection = s; - inst->timer = 0; + break; } + case FT(HAL_REAL, HAL_U32): { //HAL_FLOAT => HAL_U32 + rtapi_real v = hal_get_real(inst->inputs[s].r); + if (v > RTAPI_UINT32_MAX) { + hal_set_ui32(inst->output.u, RTAPI_UINT32_MAX); + } else if (v < 0) { + hal_set_ui32(inst->output.u, 0); + } else { + hal_set_ui32(inst->output.u, v); + } + break; } - if ((int)s >= inst->size) - s = inst->size - 1; - switch (inst->in_type * 8 + inst->out_type) { - case 011: //HAL_BIT => HAL_BIT - inst->output->b = inst->inputs[s]->b; - break; - case 013: //HAL_BIT => HAL_S32 - inst->output->s = inst->inputs[s]->b; - break; - case 014: //HAL_BIT => HAL_U32 - inst->output->u = inst->inputs[s]->b; + case FT(HAL_S32, HAL_BOOL): //HAL_S32 => HAL_BIT + hal_set_bool(inst->output.b, hal_get_si32(inst->inputs[s].s) != 0); break; - case 031: //HAL_S32 => HAL_BIT - inst->output->b = inst->inputs[s]->s == 0 ? 0 : 1; + case FT(HAL_S32, HAL_S32): //HAL_S32 => HAL_S32 + hal_set_si32(inst->output.s, hal_get_si32(inst->inputs[s].s)); break; - case 033: //HAL_S32 => HAL_S32 - inst->output->s = inst->inputs[s]->s; + case FT(HAL_S32, HAL_U32): { //HAL_S32 => HAL_U32 + rtapi_s32 v = hal_get_si32(inst->inputs[s].s); + hal_set_ui32(inst->output.u, v >= 0 ? v : 0); + break; } + case FT(HAL_S32, HAL_REAL): //HAL_S32 => HAL_FLOAT + hal_set_real(inst->output.r, hal_get_si32(inst->inputs[s].s)); break; - case 034: //HAL_S32 => HAL_U32 - inst->output->u = (inst->inputs[s]->s > 0) ? inst->inputs[s]->s : 0; - break; - case 041: //HAL_U32 => HAL_BIT - inst->output->b = inst->inputs[s]->u == 0 ? 0 : 1; + + case FT(HAL_U32, HAL_BOOL): //HAL_U32 => HAL_BIT + hal_set_bool(inst->output.b, hal_get_ui32(inst->inputs[s].u) != 0); break; - case 043: //HAL_U32 => HAL_S32 - inst->output->s = - ((unsigned int) inst->inputs[s]->u > MAX_S32) ? - MAX_S32 : inst->inputs[s]->u; + case FT(HAL_U32, HAL_S32): { //HAL_U32 => HAL_S32 + rtapi_u32 v = hal_get_ui32(inst->inputs[s].u); + hal_set_si32(inst->output.s, v > RTAPI_INT32_MAX ? RTAPI_INT32_MAX : v); + break; } + case FT(HAL_U32, HAL_U32): //HAL_U32 => HAL_U32 + hal_set_ui32(inst->output.u, hal_get_ui32(inst->inputs[s].u)); break; - case 044: //HAL_U32 => HAL_U32 - inst->output->u = inst->inputs[s]->u; + case FT(HAL_U32, HAL_REAL): //HAL_U32 => HAL_FLOAT + hal_set_real(inst->output.r, hal_get_ui32(inst->inputs[s].u)); break; } } diff --git a/src/hal/components/near.comp b/src/hal/components/near.comp index 20793c68b47..fed1d9b48df 100644 --- a/src/hal/components/near.comp +++ b/src/hal/components/near.comp @@ -1,9 +1,9 @@ component near "Determine whether two values are roughly equal."; -pin in float in1_; -pin in float in2_; -param rw float scale=1; -param rw float difference=0; -pin out bit out """ +pin in real in1_; +pin in real in2_; +param rw real scale=1; +param rw real difference=0; +pin out bool out """ *out* is true if *in1* and *in2* are within a factor of *scale* (i.e., for in1 positive, in1/scale ≤ in2 ≤ in1*scale), OR if their absolute difference is no greater than *difference* (i.e., @@ -15,15 +15,15 @@ author "Chris Radek"; ;; #include FUNCTION(_) { - double in1 = in1_, in2 = in2_; + rtapi_real in1 = in1_, in2 = in2_; if(in1 < 0) { in1 = -in1; in2 = -in2; } if((scale > 1 && in1/scale <= in2 && in2 <= in1*scale) || fabs(in1-in2) <= difference) { - out = 1; + out_set(1); } else { - out = 0; + out_set(0); } } diff --git a/src/hal/components/not.comp b/src/hal/components/not.comp index 113dd969323..ca7c11d431d 100644 --- a/src/hal/components/not.comp +++ b/src/hal/components/not.comp @@ -1,6 +1,6 @@ component not "Inverter"; -pin in bit in; -pin out bit out; +pin in bool in; +pin out bool out; description """ The *out* output pin is set to the inverted logic level of the *in* input pin. """; @@ -16,4 +16,4 @@ license "GPL"; author "Jeff Epler"; option period no; ;; -FUNCTION(_) { out = ! in; } +FUNCTION(_) { out_set(! in); } diff --git a/src/hal/components/offset.comp b/src/hal/components/offset.comp index 2265490a97e..34718794c49 100644 --- a/src/hal/components/offset.comp +++ b/src/hal/components/offset.comp @@ -19,18 +19,18 @@ component offset "Adds an offset to an input, and subtracts it from the feedback function update_output "Updated the output value by adding the offset to the input."; function update_feedback "Update the feedback value by subtracting the offset from the feedback."; -pin in float offset "The offset value"; +pin in real offset "The offset value"; -pin in float in "The input value"; -pin out float out "The output value"; +pin in real in "The input value"; +pin out real out "The output value"; -pin in float fb_in "The feedback input value"; -pin out float fb_out "The feedback output value"; +pin in real fb_in "The feedback input value"; +pin out real fb_out "The feedback output value"; license "GPL"; author "Jeff Epler"; option period no; ;; -FUNCTION(update_feedback) { fb_out = fb_in - offset; } -FUNCTION(update_output) { out = in + offset; } +FUNCTION(update_feedback) { fb_out_set(fb_in - offset); } +FUNCTION(update_output) { out_set(in + offset); } diff --git a/src/hal/components/ohmic.comp b/src/hal/components/ohmic.comp index 2a244c55d21..0979c49afdd 100644 --- a/src/hal/components/ohmic.comp +++ b/src/hal/components/ohmic.comp @@ -49,17 +49,17 @@ net ohmic-true ohmicsense.ohmic-on => plasmac.ohmic-probe author "Rod Webster"; -pin in bit is_probing "True if probing"; -pin in float ohmic_low = 21 "The threshold volts below which ohmic sensing is set to be false"; -pin in float ohmic_threshold = 22 "The threshold volts above which ohmic sensing is set to be true"; -pin in float thcad_0_volt_freq "0 volt calibration data for THCAD card in Hz"; -pin in float thcad_divide = 32 "THCAD divider set by links on THCAD board (1, 32, 64, or 128)"; -pin in float thcad_fullscale = 5 "THCAD full scale in Volt (5, 10, or 300 Volt)"; -pin in float thcad_max_volt_freq "Full scale calibration data for THCAD Card in Hz"; -pin in float velocity_in "The velocity returned from the THCAD and read by the Mesa encoder input"; -pin in float volt_divider = 4.9 "The divide ratio"; -pin out bit ohmic_on "True if ohmic circuit is closed (material is sensed)"; -pin out float ohmic_volts "Calculated ohmic voltage"; +pin in bool is_probing "True if probing"; +pin in real ohmic_low = 21 "The threshold volts below which ohmic sensing is set to be false"; +pin in real ohmic_threshold = 22 "The threshold volts above which ohmic sensing is set to be true"; +pin in real thcad_0_volt_freq "0 volt calibration data for THCAD card in Hz"; +pin in real thcad_divide = 32 "THCAD divider set by links on THCAD board (1, 32, 64, or 128)"; +pin in real thcad_fullscale = 5 "THCAD full scale in Volt (5, 10, or 300 Volt)"; +pin in real thcad_max_volt_freq "Full scale calibration data for THCAD Card in Hz"; +pin in real velocity_in "The velocity returned from the THCAD and read by the Mesa encoder input"; +pin in real volt_divider = 4.9 "The divide ratio"; +pin out bool ohmic_on "True if ohmic circuit is closed (material is sensed)"; +pin out real ohmic_volts "Calculated ohmic voltage"; option period no; function _; @@ -68,13 +68,13 @@ license "GPL"; #include FUNCTION(_) { - double thcad_vel_scale = 1/((thcad_max_volt_freq - thcad_0_volt_freq)/thcad_fullscale/thcad_divide); - double thcad_scale_offset = thcad_0_volt_freq/thcad_divide; + rtapi_real thcad_vel_scale = 1/((thcad_max_volt_freq - thcad_0_volt_freq)/thcad_fullscale/thcad_divide); + rtapi_real thcad_scale_offset = thcad_0_volt_freq/thcad_divide; - ohmic_volts = (velocity_in - thcad_scale_offset) * thcad_vel_scale * volt_divider; + ohmic_volts_set((velocity_in - thcad_scale_offset) * thcad_vel_scale * volt_divider); if(is_probing) - ohmic_on = (ohmic_volts >= ohmic_threshold ? 1 : 0); + ohmic_on_set(ohmic_volts >= ohmic_threshold); else if(ohmic_volts <= ohmic_low) - ohmic_on = 0; + ohmic_on_set(0); } diff --git a/src/hal/components/oneshot.comp b/src/hal/components/oneshot.comp index c5af056897b..c19ecfcb60b 100644 --- a/src/hal/components/oneshot.comp +++ b/src/hal/components/oneshot.comp @@ -24,16 +24,16 @@ multiple of that thread period, typically 1ms. For a similar function that can run in the base thread, and which offers higher resolution, see "edge"."""; -pin in bit in "Trigger input"; -pin in bit reset "Reset"; -pin out bit out "Active high pulse"; -pin out bit out_not "Active low pulse"; -pin in float width=0 "Pulse width in seconds"; -pin out float time_left "Time left in current output pulse"; +pin in bool in "Trigger input"; +pin in bool reset "Reset"; +pin out bool out "Active high pulse"; +pin out bool out_not "Active low pulse"; +pin in real width=0 "Pulse width in seconds"; +pin out real time_left "Time left in current output pulse"; -param rw bit retriggerable=TRUE "Allow additional edges to extend pulse"; -param rw bit rising=TRUE "Trigger on rising edge"; -param rw bit falling=FALSE "Trigger on falling edge"; +param rw bool retriggerable=TRUE "Allow additional edges to extend pulse"; +param rw bool rising=TRUE "Trigger on rising edge"; +param rw bool falling=FALSE "Trigger on falling edge"; option data internal; option extra_setup yes; @@ -44,7 +44,7 @@ author "John Kasunich"; ;; typedef struct { - double timer; + rtapi_real timer; char old_in; } internal; @@ -62,8 +62,8 @@ FUNCTION(_){ if (reset) { data.timer = 0.0; data.old_in = 0; - out = 0; - out_not = 1; + out_set(0); + out_not_set(1); return; } new = in; @@ -88,13 +88,13 @@ FUNCTION(_){ data.timer = width; } /* drive outputs */ - time_left = data.timer; + time_left_set(data.timer); if ( data.timer > 0.0 ) { - out = 1; - out_not = 0; + out_set(1); + out_not_set(0); } else { - out = 0; - out_not = 1; + out_set(0); + out_not_set(1); } } diff --git a/src/hal/components/or2.comp b/src/hal/components/or2.comp index 99dccb9ea83..bb04d4b2cce 100644 --- a/src/hal/components/or2.comp +++ b/src/hal/components/or2.comp @@ -1,7 +1,7 @@ component or2 "Two-input OR gate"; -pin in bit in0 "First input"; -pin in bit in1 "Second input"; -pin out bit out "Output"; +pin in bool in0 "First input"; +pin in bool in1 "Second input"; +pin out bool out "Output"; description """ The *out* pin is computed from the value of the *in0* and *in1* pins according @@ -29,4 +29,4 @@ license "GPL"; author "Jeff Epler"; option period no; ;; -FUNCTION(_) { out = in0 || in1; } +FUNCTION(_) { out_set(in0 || in1); } diff --git a/src/hal/components/orient.comp b/src/hal/components/orient.comp index 230f66fd6b4..fdff8714f48 100644 --- a/src/hal/components/orient.comp +++ b/src/hal/components/orient.comp @@ -1,18 +1,17 @@ component orient "Provide a PID command input for orientation mode based on current spindle position, target angle and orient mode"; -pin in bit enable "enable angular output for orientation mode"; -pin in s32 mode "0: rotate - shortest move; 1: always rotate clockwise; 2: always rotate counterclockwise"; -pin in float position "spindle position input, unit 1 rev"; -pin in float angle "orient target position in degrees, 0 ≤ angle < 360"; -pin out float command "target spindle position, input to PID command"; -pin out float poserr "in degrees - aid for PID tuning"; -pin out bit is-oriented "This pin goes high when poserr < tolerance. Use to drive spindle.N.is-oriented"; -pin in float tolerance = 0.5 "The tolerance in degrees for considering the align completed"; +pin in bool enable "enable angular output for orientation mode"; +pin in si32 mode "0: rotate - shortest move; 1: always rotate clockwise; 2: always rotate counterclockwise"; +pin in real position "spindle position input, unit 1 rev"; +pin in real angle "orient target position in degrees, 0 ≤ angle < 360"; +pin out real command "target spindle position, input to PID command"; +pin out real poserr "in degrees - aid for PID tuning"; +pin out bool is-oriented "This pin goes high when poserr < tolerance. Use to drive spindle.N.is-oriented"; +pin in real tolerance = 0.5 "The tolerance in degrees for considering the align completed"; variable int last_enable = 0; variable int debounce = 0; // to prevent the in-position triggering with the spindle moving -option fp yes; option period no; function _ "Update *command* based on *enable*, *position*, *mode* and *angle*."; @@ -63,30 +62,30 @@ license "GPL"; FUNCTION(_) { - double target_angle; - double latched_position; - is_oriented = 0; // spindle.is-oriented inhibits spindle.orient + rtapi_real target_angle; + rtapi_real latched_position; + is_oriented_set(0); // spindle.is-oriented inhibits spindle.orient if (enable) { if (enable ^ last_enable) { // positive edge on enable - is_oriented = 0; + is_oriented_set(0); debounce = 0; latched_position = position; // sample now target_angle = angle/360.0; switch (mode) { case 0: // shortest move - command = floor(latched_position+0.5-target_angle) + target_angle; + command_set(floor(latched_position+0.5-target_angle) + target_angle); break; case 1: // always cw - command = ceil(latched_position-target_angle) + target_angle; + command_set(ceil(latched_position-target_angle) + target_angle); break; case 2: // always ccw - command = floor(latched_position-target_angle) + target_angle ; + command_set(floor(latched_position-target_angle) + target_angle ); break; } } - poserr = (position - command) * 360.0; + poserr_set((position - command) * 360.0); debounce += (fabs(poserr) < tolerance && debounce <=100); - is_oriented = (debounce > 100); + is_oriented_set((debounce > 100)); } last_enable = enable; } diff --git a/src/hal/components/output_buffer.comp b/src/hal/components/output_buffer.comp index 0c942a776dd..facf8c58bb5 100644 --- a/src/hal/components/output_buffer.comp +++ b/src/hal/components/output_buffer.comp @@ -1,8 +1,8 @@ component output_buffer "Feed through multiple bits when enable pin is set"; -pin in bit enable "Enable input"; -pin in bit off-level = 0 "Signal level when output is off (enable=0)"; -pin in bit in-#[32 : personality] "Inputs"; -pin out bit out-#[32 : personality] "Outputs (Follow inputs when enable=1)"; +pin in bool enable "Enable input"; +pin in bool off-level = 0 "Signal level when output is off (enable=0)"; +pin in bool in-#[32 : personality] "Inputs"; +pin out bool out-#[32 : personality] "Outputs (Follow inputs when enable=1)"; function _; description """ @@ -37,12 +37,12 @@ option period no; FUNCTION(_) { if(enable) { for(int i = 0; i < personality; i++) { - out(i) = in(i); + out_set(i, in(i)); } } else { bool lvl = off_level; for(int i = 0; i < personality; i++) { - out(i) = lvl; + out_set(i, lvl); } } -} \ No newline at end of file +} diff --git a/src/hal/components/pid.c b/src/hal/components/pid.c index 15828331e66..80a30dfb55b 100644 --- a/src/hal/components/pid.c +++ b/src/hal/components/pid.c @@ -190,68 +190,65 @@ typedef enum { */ typedef struct { - hal_bit_t *enable; /* pin: enable input */ - hal_float_t *command; /* pin: commanded value */ - hal_float_t *commandvds; /* pin: commanded derivative dummysig */ - hal_float_t *commandv; /* pin: commanded derivative value */ - hal_float_t *feedback; /* pin: feedback value */ - hal_float_t *feedbackvds; /* pin: feedback derivative dummysig */ - hal_float_t *feedbackv; /* pin: feedback derivative value */ - hal_float_t *error; /* pin: command - feedback */ - hal_float_t *deadband; /* pin: deadband */ - hal_float_t *maxerror; /* pin: limit for error */ - hal_float_t *maxerror_i; /* pin: limit for integrated error */ - hal_float_t *maxerror_d; /* pin: limit for differentiated error */ - hal_float_t *maxcmd_d; /* pin: limit for differentiated cmd */ - hal_float_t *maxcmd_dd; /* pin: limit for 2nd derivative of cmd */ - hal_float_t *maxcmd_ddd; /* pin: limit for 3rd derivative of cmd */ - hal_float_t *error_i; /* opt. pin: integrated error */ - double prev_error; /* previous error for differentiator */ - hal_float_t *error_d; /* opt. pin: differentiated error */ - double prev_cmd; /* previous command for differentiator */ - double prev_fb; /* previous feedback for differentiator */ - double limit_state; /* +1 or -1 if in limit, else 0.0 */ - hal_float_t *cmd_d; /* opt. pin: differentiated command */ - hal_float_t *cmd_dd; /* opt. pin: 2nd derivative of command */ - hal_float_t *cmd_ddd; /* opt. pin: 3rd derivative of command */ - hal_float_t *bias; /* param: steady state offset */ - hal_float_t *pgain; /* pin: proportional gain */ - hal_float_t *igain; /* pin: integral gain */ - hal_float_t *dgain; /* pin: derivative gain */ - hal_float_t *ff0gain; /* pin: feedforward proportional */ - hal_float_t *ff1gain; /* pin: feedforward derivative */ - hal_float_t *ff2gain; /* pin: feedforward 2nd derivative */ - hal_float_t *ff3gain; /* pin: feedforward 3rd derivative */ - hal_float_t *maxoutput; /* pin: limit for PID output */ - hal_float_t *output; /* pin: the output value */ - hal_bit_t *saturated; /* pin: TRUE when the output is saturated */ - hal_float_t *saturated_s; /* pin: the time the output has been saturated */ - hal_s32_t *saturated_count; - /* pin: the time the output has been saturated */ - hal_bit_t *index_enable; /* pin: to monitor for step changes that would - otherwise screw up FF */ - hal_bit_t *error_previous_target; /* pin: measure error as new position vs previous command, to match motion's ideas */ + hal_bool_t enable; /* pin: enable input */ + hal_real_t command; /* pin: commanded value */ + hal_real_t commandvds; /* pin: commanded derivative dummysig */ + hal_real_t commandv; /* pin: commanded derivative value */ + hal_real_t feedback; /* pin: feedback value */ + hal_real_t feedbackvds; /* pin: feedback derivative dummysig */ + hal_real_t feedbackv; /* pin: feedback derivative value */ + hal_real_t error; /* pin: command - feedback */ + hal_real_t deadband; /* pin: deadband */ + hal_real_t maxerror; /* pin: limit for error */ + hal_real_t maxerror_i; /* pin: limit for integrated error */ + hal_real_t maxerror_d; /* pin: limit for differentiated error */ + hal_real_t maxcmd_d; /* pin: limit for differentiated cmd */ + hal_real_t maxcmd_dd; /* pin: limit for 2nd derivative of cmd */ + hal_real_t maxcmd_ddd; /* pin: limit for 3rd derivative of cmd */ + hal_real_t error_i; /* opt. pin: integrated error */ + double prev_error; /* previous error for differentiator */ + hal_real_t error_d; /* opt. pin: differentiated error */ + double prev_cmd; /* previous command for differentiator */ + double prev_fb; /* previous feedback for differentiator */ + double limit_state; /* +1 or -1 if in limit, else 0.0 */ + hal_real_t cmd_d; /* opt. pin: differentiated command */ + hal_real_t cmd_dd; /* opt. pin: 2nd derivative of command */ + hal_real_t cmd_ddd; /* opt. pin: 3rd derivative of command */ + hal_real_t bias; /* param: steady state offset */ + hal_real_t pgain; /* pin: proportional gain */ + hal_real_t igain; /* pin: integral gain */ + hal_real_t dgain; /* pin: derivative gain */ + hal_real_t ff0gain; /* pin: feedforward proportional */ + hal_real_t ff1gain; /* pin: feedforward derivative */ + hal_real_t ff2gain; /* pin: feedforward 2nd derivative */ + hal_real_t ff3gain; /* pin: feedforward 3rd derivative */ + hal_real_t maxoutput; /* pin: limit for PID output */ + hal_real_t output; /* pin: the output value */ + hal_bool_t saturated; /* pin: TRUE when the output is saturated */ + hal_real_t saturated_s; /* pin: the time the output has been saturated */ + hal_sint_t saturated_count; /* pin: the time the output has been saturated */ + hal_bool_t index_enable; /* pin: to monitor for step changes that would otherwise screw up FF */ + hal_bool_t error_previous_target; /* pin: measure error as new position vs previous command, to match motion's ideas */ char prev_ie; #ifdef AUTO_TUNER /* Autotune related */ - hal_float_t *tuneEffort; /* pin: Control effort for limit cycle. */ - hal_u32_t *tuneCycles; - hal_u32_t *tuneType; - hal_bit_t *pTuneMode; /* pin: 0=PID, 1=tune.*/ - hal_bit_t *pTuneStart; /* pin: Set to 1 to start an auto-tune - cycle. Clears automatically when - the cycle has finished. */ - hal_float_t *ultimateGain; /* Calc by auto-tune from limit cycle. */ - hal_float_t *ultimatePeriod; /* Calc by auto-tune from limit cycle. */ + hal_real_t tuneEffort; /* pin: Control effort for limit cycle. */ + hal_uint_t tuneCycles; + hal_uint_t tuneType; + hal_bool_t pTuneMode; /* pin: 0=PID, 1=tune.*/ + hal_bool_t pTuneStart; /* pin: Set to 1 to start an auto-tune + cycle. Clears automatically when the cycle has finished. */ + hal_real_t ultimateGain; /* Calc by auto-tune from limit cycle. */ + hal_real_t ultimatePeriod; /* Calc by auto-tune from limit cycle. */ /* Private data */ State state; - hal_u32_t cycleCount; - hal_u32_t cyclePeriod; - hal_float_t cycleAmplitude; - hal_float_t totalTime; - hal_float_t avgAmplitude; + rtapi_u32 cycleCount; + rtapi_u32 cyclePeriod; + rtapi_real cycleAmplitude; + rtapi_real totalTime; + rtapi_real avgAmplitude; #endif /* AUTO_TUNER */ } hal_pid_t; @@ -353,7 +350,7 @@ static void Pid_CycleEnd(hal_pid_t *pid) { pid->cycleCount++; - pid->avgAmplitude += pid->cycleAmplitude / *(pid->tuneCycles); + pid->avgAmplitude += pid->cycleAmplitude / hal_get_ui32(pid->tuneCycles); pid->cycleAmplitude = 0; pid->totalTime += pid->cyclePeriod * 0.000000001; pid->cyclePeriod = 0; @@ -378,21 +375,21 @@ Pid_CycleEnd(hal_pid_t *pid) static void Pid_AutoTune(hal_pid_t *pid, long period) { - hal_float_t error; + rtapi_real error; // Calculate the error. - error = *pid->command - *pid->feedback; - *pid->error = error; + error = hal_get_real(pid->command) - hal_get_real(pid->feedback); + hal_set_real(pid->error, error); // Check if enabled and if still in tune mode. - if(!*pid->enable || !*pid->pTuneMode){ + if(!hal_get_bool(pid->enable) || !hal_get_bool(pid->pTuneMode)) { pid->state = STATE_TUNE_ABORT; } switch(pid->state){ case STATE_TUNE_IDLE: // Wait for tune start command. - if(*pid->pTuneStart) + if(hal_get_bool(pid->pTuneStart)) pid->state = STATE_TUNE_START; break; @@ -404,9 +401,9 @@ Pid_AutoTune(hal_pid_t *pid, long period) pid->cycleAmplitude = 0; pid->totalTime = 0; pid->avgAmplitude = 0; - *(pid->ultimateGain) = 0; - *(pid->ultimatePeriod) = 0; - *pid->output = *(pid->bias) + fabs(*(pid->tuneEffort)); + hal_set_real(pid->ultimateGain, 0); + hal_set_real(pid->ultimatePeriod, 0); + hal_set_real(pid->output, hal_get_real(pid->bias) + fabs(hal_get_real(pid->tuneEffort))); break; case STATE_TUNE_POS: @@ -425,7 +422,7 @@ Pid_AutoTune(hal_pid_t *pid, long period) } // Update output so user can ramp effort until movement occurs. - *pid->output = *(pid->bias) - fabs(*(pid->tuneEffort)); + hal_set_real(pid->output, hal_get_real(pid->bias) - fabs(hal_get_real(pid->tuneEffort))); }else{ // Check amplitude. if(error > pid->cycleAmplitude) @@ -438,34 +435,34 @@ Pid_AutoTune(hal_pid_t *pid, long period) } // Update output so user can ramp effort until movement occurs. - *pid->output = *(pid->bias) + fabs(*(pid->tuneEffort)); + hal_set_real(pid->output, hal_get_real(pid->bias) + fabs(hal_get_real(pid->tuneEffort))); } // Check if the last cycle just ended. This is really the number // of half cycles. - if(pid->cycleCount < *(pid->tuneCycles)) + if(pid->cycleCount < hal_get_ui32(pid->tuneCycles)) break; // Calculate PID using Relay (Åström-Hägglund) method - *(pid->ultimateGain) = (4.0 * fabs(*(pid->tuneEffort)))/(PI * pid->avgAmplitude); - *(pid->ultimatePeriod) = 2.0 * pid->totalTime / *(pid->tuneCycles); - *(pid->ff0gain) = 0; - *(pid->ff2gain) = 0; + hal_set_real(pid->ultimateGain, (4.0 * fabs(hal_get_real(pid->tuneEffort)))/(PI * pid->avgAmplitude)); + hal_set_real(pid->ultimatePeriod, 2.0 * pid->totalTime / hal_get_ui32(pid->tuneCycles)); + hal_set_real(pid->ff0gain, 0); + hal_set_real(pid->ff2gain, 0); - if(*(pid->tuneType) == TYPE_PID){ + if(hal_get_ui32(pid->tuneType) == TYPE_PID){ // insert ultimate gain and period in Ziegler-Nichols PID method - *(pid->pgain) = 0.6 * *(pid->ultimateGain); - *(pid->igain) = 1.2 * *(pid->ultimateGain) / (*(pid->ultimatePeriod)); - *(pid->dgain) = (3.0/40.0) * *(pid->ultimateGain) * *(pid->ultimatePeriod); - *(pid->ff1gain) = 0; + hal_set_real(pid->pgain, 0.6 * hal_get_real(pid->ultimateGain)); + hal_set_real(pid->igain, 1.2 * hal_get_real(pid->ultimateGain) / (hal_get_real(pid->ultimatePeriod))); + hal_set_real(pid->dgain, (3.0/40.0) * hal_get_real(pid->ultimateGain) * hal_get_real(pid->ultimatePeriod)); + hal_set_real(pid->ff1gain, 0); }else{ // insert ultimate gain and period in Ziegler-Nichols PI method - *(pid->pgain) = 0.45 * *(pid->ultimateGain); - *(pid->igain) = 0.54 * *(pid->ultimateGain) / (*(pid->ultimatePeriod)); - *(pid->dgain) = 0; + hal_set_real(pid->pgain, 0.45 * hal_get_real(pid->ultimateGain)); + hal_set_real(pid->igain, 0.54 * hal_get_real(pid->ultimateGain) / (hal_get_real(pid->ultimatePeriod))); + hal_set_real(pid->dgain, 0); // Scaling must be set so PID output is in user units per second. - *(pid->ff1gain) = 1; + hal_set_real(pid->ff1gain, 1); } // Fall through. @@ -473,11 +470,11 @@ Pid_AutoTune(hal_pid_t *pid, long period) case STATE_TUNE_ABORT: default: // Force output to bias. - *pid->output = *(pid->bias); + hal_set_real(pid->output, hal_get_real(pid->bias)); // Abort any tuning cycle in progress. - *pid->pTuneStart = 0; - pid->state = (*pid->pTuneMode)? STATE_TUNE_IDLE: STATE_PID; + hal_set_bool(pid->pTuneStart, 0); + pid->state = hal_get_bool(pid->pTuneMode) ? STATE_TUNE_IDLE : STATE_PID; } } #endif /* AUTO_TUNER */ @@ -506,13 +503,13 @@ static void calc_pid(void *arg, long period) periodfp = period * 0.000000001; periodrecip = 1.0 / periodfp; /* get the enable bit */ - enable = *(pid->enable); + enable = hal_get_bool(pid->enable); /* read the command and feedback only once */ - command = *(pid->command); - feedback = *(pid->feedback); + command = hal_get_real(pid->command); + feedback = hal_get_real(pid->feedback); /* calculate the error */ - if((!(pid->prev_ie && !*(pid->index_enable))) && - (*(pid->error_previous_target))) { + if((!(pid->prev_ie && !hal_get_bool(pid->index_enable))) && + (hal_get_bool(pid->error_previous_target))) { // the user requests ferror against prev_cmd, and we can honor // that request because we haven't just had an index reset that // screwed it up. Otherwise, if we did just have an index @@ -524,21 +521,21 @@ static void calc_pid(void *arg, long period) tmp1 = command - feedback; } /* store error to error pin */ - *(pid->error) = tmp1; + hal_set_real(pid->error, tmp1); #ifdef AUTO_TUNER /* Check for auto tuning mode request. */ - if(*pid->pTuneMode){ - *(pid->error_i) = 0; + if(hal_get_bool(pid->pTuneMode)) { + hal_set_real(pid->error_i, 0); pid->prev_error = 0; - *(pid->error_d) = 0; + hal_set_real(pid->error_d, 0); pid->prev_cmd = 0; pid->limit_state = 0; - *(pid->cmd_d) = 0; - *(pid->cmd_dd) = 0; + hal_set_real(pid->cmd_d, 0); + hal_set_real(pid->cmd_dd, 0); // Force output to zero. - *(pid->output) = 0; + hal_set_real(pid->output, 0); // Switch to tuning mode. pid->state = STATE_TUNE_IDLE; @@ -548,136 +545,144 @@ static void calc_pid(void *arg, long period) #endif /* AUTO_TUNER */ /* apply error limits */ - if (*(pid->maxerror) != 0.0) { - if (tmp1 > *(pid->maxerror)) { - tmp1 = *(pid->maxerror); - } else if (tmp1 < -*(pid->maxerror)) { - tmp1 = -*(pid->maxerror); - } + rtapi_real maxerror = hal_get_real(pid->maxerror); + if (maxerror != 0.0) { + if (tmp1 > maxerror) { + tmp1 = maxerror; + } else if (tmp1 < -maxerror) { + tmp1 = -maxerror; + } } /* apply the deadband */ - if (tmp1 > *(pid->deadband)) { - tmp1 -= *(pid->deadband); - } else if (tmp1 < -*(pid->deadband)) { - tmp1 += *(pid->deadband); + rtapi_real deadband = hal_get_real(pid->deadband); + if (tmp1 > deadband) { + tmp1 -= deadband; + } else if (tmp1 < -deadband) { + tmp1 += deadband; } else { - tmp1 = 0; + tmp1 = 0; } /* do integrator calcs only if enabled */ if (enable != 0) { - /* if output is in limit, don't let integrator wind up */ - if ( ( tmp1 * pid->limit_state ) <= 0.0 ) { - /* compute integral term */ - *(pid->error_i) += tmp1 * periodfp; - } - /* apply integrator limits */ - if (*(pid->maxerror_i) != 0.0) { - if (*(pid->error_i) > *(pid->maxerror_i)) { - *(pid->error_i) = *(pid->maxerror_i); - } else if (*(pid->error_i) < -*(pid->maxerror_i)) { - *(pid->error_i) = -*(pid->maxerror_i); - } - } + /* if output is in limit, don't let integrator wind up */ + if ( ( tmp1 * pid->limit_state ) <= 0.0 ) { + /* compute integral term */ + hal_set_real(pid->error_i, hal_get_real(pid->error_i) + tmp1 * periodfp); + } + /* apply integrator limits */ + rtapi_real maxerror_i = hal_get_real(pid->maxerror_i); + if (maxerror_i != 0.0) { + if (hal_get_real(pid->error_i) > maxerror_i) { + hal_set_real(pid->error_i, maxerror_i); + } else if (hal_get_real(pid->error_i) < -maxerror_i) { + hal_set_real(pid->error_i, -maxerror_i); + } + } } else { - /* not enabled, reset integrator */ - *(pid->error_i) = 0; + /* not enabled, reset integrator */ + hal_set_real(pid->error_i, 0); } /* compute command and feedback derivatives to dummysigs */ - if(!(pid->prev_ie && !*(pid->index_enable))) { - *(pid->commandvds) = (command - pid->prev_cmd) * periodrecip; - *(pid->feedbackvds) = (feedback - pid->prev_fb) * periodrecip; + if(!(pid->prev_ie && !hal_get_bool(pid->index_enable))) { + hal_set_real(pid->commandvds, (command - pid->prev_cmd) * periodrecip); + hal_set_real(pid->feedbackvds, (feedback - pid->prev_fb) * periodrecip); } /* and calculate derivative term as difference of derivatives */ - *(pid->error_d) = *(pid->commandv) - *(pid->feedbackv); + hal_set_real(pid->error_d, hal_get_real(pid->commandv) - hal_get_real(pid->feedbackv)); pid->prev_error = tmp1; /* apply derivative limits */ - if (*(pid->maxerror_d) != 0.0) { - if (*(pid->error_d) > *(pid->maxerror_d)) { - *(pid->error_d) = *(pid->maxerror_d); - } else if (*(pid->error_d) < -*(pid->maxerror_d)) { - *(pid->error_d) = -*(pid->maxerror_d); - } + rtapi_real maxerror_d = hal_get_real(pid->maxerror_d); + if (maxerror_d != 0.0) { + if (hal_get_real(pid->error_d) > maxerror_d) { + hal_set_real(pid->error_d, maxerror_d); + } else if (hal_get_real(pid->error_d) < -maxerror_d) { + hal_set_real(pid->error_d, -maxerror_d); + } } /* save old value for 2nd derivative calc later */ - tmp2 = *(pid->cmd_d); - *(pid->cmd_d) = *(pid->commandv); + tmp2 = hal_get_real(pid->cmd_d); + hal_set_real(pid->cmd_d, hal_get_real(pid->commandv)); // save ie for next time - pid->prev_ie = *(pid->index_enable); + pid->prev_ie = hal_get_bool(pid->index_enable); pid->prev_cmd = command; pid->prev_fb = feedback; /* apply derivative limits */ - if (*(pid->maxcmd_d) != 0.0) { - if (*(pid->cmd_d) > *(pid->maxcmd_d)) { - *(pid->cmd_d) = *(pid->maxcmd_d); - } else if (*(pid->cmd_d) < -*(pid->maxcmd_d)) { - *(pid->cmd_d) = -*(pid->maxcmd_d); - } + rtapi_real maxcmd_d = hal_get_real(pid->maxcmd_d); + if (maxcmd_d != 0.0) { + if (hal_get_real(pid->cmd_d) > maxcmd_d) { + hal_set_real(pid->cmd_d, maxcmd_d); + } else if (hal_get_real(pid->cmd_d) < -maxcmd_d) { + hal_set_real(pid->cmd_d, -maxcmd_d); + } } /* save old value for 3rd derivative calc later */ - tmp3 = *(pid->cmd_dd); + tmp3 = hal_get_real(pid->cmd_dd); /* calculate 2nd derivative of command */ - *(pid->cmd_dd) = (*(pid->cmd_d) - tmp2) * periodrecip; + hal_set_real(pid->cmd_dd, (hal_get_real(pid->cmd_d) - tmp2) * periodrecip); /* apply 2nd derivative limits */ - if (*(pid->maxcmd_dd) != 0.0) { - if (*(pid->cmd_dd) > *(pid->maxcmd_dd)) { - *(pid->cmd_dd) = *(pid->maxcmd_dd); - } else if (*(pid->cmd_dd) < -*(pid->maxcmd_dd)) { - *(pid->cmd_dd) = -*(pid->maxcmd_dd); - } + rtapi_real maxcmd_dd = hal_get_real(pid->maxcmd_dd); + if (maxcmd_dd != 0.0) { + if (hal_get_real(pid->cmd_dd) > maxcmd_dd) { + hal_set_real(pid->cmd_dd, maxcmd_dd); + } else if (hal_get_real(pid->cmd_dd) < -maxcmd_dd) { + hal_set_real(pid->cmd_dd, -maxcmd_dd); + } } /* calculate 3rd derivative of command */ - *(pid->cmd_ddd) = (*(pid->cmd_dd) - tmp3) * periodrecip; + hal_set_real(pid->cmd_ddd, (hal_get_real(pid->cmd_dd) - tmp3) * periodrecip); /* apply 3rd derivative limits */ - if (*(pid->maxcmd_ddd) != 0.0) { - if (*(pid->cmd_ddd) > *(pid->maxcmd_ddd)) { - *(pid->cmd_ddd) = *(pid->maxcmd_ddd); - } else if (*(pid->cmd_ddd) < -*(pid->maxcmd_ddd)) { - *(pid->cmd_ddd) = -*(pid->maxcmd_ddd); - } + rtapi_real maxcmd_ddd = hal_get_real(pid->maxcmd_ddd); + if (maxcmd_ddd != 0.0) { + if (hal_get_real(pid->cmd_ddd) > maxcmd_ddd) { + hal_set_real(pid->cmd_ddd, maxcmd_ddd); + } else if (hal_get_real(pid->cmd_ddd) < -maxcmd_ddd) { + hal_set_real(pid->cmd_ddd, -maxcmd_ddd); + } } /* do output calcs only if enabled */ if (enable != 0) { - /* calculate the output value */ - tmp1 = - *(pid->bias) + *(pid->pgain) * tmp1 + *(pid->igain) * *(pid->error_i) + - *(pid->dgain) * *(pid->error_d); - tmp1 += command * *(pid->ff0gain) + *(pid->cmd_d) * *(pid->ff1gain) + - *(pid->cmd_dd) * *(pid->ff2gain) + *(pid->cmd_ddd) * *(pid->ff3gain); - /* apply output limits */ - if (*(pid->maxoutput) != 0.0) { - if (tmp1 > *(pid->maxoutput)) { - tmp1 = *(pid->maxoutput); - pid->limit_state = 1.0; - } else if (tmp1 < -*(pid->maxoutput)) { - tmp1 = -*(pid->maxoutput); - pid->limit_state = -1.0; - } else { - pid->limit_state = 0.0; - } - } + /* calculate the output value */ + tmp1 = + hal_get_real(pid->bias) + hal_get_real(pid->pgain) * tmp1 + hal_get_real(pid->igain) * hal_get_real(pid->error_i) + + hal_get_real(pid->dgain) * hal_get_real(pid->error_d); + tmp1 += command * hal_get_real(pid->ff0gain) + hal_get_real(pid->cmd_d) * hal_get_real(pid->ff1gain) + + hal_get_real(pid->cmd_dd) * hal_get_real(pid->ff2gain) + hal_get_real(pid->cmd_ddd) * hal_get_real(pid->ff3gain); + /* apply output limits */ + rtapi_real maxoutput = hal_get_real(pid->maxoutput); + if (maxoutput != 0.0) { + if (tmp1 > maxoutput) { + tmp1 = maxoutput; + pid->limit_state = 1.0; + } else if (tmp1 < -maxoutput) { + tmp1 = -maxoutput; + pid->limit_state = -1.0; + } else { + pid->limit_state = 0.0; + } + } } else { - /* not enabled, force output to zero */ - tmp1 = 0.0; - pid->limit_state = 0.0; + /* not enabled, force output to zero */ + tmp1 = 0.0; + pid->limit_state = 0.0; } /* write final output value to output pin */ - *(pid->output) = tmp1; + hal_set_real(pid->output, tmp1); /* set 'saturated' outputs */ - if(pid->limit_state) { - *(pid->saturated) = 1; - *(pid->saturated_s) += period * 1e-9; - if(*(pid->saturated_count) != 2147483647) - (*pid->saturated_count) ++; + if(pid->limit_state) { + hal_set_bool(pid->saturated, 1); + hal_set_real(pid->saturated_s, hal_get_real(pid->saturated_s) + period * 1e-9); + if(hal_get_si32(pid->saturated_count) != 2147483647) + hal_set_si32(pid->saturated_count, hal_get_si32(pid->saturated_count) + 1); } else { - *(pid->saturated) = 0; - *(pid->saturated_s) = 0; - *(pid->saturated_count) = 0; + hal_set_bool(pid->saturated, 0); + hal_set_real(pid->saturated_s, 0); + hal_set_si32(pid->saturated_count, 0); } /* done */ } @@ -686,6 +691,12 @@ static void calc_pid(void *arg, long period) * LOCAL FUNCTION DEFINITIONS * ************************************************************************/ +#define CHK(v) do { \ + int _rv = (v); \ + if (0 != _rv) \ + return _rv; \ + } while(0) + static int export_pid(hal_pid_t * addr, char * prefix) { int retval, msg; @@ -698,277 +709,85 @@ static int export_pid(hal_pid_t * addr, char * prefix) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pins */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->enable), comp_id, - "%s.enable", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->command), comp_id, - "%s.command", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->commandv), comp_id, - "%s.command-deriv", prefix); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(addr->enable), 0, "%s.enable", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->command), 0.0, "%s.command", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->commandv), 0.0, "%s.command-deriv", prefix)); addr->commandvds = addr->commandv; - retval = hal_pin_float_newf(HAL_IN, &(addr->feedback), comp_id, - "%s.feedback", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->feedbackv), comp_id, - "%s.feedback-deriv", prefix); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->feedback), 0.0, "%s.feedback", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->feedbackv), 0.0, "%s.feedback-deriv", prefix)); addr->feedbackvds = addr->feedbackv; - retval = hal_pin_float_newf(HAL_OUT, &(addr->error), comp_id, - "%s.error", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->output), comp_id, - "%s.output", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_bit_newf(HAL_OUT, &(addr->saturated), comp_id, - "%s.saturated", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->saturated_s), comp_id, - "%s.saturated-s", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_s32_newf(HAL_OUT, &(addr->saturated_count), comp_id, - "%s.saturated-count", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->pgain), comp_id, - "%s.Pgain", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->igain), comp_id, - "%s.Igain", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->dgain), comp_id, - "%s.Dgain", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->ff0gain), comp_id, - "%s.FF0", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->ff1gain), comp_id, - "%s.FF1", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->ff2gain), comp_id, - "%s.FF2", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->ff3gain), comp_id, - "%s.FF3", prefix); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->error), 0.0, "%s.error", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->output), 0.0, "%s.output", prefix)); + CHK(hal_pin_new_bool(comp_id, HAL_OUT, &(addr->saturated), 0, "%s.saturated", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->saturated_s), 0.0, "%s.saturated-s", prefix)); + CHK(hal_pin_new_si32(comp_id, HAL_OUT, &(addr->saturated_count), 0, "%s.saturated-count", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->pgain), 1.0, "%s.Pgain", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->igain), 0.0, "%s.Igain", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->dgain), 0.0, "%s.Dgain", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->ff0gain), 0.0, "%s.FF0", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->ff1gain), 0.0, "%s.FF1", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->ff2gain), 0.0, "%s.FF2", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->ff3gain), 0.0, "%s.FF3", prefix)); /* export pins (previously parameters) */ - retval = hal_pin_float_newf(HAL_IN, &(addr->deadband), comp_id, - "%s.deadband", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxerror), comp_id, - "%s.maxerror", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxerror_i), comp_id, - "%s.maxerrorI", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxerror_d), comp_id, - "%s.maxerrorD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxcmd_d), comp_id, - "%s.maxcmdD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxcmd_dd), comp_id, - "%s.maxcmdDD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxcmd_ddd), comp_id, - "%s.maxcmdDDD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->bias), comp_id, - "%s.bias", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_IN, &(addr->maxoutput), comp_id, - "%s.maxoutput", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_bit_newf(HAL_IN, &(addr->index_enable), comp_id, - "%s.index-enable", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_bit_newf(HAL_IN, &(addr->error_previous_target), comp_id, - "%s.error-previous-target", prefix); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->deadband), 0.0, "%s.deadband", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxerror), 0.0, "%s.maxerror", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxerror_i), 0.0, "%s.maxerrorI", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxerror_d), 0.0, "%s.maxerrorD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxcmd_d), 0.0, "%s.maxcmdD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxcmd_dd), 0.0, "%s.maxcmdDD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxcmd_ddd), 0.0, "%s.maxcmdDDD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->bias), 0.0, "%s.bias", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_IN, &(addr->maxoutput), 0.0, "%s.maxoutput", prefix)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(addr->index_enable), 0, "%s.index-enable", prefix)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(addr->error_previous_target), 1, "%s.error-previous-target", prefix)); #ifdef AUTO_TUNER /* Auto tune related */ - retval = hal_pin_float_newf(HAL_IO, &(addr->tuneEffort), comp_id, "%s.tune-effort", prefix); - if(retval != 0){ - return retval; - } - - retval = hal_pin_u32_newf(HAL_IO, &(addr->tuneCycles), comp_id, "%s.tune-cycles", prefix); - if(retval != 0){ - return retval; - } - - retval = hal_pin_u32_newf(HAL_IO, &(addr->tuneType), comp_id, "%s.tune-type", prefix); - if(retval != 0){ - return retval; - } - - retval = hal_pin_bit_newf(HAL_IN, &(addr->pTuneMode), comp_id, "%s.tune-mode", prefix); - if(retval != 0){ - return retval; - } - - retval = hal_pin_bit_newf(HAL_IO, &(addr->pTuneStart), comp_id, "%s.tune-start", prefix); - if(retval != 0){ - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_IO, &(addr->tuneEffort), 0.5, "%s.tune-effort", prefix)); + CHK(hal_pin_new_ui32(comp_id, HAL_IO, &(addr->tuneCycles), 50, "%s.tune-cycles", prefix)); + CHK(hal_pin_new_ui32(comp_id, HAL_IO, &(addr->tuneType), TYPE_PID, "%s.tune-type", prefix)); + CHK(hal_pin_new_bool(comp_id, HAL_IN, &(addr->pTuneMode), 0, "%s.tune-mode", prefix)); + CHK(hal_pin_new_bool(comp_id, HAL_IO, &(addr->pTuneStart), 0, "%s.tune-start", prefix)); #endif /* AUTO_TUNER */ /* export optional parameters */ if (debug > 0) { - retval = hal_pin_float_newf(HAL_OUT, &(addr->error_i), comp_id, - "%s.errorI", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->error_d), comp_id, - "%s.errorD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->cmd_d), comp_id, - "%s.commandD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->cmd_dd), comp_id, - "%s.commandDD", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->cmd_ddd), comp_id, - "%s.commandDDD", prefix); - if (retval != 0) { - return retval; - } - + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->error_i), 0.0, "%s.errorI", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->error_d), 0.0, "%s.errorD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->cmd_d), 0.0, "%s.commandD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->cmd_dd), 0.0, "%s.commandDD", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->cmd_ddd), 0.0, "%s.commandDDD", prefix)); #ifdef AUTO_TUNER - retval = hal_pin_float_newf(HAL_OUT, &(addr->ultimateGain), comp_id, "%s.ultimate-gain", prefix); - if (retval != 0) { - return retval; - } - retval = hal_pin_float_newf(HAL_OUT, &(addr->ultimatePeriod), comp_id, "%s.ultimate-period", prefix); - if (retval != 0) { - return retval; - } + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->ultimateGain), 0.0, "%s.ultimate-gain", prefix)); + CHK(hal_pin_new_real(comp_id, HAL_OUT, &(addr->ultimatePeriod), 0.0, "%s.ultimate-period", prefix)); #endif /* AUTO_TUNER */ } else { - addr->error_i = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); - addr->error_d = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); - addr->cmd_d = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); - addr->cmd_dd = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); - addr->cmd_ddd = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); + addr->error_i = (hal_real_t)hal_malloc(sizeof(rtapi_real)); + addr->error_d = (hal_real_t)hal_malloc(sizeof(rtapi_real)); + addr->cmd_d = (hal_real_t)hal_malloc(sizeof(rtapi_real)); + addr->cmd_dd = (hal_real_t)hal_malloc(sizeof(rtapi_real)); + addr->cmd_ddd = (hal_real_t)hal_malloc(sizeof(rtapi_real)); #ifdef AUTO_TUNER - addr->ultimateGain = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); - addr->ultimatePeriod = (hal_float_t *) hal_malloc(sizeof(hal_float_t)); + addr->ultimateGain = (hal_real_t)hal_malloc(sizeof(rtapi_real)); + addr->ultimatePeriod = (hal_real_t)hal_malloc(sizeof(rtapi_real)); #endif /* AUTO_TUNER */ } - *(addr->error_i) = 0.0; - *(addr->error_d) = 0.0; - *(addr->cmd_d) = 0.0; - *(addr->cmd_dd) = 0.0; - *(addr->cmd_ddd) = 0.0; /* init all structure members */ - *(addr->enable) = 0; - *(addr->error_previous_target) = 1; - *(addr->command) = 0; - *(addr->feedback) = 0; - *(addr->error) = 0; - *(addr->output) = 0; - *(addr->deadband) = 0.0; - *(addr->maxerror) = 0.0; - *(addr->maxerror_i) = 0.0; - *(addr->maxerror_d) = 0.0; - *(addr->maxcmd_d) = 0.0; - *(addr->maxcmd_dd) = 0.0; - *(addr->maxcmd_ddd) = 0.0; addr->prev_error = 0.0; addr->prev_cmd = 0.0; addr->limit_state = 0.0; - *(addr->bias) = 0.0; - *(addr->pgain) = 1.0; - *(addr->igain) = 0.0; - *(addr->dgain) = 0.0; - *(addr->ff0gain) = 0.0; - *(addr->ff1gain) = 0.0; - *(addr->ff2gain) = 0.0; - *(addr->ff3gain) = 0.0; - *(addr->maxoutput) = 0.0; #ifdef AUTO_TUNER /* Initialize auto tune related values */ addr->state = STATE_PID; - *(addr->tuneCycles) = 50; - *(addr->tuneEffort) = 0.5; - *(addr->tuneType) = TYPE_PID; - *(addr->pTuneMode) = 0; - *(addr->pTuneStart) = 0; #endif /* AUTO_TUNER */ /* export function for this loop */ - retval = - hal_export_functf(calc_pid, addr, 1, 0, comp_id, "%s.do-pid-calcs", prefix); + retval = hal_export_functf(calc_pid, addr, 1, 0, comp_id, "%s.do-pid-calcs", prefix); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - NAME ": ERROR: do_pid_calcs funct export failed\n"); - hal_exit(comp_id); - return -1; + rtapi_print_msg(RTAPI_MSG_ERR, NAME ": ERROR: do_pid_calcs funct export failed\n"); + hal_exit(comp_id); + return -1; } /* restore saved message level */ rtapi_set_msg_level(msg); diff --git a/src/hal/components/plasmac.comp b/src/hal/components/plasmac.comp index b206c1b130b..007e0199651 100644 --- a/src/hal/components/plasmac.comp +++ b/src/hal/components/plasmac.comp @@ -25,237 +25,237 @@ All machinery must be designed to comply with local and national safety codes, a """; /* INPUT PINS */ -pin in float arc_fail_delay "arc start failure timeout (seconds)"; -pin in float arc_lost_delay "arc lost delay during a cut (seconds)"; -pin in float arc_ok_high "maximum voltage level for Arc OK signal [mode 0] (volts)"; -pin in bit arc_ok_in "external arc ok input signal [mode 1 & mode 2]"; -pin in float arc_ok_low "minimum voltage level for Arc OK signal [mode 0] (volts)"; -pin in s32 arc_max_starts "maximum attempts at starting the arc"; -pin in float arc_voltage_in "arc voltage input [mode 0 & mode 1] see Notes above"; -pin in float arc_voltage_offset "offset to set arc voltage to 0 at 0 volts"; -pin in float arc_voltage_scale "scale to convert arc_voltage input to actual volts"; -pin in float axis_x_max_limit "axis x maximum limit, connect to ini.x.max-limit"; -pin in float axis_x_min_limit "axis x minimum limit, connect to ini.x.min-limit"; -pin in float axis_x_position "current x axis position, connect to axis.x.pos-cmd"; -pin in float axis_y_max_limit "axis y maximum limit, connect to ini.y.max-limit"; -pin in float axis_y_min_limit "axis y minimum limit, connect to ini.y.min-limit"; -pin in float axis_y_position "current y axis position, connect to axis.y.pos-cmd"; -pin in float axis_z_max_limit "axis z maximum limit, connect to ini.z.max-limit"; -pin in float axis_z_min_limit "axis z minimum limit, connect to ini.z.min-limit"; -pin in float axis_z_position "current z axis position, connect to joint.N.pos-fb"; -pin in bit breakaway "torch breakaway switch (optional, see float_switch)"; -pin in bit consumable_change "change consumables in torch"; -pin in bit cornerlock_enable "enable corner lock"; -pin in float cornerlock_threshold "corner lock threshold (% of requested feed rate), speeds below this disable THC"; -pin in float current_velocity "current machine velocity, connect to motion.current-vel"; -pin in float cut_feed_rate "cut feed rate from current material (machine units per minute)"; -pin in float cut_height "cut height (machine units)"; -pin in bit cut_recovery "recover from cut error"; -pin in float cut_volts "cut voltage (volts)"; -pin in bit cutting_start "start a new cut, connect to spindle.0.on"; -pin in bit debug_print "if true will print state changes as a debug aid"; -pin in bit dry_run "perform a dry run without probing"; -pin in bit external_estop "external E-stop input"; -pin in float feed_override "feed override value from GUI (connect to halui.feed-override.value)"; -pin in float feed_reduction "reduce adaptive feed to this percentage (connect to motion.analog-out-03)"; -pin in float feed_upm "requested feed_rate, connect to motion.feed-upm to use as the default (G-code units per minute)"; -pin in bit float_switch "float switch input (can also act as breakaway if it actuates when torch breaks away)"; -pin in float float_switch_travel "float switch travel (machine units)"; -pin in float gcode_scale = 1 "current G-code scale"; -pin in float height_override "height override adjustment (volts)"; -pin in float height_per_volt "torch height change per volt (machine units)"; -pin in bit homed "machine is homed"; -pin in bit ignore_arc_ok_0 "Do not require arc ok for start or cutting."; -pin in bit ignore_arc_ok_1 "Do not require arc ok for start or cutting."; -pin in float kerf_width "placeholder for better G-code portability between GUIs"; -pin in bit laser_mode "laser mode for fiber lasers"; -pin in s32 laser_recovery_start "start laser offset for cut recovery"; -pin in s32 laser_x_offset "alignment laser x axis offset (scaled units)"; -pin in s32 laser_y_offset "alignment laser y axis offset (scaled units)"; -pin in float lowpass_frequency "lowpass cutoff frequency for arc voltage output"; -pin in bit machine_is_on "machine is on signal, connect to halui.machine.is-on"; -pin in float material_thickness "material thickness (machine units)"; -pin in s32 max_offset = 5 "maximum height offset (mm)"; -pin in bit mesh_arc_ok = FALSE "Do not require arc ok for mesh mode."; -pin in bit mesh_enable "enable mesh cutting mode"; -pin in s32 mode "operating mode"; -pin in s32 motion_type "motion type, connect to motion.motion-type"; -pin in bit move_down "external thc down switch [mode 2]"; -pin in bit move_up "external thc up switch [mode 2]"; -pin in bit multi_tool = 1 "allows the use of multiple tools"; -pin in float offset_feed_rate "probe offset velocity (machine units per minute)"; -pin in float offset_probe_delay "wait for probe to deploy (seconds)"; -pin in float offset_probe_x "X axis offset for offset probe (machine units)"; -pin in float offset_probe_y "Y axis offset for offset probe (machine units)"; -pin in bit offset_set_probe "deploy probe for setting offsets"; -pin in bit offset_set_scribe "deploy scribe for setting offsets"; -pin in bit offsets_active "offsets are active, connect to motion.eoffset-active"; -pin in bit offsets_limited "offsets are limited, connect to motion.eoffset-limited"; -pin in s32 ohmic_max_attempts "maximum ohmic probe attempts before fallback to float switch"; -pin in bit ohmic_probe "ohmic probe input, from ohmic-sense-out or external component/pin"; -pin in bit ohmic_probe_enable "enable ohmic probe"; -pin in float ohmic_probe_offset "Z axis offset for ohmic probe (machine units)"; -pin in s32 ohmic_sense_on_delay = 3 "debounce cycles for ohmic sense on"; -pin in s32 ohmic_sense_off_delay = 3 "debounce cycles for ohmic sense off"; -pin in bit ohmic_sense_in "ohmic sense relay input"; -pin in bit ohmic_test "test for shorted torch"; -pin in s32 ok_sample_counts = 10 "arc_ok number of valid samples required [mode 0]"; -pin in float ok_sample_threshold = 10 "arc_ok maximum arc voltage deviation allowed [mode 0]"; -pin in bit override_jog "override jog inhibit"; -pin in float pause_at_end "time to pause at end of cut"; -pin in float paused_motion_speed "multiplier for speed of motion when paused, from -1 to 1"; -pin in float pid_d_gain "derivative gain input [mode 0 & mode 1]"; -pin in float pid_i_gain "integral gain input [mode 0 & mode 1]"; -pin in float pid_p_gain "proportional gain input [mode 0 & mode 1]"; -pin in float pierce_delay "time required to pierce stock (seconds)"; -pin in float pierce_height "pierce height (machine units)"; -pin in float probe_feed_rate "probe down velocity (machine units per minute)"; -pin in s32 probe_final_speed = 1 "final probe speed (steps per servo period)"; -pin in float probe_start_height "probe starting height"; -pin in bit probe_test "probe test only"; -pin in bit program_is_idle "program is idle, connect to halui.program.is-idle"; -pin in bit program_is_paused "program is paused, connect to halui.program.is-paused"; -pin in bit program_is_running "program is running, connect to halui.program.is-running"; -pin in float puddle_jump_delay "Delay move from pierce height to cut height (seconds), leave disconnected if not required."; -pin in float puddle_jump_height "Puddle jump height (percentage of pierce height), leave disconnected if not required."; +pin in real arc_fail_delay "arc start failure timeout (seconds)"; +pin in real arc_lost_delay "arc lost delay during a cut (seconds)"; +pin in real arc_ok_high "maximum voltage level for Arc OK signal [mode 0] (volts)"; +pin in bool arc_ok_in "external arc ok input signal [mode 1 & mode 2]"; +pin in real arc_ok_low "minimum voltage level for Arc OK signal [mode 0] (volts)"; +pin in si32 arc_max_starts "maximum attempts at starting the arc"; +pin in real arc_voltage_in "arc voltage input [mode 0 & mode 1] see Notes above"; +pin in real arc_voltage_offset "offset to set arc voltage to 0 at 0 volts"; +pin in real arc_voltage_scale "scale to convert arc_voltage input to actual volts"; +pin in real axis_x_max_limit "axis x maximum limit, connect to ini.x.max-limit"; +pin in real axis_x_min_limit "axis x minimum limit, connect to ini.x.min-limit"; +pin in real axis_x_position "current x axis position, connect to axis.x.pos-cmd"; +pin in real axis_y_max_limit "axis y maximum limit, connect to ini.y.max-limit"; +pin in real axis_y_min_limit "axis y minimum limit, connect to ini.y.min-limit"; +pin in real axis_y_position "current y axis position, connect to axis.y.pos-cmd"; +pin in real axis_z_max_limit "axis z maximum limit, connect to ini.z.max-limit"; +pin in real axis_z_min_limit "axis z minimum limit, connect to ini.z.min-limit"; +pin in real axis_z_position "current z axis position, connect to joint.N.pos-fb"; +pin in bool breakaway "torch breakaway switch (optional, see float_switch)"; +pin in bool consumable_change "change consumables in torch"; +pin in bool cornerlock_enable "enable corner lock"; +pin in real cornerlock_threshold "corner lock threshold (% of requested feed rate), speeds below this disable THC"; +pin in real current_velocity "current machine velocity, connect to motion.current-vel"; +pin in real cut_feed_rate "cut feed rate from current material (machine units per minute)"; +pin in real cut_height "cut height (machine units)"; +pin in bool cut_recovery "recover from cut error"; +pin in real cut_volts "cut voltage (volts)"; +pin in bool cutting_start "start a new cut, connect to spindle.0.on"; +pin in bool debug_print "if true will print state changes as a debug aid"; +pin in bool dry_run "perform a dry run without probing"; +pin in bool external_estop "external E-stop input"; +pin in real feed_override "feed override value from GUI (connect to halui.feed-override.value)"; +pin in real feed_reduction "reduce adaptive feed to this percentage (connect to motion.analog-out-03)"; +pin in real feed_upm "requested feed_rate, connect to motion.feed-upm to use as the default (G-code units per minute)"; +pin in bool float_switch "float switch input (can also act as breakaway if it actuates when torch breaks away)"; +pin in real float_switch_travel "float switch travel (machine units)"; +pin in real gcode_scale = 1 "current G-code scale"; +pin in real height_override "height override adjustment (volts)"; +pin in real height_per_volt "torch height change per volt (machine units)"; +pin in bool homed "machine is homed"; +pin in bool ignore_arc_ok_0 "Do not require arc ok for start or cutting."; +pin in bool ignore_arc_ok_1 "Do not require arc ok for start or cutting."; +pin in real kerf_width "placeholder for better G-code portability between GUIs"; +pin in bool laser_mode "laser mode for fiber lasers"; +pin in si32 laser_recovery_start "start laser offset for cut recovery"; +pin in si32 laser_x_offset "alignment laser x axis offset (scaled units)"; +pin in si32 laser_y_offset "alignment laser y axis offset (scaled units)"; +pin in real lowpass_frequency "lowpass cutoff frequency for arc voltage output"; +pin in bool machine_is_on "machine is on signal, connect to halui.machine.is-on"; +pin in real material_thickness "material thickness (machine units)"; +pin in si32 max_offset = 5 "maximum height offset (mm)"; +pin in bool mesh_arc_ok = FALSE "Do not require arc ok for mesh mode."; +pin in bool mesh_enable "enable mesh cutting mode"; +pin in si32 mode "operating mode"; +pin in si32 motion_type "motion type, connect to motion.motion-type"; +pin in bool move_down "external thc down switch [mode 2]"; +pin in bool move_up "external thc up switch [mode 2]"; +pin in bool multi_tool = 1 "allows the use of multiple tools"; +pin in real offset_feed_rate "probe offset velocity (machine units per minute)"; +pin in real offset_probe_delay "wait for probe to deploy (seconds)"; +pin in real offset_probe_x "X axis offset for offset probe (machine units)"; +pin in real offset_probe_y "Y axis offset for offset probe (machine units)"; +pin in bool offset_set_probe "deploy probe for setting offsets"; +pin in bool offset_set_scribe "deploy scribe for setting offsets"; +pin in bool offsets_active "offsets are active, connect to motion.eoffset-active"; +pin in bool offsets_limited "offsets are limited, connect to motion.eoffset-limited"; +pin in si32 ohmic_max_attempts "maximum ohmic probe attempts before fallback to real switch"; +pin in bool ohmic_probe "ohmic probe input, from ohmic-sense-out or external component/pin"; +pin in bool ohmic_probe_enable "enable ohmic probe"; +pin in real ohmic_probe_offset "Z axis offset for ohmic probe (machine units)"; +pin in si32 ohmic_sense_on_delay = 3 "debounce cycles for ohmic sense on"; +pin in si32 ohmic_sense_off_delay = 3 "debounce cycles for ohmic sense off"; +pin in bool ohmic_sense_in "ohmic sense relay input"; +pin in bool ohmic_test "test for shorted torch"; +pin in si32 ok_sample_counts = 10 "arc_ok number of valid samples required [mode 0]"; +pin in real ok_sample_threshold = 10 "arc_ok maximum arc voltage deviation allowed [mode 0]"; +pin in bool override_jog "override jog inhibit"; +pin in real pause_at_end "time to pause at end of cut"; +pin in real paused_motion_speed "multiplier for speed of motion when paused, from -1 to 1"; +pin in real pid_d_gain "derivative gain input [mode 0 & mode 1]"; +pin in real pid_i_gain "integral gain input [mode 0 & mode 1]"; +pin in real pid_p_gain "proportional gain input [mode 0 & mode 1]"; +pin in real pierce_delay "time required to pierce stock (seconds)"; +pin in real pierce_height "pierce height (machine units)"; +pin in real probe_feed_rate "probe down velocity (machine units per minute)"; +pin in si32 probe_final_speed = 1 "final probe speed (steps per servo period)"; +pin in real probe_start_height "probe starting height"; +pin in bool probe_test "probe test only"; +pin in bool program_is_idle "program is idle, connect to halui.program.is-idle"; +pin in bool program_is_paused "program is paused, connect to halui.program.is-paused"; +pin in bool program_is_running "program is running, connect to halui.program.is-running"; +pin in real puddle_jump_delay "Delay move from pierce height to cut height (seconds), leave disconnected if not required."; +pin in real puddle_jump_height "Puddle jump height (percentage of pierce height), leave disconnected if not required."; /* requested_velocity is deprecated in favour of feed_upm, the pin is kept so as not to break existing configs */ -pin in float requested_velocity "deprecated"; -pin in s32 resolution = 100 "multiplier for resolution of the offset counts"; -pin in float restart_delay "time from arc failure till next restart attempt"; -pin in float safe_height "requested safe traverse height (machine units)"; -pin in float scribe_arm_delay "delay from scribe arm to scribe on"; -pin in float scribe_on_delay "delay from scribe on to motion beginning"; -pin in bit scribe_start "start a new scribe, connect to spindle.1.on"; -pin in float setup_feed_rate "feed rate for moves to pierce and cut heights (machine units per minute)"; -pin in float skip_ihs_distance "skip IHS if less than this distance from last cut"; -pin in float slat_height "slat height (machine units)"; -pin in bit spotting_start "start a new spot, connect to spindle.2.on"; -pin in float spotting_threshold "threshold voltage to start spotting delay"; -pin in float spotting_time "torch off delay after spotting threshold reached"; -pin in bit thc_auto "enable automatic thc activation"; -pin in float thc_delay "delay from cut feed rate reached to THC activate (seconds) [non auto THC]"; -pin in bit thc_disable "thc disable"; -pin in bit thc_enable "enable/disable thc and set the IHS skip type"; -pin in float thc_feed_rate "maximum feed rate for thc (machine units per minute)"; -pin in s32 thc_sample_counts = 50 "thc number of valid samples required [auto THC]"; -pin in float thc_sample_threshold = 1 "thc maximum arc voltage deviation allowed [auto THC]"; -pin in float thc_threshold "thc threshold (volts), changes below this have no effect"; -pin in bit torch_enable "enable torch"; -pin in bit torch_off "turn torch off"; -pin in bit torch_pulse_abort "torch pulse abort"; -pin in bit torch_pulse_hold "torch pulse hold"; -pin in bit torch_pulse_start "torch pulse start"; -pin in float torch_pulse_time "torch pulse time (seconds)"; -pin in bit tube_cut "set the current job as tube cutting"; -pin in float units_per_mm "for scale calcs, connect to halui.machine.units-per-mm"; -pin in bit use_auto_volts "use calculated voltage for thc baseline"; -pin in bit voidlock_enable "enable voidlock [mode 0 & mode 1]"; -pin in s32 voidlock_off_cycles = 10 "number of sampling cycles to deactivate voidlock"; -pin in s32 voidlock_on_cycles = 2 "number of sampling cycles to activate voidlock "; -pin in s32 voidlock_slope = 500 "voidlock slope in volts per second"; -pin in s32 x_offset "offset to apply to axis x for consumable change and cut recovery (scaled units)"; -pin in float x_offset_current "current x axis offset, connect to axis.x.eoffset"; -pin in float xy_feed_rate "feed-rate for consumable change"; -pin in s32 y_offset "offset to apply to axis y for consumable change and cut recovery (scaled units)"; -pin in float y_offset_current "current y axis offset, connect to axis.y.eoffset"; -pin in float z_offset_current "current z axis offset, connect to axis.z.eoffset"; -pin in float zero_window = 0.1 "sets window that voltage fluctuations show as zero (-0.1 to 0.1 at default value)"; +pin in real requested_velocity "deprecated"; +pin in si32 resolution = 100 "multiplier for resolution of the offset counts"; +pin in real restart_delay "time from arc failure till next restart attempt"; +pin in real safe_height "requested safe traverse height (machine units)"; +pin in real scribe_arm_delay "delay from scribe arm to scribe on"; +pin in real scribe_on_delay "delay from scribe on to motion beginning"; +pin in bool scribe_start "start a new scribe, connect to spindle.1.on"; +pin in real setup_feed_rate "feed rate for moves to pierce and cut heights (machine units per minute)"; +pin in real skip_ihs_distance "skip IHS if less than this distance from last cut"; +pin in real slat_height "slat height (machine units)"; +pin in bool spotting_start "start a new spot, connect to spindle.2.on"; +pin in real spotting_threshold "threshold voltage to start spotting delay"; +pin in real spotting_time "torch off delay after spotting threshold reached"; +pin in bool thc_auto "enable automatic thc activation"; +pin in real thc_delay "delay from cut feed rate reached to THC activate (seconds) [non auto THC]"; +pin in bool thc_disable "thc disable"; +pin in bool thc_enable "enable/disable thc and set the IHS skip type"; +pin in real thc_feed_rate "maximum feed rate for thc (machine units per minute)"; +pin in si32 thc_sample_counts = 50 "thc number of valid samples required [auto THC]"; +pin in real thc_sample_threshold = 1 "thc maximum arc voltage deviation allowed [auto THC]"; +pin in real thc_threshold "thc threshold (volts), changes below this have no effect"; +pin in bool torch_enable "enable torch"; +pin in bool torch_off "turn torch off"; +pin in bool torch_pulse_abort "torch pulse abort"; +pin in bool torch_pulse_hold "torch pulse hold"; +pin in bool torch_pulse_start "torch pulse start"; +pin in real torch_pulse_time "torch pulse time (seconds)"; +pin in bool tube_cut "set the current job as tube cutting"; +pin in real units_per_mm "for scale calcs, connect to halui.machine.units-per-mm"; +pin in bool use_auto_volts "use calculated voltage for thc baseline"; +pin in bool voidlock_enable "enable voidlock [mode 0 & mode 1]"; +pin in si32 voidlock_off_cycles = 10 "number of sampling cycles to deactivate voidlock"; +pin in si32 voidlock_on_cycles = 2 "number of sampling cycles to activate voidlock "; +pin in si32 voidlock_slope = 500 "voidlock slope in volts per second"; +pin in si32 x_offset "offset to apply to axis x for consumable change and cut recovery (scaled units)"; +pin in real x_offset_current "current x axis offset, connect to axis.x.eoffset"; +pin in real xy_feed_rate "feed-rate for consumable change"; +pin in si32 y_offset "offset to apply to axis y for consumable change and cut recovery (scaled units)"; +pin in real y_offset_current "current y axis offset, connect to axis.y.eoffset"; +pin in real z_offset_current "current z axis offset, connect to axis.z.eoffset"; +pin in real zero_window = 0.1 "sets window that voltage fluctuations show as zero (-0.1 to 0.1 at default value)"; // Pierce type user control pins -pin in s32 pierce_type = 0 "allows motion to progress during pierce. 0=No movement, 1=Wiggle, 2=Ramp"; -pin in float pierce_motion_delay = 0 "delay starting motion during pierce delay period. This is a % of Pierce Delay. Only used when pierce-with-motion is True."; -pin in float cut_height_delay = 0 "at the end of transition to end-pierce-height how long to pause before transition to cut height."; -pin in float pierce_end_height = 0 "height at end of piercing (in machine units). Can be different to Cut Height. Default 0 means not used. i.e. no change in height."; -pin in float gouge_speed = 0 "ramp starting speed for gouge. In machine units/min."; -pin in float gouge_speed_distance = 0 "distance gouge will run in machine units. Gouge plus creep distance should not be longer than any lead in."; -pin in float creep_speed = 0 "ramp creep or intermediate speed. Comes after gouge and is before cut speed. In machine units/min."; -pin in float creep_speed_distance = 0 "distance creep will run in machine units. Gouge plus creep distance should not be longer than any lead in."; +pin in si32 pierce_type = 0 "allows motion to progress during pierce. 0=No movement, 1=Wiggle, 2=Ramp"; +pin in real pierce_motion_delay = 0 "delay starting motion during pierce delay period. This is a % of Pierce Delay. Only used when pierce-with-motion is True."; +pin in real cut_height_delay = 0 "at the end of transition to end-pierce-height how long to pause before transition to cut height."; +pin in real pierce_end_height = 0 "height at end of piercing (in machine units). Can be different to Cut Height. Default 0 means not used. i.e. no change in height."; +pin in real gouge_speed = 0 "ramp starting speed for gouge. In machine units/min."; +pin in real gouge_speed_distance = 0 "distance gouge will run in machine units. Gouge plus creep distance should not be longer than any lead in."; +pin in real creep_speed = 0 "ramp creep or intermediate speed. Comes after gouge and is before cut speed. In machine units/min."; +pin in real creep_speed_distance = 0 "distance creep will run in machine units. Gouge plus creep distance should not be longer than any lead in."; /* OUTPUT PINS */ -pin out float adaptive_feed "for reverse-run, connect to motion.adaptive-feed"; -pin out bit arc_ok_out "arc ok output"; -pin out float arc_voltage_out "arc voltage output [mode 0 & mode 1]"; -pin out bit consumable_changing "consumables are being changed"; -pin out bit cornerlock_is_locked "corner locked indicator"; -pin out float current_feed_rate "current feed rate per minute (for auto-thc)"; -pin out float cut_length "length of current cut job"; -pin out bit cut_recovering "recovering from cut error"; -pin out float cut_time "cut time of current job"; -pin out bit cutting_stop "stop manual cut, connect to halui.spindle.0.stop"; -pin out bit feed_hold "feed hold, connect to motion.feed-hold"; -pin out bit jog_inhibit "jog inhibit, connect to motion.jog-inhibit"; -pin out s32 laser_recovery_state "laser recovery status"; -pin out bit led_down "thc move down indicator"; -pin out bit led_up "thc move up indicator"; -pin out float offset_scale "offset scale, connect to axis..eoffset-scale"; -pin out bit ohmic_enable "on only while probing"; -pin out bit ohmic_sense_out "ohmic sense output state"; -pin out bit paused_motion "paused motion flag, true when paused motion is active"; -pin out float paused_time "paused time during current job"; -pin out s32 pierce_count "number of pierce attempts (torch starts)"; -pin out bit probe_out "probe for tube cutting, connect to motion.probe-input"; -pin out bit probe_test_error "minimum limit reached while probe testing"; -pin out float probe_time "probe time of current job"; -pin out bit program_pause "pause the current program, connect to halui.program.pause"; -pin out bit program_resume "resume the currently paused program, connect to halui.program.resume"; -pin out bit program_run "run the currently loaded program, connect to halui.program.run"; -pin out bit program_stop "stop current program, connect to halui.program.stop"; -pin out float rapid_time "rapid motion time of current job"; -pin out float requested_feed_rate "requested feed rate (for auto-thc)"; -pin out float run_time "run time of current job"; -pin out bit safe_height_is_limited "safe height is limited indicator"; -pin out bit sensor_active "one of float, ohmic, or breakaway is detected"; -pin out bit scribe_arm "arm the scribe"; -pin out bit scribe_on "turn scribe on"; -pin out s32 state_out "current state"; -pin out s32 stop_type_out "current stop type"; -pin out bit thc_active "thc status output"; -pin out bit thc_enabled "thc is enabled"; -pin out bit torch_on "turn torch on, connect to your torch on input"; -pin out float torch_time "torch on time of current job"; -pin out bit voidlock_is_locked "voidlock is locked indicator [mode 0 & mode 1]"; -pin out s32 x_offset_counts "x offset for consumable change, connect to axis.x.eoffset-counts"; -pin out bit xy_offset_enable "enable x and y offsets, connect to axis..eoffset-enable"; -pin out s32 y_offset_counts "y offset for consumable change, connect to axis.y.eoffset-counts"; -pin out float z_height "current z axis height relative to the probed zero height"; -pin out s32 z_offset_counts "z offset for height control, connect to axis.z.eoffset-counts"; -pin out bit z_offset_enable "enable z offsets, connect to axis.z.eoffset-enable"; -pin out float z_relative "distance of Z from last probed height"; +pin out real adaptive_feed "for reverse-run, connect to motion.adaptive-feed"; +pin out bool arc_ok_out "arc ok output"; +pin out real arc_voltage_out "arc voltage output [mode 0 & mode 1]"; +pin out bool consumable_changing "consumables are being changed"; +pin out bool cornerlock_is_locked "corner locked indicator"; +pin out real current_feed_rate "current feed rate per minute (for auto-thc)"; +pin out real cut_length "length of current cut job"; +pin out bool cut_recovering "recovering from cut error"; +pin out real cut_time "cut time of current job"; +pin out bool cutting_stop "stop manual cut, connect to halui.spindle.0.stop"; +pin out bool feed_hold "feed hold, connect to motion.feed-hold"; +pin out bool jog_inhibit "jog inhibit, connect to motion.jog-inhibit"; +pin out si32 laser_recovery_state "laser recovery status"; +pin out bool led_down "thc move down indicator"; +pin out bool led_up "thc move up indicator"; +pin out real offset_scale "offset scale, connect to axis..eoffset-scale"; +pin out bool ohmic_enable "on only while probing"; +pin out bool ohmic_sense_out "ohmic sense output state"; +pin out bool paused_motion "paused motion flag, true when paused motion is active"; +pin out real paused_time "paused time during current job"; +pin out si32 pierce_count "number of pierce attempts (torch starts)"; +pin out bool probe_out "probe for tube cutting, connect to motion.probe-input"; +pin out bool probe_test_error "minimum limit reached while probe testing"; +pin out real probe_time "probe time of current job"; +pin out bool program_pause "pause the current program, connect to halui.program.pause"; +pin out bool program_resume "resume the currently paused program, connect to halui.program.resume"; +pin out bool program_run "run the currently loaded program, connect to halui.program.run"; +pin out bool program_stop "stop current program, connect to halui.program.stop"; +pin out real rapid_time "rapid motion time of current job"; +pin out real requested_feed_rate "requested feed rate (for auto-thc)"; +pin out real run_time "run time of current job"; +pin out bool safe_height_is_limited "safe height is limited indicator"; +pin out bool sensor_active "one of float, ohmic, or breakaway is detected"; +pin out bool scribe_arm "arm the scribe"; +pin out bool scribe_on "turn scribe on"; +pin out si32 state_out "current state"; +pin out si32 stop_type_out "current stop type"; +pin out bool thc_active "thc status output"; +pin out bool thc_enabled "thc is enabled"; +pin out bool torch_on "turn torch on, connect to your torch on input"; +pin out real torch_time "torch on time of current job"; +pin out bool voidlock_is_locked "voidlock is locked indicator [mode 0 & mode 1]"; +pin out si32 x_offset_counts "x offset for consumable change, connect to axis.x.eoffset-counts"; +pin out bool xy_offset_enable "enable x and y offsets, connect to axis..eoffset-enable"; +pin out si32 y_offset_counts "y offset for consumable change, connect to axis.y.eoffset-counts"; +pin out real z_height "current z axis height relative to the probed zero height"; +pin out si32 z_offset_counts "z offset for height control, connect to axis.z.eoffset-counts"; +pin out bool z_offset_enable "enable z offsets, connect to axis.z.eoffset-enable"; +pin out real z_relative "distance of Z from last probed height"; /* VARIABLES */ variable double angle_x_y; /* angle for x/y velocity calcs in radians*/ -variable float arc_fail_timer; /* arc failure timer */ -variable float arc_lost_timer; /* arc lost timer */ +variable double arc_fail_timer; /* arc failure timer */ +variable double arc_lost_timer; /* arc lost timer */ variable int arc_starts; /* number of attempts to start torch */ -variable float arc_valid_timer; /* timer to wait for valid arc_voltage_in */ -variable float arc_voltage_raw; /* filtered arc voltage to be scaled */ +variable double arc_valid_timer; /* timer to wait for valid arc_voltage_in */ +variable double arc_voltage_raw; /* filtered arc voltage to be scaled */ variable int arc_voltage_buffer_index; /* arc voltage sampler write index */ variable bool auto_cut; /* auto cut mode is active */ -variable float axis_x_finish; /* axis x position at end of cut */ -variable float axis_x_start; /* axis x position at start of cut */ -variable float axis_y_finish; /* axis y position at end of cut */ -variable float axis_y_start; /* axis y position at start of cut */ +variable double axis_x_finish; /* axis x position at end of cut */ +variable double axis_x_start; /* axis x position at start of cut */ +variable double axis_y_finish; /* axis y position at end of cut */ +variable double axis_y_start; /* axis y position at start of cut */ variable int cons_change_clear; /* consumable change is clearing */ variable int count; /* for counting */ variable int cut_height_first; /* cut height at start of cut */ variable int cut_height_last; /* cut height at end of cut */ -variable float cut_offset; /* offset from last cut end to this cut start */ +variable double cut_offset; /* offset from last cut end to this cut start */ variable bool cut_started; /* cut has started */ variable int cut_target; /* cut height target offset */ variable bool error_message; /* 1 if error message has been sent */ variable bool first_cut_finished; /* first cut is complete */ variable bool float_detected; /* float switch detected */ variable int height_ovr_counts; /* number of counts to change height via override */ -variable float height_ovr_old; /* old height override value */ +variable double height_ovr_old; /* old height override value */ variable bool initialized; /* initialization flag */ variable int laser_x_target; /* target count for laser recovery x offset */ variable int laser_y_target; /* target count for laser recovery y offset */ -variable float last_arc_voltage; /* last sensed arc voltage */ +variable double last_arc_voltage; /* last sensed arc voltage */ variable bool manual_cut; /* manual cut mode is active */ variable int offset_datum; /* datum for safe height calcs */ variable bool offset_limit_error = false; /* has an offset error been reported (prevents repeat messages)*/ variable int offset_max; /* maximum allowed offset */ variable int offset_min; /* minimum allowed offset */ -variable float offset_probe_timer; /* offset probe deployment delay time */ +variable double offset_probe_timer; /* offset probe deployment delay time */ variable bool offset_probing; /* offset probing is enabled */ variable int offset_res; /* resolution for comparing offset move to target*/ variable bool offset_set; /* probe or scribe is being offset*/ @@ -272,14 +272,14 @@ variable double op_xy_angle; /* angle for x/y probe offset calcs variable int op_y_start; /* y offset when offset probing started */ variable int op_y_target; /* target offset for y probe offset */ variable int op_y_velocity; /* velocity for y probe offset */ -variable float pause_at_end_timer; /* pause at end of cut timer */ -variable float paused_motion_timer; /* minimum run timer for paused motion */ -variable float pid_error_now; /* current error for pid calcs */ -variable float pid_error_old; /* old error for pid calcs */ -variable float pid_output; /* calculated pid output value */ +variable double pause_at_end_timer; /* pause at end of cut timer */ +variable double paused_motion_timer; /* minimum run timer for paused motion */ +variable double pid_error_now; /* current error for pid calcs */ +variable double pid_error_old; /* old error for pid calcs */ +variable double pid_output; /* calculated pid output value */ variable int pierce_target; /* pierce height target offset */ -variable float pierce_timer; /* pierce delay timer */ -variable float probe_at_bottom; /* probe is at bottom limit */ +variable double pierce_timer; /* pierce delay timer */ +variable double probe_at_bottom; /* probe is at bottom limit */ variable bool probe_inhibit; /* inhibit probing */ variable int probe_offset; /* offset for active probe */ variable bool probe_required = 1; /* a probe sequence is required */ @@ -289,62 +289,62 @@ variable bool probe_testing; /* probe test active */ variable int probe_velocity; /* probe down velocity */ variable int puddle_jump_percent; /* puddle jump height as percentage of pierce height */ variable int puddle_jump_target; /* puddle jump height target offset */ -variable float puddle_jump_timer; /* puddle jump delay timer */ -variable float recovery_velocity; /* cut recovery step velocity */ +variable double puddle_jump_timer; /* puddle jump delay timer */ +variable double recovery_velocity; /* cut recovery step velocity */ variable int res; /* resolution of offset move*/ -variable float restart_timer; /* time between torch on attempts*/ +variable double restart_timer; /* time between torch on attempts*/ variable int safe_alarm; /* warn if safe_available falls below this value during a cut */ variable int safe_available; /* available safe height */ variable int safe_min; /* minimum safe height allowed */ variable int safe_preferred; /* preferred safe height offset */ variable int safe_target; /* safe height target offset */ -variable float scribe_arm_timer; /* scribe timer from arm to on*/ -variable float scribe_on_timer; /* scribe timer from on to motion*/ +variable double scribe_arm_timer; /* scribe timer from arm to on*/ +variable double scribe_on_timer; /* scribe timer from on to motion*/ variable bool scribe_pause; /* scribe pause flag */ variable int setup_velocity; /* velocity for setup moves */ variable bool spotting; /* spotting flag */ -variable float spotting_timer; /* spotting timer */ +variable double spotting_timer; /* spotting timer */ variable int state_old = -1; /* old state */ variable int statistics_reset; /* statistics are reset */ //temp changed to a pin for testing forum post #210558 //variable int target_samples = 6; /* number of samples for setting target_volts */ -variable float target_total; /* total voltage of samples for setting target_volts */ +variable double target_total; /* total voltage of samples for setting target_volts */ //temp changed to a pin for testing forum post #210558 -//variable float target_volts; /* target voltage for thc, set by arc voltage at cut height */ +//variable double target_volts; /* target voltage for thc, set by arc voltage at cut height */ variable bool thc_activated; /* thc was activated */ -variable float thc_activated_timer; /* timer to reset thc_activated - end of cut is detected from userspace :( */ -variable float thc_delay_timer; /* thc delay timer [non auto THC] */ +variable double thc_activated_timer; /* timer to reset thc_activated - end of cut is detected from userspace :( */ +variable double thc_delay_timer; /* thc delay timer [non auto THC] */ variable int thc_sampler_samples; /* required number of thc samples [auto THC] */ variable int thc_velocity; /* velocity for thc moves */ -variable float torch_off_timer; /* arc off delay timer */ -variable float torch_pulse_timer; /* torch pulse timer */ -variable float velocity_scale; /* the velocity multiplier */ -variable float voidlock_change; /* voltage change this cycle */ -variable float voidlock_off_count; /* current count of voidlock deactivate cycles */ +variable double torch_off_timer; /* arc off delay timer */ +variable double torch_pulse_timer; /* torch pulse timer */ +variable double velocity_scale; /* the velocity multiplier */ +variable double voidlock_change; /* voltage change this cycle */ +variable double voidlock_off_count; /* current count of voidlock deactivate cycles */ variable int voidlock_on_count; /* current count of voidlock activate cycles */ -variable float voidlock_threshold; /* voidlock threshold voltage per cycle */ +variable double voidlock_threshold; /* voidlock threshold voltage per cycle */ variable int x_velocity; /* velocity for x motion for consumable change */ variable int y_velocity; /* velocity for y motion for consumable change */ variable int z_max; /* max height for testing against pierce height*/ variable int z_pierce; /* pierce height for testing against max height*/ variable int zero_target; /* zero height target offset */ // Pierce type user control variables -variable float creep_speed_dist_travelled; /* Sum of distance traveled during creep stage */ -variable float creep_speed_scale; /* scale of creep speed in proportion to standard cut feed rate */ -variable float cut_height_delay_timer; /* at the end of transition to end-perice-height how long to pause before transition to cut height*/ -variable float gouge_speed_dist_travelled; /* Sum of distance traveled during gouge stage */ -variable float gouge_speed_scale; /* scale of gouge speed in proportion to standard cut feed rate */ +variable double creep_speed_dist_travelled; /* Sum of distance traveled during creep stage */ +variable double creep_speed_scale; /* scale of creep speed in proportion to standard cut feed rate */ +variable double cut_height_delay_timer; /* at the end of transition to end-perice-height how long to pause before transition to cut height*/ +variable double gouge_speed_dist_travelled; /* Sum of distance traveled during gouge stage */ +variable double gouge_speed_scale; /* scale of gouge speed in proportion to standard cut feed rate */ variable int pierce_end_target; /* Target pierce height at end of pierce motion. Usually less than the starting pierce height */ -variable float pierce_motion_delay_timer; /* delay starting motion during pierce delay period. Only used when pierce-type is 2. Is calced from a % of Pierce Delay*/ -variable float pierce_old_x; /* tracking the last x location during pierce */ -variable float pierce_old_y; /* tracking the last y location during pierce */ -variable float total_pierce_state_delay; /* Total of pierce delay and cut motion delay */ +variable double pierce_motion_delay_timer; /* delay starting motion during pierce delay period. Only used when pierce-type is 2. Is calced from a % of Pierce Delay*/ +variable double pierce_old_x; /* tracking the last x location during pierce */ +variable double pierce_old_y; /* tracking the last y location during pierce */ +variable double total_pierce_state_delay; /* Total of pierce delay and cut motion delay */ // temp for testing forum post #210558 // https://forum.linuxcnc.org/plasmac/42690-is-this-qtplasmac-expected-behaviour-cycle-start-and-jog-disabled?start=0#210558 -pin in s32 low_cut_volts "low cut voltage threshold while thc active"; -pin in s32 target_samples = 6 "number of samples for setting target_volts"; -pin out float target_volts "target voltage for thc, set by arc voltage at cut height"; +pin in si32 low_cut_volts "low cut voltage threshold while thc active"; +pin in si32 target_samples = 6 "number of samples for setting target_volts"; +pin out real target_volts "target voltage for thc, set by arc voltage at cut height"; function _; @@ -534,7 +534,7 @@ FUNCTION(_) { }else{ offset_res = res * 10; } - offset_scale = units_per_mm * fperiod / res; + offset_scale_set(units_per_mm * fperiod / res); velocity_scale = res / units_per_mm / 60; recovery_velocity = cut_feed_rate * velocity_scale * 0.5; @@ -551,17 +551,17 @@ FUNCTION(_) { /* check for active sensor */ if(breakaway || float_switch || ohmic_detected){ - sensor_active = TRUE; + sensor_active_set(TRUE); }else{ - sensor_active = FALSE; + sensor_active_set(FALSE); } - probe_out = float_switch && tube_cut && state == IDLE; + probe_out_set(float_switch && tube_cut && state == IDLE); if(offsets_limited && offsets_active) { if(!offset_limit_error) { - torch_on = FALSE; + torch_on_set(FALSE); if(program_is_running && !program_is_paused) { - program_pause = TRUE; + program_pause_set(TRUE); } stop_type = PAUSE; probe_inhibit = TRUE; @@ -591,13 +591,13 @@ FUNCTION(_) { // we don't use z_relative anywhere so we could probably just rename it to z_height and remove the z_relative pin. /* output the relative Z height */ if(zero_target){ - z_height = z_offset_current - (zero_target * offset_scale); + z_height_set(z_offset_current - (zero_target * offset_scale)); }else{ - z_height = axis_z_position - axis_z_min_limit; + z_height_set(axis_z_position - axis_z_min_limit); } // check when we at "at speed" (used by auto-thc) - current_feed_rate = current_velocity * 60; + current_feed_rate_set(current_velocity * 60); /* convert feed rates to velocity */ setup_velocity = setup_feed_rate * velocity_scale; @@ -620,23 +620,23 @@ FUNCTION(_) { if(torch_off_timer > 0){ torch_off_timer -= fperiod; if(torch_off_timer <= 0){ - torch_on = FALSE; + torch_on_set(FALSE); torch_off_timer = 0; } } /* turn torch off from external input */ if(torch_off){ - torch_on = FALSE; + torch_on_set(FALSE); } /* set THC state */ //FIXME not sure if we really need thc for tube cutting // thc_enabled = (thc_enable && !thc_disable && !mesh_enable && !ignore_arc_ok_0 && !ignore_arc_ok_1 && (arc_lost_timer > arc_lost_delay - 0.000001) && tool != TUBE ? 1:0); - thc_enabled = (thc_enable && !thc_disable && !mesh_enable && !ignore_arc_ok_0 && !ignore_arc_ok_1 && (arc_lost_timer > arc_lost_delay - 0.000001) ? 1:0); + thc_enabled_set((thc_enable && !thc_disable && !mesh_enable && !ignore_arc_ok_0 && !ignore_arc_ok_1 && (arc_lost_timer > arc_lost_delay - 0.000001) ? 1:0)); /* set THC status */ - thc_active = (state == CUT_MODE_01 || state == CUT_MODE_2) && ((mode < 2 && target_volts) || (mode == 2 && arc_ok_out)) && thc_enabled && !cornerlock_is_locked && !voidlock_is_locked ? 1:0; + thc_active_set((state == CUT_MODE_01 || state == CUT_MODE_2) && ((mode < 2 && target_volts) || (mode == 2 && arc_ok_out)) && thc_enabled && !cornerlock_is_locked && !voidlock_is_locked ? 1:0); if(thc_active){ thc_activated = TRUE; thc_activated_timer = 0.25; @@ -656,9 +656,9 @@ FUNCTION(_) { /* paused motion requires allowing negative values for reverse run */ if(state != PAUSED_MOTION){ if(state == CUT_MODE_01 || state == CUT_MODE_2){ - adaptive_feed = (feed_reduction <= 0 || feed_reduction >= 100) ? 1:feed_reduction * 0.01; + adaptive_feed_set((feed_reduction <= 0 || feed_reduction >= 100) ? 1:feed_reduction * 0.01); }else{ - adaptive_feed = 1; + adaptive_feed_set(1); } } @@ -671,7 +671,7 @@ FUNCTION(_) { /* or for a pause or wait while active */ if(auto_cut){ if(state == IDLE && sensor_active && !program_is_idle && !tube_cut){ - torch_on = FALSE; + torch_on_set(FALSE); if(!program_is_paused && !program_pause){ if(breakaway){ rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch activated\n" @@ -684,7 +684,7 @@ FUNCTION(_) { "program is paused.\n"); } } - program_pause = TRUE; + program_pause_set(TRUE); if(stop_type != WAIT){ stop_type = PAUSE; } @@ -698,10 +698,10 @@ FUNCTION(_) { state = CUT_RECOVERY_OFF; }else{ if(!pause_at_end){ - torch_on = FALSE; + torch_on_set(FALSE); } stop_type = STOP; - program_stop = TRUE; + program_stop_set(TRUE); cut_started = FALSE; probe_required = TRUE; axis_x_finish = 0; @@ -714,14 +714,14 @@ FUNCTION(_) { } }else if(!probe_test && state > IDLE && state <= CUT_MODE_2 && stop_type == NONE && cut_started){ if(program_is_paused){ - torch_on = FALSE; + torch_on_set(FALSE); stop_type = PAUSE; probe_required = TRUE; pause_at_end_timer = pause_at_end; state = MAX_HEIGHT; }else if(tool == EMPTY){ if(!pause_at_end){ - torch_on = FALSE; + torch_on_set(FALSE); } stop_type = WAIT; if(thc_enabled || !torch_enable){ @@ -734,8 +734,8 @@ FUNCTION(_) { pause_at_end_timer = pause_at_end; state = PAUSE_AT_END; }else if(breakaway){ - torch_on = FALSE; - program_pause = TRUE; + torch_on_set(FALSE); + program_pause_set(TRUE); stop_type = PAUSE; probe_required = TRUE; rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch activated\n" @@ -743,8 +743,8 @@ FUNCTION(_) { probe_inhibit = TRUE; state = MAX_HEIGHT; }else if(state > ARC_OK && float_switch && !tube_cut){ - torch_on = FALSE; - program_pause = TRUE; + torch_on_set(FALSE); + program_pause_set(TRUE); stop_type = PAUSE; probe_required = TRUE; rtapi_print_msg(RTAPI_MSG_ERR,"float switch activated\n" @@ -752,8 +752,8 @@ FUNCTION(_) { probe_inhibit = TRUE; state = MAX_HEIGHT; }else if(state > ARC_OK && ohmic_detected){ - torch_on = FALSE; - program_pause = TRUE; + torch_on_set(FALSE); + program_pause_set(TRUE); stop_type = PAUSE; probe_required = TRUE; rtapi_print_msg(RTAPI_MSG_ERR,"ohmic probe activated\n" @@ -761,8 +761,8 @@ FUNCTION(_) { probe_inhibit = TRUE; state = MAX_HEIGHT; }else if(state > ARC_OK && !arc_ok_out && torch_enable && !torch_off && !(mesh_enable || ignore_arc_ok_0 || ignore_arc_ok_1)){ ; - torch_on = FALSE; - program_pause = TRUE; + torch_on_set(FALSE); + program_pause_set(TRUE); stop_type = PAUSE; probe_required = TRUE; rtapi_print_msg(RTAPI_MSG_ERR,"valid arc lost\n" @@ -773,9 +773,9 @@ FUNCTION(_) { }else if(manual_cut){ if(tool == EMPTY){ manual_cut = FALSE; - torch_on = FALSE; + torch_on_set(FALSE); stop_type = NONE; - program_stop = TRUE; + program_stop_set(TRUE); cut_started = FALSE; probe_required = TRUE; axis_x_finish = 0; @@ -790,15 +790,15 @@ FUNCTION(_) { }else{ arc_voltage_raw = arc_voltage_in; } - arc_voltage_out = round(((fabs(arc_voltage_raw) - arc_voltage_offset) * fabs(arc_voltage_scale)) * 1000) / 1000; + arc_voltage_out_set(round(((fabs(arc_voltage_raw) - arc_voltage_offset) * fabs(arc_voltage_scale)) * 1000) / 1000); if(arc_voltage_out < zero_window && arc_voltage_out > zero_window * -1){ - arc_voltage_out = 0; + arc_voltage_out_set(0); } /* temporary for forum issue #210558 */ if(thc_active && low_cut_volts && arc_voltage_out < low_cut_volts){ - torch_on = FALSE; - program_pause = TRUE; + torch_on_set(FALSE); + program_pause_set(TRUE); stop_type = PAUSE; probe_required = TRUE; rtapi_print_msg(RTAPI_MSG_ERR,"arc voltage fell below safe level while THC active\n" @@ -816,21 +816,21 @@ FUNCTION(_) { if(ohmic_sense_counts < ohmic_sense_on_delay){ ohmic_sense_counts += 1; }else{ - ohmic_sense_out = TRUE; + ohmic_sense_out_set(TRUE); ohmic_sense_counts = 0; } }else if(!ohmic_sense_in && ohmic_sense_out){ if(ohmic_sense_counts < ohmic_sense_off_delay){ ohmic_sense_counts += 1; }else{ - ohmic_sense_out = FALSE; + ohmic_sense_out_set(FALSE); ohmic_sense_counts = 0; } }else{ ohmic_sense_counts = 0; } }else{ - ohmic_sense_out = FALSE; + ohmic_sense_out_set(FALSE); ohmic_sense_counts = 0; } @@ -851,7 +851,7 @@ FUNCTION(_) { /* set arc ok from either arc ok input of from actual arc voltage * if using arc ok input, set arc_ok_low_in and/or arc_ok_high_in to 0 */ if(torch_on){ - torch_time += fperiod; + torch_time_set(torch_time + fperiod); /* add the current arc voltage to the arc voltage buffer */ arc_voltage_buffer[arc_voltage_buffer_index] = arc_voltage_out; if (arc_voltage_buffer_index == BUFFERSIZE - 1) { @@ -862,12 +862,12 @@ FUNCTION(_) { /* set from arc ok input */ if(mode > 0){ if(arc_ok_in){ - arc_ok_out = TRUE; + arc_ok_out_set(TRUE); arc_lost_timer = arc_lost_delay; }else if(arc_lost_timer > 0){ arc_lost_timer -= fperiod; }else{ - arc_ok_out = FALSE; + arc_ok_out_set(FALSE); } /* synthesised from arc voltage */ }else{ @@ -876,14 +876,14 @@ FUNCTION(_) { if(arc_voltage_out >= arc_ok_low && arc_voltage_out <= arc_ok_high && !read_arc_voltage_buffer(READ_OK, ok_sampler_samples, (arc_voltage_buffer_index == 0) ? BUFFERSIZE - 1 : arc_voltage_buffer_index - 1, arc_voltage_out, ok_sample_threshold)){ - arc_ok_out = TRUE; + arc_ok_out_set(TRUE); arc_lost_timer = arc_lost_delay; } /* stable voltages required to maintain arc_ok */ }else if((arc_voltage_out < arc_ok_low || arc_voltage_out > arc_ok_high) && read_arc_voltage_buffer(READ_OK, ok_sampler_samples, (arc_voltage_buffer_index == 0) ? BUFFERSIZE - 1 : arc_voltage_buffer_index - 1, target_volts, ok_sample_threshold) >= ok_sampler_samples){ if(arc_lost_timer <= 0){ - arc_ok_out = FALSE; + arc_ok_out_set(FALSE); }else{ arc_lost_timer -= fperiod; } @@ -892,35 +892,35 @@ FUNCTION(_) { /* unset arc ok */ }else{ arc_lost_timer = arc_lost_delay; - arc_ok_out = FALSE; + arc_ok_out_set(FALSE); } /* reset program states */ if(program_is_idle){ - program_stop = FALSE; - program_resume = FALSE; + program_stop_set(FALSE); + program_resume_set(FALSE); statistics_reset = FALSE; }else if(program_is_paused){ - program_pause = FALSE; - paused_time += fperiod; - run_time += fperiod; + program_pause_set(FALSE); + paused_time_set(paused_time + fperiod); + run_time_set(run_time + fperiod); }else if(program_is_running){ - program_run = FALSE; - program_resume = FALSE; + program_run_set(FALSE); + program_resume_set(FALSE); auto_cut = TRUE; - run_time += fperiod; + run_time_set(run_time + fperiod); if(motion_type == 1){ - rapid_time += fperiod; + rapid_time_set(rapid_time + fperiod); } if(!statistics_reset){ - cut_length = 0; - cut_time = 0; - paused_time = 0; - pierce_count = 0; - probe_time = 0; - rapid_time = 0; - run_time = 0; - torch_time = 0; + cut_length_set(0); + cut_time_set(0); + paused_time_set(0); + pierce_count_set(0); + probe_time_set(0); + rapid_time_set(0); + run_time_set(0); + torch_time_set(0); statistics_reset = TRUE; } } @@ -930,36 +930,36 @@ FUNCTION(_) { /* set jog inhibit if required */ if(sensor_active && program_is_idle && !(override_jog || state == PROBE_DOWN || state == PROBE_UP)){ - jog_inhibit = TRUE; + jog_inhibit_set(TRUE); }else{ - jog_inhibit = FALSE; + jog_inhibit_set(FALSE); } /* probe and scribe deployment for setting offsets */ if(offset_set_probe && !offset_set && homed && program_is_idle && state == IDLE){ offset_set = TRUE; - ohmic_enable = TRUE; + ohmic_enable_set(TRUE); }else if(offset_set_scribe && !offset_set && homed && program_is_idle && state == IDLE){ offset_set = TRUE; - scribe_arm = TRUE; + scribe_arm_set(TRUE); }else if(offset_set && !offset_set_probe && !offset_set_scribe){ offset_set = FALSE; - ohmic_enable = FALSE; - scribe_arm = FALSE; + ohmic_enable_set(FALSE); + scribe_arm_set(FALSE); } if(!machine_is_on){ /* if machine is off */ - x_offset_counts = 0; - y_offset_counts = 0; - z_offset_counts = 0; + x_offset_counts_set(0); + y_offset_counts_set(0); + z_offset_counts_set(0); stop_type = NONE; cut_started = FALSE; probe_required = TRUE; - program_stop = FALSE; - program_resume = FALSE; - program_pause = FALSE; - torch_on = FALSE; + program_stop_set(FALSE); + program_resume_set(FALSE); + program_pause_set(FALSE); + torch_on_set(FALSE); torch_pulse_timer = 0; state = IDLE; }else{ @@ -973,8 +973,8 @@ FUNCTION(_) { // z_offset_enable = FALSE; // } if (mode == 2 && program_is_idle){ - led_down = move_down; - led_up = move_up; + led_down_set(move_down); + led_up_set(move_up); } if(probe_inhibit && !float_switch && !breakaway && !ohmic_detected){ probe_inhibit = FALSE; @@ -993,18 +993,18 @@ FUNCTION(_) { state = CUT_RECOVERY_ON; /* if we get a tube start request and we are stopped or waiting for a restart */ }else if(tube_cut && tool == CUTTING && (stop_type == NONE || stop_type == WAIT) && homed){ - feed_hold = TRUE; + feed_hold_set(TRUE); cut_started = TRUE; stop_type = NONE; if(torch_enable){ state = TORCH_ON; }else{ - feed_hold = FALSE; + feed_hold_set(FALSE); state = CUT_MODE_01; } /* if we get a torch start request and we are stopped or waiting for a restart */ }else if((tool == CUTTING || tool == SPOTTING || probe_test) && (stop_type == NONE || stop_type == WAIT) && homed){ - feed_hold = TRUE; + feed_hold_set(TRUE); stop_type = NONE; //touchdown = FALSE; if(!probe_test){ @@ -1036,10 +1036,10 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"ohmic probe detected before probing.\n" "probe test aborted.\n"); state = PROBE_TEST; - probe_test_error = TRUE; + probe_test_error_set(TRUE); }else{ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"ohmic probe detected before probing.\n" "program is paused.\n"); } @@ -1049,10 +1049,10 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"float switch detected before probing.\n" "probe test aborted."); state = PROBE_TEST; - probe_test_error = TRUE; + probe_test_error_set(TRUE); }else{ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"float switch detected before probing.\n" "program is paused.\n"); } @@ -1062,10 +1062,10 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch detected before probing.\n" "probe test aborted.\n"); state = PROBE_TEST; - probe_test_error = TRUE; + probe_test_error_set(TRUE); }else{ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch detected before probing.\n" "program is paused.\n"); } @@ -1093,48 +1093,48 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"probe offset would violate axis X minimum limit.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); break; } if(axis_y_position + (op_y_target * offset_scale) < axis_y_min_limit){ rtapi_print_msg(RTAPI_MSG_ERR,"probe offset would violate axis Y minimum limit.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); break; } if(axis_x_position + (op_x_target * offset_scale) > axis_x_max_limit){ rtapi_print_msg(RTAPI_MSG_ERR,"probe offset would violate axis X maximum limit.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); break; } if(axis_y_position + (op_y_target * offset_scale) > axis_y_max_limit){ rtapi_print_msg(RTAPI_MSG_ERR,"probe offset would violate axis Y maximum limit.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); break; } } /* clear any laser recovery offset */ if(laser_recovery_state > OFF && laser_recovery_state < RESET){ - laser_recovery_state = RESET; + laser_recovery_state_set(RESET); }else if(laser_recovery_state == RESET){ angle_x_y = atan2(laser_y_offset, laser_x_offset); x_velocity = fabs(cut_feed_rate * velocity_scale * cos(angle_x_y)); y_velocity = fabs(cut_feed_rate * velocity_scale * sin(angle_x_y)); - laser_recovery_state = RESETTING; + laser_recovery_state_set(RESETTING); }else if(laser_recovery_state == RESETTING){ if(x_offset_counts == x_offset && y_offset_counts == y_offset){ - laser_recovery_state = OFF; + laser_recovery_state_set(OFF); }else{ if(x_offset_counts != x_offset){ - x_offset_counts = offset_move(x_offset_counts, x_velocity, x_offset); + x_offset_counts_set(offset_move(x_offset_counts, x_velocity, x_offset)); } if(y_offset_counts != y_offset){ - y_offset_counts = offset_move(y_offset_counts, y_velocity, y_offset); + y_offset_counts_set(offset_move(y_offset_counts, y_velocity, y_offset)); } } /* laser recovery offset complete if required */ @@ -1148,19 +1148,19 @@ FUNCTION(_) { if(consumable_changing){ state = CONSUMABLE_CHANGE_OFF; }else if(motion_type == 1){ - feed_hold = FALSE; + feed_hold_set(FALSE); }else{ - feed_hold = TRUE; + feed_hold_set(TRUE); } stop_type = NONE; /* if torch pulse requested */ }else if(torch_pulse_start && torch_enable && !breakaway && !float_switch && !ohmic_probe){ - feed_hold = TRUE; + feed_hold_set(TRUE); state = TORCHPULSE; /* if ohmic probe shorted test requested */ }else if(ohmic_test && ohmic_probe_enable){ - feed_hold = TRUE; - ohmic_enable = TRUE; + feed_hold_set(TRUE); + ohmic_enable_set(TRUE); state = OHMIC_TEST; /* if we get a air-scribe start request */ }else if(tool == SCRIBE && !probe_test && homed){ @@ -1168,15 +1168,15 @@ FUNCTION(_) { scribe_arm_timer = scribe_arm_delay; scribe_pause = FALSE; }else if(!cut_started){ - feed_hold = FALSE; + feed_hold_set(FALSE); } } break; case PROBE_HEIGHT: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); stop_type = NONE; if(ohmic_probe_enable){ - ohmic_enable = TRUE; + ohmic_enable_set(TRUE); } if(probe_testing && !probe_test){ state = PROBE_TEST; @@ -1184,19 +1184,19 @@ FUNCTION(_) { } if(probe_testing && breakaway){ rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch detected during probe test\n"); - probe_test_error = TRUE; + probe_test_error_set(TRUE); state = PROBE_TEST; break; } /* move probe to x/y offsets if required */ if(offset_probing){ - xy_offset_enable = TRUE; + xy_offset_enable_set(TRUE); if(x_offset_counts != op_x_target || y_offset_counts != op_y_target){ if(x_offset_counts != op_x_target){ - x_offset_counts = offset_move(x_offset_counts, op_x_velocity, op_x_target); + x_offset_counts_set(offset_move(x_offset_counts, op_x_velocity, op_x_target)); } if(y_offset_counts != op_y_target){ - y_offset_counts = offset_move(y_offset_counts, op_y_velocity, op_y_target); + y_offset_counts_set(offset_move(y_offset_counts, op_y_velocity, op_y_target)); } } } @@ -1206,7 +1206,7 @@ FUNCTION(_) { if(z_pierce > z_max){ if(probe_testing){ state = PROBE_TEST; - probe_test_error = TRUE; + probe_test_error_set(TRUE); if(float_switch){ rtapi_print_msg(RTAPI_MSG_ERR,"pierce height would exceed Z axis maximum limit\n" "condition found while moving to probe height during float switch probe testing"); @@ -1216,7 +1216,7 @@ FUNCTION(_) { } }else{ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; if(float_switch){ rtapi_print_msg(RTAPI_MSG_ERR,"pierce height would exceed Z axis maximum limit\n" @@ -1229,7 +1229,7 @@ FUNCTION(_) { break; }else if(ohmic_probe_enable && (x_offset_counts != op_x_target || y_offset_counts != op_y_target)){ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"probe contact detected before probe offset reached\n" "try increasing PROBE HEIGHT parameter\n"); state = MAX_HEIGHT; @@ -1239,7 +1239,7 @@ FUNCTION(_) { state = PROBE_UP; /* move to probe height at setup velocity */ }else if(z_offset_counts != probe_start_target){ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, probe_start_target); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, probe_start_target)); }else{ if(float_detected){ if(!float_switch){ @@ -1257,14 +1257,14 @@ FUNCTION(_) { } } } - probe_time += fperiod; + probe_time_set(probe_time + fperiod); break; case PROBE_DOWN: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); stop_type = NONE; - feed_hold = TRUE; + feed_hold_set(TRUE); if(ohmic_probe_enable){ - ohmic_enable = TRUE; + ohmic_enable_set(TRUE); } if(probe_testing && !probe_test){ state = PROBE_TEST; @@ -1272,7 +1272,7 @@ FUNCTION(_) { } if(probe_testing && breakaway){ rtapi_print_msg(RTAPI_MSG_ERR,"breakaway switch detected during probe test\n"); - probe_test_error = TRUE; + probe_test_error_set(TRUE); state = PROBE_TEST; break; } @@ -1287,7 +1287,7 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"pierce height would exceed Z axis maximum safe height\n" "condition found while float switch probing\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; break; } @@ -1307,7 +1307,7 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"pierce height would exceed Z axis maximum safe height\n" "condition found while ohmic probing\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; break; } @@ -1322,24 +1322,24 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR,"bottom limit reached while probing down.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; }else{ rtapi_print_msg(RTAPI_MSG_ERR,"bottom limit reached while probe testing.\n"); state = PROBE_TEST; - probe_test_error = TRUE; + probe_test_error_set(TRUE); } }else{ probe_at_bottom = z_offset_current; } }else{ - z_offset_counts -= probe_velocity; + z_offset_counts_set(z_offset_counts - probe_velocity); } } - probe_time += fperiod; + probe_time_set(probe_time + fperiod); break; case PROBE_UP: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); stop_type = NONE; offset_probe_timer = 0; if(probe_testing && !probe_test){ @@ -1349,14 +1349,14 @@ FUNCTION(_) { /* probe up at minimum speed to find top of stock */ if(float_switch || ohmic_detected){ if(probe_retry){ - z_offset_counts += 10 * res; + z_offset_counts_set(z_offset_counts + 10 * res); }else{ if(probe_final_speed > 10){ - z_offset_counts += 10 * res; + z_offset_counts_set(z_offset_counts + 10 * res); }else if(probe_final_speed < 1){ - z_offset_counts += 1 * res; + z_offset_counts_set(z_offset_counts + 1 * res); }else{ - z_offset_counts += probe_final_speed * res; + z_offset_counts_set(z_offset_counts + probe_final_speed * res); } } }else{ @@ -1365,7 +1365,7 @@ FUNCTION(_) { state = PROBE_DOWN; break; } - ohmic_enable = FALSE; + ohmic_enable_set(FALSE); if(probe_type == OHMIC){ probe_offset = ohmic_probe_offset / offset_scale; }else{ @@ -1401,7 +1401,7 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_ERR, "material is too high for safe traverse.\n" "program is paused.\n"); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; }else if(safe_preferred >= offset_max && !probe_testing){ safe_target = offset_max; @@ -1426,7 +1426,7 @@ FUNCTION(_) { state = ZERO_HEIGHT; } } - probe_time += fperiod; + probe_time_set(probe_time + fperiod); break; case ZERO_HEIGHT: /* this case is not used at present it is just a waypoint */ @@ -1434,7 +1434,7 @@ FUNCTION(_) { state = PIERCE_HEIGHT; break; case PIERCE_HEIGHT: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); stop_type = NONE; probe_required = FALSE; if(probe_testing && !probe_test){ @@ -1443,19 +1443,19 @@ FUNCTION(_) { } /* clear x/y probe offsets if required */ if(offset_probing){ - xy_offset_enable = TRUE; + xy_offset_enable_set(TRUE); if(x_offset_counts != op_x_start){ - x_offset_counts = offset_move(x_offset_counts, op_x_velocity, op_x_start); + x_offset_counts_set(offset_move(x_offset_counts, op_x_velocity, op_x_start)); } if(y_offset_counts != op_y_start){ - y_offset_counts = offset_move(y_offset_counts, op_y_velocity, op_y_start); + y_offset_counts_set(offset_move(y_offset_counts, op_y_velocity, op_y_start)); } if(ohmic_probe_enable && offset_probe_timer < offset_probe_delay){ break; } } if(pierce_height && cut_height && (use_auto_volts || (!use_auto_volts && cut_volts))){ - feed_hold = TRUE; + feed_hold_set(TRUE); if(z_offset_counts == pierce_target){ if((int)(z_offset_current * offset_res) == (int)(pierce_target * offset_scale * offset_res) && (((offset_probing && x_offset_counts == op_x_start && y_offset_counts == op_y_start)) || !offset_probing)){ @@ -1480,11 +1480,11 @@ FUNCTION(_) { } /* move to pierce height at setup velocity*/ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, pierce_target); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, pierce_target)); } }else if(!probe_testing){ stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); state = MAX_HEIGHT; rtapi_print_msg(RTAPI_MSG_ERR,"invalid pierce height.\n" "or invalid cut height.\n" @@ -1496,18 +1496,18 @@ FUNCTION(_) { stop_type = NONE; /* turn torch on and start arc fail timer * if too many attempts then turn torch off, pause program and return to idle state */ - feed_hold = TRUE; + feed_hold_set(TRUE); if(arc_starts > arc_max_starts - 1){ restart_timer = 0; if(program_is_idle){ - cutting_stop = 1; + cutting_stop_set(1); state = MAX_HEIGHT; if (!error_message){ rtapi_print_msg(RTAPI_MSG_ERR,"no arc detected after %d start attempts\nmanual cut is stopped.\n", arc_max_starts); error_message = 1; } }else{ - program_pause = TRUE; + program_pause_set(TRUE); if (!error_message){ rtapi_print_msg(RTAPI_MSG_ERR,"no arc detected after %d start attempts\nprogram is paused.\n", arc_max_starts); error_message = 1; @@ -1520,8 +1520,8 @@ FUNCTION(_) { restart_timer = 0; arc_fail_timer = arc_fail_delay; if(torch_enable){ - torch_on = TRUE; - pierce_count += 1; + torch_on_set(TRUE); + pierce_count_set(pierce_count + 1); } spotting = FALSE; /* clear arc voltage buffer */ @@ -1534,7 +1534,7 @@ FUNCTION(_) { stop_type = NONE; /* wait for arc ok * if timeout occurs turn torch off then return to TORCH_ON for another attempt */ - feed_hold = TRUE; + feed_hold_set(TRUE); if(tool == SPOTTING){ if(!spotting){ if(arc_voltage_out >= spotting_threshold){ @@ -1546,7 +1546,7 @@ FUNCTION(_) { if(spotting_timer <= 0){ spotting = FALSE; spotting_timer = 0; - torch_on = FALSE; + torch_on_set(FALSE); stop_type = WAIT; state = SAFE_HEIGHT; } @@ -1554,7 +1554,7 @@ FUNCTION(_) { } arc_fail_timer -= fperiod; if(arc_fail_timer <= 0){ - torch_on = FALSE; + torch_on_set(FALSE); restart_timer = restart_delay; arc_starts += 1; state = TORCH_ON; @@ -1573,10 +1573,10 @@ FUNCTION(_) { rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY\n"); stop_type = NONE; /* wait for arc to pierce stock */ - feed_hold = TRUE; // base assumption is no motion + feed_hold_set(TRUE); // base assumption is no motion if(pierce_type != 0){ // Test pierce type. 0=Normal, 1=Wiggle, 2=Ramp rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - pierce_type > 0\n"); - feed_hold = FALSE; // We have motion for non normal pierce (wiggle and ramp) + feed_hold_set(FALSE); // We have motion for non normal pierce (wiggle and ramp) if(pierce_type == 2){ /* for ramp we map have no motion for a period at the start before commencing a moving pierce and loweing height Sequence being tested for is @@ -1603,11 +1603,11 @@ FUNCTION(_) { /* Seq A - gouge distance*/ rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - Seq A\n"); if(gcode_scale == 1){ - requested_feed_rate = cut_feed_rate * gouge_speed_scale; + requested_feed_rate_set(cut_feed_rate * gouge_speed_scale); }else{ - requested_feed_rate = (cut_feed_rate * gouge_speed_scale) / gcode_scale; + requested_feed_rate_set((cut_feed_rate * gouge_speed_scale) / gcode_scale); } - adaptive_feed = gouge_speed_scale; + adaptive_feed_set(gouge_speed_scale); // accumulate gouge distance traveled in XY plane gouge_speed_dist_travelled += fabs(sqrt(pow(pierce_old_x - axis_x_position, 2) + pow(pierce_old_y - axis_y_position, 2))); // record current X/Y for next accumulation calc @@ -1617,11 +1617,11 @@ FUNCTION(_) { /* Seq B - creep distance */ rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - Seq B\n"); if(gcode_scale == 1){ - requested_feed_rate = cut_feed_rate * creep_speed_scale; + requested_feed_rate_set(cut_feed_rate * creep_speed_scale); }else{ - requested_feed_rate = (cut_feed_rate * creep_speed_scale) / gcode_scale; + requested_feed_rate_set((cut_feed_rate * creep_speed_scale) / gcode_scale); } - adaptive_feed = creep_speed_scale; + adaptive_feed_set(creep_speed_scale); // accumulate gouge distance traveled in XY plane creep_speed_dist_travelled += fabs(sqrt(pow(pierce_old_x - axis_x_position, 2) + pow(pierce_old_y - axis_y_position, 2))); // record current X/Y for next accumulation calc @@ -1630,8 +1630,8 @@ FUNCTION(_) { }else{ /* Seq C - set to cut speed */ rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - set requested feed = cut feed\n"); - requested_feed_rate = cut_feed_rate; - adaptive_feed = 1; + requested_feed_rate_set(cut_feed_rate); + adaptive_feed_set(1); } /* --------------------------------- @@ -1644,11 +1644,11 @@ FUNCTION(_) { }else if(z_offset_counts != pierce_end_target){ // Sequence 2 rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - Seq 2\n"); - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - move z_offset_counts\n"); - z_offset_counts = offset_move(z_offset_counts, + z_offset_counts_set(offset_move(z_offset_counts, (((pierce_height - pierce_end_height)/(pierce_delay - ((pierce_motion_delay/100)*pierce_delay)))*60)*velocity_scale, - pierce_end_target); + pierce_end_target)); }else{ // Sequence 3 rtapi_print_msg(RTAPI_MSG_DBG,"PIERCE_DELAY - Seq 3\n"); @@ -1669,7 +1669,7 @@ FUNCTION(_) { safe_preferred = 0; offset_min = z_offset_counts - ((axis_z_position - axis_z_min_limit) / offset_scale); offset_max = z_offset_counts + (axis_z_max_limit - axis_z_position - (max_offset * units_per_mm)) / offset_scale; - feed_hold = FALSE; + feed_hold_set(FALSE); state = CUT_MODE_01; }else if((puddle_jump_delay || puddle_jump_percent != 100) && !cut_recovering){ puddle_jump_timer = puddle_jump_delay; @@ -1679,8 +1679,8 @@ FUNCTION(_) { } break; case PUDDLE_JUMP: - z_offset_enable = TRUE; - feed_hold = FALSE; + z_offset_enable_set(TRUE); + feed_hold_set(FALSE); if(z_offset_counts == puddle_jump_target){ if((int)(z_offset_current * offset_res) == (int)(puddle_jump_target * offset_scale * offset_res)){ count = 0; @@ -1693,11 +1693,11 @@ FUNCTION(_) { } /* move to puddle_jump height at setup velocity*/ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, puddle_jump_target); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, puddle_jump_target)); } break; case CUT_HEIGHT: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); stop_type = NONE; // /* hold x/y motion until cut height reached */ // if(!cut_recovering){ @@ -1712,7 +1712,7 @@ FUNCTION(_) { y_velocity = fabs(cut_feed_rate * velocity_scale * sin(angle_x_y)); state = CUT_RECOVERY_OFF; }else{ - feed_hold = FALSE; + feed_hold_set(FALSE); thc_delay_timer = thc_delay; if(mode < 2){ voidlock_on_count = 0; @@ -1724,7 +1724,7 @@ FUNCTION(_) { } /* move to cut height at setup velocity*/ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, cut_target); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, cut_target)); } break; case CUT_MODE_01: @@ -1733,20 +1733,20 @@ FUNCTION(_) { if(program_is_idle && !cutting_start){ state = IDLE; } - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); /* use feed_upm if it has a value */ if(feed_upm){ if(gcode_scale == 1){ - requested_feed_rate = feed_upm / adaptive_feed; + requested_feed_rate_set(feed_upm / adaptive_feed); }else{ - requested_feed_rate = feed_upm / adaptive_feed / gcode_scale; + requested_feed_rate_set(feed_upm / adaptive_feed / gcode_scale); } /* otherwise fall back to cut feed rate parameter */ }else{ if(gcode_scale == 1){ - requested_feed_rate = cut_feed_rate * feed_override; + requested_feed_rate_set(cut_feed_rate * feed_override); }else{ - requested_feed_rate = cut_feed_rate * feed_override / gcode_scale; + requested_feed_rate_set(cut_feed_rate * feed_override / gcode_scale); } } /* while cutting and it is not a dry run or laser mode is enabled and mesh mode is not enabled: @@ -1756,7 +1756,7 @@ FUNCTION(_) { * adjust torch height and target voltage to suit if height override requested */ if((torch_on || laser_mode) && !mesh_enable && !ignore_arc_ok_0 && !ignore_arc_ok_1){ if(target_volts == 0){ - cornerlock_is_locked = TRUE; + cornerlock_is_locked_set(TRUE); /* wait until velocity reaches 99.9% of requested velocity or if laser mode is enabled */ if((current_velocity * 60 > requested_feed_rate * 0.999) || laser_mode){ if(thc_auto && use_auto_volts){ @@ -1765,7 +1765,7 @@ FUNCTION(_) { if(target){ // should we use average voltage or current voltage??? // target_volts = arc_voltage_out; // current voltage - target_volts = target; // average voltage + target_volts_set(target); // average voltage } }else{ /* wait until thc delay is completed before setting target voltage */ @@ -1774,13 +1774,13 @@ FUNCTION(_) { count += 1; target_total += arc_voltage_out; if(count == target_samples){ - target_volts = target_total / target_samples; + target_volts_set(target_total / target_samples); last_arc_voltage = target_volts; count = 0; target_total = 0; } }else{ - target_volts = cut_volts; + target_volts_set(cut_volts); } }else{ thc_delay_timer -= fperiod; @@ -1794,10 +1794,10 @@ FUNCTION(_) { /* height override z motion */ }else if(height_ovr_counts != 0){ if((setup_velocity) < height_ovr_counts){ - z_offset_counts -= setup_velocity; + z_offset_counts_set(z_offset_counts - setup_velocity); height_ovr_counts -= setup_velocity; }else{ - z_offset_counts -= height_ovr_counts; + z_offset_counts_set(z_offset_counts - height_ovr_counts); height_ovr_counts = 0; } /* torch height control */ @@ -1805,12 +1805,12 @@ FUNCTION(_) { /* lock thc if velocity < requested velocity * cornerlock threshold percentage */ if(cornerlock_enable){ if(current_velocity * 60 < requested_feed_rate * cornerlock_threshold * 0.01){ - cornerlock_is_locked = TRUE; + cornerlock_is_locked_set(TRUE); }else if(cornerlock_is_locked && current_velocity * 60 > requested_feed_rate * 0.99){ - cornerlock_is_locked = FALSE; + cornerlock_is_locked_set(FALSE); } }else{ - cornerlock_is_locked = FALSE; + cornerlock_is_locked_set(FALSE); } if(voidlock_enable){ voidlock_threshold = (voidlock_slope * voidlock_on_cycles * fperiod); @@ -1819,7 +1819,7 @@ FUNCTION(_) { if(voidlock_change > voidlock_threshold){ if(voidlock_on_count >= voidlock_on_cycles){ voidlock_off_count = 0; - voidlock_is_locked = TRUE; + voidlock_is_locked_set(TRUE); }else{ voidlock_on_count += 1; } @@ -1829,10 +1829,10 @@ FUNCTION(_) { voidlock_on_count = 0; } if(voidlock_is_locked && voidlock_off_count >= voidlock_off_cycles){ - voidlock_is_locked = FALSE; + voidlock_is_locked_set(FALSE); } }else{ - voidlock_is_locked = FALSE; + voidlock_is_locked_set(FALSE); voidlock_on_count = 0; last_arc_voltage = arc_voltage_out; } @@ -1853,9 +1853,9 @@ FUNCTION(_) { } /* if we hit a soft limit during thc*/ if(z_offset_counts + pid_output <= offset_min || z_offset_counts + pid_output >= offset_max){ - torch_on = FALSE; + torch_on_set(FALSE); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); if(z_offset_counts + pid_output <= offset_min){ rtapi_print_msg(RTAPI_MSG_ERR,"bottom limit reached while THC moving down.\n" "program is paused.\n"); @@ -1867,16 +1867,16 @@ FUNCTION(_) { state = MAX_HEIGHT; } - z_offset_counts += pid_output; + z_offset_counts_set(z_offset_counts + pid_output); } } if(pid_output > 0){ - led_up = TRUE; + led_up_set(TRUE); }else if((pid_output) < 0){ - led_down = TRUE; + led_down_set(TRUE); }else{ - led_down = FALSE; - led_up = FALSE; + led_down_set(FALSE); + led_up_set(FALSE); } pid_output = 0; /* check if safe height is below maximum offset */ @@ -1887,7 +1887,7 @@ FUNCTION(_) { safe_target = offset_max; // warn if safe height less than 10mm (0.4") if(!safe_height_is_limited && z_offset_counts > safe_alarm){ - safe_height_is_limited = TRUE; + safe_height_is_limited_set(TRUE); if(units_per_mm == 1){ rtapi_print_msg(RTAPI_MSG_ERR, "safe traverse height has been reduced to less than 13mm.\n"); }else{ @@ -1899,8 +1899,8 @@ FUNCTION(_) { } } cut_height_last = z_offset_counts; - cut_length = cut_length + current_velocity * fperiod; - cut_time = cut_time + fperiod; + cut_length_set(cut_length + current_velocity * fperiod); + cut_time_set(cut_time + fperiod); break; case CUT_MODE_2: /* thc control for mode 2 by move-up and move-down inputs (no void lock in this mode) */ @@ -1908,20 +1908,20 @@ FUNCTION(_) { if(program_is_idle && !cutting_start){ state = IDLE; } - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); /* use feed_upm if it has a value */ if(feed_upm){ if(gcode_scale == 1){ - requested_feed_rate = feed_upm / adaptive_feed; + requested_feed_rate_set(feed_upm / adaptive_feed); }else{ - requested_feed_rate = feed_upm / adaptive_feed / gcode_scale; + requested_feed_rate_set(feed_upm / adaptive_feed / gcode_scale); } /* otherwise fall back to cut feed rate parameter */ }else{ if(gcode_scale == 1){ - requested_feed_rate = cut_feed_rate * feed_override; + requested_feed_rate_set(cut_feed_rate * feed_override); }else{ - requested_feed_rate = cut_feed_rate * feed_override / gcode_scale; + requested_feed_rate_set(cut_feed_rate * feed_override / gcode_scale); } } /* while cutting and it is not a dry run and mesh mode is not enabled: @@ -1932,40 +1932,40 @@ FUNCTION(_) { /* lock thc if velocity < requested velocity * cornerlock threshold percentage */ if(cornerlock_enable){ if(current_velocity * 60 < requested_feed_rate * cornerlock_threshold * 0.01){ - cornerlock_is_locked = TRUE; + cornerlock_is_locked_set(TRUE); }else if(cornerlock_is_locked && current_velocity * 60 > requested_feed_rate * 0.99){ - cornerlock_is_locked = FALSE; + cornerlock_is_locked_set(FALSE); } }else{ - cornerlock_is_locked = FALSE; + cornerlock_is_locked_set(FALSE); } if(move_down && !cornerlock_is_locked){ if(z_offset_counts - thc_velocity <= offset_min){ - torch_on = FALSE; + torch_on_set(FALSE); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"bottom limit reached while THC moving down.\n" "program is paused.\n"); state = MAX_HEIGHT; }else{ /* move down at requested velocity */ - z_offset_counts -= thc_velocity; - led_down = TRUE; + z_offset_counts_set(z_offset_counts - thc_velocity); + led_down_set(TRUE); } }else if(move_up && !cornerlock_is_locked){ if(z_offset_counts + thc_velocity >= offset_max){ - torch_on = FALSE; + torch_on_set(FALSE); stop_type = PAUSE; - program_pause = TRUE; + program_pause_set(TRUE); rtapi_print_msg(RTAPI_MSG_ERR,"top limit reached while THC moving up.\n" "program is paused.\n"); state = MAX_HEIGHT; }else{ /* move up at requested velocity */ - z_offset_counts += thc_velocity; - led_up = TRUE; + z_offset_counts_set(z_offset_counts + thc_velocity); + led_up_set(TRUE); } }else{ - led_down = FALSE; - led_up = FALSE; + led_down_set(FALSE); + led_up_set(FALSE); } } /* check if safe height is below maximum offset */ @@ -1976,7 +1976,7 @@ FUNCTION(_) { safe_target = offset_max; // warn if safe height less than 10mm (0.4") if(!safe_height_is_limited && z_offset_counts > safe_alarm){ - safe_height_is_limited = TRUE; + safe_height_is_limited_set(TRUE); if(units_per_mm == 1){ rtapi_print_msg(RTAPI_MSG_ERR, "safe traverse height has been reduced to less than 13mm.\n"); }else{ @@ -1988,15 +1988,15 @@ FUNCTION(_) { } } cut_height_last = z_offset_counts; - cut_length = cut_length + current_velocity * fperiod; - cut_time = cut_time + fperiod; + cut_length_set(cut_length + current_velocity * fperiod); + cut_time_set(cut_time + fperiod); break; case PAUSE_AT_END: - feed_hold = TRUE; + feed_hold_set(TRUE); pause_at_end_timer -= fperiod; if(pause_at_end_timer <= 0){ pause_at_end_timer = 0; - torch_on = FALSE; + torch_on_set(FALSE); if(program_is_idle){ state = MAX_HEIGHT; }else{ @@ -2005,16 +2005,16 @@ FUNCTION(_) { } break; case SAFE_HEIGHT: - z_offset_enable = TRUE; - feed_hold = TRUE; - torch_on = FALSE; + z_offset_enable_set(TRUE); + feed_hold_set(TRUE); + torch_on_set(FALSE); if(!torch_off_timer || !torch_on){ - cornerlock_is_locked = FALSE; + cornerlock_is_locked_set(FALSE); if(!probe_test || probe_test_error){ if(z_offset_counts == safe_target){ if((int)(z_offset_current * offset_res) == (int)(safe_target * offset_scale * offset_res)){ if(stop_type == WAIT){ - feed_hold = FALSE; + feed_hold_set(FALSE); } first_cut_finished = TRUE; /* do height override here for for remainder of job */ @@ -2023,21 +2023,21 @@ FUNCTION(_) { } /* move to safe height at setup velocity*/ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, safe_target); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, safe_target)); } } } break; case MAX_HEIGHT: - z_offset_enable = TRUE; - feed_hold = TRUE; - torch_on = FALSE; - cornerlock_is_locked = FALSE; + z_offset_enable_set(TRUE); + feed_hold_set(TRUE); + torch_on_set(FALSE); + cornerlock_is_locked_set(FALSE); if(!probe_test || probe_test_error){ if(z_offset_counts == 0){ if((int)(z_offset_current * offset_res) == 0){ if(stop_type == WAIT){ - feed_hold = FALSE; + feed_hold_set(FALSE); } /* do height override here for remainder of job */ height_ovr_old = 0; @@ -2048,10 +2048,10 @@ FUNCTION(_) { /* clear x/y probe offsets if required */ }else if((offset_probe_x || offset_probe_y) && (x_offset_counts || y_offset_counts)){ if(x_offset_counts != 0){ - x_offset_counts = offset_move(x_offset_counts, op_x_velocity, 0); + x_offset_counts_set(offset_move(x_offset_counts, op_x_velocity, 0)); } if(y_offset_counts != 0){ - y_offset_counts = offset_move(y_offset_counts, op_y_velocity, 0); + y_offset_counts_set(offset_move(y_offset_counts, op_y_velocity, 0)); } }else{ state = END_CUT; @@ -2059,20 +2059,20 @@ FUNCTION(_) { } /* move to maximum height at setup velocity */ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, 0); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, 0)); } } break; case END_CUT: /* clean up and return to idle state */ - target_volts = 0; - cornerlock_is_locked = FALSE; - voidlock_is_locked = FALSE; - led_down = FALSE; - led_up = FALSE; - ohmic_enable = FALSE; - probe_test_error = FALSE; - cutting_stop = 0; + target_volts_set(0); + cornerlock_is_locked_set(FALSE); + voidlock_is_locked_set(FALSE); + led_down_set(FALSE); + led_up_set(FALSE); + ohmic_enable_set(FALSE); + probe_test_error_set(FALSE); + cutting_stop_set(0); if(program_is_idle){ state = END_JOB; }else{ @@ -2082,18 +2082,18 @@ FUNCTION(_) { case END_JOB: auto_cut = FALSE; manual_cut = FALSE; - program_run = FALSE; - paused_motion = FALSE; - adaptive_feed = 1; + program_run_set(FALSE); + paused_motion_set(FALSE); + adaptive_feed_set(1); cut_height_first = 0; cut_height_last = 0; if(program_is_idle){ - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); if (z_offset_counts == 0){ if(!offsets_active){ first_cut_finished = FALSE; stop_type = NONE; - safe_height_is_limited = FALSE; + safe_height_is_limited_set(FALSE); safe_available = 0; cut_started = FALSE; /* do height override here for one cut only */ @@ -2105,28 +2105,28 @@ FUNCTION(_) { x_velocity = fabs(cut_feed_rate * velocity_scale * cos(angle_x_y)); y_velocity = fabs(cut_feed_rate * velocity_scale * sin(angle_x_y)); state = CUT_RECOVERY_OFF; - cut_recovering = FALSE; - laser_recovery_state = OFF; + cut_recovering_set(FALSE); + laser_recovery_state_set(OFF); }else{ state = IDLE; } } /* clear z offset at setup velocity */ }else{ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, 0); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, 0)); } } break; case TORCHPULSE: if (torch_pulse_abort || !torch_enable) { - torch_on = FALSE; + torch_on_set(FALSE); torch_pulse_timer = 0; state = cut_recovering ? CUT_RECOVERY_ON : IDLE; break; } if (!torch_on) { torch_pulse_timer = torch_pulse_time; - torch_on = TRUE; + torch_on_set(TRUE); break; } if (torch_pulse_timer > 0) { @@ -2134,31 +2134,31 @@ FUNCTION(_) { if (torch_pulse_timer < 0) torch_pulse_timer = 0; } if (torch_pulse_timer > 0 || torch_pulse_hold) { - torch_on = TRUE; + torch_on_set(TRUE); } else { - torch_on = FALSE; + torch_on_set(FALSE); state = cut_recovering ? CUT_RECOVERY_ON : IDLE; } break; case PAUSED_MOTION: if(paused_motion_speed){ - paused_motion = TRUE; - adaptive_feed = paused_motion_speed; - program_resume = TRUE; - feed_hold = FALSE; + paused_motion_set(TRUE); + adaptive_feed_set(paused_motion_speed); + program_resume_set(TRUE); + feed_hold_set(FALSE); }else if(program_is_running){ - program_pause = TRUE; - feed_hold = TRUE; - adaptive_feed = 1; + program_pause_set(TRUE); + feed_hold_set(TRUE); + adaptive_feed_set(1); }else if(program_is_paused && feed_hold){ - paused_motion = FALSE; + paused_motion_set(FALSE); state = CUT_RECOVERY_ON; } break; case OHMIC_TEST: /* wait here until ohmic_test input released */ if (!ohmic_test){ - ohmic_enable = FALSE; + ohmic_enable_set(FALSE); if(cut_recovering){ state = CUT_RECOVERY_ON; }else{ @@ -2167,14 +2167,14 @@ FUNCTION(_) { } break; case PROBE_TEST: - z_offset_enable = TRUE; + z_offset_enable_set(TRUE); /* wait here until probe_test input released */ if(!probe_test){ /* clear z offset at setup velocity */ - z_offset_counts = offset_move(z_offset_counts, setup_velocity, 0); + z_offset_counts_set(offset_move(z_offset_counts, setup_velocity, 0)); if((offset_probe_x || offset_probe_y) && (x_offset_counts || y_offset_counts)){ - x_offset_counts = offset_move(x_offset_counts, op_x_velocity, 0); - y_offset_counts = offset_move(y_offset_counts, op_y_velocity, 0); + x_offset_counts_set(offset_move(x_offset_counts, op_x_velocity, 0)); + y_offset_counts_set(offset_move(y_offset_counts, op_y_velocity, 0)); } if(!x_offset_counts && !y_offset_counts && !z_offset_counts){ probe_inhibit = FALSE; @@ -2187,44 +2187,44 @@ FUNCTION(_) { case SCRIBING: if(tool == SCRIBE){ if(!program_is_paused){ - scribe_arm = TRUE; + scribe_arm_set(TRUE); if(scribe_arm_timer){ - feed_hold = TRUE; + feed_hold_set(TRUE); scribe_arm_timer -= fperiod; if(scribe_arm_timer < 0){ scribe_arm_timer = 0; } }else if(scribe_on_timer){ - feed_hold = TRUE; + feed_hold_set(TRUE); scribe_on_timer -= fperiod; if(scribe_on_timer < 0){ scribe_on_timer = 0; } }else if(scribe_arm && !scribe_arm_timer && !scribe_on){ - feed_hold = TRUE; + feed_hold_set(TRUE); scribe_on_timer = scribe_on_delay; - scribe_on = TRUE; + scribe_on_set(TRUE); }else if(scribe_on && !scribe_on_timer){ - feed_hold = FALSE; + feed_hold_set(FALSE); } }else{ - scribe_arm = FALSE; - scribe_on = FALSE; + scribe_arm_set(FALSE); + scribe_on_set(FALSE); scribe_arm_timer = scribe_arm_delay; scribe_on_timer = 0; } }else{ - scribe_arm = FALSE; - scribe_on = FALSE; + scribe_arm_set(FALSE); + scribe_on_set(FALSE); scribe_arm_timer = 0; scribe_on_timer = 0; state = IDLE; } break; case CONSUMABLE_CHANGE_ON: - xy_offset_enable = TRUE; - feed_hold = TRUE; + xy_offset_enable_set(TRUE); + feed_hold_set(TRUE); if(sensor_active){ if(!error_message){ error_message = TRUE; @@ -2249,7 +2249,7 @@ FUNCTION(_) { x_velocity = fabs(xy_feed_rate * velocity_scale * cos(angle_x_y)); y_velocity = fabs(xy_feed_rate * velocity_scale * sin(angle_x_y)); } - consumable_changing = TRUE; + consumable_changing_set(TRUE); }else{ if(((int)(x_offset_current * offset_res) == (int)(x_offset * offset_scale * offset_res) && (int)(y_offset_current * offset_res) == (int)(y_offset * offset_scale * offset_res)) || @@ -2259,30 +2259,30 @@ FUNCTION(_) { if(x_velocity && x_offset_counts != x_offset){ if(x_offset > 0){ if(x_offset_counts + x_velocity < x_offset){ - x_offset_counts += x_velocity; + x_offset_counts_set(x_offset_counts + x_velocity); }else{ - x_offset_counts = x_offset; + x_offset_counts_set(x_offset); } }else{ if(x_offset_counts - x_velocity > x_offset){ - x_offset_counts -= x_velocity; + x_offset_counts_set(x_offset_counts - x_velocity); }else{ - x_offset_counts = x_offset; + x_offset_counts_set(x_offset); } } } if(y_velocity && y_offset_counts != y_offset){ if(y_offset > 0){ if(y_offset_counts + y_velocity < y_offset){ - y_offset_counts += y_velocity; + y_offset_counts_set(y_offset_counts + y_velocity); }else{ - y_offset_counts = y_offset; + y_offset_counts_set(y_offset); } }else{ if(y_offset_counts - y_velocity > y_offset){ - y_offset_counts -= y_velocity; + y_offset_counts_set(y_offset_counts - y_velocity); }else{ - y_offset_counts = y_offset; + y_offset_counts_set(y_offset); } } } @@ -2290,7 +2290,7 @@ FUNCTION(_) { } break; case CONSUMABLE_CHANGE_OFF: - xy_offset_enable = TRUE; + xy_offset_enable_set(TRUE); if(sensor_active){ if(!error_message){ error_message = TRUE; @@ -2303,94 +2303,94 @@ FUNCTION(_) { error_message = FALSE; if(x_offset_counts == 0 && y_offset_counts == 0){ if((int)(x_offset_current * offset_res) == 0 && (int)(y_offset_current * offset_res) == 0){ - consumable_changing = FALSE; + consumable_changing_set(FALSE); cons_change_clear = FALSE; - feed_hold = FALSE; + feed_hold_set(FALSE); state = IDLE; } }else{ if(x_velocity && x_offset_counts != 0){ if(x_offset_counts > 0){ if(x_offset_counts - x_velocity > 0){ - x_offset_counts -= x_velocity; + x_offset_counts_set(x_offset_counts - x_velocity); }else{ - x_offset_counts = 0; + x_offset_counts_set(0); } }else{ if(x_offset_counts + x_velocity < 0){ - x_offset_counts += x_velocity; + x_offset_counts_set(x_offset_counts + x_velocity); }else{ - x_offset_counts = 0; + x_offset_counts_set(0); } } } if(y_velocity && y_offset_counts != 0){ if(y_offset_counts > 0){ if(y_offset_counts - y_velocity > 0){ - y_offset_counts -= y_velocity; + y_offset_counts_set(y_offset_counts - y_velocity); }else{ - y_offset_counts = 0; + y_offset_counts_set(0); } }else{ if(y_offset_counts + y_velocity < 0){ - y_offset_counts += y_velocity; + y_offset_counts_set(y_offset_counts + y_velocity); }else{ - y_offset_counts = 0; + y_offset_counts_set(0); } } } } break; case CUT_RECOVERY_ON: - xy_offset_enable = TRUE; + xy_offset_enable_set(TRUE); if(program_is_running){ state = IDLE; } if(!cut_recovering){ - cut_recovering = TRUE; + cut_recovering_set(TRUE); if(puddle_jump_delay || puddle_jump_percent != 100){ rtapi_print_msg(RTAPI_MSG_ERR, "Puddle Jump is disabled during Cut Recovery.\n"); } } if(torch_pulse_start && torch_enable && !breakaway && !float_switch && !ohmic_probe){ - feed_hold = TRUE; + feed_hold_set(TRUE); state = TORCHPULSE; } if(ohmic_test && ohmic_probe_enable){ - feed_hold = TRUE; - ohmic_enable = TRUE; + feed_hold_set(TRUE); + ohmic_enable_set(TRUE); state = OHMIC_TEST; } /* offset for laser recovery if required */ if(laser_recovery_start && laser_recovery_state == OFF){ - laser_recovery_state = SET; + laser_recovery_state_set(SET); }else if(laser_recovery_state == SET){ angle_x_y = atan2(laser_y_offset, laser_x_offset); x_velocity = fabs(cut_feed_rate * velocity_scale * cos(angle_x_y)); y_velocity = fabs(cut_feed_rate * velocity_scale * sin(angle_x_y)); laser_x_target = x_offset_counts + laser_x_offset; laser_y_target = y_offset_counts + laser_y_offset; - laser_recovery_state = SETTING; + laser_recovery_state_set(SETTING); }else if(laser_recovery_state == SETTING){ if(x_offset_counts == laser_x_target && y_offset_counts == laser_y_target){ - laser_recovery_state = ON; + laser_recovery_state_set(ON); }else{ if(x_offset_counts != laser_x_target){ - x_offset_counts = offset_move(x_offset_counts, x_velocity, laser_x_target); + x_offset_counts_set(offset_move(x_offset_counts, x_velocity, laser_x_target)); } if(y_offset_counts != laser_y_target){ - y_offset_counts = offset_move(y_offset_counts, y_velocity, laser_y_target); + y_offset_counts_set(offset_move(y_offset_counts, y_velocity, laser_y_target)); } } /* laser recovery offset is clear */ }else if(cut_recovery){ /* move x axis to recovery position at recovery velocity */ if(x_offset_counts != x_offset + laser_x_offset * (laser_recovery_state > 1)){ - x_offset_counts = offset_move(x_offset_counts, recovery_velocity, x_offset + laser_x_offset * (laser_recovery_state > 1)); + x_offset_counts_set(offset_move(x_offset_counts, recovery_velocity, x_offset + laser_x_offset * (laser_recovery_state > 1))); } /* move y axis to recovery position at recovery velocity */ if(y_offset_counts != y_offset + laser_y_offset * (laser_recovery_state > 1)){ - y_offset_counts = offset_move(y_offset_counts, recovery_velocity, y_offset + laser_y_offset * (laser_recovery_state > 1)); + y_offset_counts_set(offset_move(y_offset_counts, recovery_velocity, y_offset + laser_y_offset * (laser_recovery_state > 1))); } }else{ state = CUT_RECOVERY_OFF; @@ -2400,7 +2400,7 @@ FUNCTION(_) { } break; case CUT_RECOVERY_OFF: - xy_offset_enable = TRUE; + xy_offset_enable_set(TRUE); angle_x_y = atan2(-y_offset_counts, -x_offset_counts); if(program_is_running){ x_velocity = fabs(cut_feed_rate * velocity_scale * cos(angle_x_y)); @@ -2411,10 +2411,10 @@ FUNCTION(_) { } if(x_offset_counts == 0 && y_offset_counts == 0){ if((int)(x_offset_current * offset_res) == 0 && (int)(y_offset_current * offset_res) == 0){ - laser_recovery_state = OFF; + laser_recovery_state_set(OFF); if(cut_recovering){ - cut_recovering = FALSE; - feed_hold = FALSE; + cut_recovering_set(FALSE); + feed_hold_set(FALSE); thc_delay_timer = thc_delay; if(cut_recovery){ if(mode < 2){ @@ -2433,11 +2433,11 @@ FUNCTION(_) { }else{ /* clear x axis offset at recovery velocity */ if(x_offset_counts != 0){ - x_offset_counts = offset_move(x_offset_counts, x_velocity, 0); + x_offset_counts_set(offset_move(x_offset_counts, x_velocity, 0)); } /* clear y axis offset at recovery velocity */ if(y_offset_counts != 0){ - y_offset_counts = offset_move(y_offset_counts, y_velocity, 0); + y_offset_counts_set(offset_move(y_offset_counts, y_velocity, 0)); } } break; @@ -2449,8 +2449,8 @@ FUNCTION(_) { } /* set status pins */ - state_out = state; - stop_type_out = stop_type; + state_out_set(state); + stop_type_out_set(stop_type); /* debug print */ if(debug_print && state_old != (int)state){ diff --git a/src/hal/components/pushmsg.comp b/src/hal/components/pushmsg.comp index cd2706332e2..e98202c7836 100644 --- a/src/hal/components/pushmsg.comp +++ b/src/hal/components/pushmsg.comp @@ -73,9 +73,9 @@ loadrt pushmsg msgs=[PUSHMSG]MSGS addf pushmsg servo-thread ... ---- -"""; +"""; //" to fix vim syntax highlight -pin in bit enable = TRUE "Enable message generation through trigger input pins"; +pin in bool enable = TRUE "Enable message generation through trigger input pins"; modparam dummy msgs "Comma separated list of custom messages in format level|pinname|message"; @@ -104,10 +104,10 @@ RTAPI_MP_ARRAY_STRING(msgs, MSG_N_MAX, "Message slots in 't|pin|message' format" // The HAL structure lives in HAL memory space typedef struct { - hal_bit_t *trigger; - hal_bit_t *force; - hal_bit_t *edge; - hal_data_u *substs[MSG_SUBST_MAX]; + hal_bool_t trigger; + hal_bool_t force; + hal_bool_t edge; + hal_refs_u substs[MSG_SUBST_MAX]; } msg_hal_t; // The admin structure lives in normal memory space @@ -214,15 +214,15 @@ static int setup_message(const char *pfx, int idx, const char *msg, msg_slot_t * } // Create the trigger, force and edge input pins - if ((rv = hal_pin_bit_newf(HAL_IN, &pin->trigger, comp_id, "%s.trigger", pinname)) < 0) { + if ((rv = hal_pin_new_bool(comp_id, HAL_IN, &pin->trigger, 0, "%s.trigger", pinname)) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: Message %d cannot create trigger pin (duplicate?)\n", pfx, idx); return rv; } - if ((rv = hal_pin_bit_newf(HAL_IN, &pin->force, comp_id, "%s.force", pinname)) < 0) { + if ((rv = hal_pin_new_bool(comp_id, HAL_IN, &pin->force, 0, "%s.force", pinname)) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: Message %d cannot create force pin (duplicate?)\n", pfx, idx); return rv; } - if ((rv = hal_pin_bit_newf(HAL_IN, &pin->edge, comp_id, "%s.edge", pinname)) < 0) { + if ((rv = hal_pin_new_bool(comp_id, HAL_IN, &pin->edge, 0, "%s.edge", pinname)) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: Message %d cannot create edge pin (duplicate?)\n", pfx, idx); return rv; } @@ -280,32 +280,32 @@ static int setup_message(const char *pfx, int idx, const char *msg, msg_slot_t * switch (tchar) { case 'b': case 'B': slot->substtype[subst] = HAL_BIT; - if ((rv = hal_pin_bit_newf(HAL_IN, (hal_bit_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_bool(comp_id, HAL_IN, &pin->substs[subst].b, 0, "%s.%s", pinname, cptr)) < 0) return rv; break; case 's': case 'S': slot->substtype[subst] = HAL_S32; - if ((rv = hal_pin_s32_newf(HAL_IN, (hal_s32_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_si32(comp_id, HAL_IN, &pin->substs[subst].s, 0, "%s.%s", pinname, cptr)) < 0) return rv; break; case 'u': case 'U': slot->substtype[subst] = HAL_U32; - if ((rv = hal_pin_u32_newf(HAL_IN, (hal_u32_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_ui32(comp_id, HAL_IN, &pin->substs[subst].u, 0, "%s.%s", pinname, cptr)) < 0) return rv; break; case 'l': case 'L': slot->substtype[subst] = HAL_S64; - if ((rv = hal_pin_s64_newf(HAL_IN, (hal_s64_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_sint(comp_id, HAL_IN, &pin->substs[subst].s, 0, "%s.%s", pinname, cptr)) < 0) return rv; break; case 'k': case 'K': slot->substtype[subst] = HAL_U64; - if ((rv = hal_pin_u64_newf(HAL_IN, (hal_u64_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_uint(comp_id, HAL_IN, &pin->substs[subst].u, 0, "%s.%s", pinname, cptr)) < 0) return rv; break; case 'f': case 'F': slot->substtype[subst] = HAL_FLOAT; - if ((rv = hal_pin_float_newf(HAL_IN, (hal_float_t **)&pin->substs[subst], comp_id, "%s.%s", pinname, cptr)) < 0) + if ((rv = hal_pin_new_real(comp_id, HAL_IN, &pin->substs[subst].r, 0.0, "%s.%s", pinname, cptr)) < 0) return rv; break; default: @@ -381,29 +381,29 @@ static void print_slot(int s) { char buf[MSG_LEN_MAX]; char *end = strcpy(buf, slots[s].msgbuf) + slots[s].msglen; - for (int i = 0; i < MSG_SUBST_MAX && pins[s].substs[i]; i++) { + for (int i = 0; i < MSG_SUBST_MAX && pins[s].substs[i].b; i++) { int left = sizeof(buf) - (end - buf); int n; if (left <= 1) // Need room for terminator break; switch (slots[s].substtype[i]) { case HAL_BIT: - n = rtapi_snprintf(end, left, "%d%s", (int)!!pins[s].substs[i]->b, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%d%s", (int)hal_get_bool(pins[s].substs[i].b), slots[s].parts[i]); break; case HAL_S32: - n = rtapi_snprintf(end, left, "%d%s", (int)pins[s].substs[i]->s, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%d%s", (int)hal_get_si32(pins[s].substs[i].s), slots[s].parts[i]); break; case HAL_U32: - n = rtapi_snprintf(end, left, "%u%s", (unsigned)pins[s].substs[i]->u, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%u%s", (unsigned)hal_get_ui32(pins[s].substs[i].u), slots[s].parts[i]); break; case HAL_S64: - n = rtapi_snprintf(end, left, "%ld%s", (long)pins[s].substs[i]->ls, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%ld%s", (long)hal_get_sint(pins[s].substs[i].s), slots[s].parts[i]); break; case HAL_U64: - n = rtapi_snprintf(end, left, "%lu%s", (unsigned long)pins[s].substs[i]->lu, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%lu%s", (unsigned long)hal_get_uint(pins[s].substs[i].u), slots[s].parts[i]); break; case HAL_FLOAT: - n = rtapi_snprintf(end, left, "%lf%s", (double)pins[s].substs[i]->f, slots[s].parts[i]); + n = rtapi_snprintf(end, left, "%lf%s", (double)hal_get_real(pins[s].substs[i].r), slots[s].parts[i]); break; default: n = 0; @@ -424,8 +424,8 @@ FUNCTION(_) bool en = enable; // Cache enable pin // For each slot, test the trigger and save the trigger state for (int i = 0; i < nslots; i++) { - bool trig = (int)!!*(pins[i].trigger) ^ (int)!!*(pins[i].edge); - bool force = *(pins[i].force); + bool trig = (int)hal_get_bool(pins[i].trigger) ^ (int)hal_get_bool(pins[i].edge); + bool force = hal_get_bool(pins[i].force); if ((en && trig && !slots[i].prevtrig) || (force && !slots[i].prevforce)) { print_slot(i); // Rising edge -> print message } diff --git a/src/hal/components/pwmgen.c b/src/hal/components/pwmgen.c index 3f4d0a720d9..3cfa9d08154 100644 --- a/src/hal/components/pwmgen.c +++ b/src/hal/components/pwmgen.c @@ -99,22 +99,22 @@ typedef struct { unsigned char output_type; unsigned char pwm_mode; unsigned char direction; - hal_bit_t *out[2]; /* pins for output signals */ + hal_bool_t out[2]; /* pins for output signals */ - hal_bit_t *enable; /* pin for enable signal */ - hal_float_t *value; /* command value */ - hal_float_t *scale; /* pin: scaling from value to duty cycle */ - hal_float_t *offset; /* pin: offset: this is added to duty cycle */ + hal_bool_t enable; /* pin for enable signal */ + hal_real_t value; /* command value */ + hal_real_t scale; /* pin: scaling from value to duty cycle */ + hal_real_t offset; /* pin: offset: this is added to duty cycle */ double old_scale; /* stored scale value */ double scale_recip; /* reciprocal value used for scaling */ - hal_float_t *pwm_freq; /* pin: (max) output frequency in Hz */ + hal_real_t pwm_freq; /* pin: (max) output frequency in Hz */ double old_pwm_freq; /* used to detect changes */ int periods; /* number of periods in PWM cycle */ double periods_recip; /* reciprocal */ - hal_bit_t *dither_pwm; /* 0 = pure PWM, 1 = dithered PWM */ - hal_float_t *min_dc; /* pin: minimum duty cycle */ - hal_float_t *max_dc; /* pin: maximum duty cycle */ - hal_float_t *curr_dc; /* pin: current duty cycle */ + hal_bool_t dither_pwm; /* 0 = pure PWM, 1 = dithered PWM */ + hal_real_t min_dc; /* pin: minimum duty cycle */ + hal_real_t max_dc; /* pin: maximum duty cycle */ + hal_real_t curr_dc; /* pin: current duty cycle */ } pwmgen_t; /* ptr to array of pwmgen_t structs in shared memory, 1 per channel */ @@ -316,11 +316,11 @@ static void make_pulses(void *arg, long period) if (pwmgen->output_type < 2) { /* PWM (and maybe DIR) output */ /* DIR is set by update(), we only do PWM */ - *(pwmgen->out[PWM_PIN]) = pwmgen->curr_output; + hal_set_bool(pwmgen->out[PWM_PIN], pwmgen->curr_output); } else { /* UP and DOWN output */ - *(pwmgen->out[UP_PIN]) = pwmgen->curr_output & ~pwmgen->direction; - *(pwmgen->out[DOWN_PIN]) = pwmgen->curr_output & pwmgen->direction; + hal_set_bool(pwmgen->out[UP_PIN], pwmgen->curr_output & ~pwmgen->direction); + hal_set_bool(pwmgen->out[DOWN_PIN], pwmgen->curr_output & pwmgen->direction); } /* move on to next PWM generator */ pwmgen++; @@ -344,42 +344,42 @@ static void update(void *arg, long period) /* validate duty cycle limits, both limits must be between 0.0 and 1.0 (inclusive) and max must be greater then min */ - if ( *(pwmgen->max_dc) > 1.0 ) { - *(pwmgen->max_dc) = 1.0; + if ( hal_get_real(pwmgen->max_dc) > 1.0 ) { + hal_set_real(pwmgen->max_dc, 1.0); } - if ( *(pwmgen->min_dc) > *(pwmgen->max_dc) ) { - *(pwmgen->min_dc) = *(pwmgen->max_dc); + if ( hal_get_real(pwmgen->min_dc) > hal_get_real(pwmgen->max_dc) ) { + hal_set_real(pwmgen->min_dc, hal_get_real(pwmgen->max_dc)); } - if ( *(pwmgen->min_dc) < 0.0 ) { - *(pwmgen->min_dc) = 0.0; + if ( hal_get_real(pwmgen->min_dc) < 0.0 ) { + hal_set_real(pwmgen->min_dc, 0.0); } - if ( *(pwmgen->max_dc) < *(pwmgen->min_dc) ) { - *(pwmgen->max_dc) = *(pwmgen->min_dc); + if ( hal_get_real(pwmgen->max_dc) < hal_get_real(pwmgen->min_dc) ) { + hal_set_real(pwmgen->max_dc, hal_get_real(pwmgen->min_dc)); } /* do scale calcs only when scale changes */ - if ( *(pwmgen->scale) != pwmgen->old_scale ) { + rtapi_real scale = hal_get_real(pwmgen->scale); + if ( scale != pwmgen->old_scale ) { /* get ready to detect future scale changes */ - pwmgen->old_scale = *(pwmgen->scale); + pwmgen->old_scale = scale; /* validate the new scale value */ - if ((*(pwmgen->scale) < 1e-20) - && (*(pwmgen->scale) > -1e-20)) { + if ((scale < 1e-20) && (scale > -1e-20)) { /* value too small, divide by zero is a bad thing */ - *(pwmgen->scale) = 1.0; + scale = hal_set_real(pwmgen->scale, 1.0); } /* we will need the reciprocal */ - pwmgen->scale_recip = 1.0 / *(pwmgen->scale); + pwmgen->scale_recip = 1.0 / scale; } - if ( *(pwmgen->enable) == 0 ) { + if ( hal_get_bool(pwmgen->enable) == 0 ) { new_pwm_mode = PWM_DISABLED; - } else if ( *(pwmgen->pwm_freq) == 0 ) { + } else if ( hal_get_real(pwmgen->pwm_freq) == 0 ) { new_pwm_mode = PWM_PDM; - } else if ( *(pwmgen->dither_pwm) != 0 ) { + } else if ( hal_get_bool(pwmgen->dither_pwm) != 0 ) { new_pwm_mode = PWM_DITHER; } else { new_pwm_mode = PWM_PURE; } /* force recalc if max_freq is changed */ - if ( *(pwmgen->pwm_freq) != pwmgen->old_pwm_freq ) { + if ( hal_get_real(pwmgen->pwm_freq) != pwmgen->old_pwm_freq ) { pwmgen->pwm_mode = PWM_DISABLED; } /* do the period calcs when mode, pwm_freq, or periodns changes */ @@ -388,35 +388,35 @@ static void update(void *arg, long period) /* disable output during calcs */ pwmgen->pwm_mode = PWM_DISABLED; /* validate max_freq */ - if ( *(pwmgen->pwm_freq) <= 0.0 ) { + if ( hal_get_real(pwmgen->pwm_freq) <= 0.0 ) { /* zero or negative means PDM mode */ - *(pwmgen->pwm_freq) = 0.0; + hal_set_real(pwmgen->pwm_freq, 0.0); pwmgen->period = periodns; } else { /* positive means PWM mode */ - if ( *(pwmgen->pwm_freq) < 0.5 ) { + if ( hal_get_real(pwmgen->pwm_freq) < 0.5 ) { /* min freq is 0.5 Hz (2 billion nsec period) */ - *(pwmgen->pwm_freq) = 0.5; - } else if ( *(pwmgen->pwm_freq) > ((1e9/2.0) / periodns) ) { + hal_set_real(pwmgen->pwm_freq, 0.5); + } else if ( hal_get_real(pwmgen->pwm_freq) > ((1e9/2.0) / periodns) ) { /* max freq is 2 base periods */ - *(pwmgen->pwm_freq) = (1e9/2.0) / periodns; + hal_set_real(pwmgen->pwm_freq, (1e9/2.0) / periodns); } if ( new_pwm_mode == PWM_PURE ) { /* period must be integral multiple of periodns */ - pwmgen->periods = (( 1e9 / *(pwmgen->pwm_freq) ) / periodns ) + 0.5; + pwmgen->periods = (( 1e9 / hal_get_real(pwmgen->pwm_freq) ) / periodns ) + 0.5; pwmgen->periods_recip = 1.0 / pwmgen->periods; pwmgen->period = pwmgen->periods * periodns; /* actual max freq after rounding */ - *(pwmgen->pwm_freq) = 1.0e9 / pwmgen->period; + hal_set_real(pwmgen->pwm_freq, 1.0e9 / pwmgen->period); } else { - pwmgen->period = 1.0e9 / *(pwmgen->pwm_freq); + pwmgen->period = 1.0e9 / hal_get_real(pwmgen->pwm_freq); } } /* save freq to detect changes */ - pwmgen->old_pwm_freq = *(pwmgen->pwm_freq); + pwmgen->old_pwm_freq = hal_get_real(pwmgen->pwm_freq); } /* convert value command to duty cycle */ - tmpdc = *(pwmgen->value) * pwmgen->scale_recip + *(pwmgen->offset); + tmpdc = hal_get_real(pwmgen->value) * pwmgen->scale_recip + hal_get_real(pwmgen->offset); if ( pwmgen->output_type == 0 ) { /* unidirectional mode, no negative output */ if ( tmpdc < 0.0 ) { @@ -425,18 +425,18 @@ static void update(void *arg, long period) } /* limit the duty cycle */ if (tmpdc >= 0.0) { - if ( tmpdc > *(pwmgen->max_dc) ) { - tmpdc = *(pwmgen->max_dc); - } else if ( tmpdc < *(pwmgen->min_dc) ) { - tmpdc = *(pwmgen->min_dc); + if ( tmpdc > hal_get_real(pwmgen->max_dc) ) { + tmpdc = hal_get_real(pwmgen->max_dc); + } else if ( tmpdc < hal_get_real(pwmgen->min_dc) ) { + tmpdc = hal_get_real(pwmgen->min_dc); } pwmgen->direction = 0; outdc = tmpdc; } else { - if ( tmpdc < -*(pwmgen->max_dc) ) { - tmpdc = -*(pwmgen->max_dc); - } else if ( tmpdc > -*(pwmgen->min_dc) ) { - tmpdc = -*(pwmgen->min_dc); + if ( tmpdc < -hal_get_real(pwmgen->max_dc) ) { + tmpdc = -hal_get_real(pwmgen->max_dc); + } else if ( tmpdc > -hal_get_real(pwmgen->min_dc) ) { + tmpdc = -hal_get_real(pwmgen->min_dc); } pwmgen->direction = 1; outdc = -tmpdc; @@ -447,18 +447,18 @@ static void update(void *arg, long period) pwmgen->high_time = high_periods * periodns; /* save rounded value to curr_dc pin */ if ( tmpdc >= 0 ) { - *(pwmgen->curr_dc) = high_periods * pwmgen->periods_recip; + hal_set_real(pwmgen->curr_dc, high_periods * pwmgen->periods_recip); } else { - *(pwmgen->curr_dc) = -high_periods * pwmgen->periods_recip; + hal_set_real(pwmgen->curr_dc, -high_periods * pwmgen->periods_recip); } } else { pwmgen->high_time = ( pwmgen->period * outdc ) + 0.5; /* save duty cycle to curr_dc pin */ - *(pwmgen->curr_dc) = tmpdc; + hal_set_real(pwmgen->curr_dc, tmpdc); } /* if using PWM/DIR outputs, set DIR pin */ if ( pwmgen->output_type == 1 ) { - *(pwmgen->out[DIR_PIN]) = pwmgen->direction; + hal_set_bool(pwmgen->out[DIR_PIN], pwmgen->direction); } /* save new mode */ pwmgen->pwm_mode = new_pwm_mode; @@ -486,97 +486,79 @@ static int export_pwmgen(int num, pwmgen_t * addr, int output_type) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pins */ - retval = hal_pin_float_newf(HAL_IO, &(addr->scale), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->scale), 1.0, "pwmgen.%d.scale", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IO, &(addr->offset), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->offset), 0.0, "pwmgen.%d.offset", num); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IO, &(addr->dither_pwm), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IO, &(addr->dither_pwm), 0, "pwmgen.%d.dither-pwm", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IO, &(addr->pwm_freq), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->pwm_freq), 0.0, "pwmgen.%d.pwm-freq", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IO, &(addr->min_dc), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->min_dc), 0.0, "pwmgen.%d.min-dc", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IO, &(addr->max_dc), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->max_dc), 1.0, "pwmgen.%d.max-dc", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->curr_dc), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->curr_dc), 0.0, "pwmgen.%d.curr-dc", num); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->enable), 0, "pwmgen.%d.enable", num); if (retval != 0) { return retval; } - *(addr->enable) = 0; - retval = hal_pin_float_newf(HAL_IN, &(addr->value), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->value), 0.0, "pwmgen.%d.value", num); if (retval != 0) { return retval; } - *(addr->value) = 0.0; if (output_type == 2) { /* export UP/DOWN pins */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->out[UP_PIN]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->out[UP_PIN]), 0, "pwmgen.%d.up", num); if (retval != 0) { return retval; } - /* init the pin */ - *(addr->out[UP_PIN]) = 0; - retval = hal_pin_bit_newf(HAL_OUT, &(addr->out[DOWN_PIN]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->out[DOWN_PIN]), 0, "pwmgen.%d.down", num); if (retval != 0) { return retval; } - /* init the pin */ - *(addr->out[DOWN_PIN]) = 0; } else { /* export PWM pin */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->out[PWM_PIN]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->out[PWM_PIN]), 0, "pwmgen.%d.pwm", num); if (retval != 0) { return retval; } - /* init the pin */ - *(addr->out[PWM_PIN]) = 0; if ( output_type == 1 ) { /* export DIR pin */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->out[DIR_PIN]), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->out[DIR_PIN]), 0, "pwmgen.%d.dir", num); if (retval != 0) { return retval; } - /* init the pin */ - *(addr->out[DIR_PIN]) = 0; } } - /* set default pin values */ - *(addr->scale) = 1.0; - *(addr->offset) = 0.0; - *(addr->dither_pwm) = 0; - *(addr->pwm_freq) = 0; - *(addr->min_dc) = 0.0; - *(addr->max_dc) = 1.0; - *(addr->curr_dc) = 0.0; /* init other fields */ addr->period = 50000; addr->high_time = 0; @@ -586,7 +568,7 @@ static int export_pwmgen(int num, pwmgen_t * addr, int output_type) addr->output_type = output_type; addr->pwm_mode = PWM_DISABLED; addr->direction = 0; - addr->old_scale = *(addr->scale) + 1.0; + addr->old_scale = hal_get_real(addr->scale) + 1.0; addr->old_pwm_freq = -1; /* restore saved message level */ rtapi_set_msg_level(msg); diff --git a/src/hal/components/radiobutton.comp b/src/hal/components/radiobutton.comp index bdab2219460..c3938516abb 100644 --- a/src/hal/components/radiobutton.comp +++ b/src/hal/components/radiobutton.comp @@ -9,11 +9,11 @@ The \\fBselected\\fR pin will indicate which set of outputs is currently active. Note that channel-0 should be used to provide the default values."""; -pin in bit sel-##[32:personality] "Inputs to select a channel"; -pin out bit out-##[32:personality] "output selected"; -pin out signed selected = 0 "indicates which output is currently active"; -pin in float input-##[32:personality] "Possible output values"; -pin out float value "currently-selected output value"; +pin in bool sel-##[32:personality] "Inputs to select a channel"; +pin out bool out-##[32:personality] "output selected"; +pin out si32 selected = 0 "indicates which output is currently active"; +pin in real input-##[32:personality] "Possible output values"; +pin out real value "currently-selected output value"; function _; option period no; @@ -23,18 +23,18 @@ author "Andy Pugh"; ;; FUNCTION(_){ - int i; - for(i = 0; i < personality; i++){ + rtapi_s32 s = selected; + for(int i = 0; i < personality; i++){ if(sel(i) !=0){ - selected = i; + s = selected_set(i); } } - for(i = 0; i < personality; i++){ - if(i == selected){ - out(i) = 1; - value = input(i); + for(int i = 0; i < personality; i++){ + if(i == s){ + out_set(i, 1); + value_set(input(i)); } else { - out(i) = 0; + out_set(i, 0); } } } diff --git a/src/hal/components/raster.comp b/src/hal/components/raster.comp index e7786a1c6c5..553c6df9515 100644 --- a/src/hal/components/raster.comp +++ b/src/hal/components/raster.comp @@ -1,24 +1,24 @@ component raster "Outputs laser power based upon pre programmed rastering data"; -pin in float position "input coordinate for raster"; -pin in bit reset "resets the component"; -pin in port program "pixel data used by the raster"; -pin in bit run "starts the raster"; - -pin out bit enabled = 0 "When a valid raster program is running."; -pin out float output = -1 "current output level command"; -pin out bit fault = 0 "If error has occurred"; -pin out signed fault_code = 0 "Code of fault"; -pin out signed state = 0 "current state"; -pin out float program_position = 0.0 "base position of program at run start"; -pin out float program_offset = 0.0 "offset to start of pixel data"; -pin out signed bpp = 0 "bits per pixel."; -pin out float ppu = 0.0 "pixels per unit"; -pin out signed count = 0 "pixel count"; -pin out float bitmap_position = 0.0 "calculated position in bitmap"; -pin out float current_pixel_value = -1.0 "current loaded pixel value"; -pin out float previous_pixel_value = -1.0 "previously loaded pixel value"; -pin out signed current_pixel_index = -1 "currently loaded pixel index"; -pin out float fraction = 0.0; +pin in real position "input coordinate for raster"; +pin in bool reset "resets the component"; +pin in port program "pixel data used by the raster"; +pin in bool run "starts the raster"; + +pin out bool enabled = 0 "When a valid raster program is running."; +pin out real output = -1 "current output level command"; +pin out bool fault = 0 "If error has occurred"; +pin out si32 fault_code = 0 "Code of fault"; +pin out si32 state = 0 "current state"; +pin out real program_position = 0.0 "base position of program at run start"; +pin out real program_offset = 0.0 "offset to start of pixel data"; +pin out si32 bpp = 0 "bits per pixel."; +pin out real ppu = 0.0 "pixels per unit"; +pin out si32 count = 0 "pixel count"; +pin out real bitmap_position = 0.0 "calculated position in bitmap"; +pin out real current_pixel_value = -1.0 "current loaded pixel value"; +pin out real previous_pixel_value = -1.0 "previously loaded pixel value"; +pin out si32 current_pixel_index = -1 "currently loaded pixel index"; +pin out real fraction = 0.0; description """ The raster component converts a single raster program line to laser output. @@ -52,7 +52,7 @@ A program line format is as follows: * *number_of_pixels*: an integer that indicates the length of the raster line in pixels. The length of the rasterline in machine units would be number_of_pixels / pixels_per_unit - + * *pixel_data*: a series of hexadeicmal digits ([0-9][a-f][A-F]) the represents the pixel data. *bits_per_pixel* determines the resolution of a pixel and how many hexadecimal digits per pixel. pixel data characters have no delimiter @@ -86,16 +86,16 @@ enum { } raster_error; typedef enum { - IDLE = 0, - RUN = 1, + IDLE = 0, + RUN = 1, FAULT = 2 } raster_state; -bool float_eq(hal_float_t a, hal_float_t b) { +static bool float_eq(rtapi_real a, rtapi_real b) { return fabs(a-b) < epsilon; } -bool read_float(const hal_port_t *port, hal_float_t* value) { +static bool read_float(const hal_port_t *port, hal_real_t value) { char data[32]; int available = hal_port_readable(port); char* pos; @@ -108,7 +108,7 @@ bool read_float(const hal_port_t *port, hal_float_t* value) { return false; } - *value = strtod(data, &pos); + hal_set_real(value, strtod(data, &pos)); if(pos == data) { return false; @@ -119,7 +119,7 @@ bool read_float(const hal_port_t *port, hal_float_t* value) { return true; } -bool read_int(const hal_port_t *port, hal_s32_t* value) { +static bool read_int(const hal_port_t *port, hal_sint_t value) { char data[10]; long val; int available = hal_port_readable(port); @@ -134,7 +134,7 @@ bool read_int(const hal_port_t *port, hal_s32_t* value) { } val = strtoul(data, &pos, 10); - + if(pos == data) { return false; } @@ -143,7 +143,7 @@ bool read_int(const hal_port_t *port, hal_s32_t* value) { return false; } - *value = val; + hal_set_si32(value, val); hal_port_peek_commit(port, pos - data + 1); @@ -152,12 +152,12 @@ bool read_int(const hal_port_t *port, hal_s32_t* value) { /* - reads and consumes a pixel value for the program port. + reads and consumes a pixel value for the program port. pixel data is encoded as ascii hex values [0-9][A-F] with each character representing 4 bits of data pixels bpp must be defined in increments of 4. a pixel value with all 1 bits is a special value considered "off" for the raster and no power will be output */ -bool read_pixel_data(const hal_port_t *port, int bits_per_pixel, hal_float_t* power) { +static bool read_pixel_data(const hal_port_t *port, int bits_per_pixel, hal_real_t power) { char data[8]; long value = 0; unsigned int off = 0xFFFFFFFF >> (32 - bits_per_pixel); @@ -180,89 +180,89 @@ bool read_pixel_data(const hal_port_t *port, int bits_per_pixel, hal_float_t* po if(value < 0) { return false; } - + if(value == off) { - *power = -1.0; + hal_set_real(power, -1.0); } else { - *power = 100.0 * ((hal_float_t)value)/((hal_float_t)(max)); + hal_set_real(power, 100.0 * ((rtapi_real)value)/((rtapi_real)max)); } return true; } -FUNCTION(_) { +FUNCTION(_) { - output = -1.0; - enabled = 0; + output_set(-1.0); + enabled_set(0); if (reset) { - state = IDLE; - fault = 0; - fault_code = ERROR_NONE; + state_set(IDLE); + fault_set(0); + fault_code_set(ERROR_NONE); hal_port_clear(program_ptr); } else if (state == FAULT) { - fault = 1; + fault_set(1); } else if (state == IDLE) { - bitmap_position = 0.0; - current_pixel_value = -1.0; - previous_pixel_value = -1.0; - current_pixel_index = -1; + bitmap_position_set(0.0); + current_pixel_value_set(-1.0); + previous_pixel_value_set(-1.0); + current_pixel_index_set(-1); //when run is asserted, the port must be full of 1 line of raster data if(run) { - if(!read_float(program_ptr, &program_offset)) { - state = FAULT; - fault_code = ERROR_INVALID_OFFSET; - } else if(!read_int(program_ptr, &bpp) || (bpp == 0) || (bpp > 32) || ((bpp % 4) != 0)) { - state = FAULT; - fault_code = ERROR_INVALID_BPP; - } else if(!read_float(program_ptr, &ppu) || (ppu <= 0.0)) { - state = FAULT; - fault_code = ERROR_INVALID_PPU; - } else if(!read_int(program_ptr, &count) || (count < 2)) { - state = FAULT; - fault_code = ERROR_INVALID_COUNT; + if(!read_float(program_ptr, program_offset_ptr)) { + state_set(FAULT); + fault_code_set(ERROR_INVALID_OFFSET); + } else if(!read_int(program_ptr, bpp_ptr) || (bpp == 0) || (bpp > 32) || ((bpp % 4) != 0)) { + state_set(FAULT); + fault_code_set(ERROR_INVALID_BPP); + } else if(!read_float(program_ptr, ppu_ptr) || (ppu <= 0.0)) { + state_set(FAULT); + fault_code_set(ERROR_INVALID_PPU); + } else if(!read_int(program_ptr, count_ptr) || (count < 2)) { + state_set(FAULT); + fault_code_set(ERROR_INVALID_COUNT); } else if((int)hal_port_readable(program_ptr) != ((bpp / 4) * count)) { - state = FAULT; - fault_code = ERROR_PROGWRONGSIZE; + state_set(FAULT); + fault_code_set(ERROR_PROGWRONGSIZE); } else { - state = RUN; - program_position = position; + state_set(RUN); + program_position_set(position); } - } + } } else if (state == RUN) { - bitmap_position = (position - (program_position + program_offset)) * ppu * (program_offset < 0.0 ? -1.0 : 1.0); + bitmap_position_set((position - (program_position + program_offset)) * ppu * (program_offset < 0.0 ? -1.0 : 1.0)); if(!run) { - state = IDLE; + state_set(IDLE); hal_port_clear(program_ptr); } else { - enabled = 1; + enabled_set(1); - //consume pixel data as needed from programng port - while((current_pixel_index < (((int)count)-1)) && ((hal_float_t)current_pixel_index < bitmap_position)) { - current_pixel_index = current_pixel_index+1; - previous_pixel_value = current_pixel_value; + //consume pixel data as needed from programming port + while((current_pixel_index < (((int)count)-1)) && ((rtapi_real)current_pixel_index < bitmap_position)) { + current_pixel_index_set(current_pixel_index+1); + previous_pixel_value_set(current_pixel_value); - if(!read_pixel_data(program_ptr, bpp, ¤t_pixel_value)) { - state = FAULT; - fault_code = ERROR_BADPIXELDATA; + if(!read_pixel_data(program_ptr, bpp, current_pixel_value_ptr)) { + state_set(FAULT); + fault_code_set(ERROR_BADPIXELDATA); return; } } - + //compute current output value - if(float_eq(bitmap_position, (hal_float_t)current_pixel_index)) { - output = current_pixel_value; - } else if(float_eq(bitmap_position, (hal_float_t)(current_pixel_index-1))) { - output = previous_pixel_value; - } else if((bitmap_position < (hal_float_t)current_pixel_index) - && (bitmap_position > (hal_float_t)(current_pixel_index-1)) - && (current_pixel_value >= 0.0) + if(float_eq(bitmap_position, (rtapi_real)current_pixel_index)) { + output_set(current_pixel_value); + } else if(float_eq(bitmap_position, (rtapi_real)(current_pixel_index-1))) { + output_set(previous_pixel_value); + } else if((bitmap_position < (rtapi_real)current_pixel_index) + && (bitmap_position > (rtapi_real)(current_pixel_index-1)) + && (current_pixel_value >= 0.0) && (previous_pixel_value >= 0.0)) { - fraction = bitmap_position - (hal_float_t)(current_pixel_index - 1); - output = fraction*(current_pixel_value-previous_pixel_value) + previous_pixel_value; + fraction_set(bitmap_position - (rtapi_real)(current_pixel_index - 1)); + output_set(fraction*(current_pixel_value-previous_pixel_value) + previous_pixel_value); } } } diff --git a/src/hal/components/reset.comp b/src/hal/components/reset.comp index 40914225297..c1eb7b39091 100644 --- a/src/hal/components/reset.comp +++ b/src/hal/components/reset.comp @@ -37,18 +37,18 @@ ******************************************************************************/ component reset "Resets an IO signal"; -pin in bit trigger "Trigger input"; -pin io u32 out_u32 = 0 "Unsigned 32 bit integer output value"; -pin in u32 reset_u32 = 0 "Unsigned 32 bit integer reset value"; -pin io s32 out_s32 = 0 "Signed 32 bit integer output value"; -pin in s32 reset_s32 = 0 "Signed 32 bit integer reset value"; -pin io float out_float = 0.0 "Float output value"; -pin in float reset_float = 0.0 "Float reset value"; -pin io bit out_bit = false "Bit integer output value"; -pin in bit reset_bit = false "Bit reset value"; -pin in bit retriggerable = true "Allow additional edges to reset"; -pin in bit rising = true "Trigger on rising edge"; -pin in bit falling = false "Trigger on falling edge"; +pin in bool trigger "Trigger input"; +pin io ui32 out_u32 = 0 "Unsigned 32 bool integer output value"; +pin in ui32 reset_u32 = 0 "Unsigned 32 bool integer reset value"; +pin io si32 out_s32 = 0 "Signed 32 bool integer output value"; +pin in si32 reset_s32 = 0 "Signed 32 bool integer reset value"; +pin io real out_float = 0.0 "Float output value"; +pin in real reset_float = 0.0 "Float reset value"; +pin io bool out_bit = false "Bit integer output value"; +pin in bool reset_bit = false "Bit reset value"; +pin in bool retriggerable = true "Allow additional edges to reset"; +pin in bool rising = true "Trigger on rising edge"; +pin in bool falling = false "Trigger on falling edge"; option period no; function _ "Update the output value"; description """ @@ -61,16 +61,16 @@ passed via the input pins reset_float/s32/u32/bit. """; license "GPL"; author "Alexander Rössler"; -variable hal_bit_t last_trigger = false; +variable rtapi_bool last_trigger = false; ;; FUNCTION(_) { - if (((rising && (trigger)) || (falling && (!trigger))) - && (trigger != last_trigger)) + rtapi_bool new_trigger = trigger; + if ((new_trigger != last_trigger) && ((rising && (new_trigger)) || (falling && (!new_trigger)))) { - out_u32 = reset_u32; - out_s32 = reset_s32; - out_float = reset_float; - out_bit = reset_bit; + out_u32_set(reset_u32); + out_s32_set(reset_s32); + out_float_set(reset_float); + out_bit_set(reset_bit); } - last_trigger = trigger; + last_trigger = new_trigger; } diff --git a/src/hal/components/safety_latch.comp b/src/hal/components/safety_latch.comp index 6d67dc07527..6c30637b27e 100644 --- a/src/hal/components/safety_latch.comp +++ b/src/hal/components/safety_latch.comp @@ -52,20 +52,20 @@ return to false when reset is set to true. The inputs pin min and max clamp the error count value to a specified range. """; -pin in bit error_in = false "Error Input"; -pin in s32 heal = 1 "Heal when ok per tick"; -pin in s32 harm = 1 "Harm when error per tick"; -pin in bit latching = true "If a reset is necessary to heal an error"; -pin in bit reset = false "Reset input"; -pin in s32 threshold = 100 "Error output threshold"; -pin in s32 min = 0 "Minimum count"; -pin in s32 max = 1000 "Maximum count"; -pin in bit enable = true "If not enabled the error count is passed to the output"; -pin out s32 count = 0 "Current count"; -pin out bit error_out = false "Error output"; -pin out bit ok_out = true "Ok output"; +pin in bool error_in = false "Error Input"; +pin in si32 heal = 1 "Heal when ok per tick"; +pin in si32 harm = 1 "Harm when error per tick"; +pin in bool latching = true "If a reset is necessary to heal an error"; +pin in bool reset = false "Reset input"; +pin in si32 threshold = 100 "Error output threshold"; +pin in si32 min_ = 0 "Minimum count"; +pin in si32 max_ = 1000 "Maximum count"; +pin in bool enable = true "If not enabled the error count is passed to the output"; +pin out si32 count = 0 "Current count"; +pin out bool error_out = false "Error output"; +pin out bool ok_out = true "Ok output"; -variable hal_bit_t last_reset = false; +variable bool last_reset = false; option period no; function _; @@ -79,38 +79,38 @@ FUNCTION(_) { if (!enable) { - error_out = error_in; - ok_out = !error_in; - count = 0; + error_out_set(error_in); + ok_out_set(!error_in); + count_set(0); } else { if ((reset ^ last_reset) && reset) { - count = 0; - error_out = false; - ok_out = true; + count_set(0); + error_out_set(false); + ok_out_set(true); } if (error_in) { - count += harm; + count_set(count + harm); } else { - count -= heal; + count_set(count - heal); } - count = MIN(MAX(count, min), max); + count_set(MIN(MAX(count, min_), max_)); if (count >= threshold) { - error_out = true; - ok_out = false; + error_out_set(true); + ok_out_set(false); } else if (!latching) { - error_out = false; - ok_out = true; + error_out_set(false); + ok_out_set(true); } } diff --git a/src/hal/components/sample_hold.comp b/src/hal/components/sample_hold.comp index c1da283ea02..bf64254c20b 100644 --- a/src/hal/components/sample_hold.comp +++ b/src/hal/components/sample_hold.comp @@ -1,7 +1,7 @@ component sample_hold "Sample and Hold"; -pin in s32 in; -pin in bit hold; -pin out s32 out; +pin in si32 in; +pin in bool hold; +pin out si32 out; option period no; function _; see_also "*tristate*(9)"; @@ -10,6 +10,6 @@ author "Stephen Wille Padnos"; ;; FUNCTION(_) { if (!hold) { - out = in; + out_set(in); } } diff --git a/src/hal/components/sampler.c b/src/hal/components/sampler.c index 52eb015013f..e695ec42f4e 100644 --- a/src/hal/components/sampler.c +++ b/src/hal/components/sampler.c @@ -77,13 +77,13 @@ RTAPI_MP_ARRAY_INT(depth,MAX_SAMPLERS,"fifo depth"); typedef struct { hal_stream_t fifo; /* pointer to user/RT fifo */ - hal_s32_t *curr_depth; /* pin: current fifo depth */ - hal_bit_t *full; /* pin: overrun flag */ - hal_bit_t *enable; /* pin: enable sampling */ - hal_s32_t *overruns; /* pin: number of overruns */ - hal_s32_t *sample_num; /* pin: sample ID / timestamp */ + hal_sint_t curr_depth; /* pin: current fifo depth */ + hal_bool_t full; /* pin: overrun flag */ + hal_bool_t enable; /* pin: enable sampling */ + hal_sint_t overruns; /* pin: number of overruns */ + hal_sint_t sample_num; /* pin: sample ID / timestamp */ + hal_refs_u pins[HAL_STREAM_MAX_PINS]; int num_pins; - pin_data_t pins[HAL_STREAM_MAX_PINS]; } sampler_t; /* other globals */ @@ -153,56 +153,39 @@ void rtapi_app_exit(void) static void sample(void *arg, long period) { (void)period; - sampler_t *samp; - pin_data_t *pptr; - int n; + sampler_t *samp = (sampler_t *)arg; /* point at sampler struct in HAL shmem */ - /* point at sampler struct in HAL shmem */ - samp = arg; /* are we enabled? */ - if ( ! *(samp->enable) ) { - *(samp->curr_depth) = hal_stream_depth(&samp->fifo); - *(samp->full) = !hal_stream_writable(&samp->fifo); - return; + if (!hal_get_bool(samp->enable)) { + hal_set_si32(samp->curr_depth, hal_stream_depth(&samp->fifo)); + hal_set_bool(samp->full, !hal_stream_writable(&samp->fifo)); + return; } - /* point at pins in hal shmem */ - pptr = samp->pins; - union hal_stream_data data[HAL_STREAM_MAX_PINS], *dptr=data; + /* copy data from HAL pins to fifo */ + union hal_stream_data data[HAL_STREAM_MAX_PINS]; int num_pins = hal_stream_element_count(&samp->fifo); - for ( n = 0 ; n < num_pins ; n++ ) { - switch ( hal_stream_element_type(&samp->fifo, n) ) { - case HAL_FLOAT: - dptr->f = *(pptr->hfloat); - break; - case HAL_BIT: - if ( *(pptr->hbit) ) { - dptr->b = 1; - } else { - dptr->b = 0; - } - break; - case HAL_U32: - dptr->u = *(pptr->hu32); - break; - case HAL_S32: - dptr->s = *(pptr->hs32); - break; - default: - break; - } - dptr++; - pptr++; + for (int n = 0; n < num_pins; n++) { + switch (hal_stream_element_type(&samp->fifo, n)) { + case HAL_FLOAT: data[n].f = hal_get_real(samp->pins[n].r); break; + case HAL_S32: data[n].s = hal_get_si32(samp->pins[n].s); break; + case HAL_U32: data[n].u = hal_get_ui32(samp->pins[n].u); break; + case HAL_S64: data[n].l = hal_get_sint(samp->pins[n].s); break; + case HAL_U64: data[n].k = hal_get_uint(samp->pins[n].u); break; + case HAL_BIT: data[n].b = hal_get_bool(samp->pins[n].b); break; + default: + break; + } } if ( hal_stream_write(&samp->fifo, data) < 0) { - /* fifo is full, data is lost */ + /* fifo is full, data is lost */ /* log the overrun */ - (*samp->overruns)++; - *(samp->full) = 1; - *(samp->curr_depth) = hal_stream_maxdepth(&samp->fifo); + hal_set_si32(samp->overruns, hal_get_si32(samp->overruns) + 1); + hal_set_bool(samp->full, 1); + hal_set_si32(samp->curr_depth, hal_stream_maxdepth(&samp->fifo)); } else { - *(samp->full) = 0; - *(samp->curr_depth) = hal_stream_depth(&samp->fifo); + hal_set_bool(samp->full, 0); + hal_set_si32(samp->curr_depth, hal_stream_depth(&samp->fifo)); } } @@ -212,91 +195,62 @@ static void sample(void *arg, long period) static int init_sampler(int num, sampler_t *str) { - int retval, usefp, n; - pin_data_t *pptr; - char buf[HAL_NAME_LEN + 1]; + int retval; + static const char strbase[] = "sampler."; /* export "standard" pins and params */ - retval = hal_pin_bit_newf(HAL_OUT, &(str->full), comp_id, - "sampler.%d.full", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &str->full, 0, "%s%d.full", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: 'full' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: 'full' pin export failed\n"); + return -EIO; } - retval = hal_pin_bit_newf(HAL_IN, &(str->enable), comp_id, - "sampler.%d.enable", num); + retval = hal_pin_new_bool(comp_id, HAL_IN, &str->enable, 1, "%s%d.enable", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: 'enable' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: 'enable' pin export failed\n"); + return -EIO; } - retval = hal_pin_s32_newf(HAL_OUT, &(str->curr_depth), comp_id, - "sampler.%d.curr-depth", num); + retval = hal_pin_new_si32(comp_id, HAL_OUT, &str->curr_depth, 0, "%s%d.curr-depth", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLEr: ERROR: 'curr_depth' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: 'curr_depth' pin export failed\n"); + return -EIO; } - retval = hal_pin_s32_newf(HAL_IO, &(str->overruns), comp_id, - "sampler.%d.overruns", num); + retval = hal_pin_new_si32(comp_id, HAL_IO, &str->overruns, 0, "%s%d.overruns", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: 'overruns' parameter export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: 'overruns' parameter export failed\n"); + return -EIO; } - retval = hal_pin_s32_newf(HAL_IO, &(str->sample_num), comp_id, - "sampler.%d.sample-num", num); + retval = hal_pin_new_si32(comp_id, HAL_IO, &str->sample_num, 0, "%s%d.sample-num", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: 'sample-num' parameter export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: 'sample-num' parameter export failed\n"); + return -EIO; } - /* init the standard pins and params */ - *(str->full) = 0; - *(str->enable) = 1; - *(str->curr_depth) = 0; - *(str->overruns) = 0; - *(str->sample_num) = 0; - pptr = str->pins; - usefp = 0; + /* export user specified pins (the ones that sample data) */ - for ( n = 0 ; n < hal_stream_element_count(&str->fifo) ; n++ ) { - rtapi_snprintf(buf, sizeof(buf), "sampler.%d.pin.%d", num, n); - retval = hal_pin_new(buf, hal_stream_element_type(&str->fifo, n), HAL_IN, (void **)pptr, comp_id ); - if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: pin '%s' export failed\n", buf); - return -EIO; - } - /* init the pin value */ - switch ( hal_stream_element_type(&str->fifo, n) ) { - case HAL_FLOAT: - *(pptr->hfloat) = 0.0; - usefp = 1; - break; - case HAL_BIT: - *(pptr->hbit) = 0; - break; - case HAL_U32: - *(pptr->hu32) = 0; - break; - case HAL_S32: - *(pptr->hs32) = 0; - break; - default: - break; - } - pptr++; + for (int n = 0; n < hal_stream_element_count(&str->fifo); n++) { + static const char pstr[] = "sampler.%d.pin.%d"; + int type; + switch(type = hal_stream_element_type(&str->fifo, n)) { + case HAL_FLOAT: retval = hal_pin_new_real(comp_id, HAL_IN, &str->pins[n].r, 0.0, pstr, num, n); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_IN, &str->pins[n].s, 0, pstr, num, n); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_IN, &str->pins[n].u, 0, pstr, num, n); break; + case HAL_S64: retval = hal_pin_new_sint(comp_id, HAL_IN, &str->pins[n].s, 0, pstr, num, n); break; + case HAL_U64: retval = hal_pin_new_uint(comp_id, HAL_IN, &str->pins[n].u, 0, pstr, num, n); break; + case HAL_BIT: retval = hal_pin_new_bool(comp_id, HAL_IN, &str->pins[n].b, 0, pstr, num, n); break; + default: + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: stream type for pin %d has bad type %d\n", n, type); + return -EIO; + } + if (retval != 0 ) { + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: pin '%d' export failed\n", n); + return -EIO; + } } /* export update function */ - retval = hal_export_functf(sample, str, usefp, 0, comp_id, "sampler.%d", num); + retval = hal_export_functf(sample, str, 1, 0, comp_id, "%s%d", strbase, num); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "SAMPLER: ERROR: function export failed\n"); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "SAMPLER: ERROR: function export failed\n"); + return retval; } return 0; } - diff --git a/src/hal/components/sampler_usr.c b/src/hal/components/sampler_usr.c index 3b8e73c4407..1562aaf3ece 100644 --- a/src/hal/components/sampler_usr.c +++ b/src/hal/components/sampler_usr.c @@ -226,6 +226,12 @@ int main(int argc, char **argv) case HAL_S32: printf ( "%ld ", (long)buf[n].s); break; + case HAL_U64: + printf ( "%llu ", (unsigned long long)buf[n].k); + break; + case HAL_S64: + printf ( "%lld ", (long long)buf[n].l); + break; default: /* better not happen */ goto out; diff --git a/src/hal/components/scale.comp b/src/hal/components/scale.comp index 4745b29a859..bae802415eb 100644 --- a/src/hal/components/scale.comp +++ b/src/hal/components/scale.comp @@ -1,13 +1,13 @@ component scale "LinuxCNC HAL component that applies a scale and offset to its input"; -pin in float in; -pin in float gain; -pin in float offset; -pin out float out "out = in * gain + offset"; +pin in real in; +pin in real gain; +pin in real offset; +pin out real out "out = in * gain + offset"; option period no; function _; license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - out = in * gain + offset; + out_set(in * gain + offset); } diff --git a/src/hal/components/scaled_s32_sums.comp b/src/hal/components/scaled_s32_sums.comp index f8b3b3e251e..86e4f611c75 100644 --- a/src/hal/components/scaled_s32_sums.comp +++ b/src/hal/components/scaled_s32_sums.comp @@ -1,20 +1,20 @@ component scaled_s32_sums "Sum of four inputs (each with a scale)"; see_also "sum2(9), weighted_sum(9)"; -pin in s32 in0; -pin in s32 in1; -pin in s32 in2; -pin in s32 in3; -pin in float scale0 = 1.0; -pin in float scale1 = 1.0; -pin in float scale2 = 1.0; -pin in float scale3 = 1.0; -pin out s32 out_s; -pin out float out_f "out-s = out-f = (in0 * scale0) + (in1 * scale1) + (in2 * scale2) + (in3 * scale3)"; +pin in si32 in0; +pin in si32 in1; +pin in si32 in2; +pin in si32 in3; +pin in real scale0 = 1.0; +pin in real scale1 = 1.0; +pin in real scale2 = 1.0; +pin in real scale3 = 1.0; +pin out si32 out_s; +pin out real out_f "out-s = out-f = (in0 * scale0) + (in1 * scale1) + (in2 * scale2) + (in3 * scale3)"; option period no; function _; license "GPL"; author "Chris S Morley"; ;; FUNCTION(_) { - out_s = out_f = in0 * scale0 + in1 * scale1 + in2 * scale2 + in3 * scale3; + out_s_set(out_f_set(in0 * scale0 + in1 * scale1 + in2 * scale2 + in3 * scale3)); } diff --git a/src/hal/components/select8.comp b/src/hal/components/select8.comp index 814d2e5b600..da4c0e5bc70 100644 --- a/src/hal/components/select8.comp +++ b/src/hal/components/select8.comp @@ -1,7 +1,7 @@ component select8 "8-bit binary match detector"; -pin in bit enable = TRUE "Set enable to FALSE to cause all outputs to be set FALSE."; -pin in s32 sel "The number of the output to set TRUE. All other outputs well be set FALSE."; -pin out bit out#[8] "Output bits. If enable is set and the sel input is between 0 and 7, then the corresponding output bit will be set true."; +pin in bool enable = TRUE "Set enable to FALSE to cause all outputs to be set FALSE."; +pin in si32 sel "The number of the output to set TRUE. All other outputs well be set FALSE."; +pin out bool out#[8] "Output bits. If enable is set and the sel input is between 0 and 7, then the corresponding output bit will be set true."; option period no; function _; see_also "*demux*(9)"; @@ -9,14 +9,12 @@ license "GPL"; author "Stephen Wille Padnos"; ;; FUNCTION(_) { - hal_s32_t temp_sel; - int i, temp_enable; - temp_sel = sel; - temp_enable = enable; - for (i=0;i<8;i++) { + rtapi_s32 temp_sel = sel; + rtapi_bool temp_enable = enable; + for (int i=0;i<8;i++) { if (!temp_enable || temp_sel!=i) - out(i)=0; + out_set(i, 0); else - out(i)=1; + out_set(i, 1); } } diff --git a/src/hal/components/siggen.c b/src/hal/components/siggen.c index 3b3af15af7c..b1c84d6560c 100644 --- a/src/hal/components/siggen.c +++ b/src/hal/components/siggen.c @@ -97,17 +97,17 @@ RTAPI_MP_ARRAY_STRING(names, MAX_CHAN, "names of siggen"); */ typedef struct { - hal_float_t *square; /* pin: output */ - hal_float_t *sawtooth; /* pin: output */ - hal_float_t *triangle; /* pin: output */ - hal_float_t *sine; /* pin: output */ - hal_float_t *cosine; /* pin: output */ - hal_bit_t *clock; /* pin: output */ - hal_float_t *frequency; /* pin: frequency */ - hal_float_t *amplitude; /* pin: amplitude */ - hal_float_t *offset; /* pin: offset */ - hal_bit_t *reset; /* pin: reset */ - double index; /* position within output cycle */ + hal_real_t square; /* pin: output */ + hal_real_t sawtooth; /* pin: output */ + hal_real_t triangle; /* pin: output */ + hal_real_t sine; /* pin: output */ + hal_real_t cosine; /* pin: output */ + hal_bool_t clock; /* pin: output */ + hal_real_t frequency; /* pin: frequency */ + hal_real_t amplitude; /* pin: amplitude */ + hal_real_t offset; /* pin: offset */ + hal_bool_t reset; /* pin: reset */ + double index; /* position within output cycle */ } hal_siggen_t; /* pointer to array of siggen_t structs in shared memory, 1 per gen */ @@ -215,14 +215,14 @@ static void calc_siggen(void *arg, long period) tmp1 = period * 0.000000001; /* calculate how much of an output cycle that has passed */ - tmp2 = *(siggen->frequency) * tmp1; + tmp2 = hal_get_real(siggen->frequency) * tmp1; /* limit frequency to comply with Nyquist limit */ if ( tmp2 > 0.5 ) { - *(siggen->frequency) = 0.5 / tmp1; + hal_set_real(siggen->frequency, 0.5 / tmp1); tmp2 = 0.5; } /* index ramps from 0.0 to 0.99999 for each output cycle */ - if ( *(siggen->reset) ) { + if ( hal_get_bool(siggen->reset) ) { siggen->index = 0.5; } else { siggen->index += tmp2; @@ -236,19 +236,21 @@ static void calc_siggen(void *arg, long period) /* tmp1 steps from -1.0 to +1.0 when index passes 0.5 */ if ( siggen->index > 0.5 ) { tmp1 = 1.0; - *(siggen->clock) = 1; + hal_set_bool(siggen->clock, 1); } else { tmp1 = -1.0; - *(siggen->clock) = 0; + hal_set_bool(siggen->clock, 0); } + rtapi_real offset = hal_get_real(siggen->offset); + rtapi_real amplitude = hal_get_real(siggen->amplitude); /* apply scaling and offset, and write to output */ - *(siggen->square) = (tmp1 * *(siggen->amplitude)) + *(siggen->offset); + hal_set_real(siggen->square, (tmp1 * amplitude) + offset); /* generate the sawtooth wave output */ /* tmp2 ramps from -1.0 to +1.0 as index goes from 0 to 1 */ tmp2 = (siggen->index * 2.0) - 1.0; /* apply scaling and offset, and write to output */ - *(siggen->sawtooth) = (tmp2 * *(siggen->amplitude)) + *(siggen->offset); + hal_set_real(siggen->sawtooth, (tmp2 * amplitude) + offset); /* generate the triangle wave output */ /* tmp2 ramps from -2.0 to +2.0 as index goes from 0 to 1 */ @@ -256,17 +258,17 @@ static void calc_siggen(void *arg, long period) /* flip first half of ramp, now goes from +1 to -1 to +1 */ tmp2 = (tmp2 * tmp1) - 1.0; /* apply scaling and offset, and write to output */ - *(siggen->triangle) = (tmp2 * *(siggen->amplitude)) + *(siggen->offset); + hal_set_real(siggen->triangle, (tmp2 * amplitude) + offset); /* generate the sine wave output */ /* tmp1 is angle in radians */ tmp1 = siggen->index * (2.0 * 3.1415927); /* get sine, apply scaling and offset, and write to output */ - *(siggen->sine) = (sin(tmp1) * *(siggen->amplitude)) + *(siggen->offset); + hal_set_real(siggen->sine, (sin(tmp1) * amplitude) + offset); /* generate the cosine wave output */ /* get cosine, apply scaling and offset, and write to output */ - *(siggen->cosine) = (cos(tmp1) * *(siggen->amplitude)) + *(siggen->offset); + hal_set_real(siggen->cosine, (cos(tmp1) * amplitude) + offset); /* done */ } @@ -279,66 +281,57 @@ static int export_siggen(int num, hal_siggen_t * addr,char* prefix) int retval; /* export pins */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->square), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->square), 0.0, "%s.square", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->sawtooth), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->sawtooth), 0.0, "%s.sawtooth", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->triangle), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->triangle), 0.0, "%s.triangle", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->sine), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->sine), 0.0, "%s.sine", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->cosine), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->cosine), 0.0, "%s.cosine", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(addr->clock), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->clock), 0, "%s.clock", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IN, &(addr->frequency), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->frequency), 1.0, "%s.frequency", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IN, &(addr->amplitude), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->amplitude), 1.0, "%s.amplitude", prefix); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IN, &(addr->offset), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->offset), 0.0, "%s.offset", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_IN, &(addr->reset), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->reset), 0, "%s.reset", prefix); if (retval != 0) { return retval; } /* init all structure members */ - *(addr->square) = 0.0; - *(addr->sawtooth) = 0.0; - *(addr->triangle) = 0.0; - *(addr->sine) = 0.0; - *(addr->cosine) = 0.0; - *(addr->clock) = 0; - *(addr->frequency) = 1.0; - *(addr->amplitude) = 1.0; - *(addr->offset) = 0.0; addr->index = 0.0; /* export function for this loop */ retval = diff --git a/src/hal/components/sim_axis_hardware.comp b/src/hal/components/sim_axis_hardware.comp index b89fdbc966d..8a77da95298 100644 --- a/src/hal/components/sim_axis_hardware.comp +++ b/src/hal/components/sim_axis_hardware.comp @@ -7,156 +7,156 @@ This component creates simulated home and limit switches based on the current po It currently can supply simulation for X, tandem X, Y, tandem Y, Z, U, V, and A axes. """; -pin in float Xcurrent_pos "The current position on the axis - eg connect to joint.0.motor-pos-fb"; -pin in float X2current_pos; -pin in float Ycurrent_pos; -pin in float Y2current_pos; -pin in float Zcurrent_pos; -pin in float Acurrent_pos; -pin in float Ucurrent_pos; -pin in float Vcurrent_pos; - -pin in float Xhomesw_pos =1 "The position of the home switch"; -pin in float X2homesw_pos =1; -pin in float Yhomesw_pos =1; -pin in float Y2homesw_pos =1; -pin in float Zhomesw_pos =1; -pin in float Ahomesw_pos =1; -pin in float Uhomesw_pos =1; -pin in float Vhomesw_pos =1; - -pin in float Xmaxsw_upper "The upper range of the maximum limit switch, above this is false."; -pin in float X2maxsw_upper; -pin in float Ymaxsw_upper; -pin in float Y2maxsw_upper; -pin in float Zmaxsw_upper; -pin in float Amaxsw_upper; -pin in float Umaxsw_upper; -pin in float Vmaxsw_upper; - -pin in float Xmaxsw_lower "The lower range of the maximum limit switch, below this is false."; -pin in float X2maxsw_lower; -pin in float Ymaxsw_lower; -pin in float Y2maxsw_lower; -pin in float Zmaxsw_lower; -pin in float Amaxsw_lower; -pin in float Umaxsw_lower; -pin in float Vmaxsw_lower; - -pin in float Xminsw_upper "The upper range of the minimum limit switch, above this is false."; -pin in float X2minsw_upper; -pin in float Yminsw_upper; -pin in float Y2minsw_upper; -pin in float Zminsw_upper; -pin in float Aminsw_upper; -pin in float Uminsw_upper; -pin in float Vminsw_upper; - -pin in float Xminsw_lower "The lower range of the minimum limit switch, below this is false."; -pin in float X2minsw_lower; -pin in float Yminsw_lower; -pin in float Y2minsw_lower; -pin in float Zminsw_lower; -pin in float Aminsw_lower; -pin in float Uminsw_lower; -pin in float Vminsw_lower; - -pin in float Xhomesw_hyst =.025 "range that home switch will be true +- half this to the home position"; -pin in float X2homesw_hyst =.025; -pin in float Yhomesw_hyst =.025; -pin in float Y2homesw_hyst =.025; -pin in float Zhomesw_hyst =.025; -pin in float Ahomesw_hyst =.025; -pin in float Uhomesw_hyst =.025; -pin in float Vhomesw_hyst =.025; - -pin in bit Xhoming "True is homing in progress"; -pin in bit X2homing; -pin in bit Yhoming; -pin in bit Y2homing; -pin in bit Zhoming; -pin in bit Ahoming; -pin in bit Uhoming; -pin in bit Vhoming; - -pin out bit Xhomesw_out "Home switch for the X axis"; -pin out bit X2homesw_out; -pin out bit Yhomesw_out; -pin out bit Y2homesw_out; -pin out bit Zhomesw_out; -pin out bit Ahomesw_out; -pin out bit Uhomesw_out; -pin out bit Vhomesw_out; -pin out bit homesw_all; - -pin out bit Xmaxsw_out "Max limit switch"; -pin out bit Xminsw_out "min limit switch"; -pin out bit Xbothsw_out "True for both max and min limit switch"; - -pin out bit X2maxsw_out; -pin out bit X2minsw_out; -pin out bit X2bothsw_out; - -pin out bit Ymaxsw_out; -pin out bit Yminsw_out; -pin out bit Ybothsw_out; - -pin out bit Y2maxsw_out; -pin out bit Y2minsw_out; -pin out bit Y2bothsw_out; - -pin out bit Zmaxsw_out; -pin out bit Zminsw_out; -pin out bit Zbothsw_out; - -pin out bit Amaxsw_out; -pin out bit Aminsw_out; -pin out bit Abothsw_out; - -pin out bit Umaxsw_out; -pin out bit Uminsw_out; -pin out bit Ubothsw_out; - -pin out bit Vmaxsw_out; -pin out bit Vminsw_out; -pin out bit Vbothsw_out; - -pin out bit limitsw_all; -pin out bit limitsw_homesw_all "True for all limits and all home."; - -pin out bit Xmaxsw_homesw_out; -pin out bit Xminsw_homesw_out; -pin out bit Xbothsw_homesw_out; - -pin out bit X2maxsw_homesw_out; -pin out bit X2minsw_homesw_out; -pin out bit X2bothsw_homesw_out; - -pin out bit Ymaxsw_homesw_out; -pin out bit Yminsw_homesw_out; -pin out bit Ybothsw_homesw_out; - -pin out bit Y2maxsw_homesw_out; -pin out bit Y2minsw_homesw_out; -pin out bit Y2bothsw_homesw_out; - -pin out bit Zmaxsw_homesw_out; -pin out bit Zminsw_homesw_out; -pin out bit Zbothsw_homesw_out; - -pin out bit Amaxsw_homesw_out; -pin out bit Aminsw_homesw_out; -pin out bit Abothsw_homesw_out; - -pin out bit Umaxsw_homesw_out; -pin out bit Uminsw_homesw_out; -pin out bit Ubothsw_homesw_out; - -pin out bit Vmaxsw_homesw_out; -pin out bit Vminsw_homesw_out; -pin out bit Vbothsw_homesw_out; - -pin in float limit_offset =.01 "how much the limit switches are offset from inputted position. added to max, subtracted from min"; +pin in real Xcurrent_pos "The current position on the axis - eg connect to joint.0.motor-pos-fb"; +pin in real X2current_pos; +pin in real Ycurrent_pos; +pin in real Y2current_pos; +pin in real Zcurrent_pos; +pin in real Acurrent_pos; +pin in real Ucurrent_pos; +pin in real Vcurrent_pos; + +pin in real Xhomesw_pos =1 "The position of the home switch"; +pin in real X2homesw_pos =1; +pin in real Yhomesw_pos =1; +pin in real Y2homesw_pos =1; +pin in real Zhomesw_pos =1; +pin in real Ahomesw_pos =1; +pin in real Uhomesw_pos =1; +pin in real Vhomesw_pos =1; + +pin in real Xmaxsw_upper "The upper range of the maximum limit switch, above this is false."; +pin in real X2maxsw_upper; +pin in real Ymaxsw_upper; +pin in real Y2maxsw_upper; +pin in real Zmaxsw_upper; +pin in real Amaxsw_upper; +pin in real Umaxsw_upper; +pin in real Vmaxsw_upper; + +pin in real Xmaxsw_lower "The lower range of the maximum limit switch, below this is false."; +pin in real X2maxsw_lower; +pin in real Ymaxsw_lower; +pin in real Y2maxsw_lower; +pin in real Zmaxsw_lower; +pin in real Amaxsw_lower; +pin in real Umaxsw_lower; +pin in real Vmaxsw_lower; + +pin in real Xminsw_upper "The upper range of the minimum limit switch, above this is false."; +pin in real X2minsw_upper; +pin in real Yminsw_upper; +pin in real Y2minsw_upper; +pin in real Zminsw_upper; +pin in real Aminsw_upper; +pin in real Uminsw_upper; +pin in real Vminsw_upper; + +pin in real Xminsw_lower "The lower range of the minimum limit switch, below this is false."; +pin in real X2minsw_lower; +pin in real Yminsw_lower; +pin in real Y2minsw_lower; +pin in real Zminsw_lower; +pin in real Aminsw_lower; +pin in real Uminsw_lower; +pin in real Vminsw_lower; + +pin in real Xhomesw_hyst =.025 "range that home switch will be true +- half this to the home position"; +pin in real X2homesw_hyst =.025; +pin in real Yhomesw_hyst =.025; +pin in real Y2homesw_hyst =.025; +pin in real Zhomesw_hyst =.025; +pin in real Ahomesw_hyst =.025; +pin in real Uhomesw_hyst =.025; +pin in real Vhomesw_hyst =.025; + +pin in bool Xhoming "True is homing in progress"; +pin in bool X2homing; +pin in bool Yhoming; +pin in bool Y2homing; +pin in bool Zhoming; +pin in bool Ahoming; +pin in bool Uhoming; +pin in bool Vhoming; + +pin out bool Xhomesw_out "Home switch for the X axis"; +pin out bool X2homesw_out; +pin out bool Yhomesw_out; +pin out bool Y2homesw_out; +pin out bool Zhomesw_out; +pin out bool Ahomesw_out; +pin out bool Uhomesw_out; +pin out bool Vhomesw_out; +pin out bool homesw_all; + +pin out bool Xmaxsw_out "Max limit switch"; +pin out bool Xminsw_out "min limit switch"; +pin out bool Xbothsw_out "True for both max and min limit switch"; + +pin out bool X2maxsw_out; +pin out bool X2minsw_out; +pin out bool X2bothsw_out; + +pin out bool Ymaxsw_out; +pin out bool Yminsw_out; +pin out bool Ybothsw_out; + +pin out bool Y2maxsw_out; +pin out bool Y2minsw_out; +pin out bool Y2bothsw_out; + +pin out bool Zmaxsw_out; +pin out bool Zminsw_out; +pin out bool Zbothsw_out; + +pin out bool Amaxsw_out; +pin out bool Aminsw_out; +pin out bool Abothsw_out; + +pin out bool Umaxsw_out; +pin out bool Uminsw_out; +pin out bool Ubothsw_out; + +pin out bool Vmaxsw_out; +pin out bool Vminsw_out; +pin out bool Vbothsw_out; + +pin out bool limitsw_all; +pin out bool limitsw_homesw_all "True for all limits and all home."; + +pin out bool Xmaxsw_homesw_out; +pin out bool Xminsw_homesw_out; +pin out bool Xbothsw_homesw_out; + +pin out bool X2maxsw_homesw_out; +pin out bool X2minsw_homesw_out; +pin out bool X2bothsw_homesw_out; + +pin out bool Ymaxsw_homesw_out; +pin out bool Yminsw_homesw_out; +pin out bool Ybothsw_homesw_out; + +pin out bool Y2maxsw_homesw_out; +pin out bool Y2minsw_homesw_out; +pin out bool Y2bothsw_homesw_out; + +pin out bool Zmaxsw_homesw_out; +pin out bool Zminsw_homesw_out; +pin out bool Zbothsw_homesw_out; + +pin out bool Amaxsw_homesw_out; +pin out bool Aminsw_homesw_out; +pin out bool Abothsw_homesw_out; + +pin out bool Umaxsw_homesw_out; +pin out bool Uminsw_homesw_out; +pin out bool Ubothsw_homesw_out; + +pin out bool Vmaxsw_homesw_out; +pin out bool Vminsw_homesw_out; +pin out bool Vbothsw_homesw_out; + +pin in real limit_offset =.01 "how much the limit switches are offset from inputted position. added to max, subtracted from min"; option period no; function update; @@ -165,9 +165,9 @@ author "Chris S Morley"; ;; /* private comparator function */ - int comp(double in0, double in1, double hyst) { - double tmp; - double halfhyst; + int comp(rtapi_real in0, rtapi_real in1, rtapi_real hyst) { + rtapi_real tmp; + rtapi_real halfhyst; tmp = in1 - in0; halfhyst = 0.5 * hyst; @@ -181,7 +181,7 @@ author "Chris S Morley"; } /* private window comparator function */ - int wcomp (double in, double max_, double min_){ + int wcomp (rtapi_real in, rtapi_real max_, rtapi_real min_){ return !((in >= max_)|| (in <= min_)); } @@ -189,82 +189,82 @@ author "Chris S Morley"; FUNCTION(update) { /*set home switches */ -Xhomesw_out = comp(Xhomesw_pos,Xcurrent_pos,Xhomesw_hyst); -X2homesw_out = comp(X2homesw_pos,X2current_pos,X2homesw_hyst); -Yhomesw_out = comp(Yhomesw_pos,Ycurrent_pos,Yhomesw_hyst); -Y2homesw_out = comp(Y2homesw_pos,Y2current_pos,Y2homesw_hyst); -Zhomesw_out = comp(Zhomesw_pos,Zcurrent_pos,Zhomesw_hyst); -Ahomesw_out = comp(Ahomesw_pos,Acurrent_pos,Ahomesw_hyst); -Uhomesw_out = comp(Uhomesw_pos,Ucurrent_pos,Uhomesw_hyst); -Vhomesw_out = comp(Vhomesw_pos,Vcurrent_pos,Vhomesw_hyst); +Xhomesw_out_set(comp(Xhomesw_pos,Xcurrent_pos,Xhomesw_hyst)); +X2homesw_out_set(comp(X2homesw_pos,X2current_pos,X2homesw_hyst)); +Yhomesw_out_set(comp(Yhomesw_pos,Ycurrent_pos,Yhomesw_hyst)); +Y2homesw_out_set(comp(Y2homesw_pos,Y2current_pos,Y2homesw_hyst)); +Zhomesw_out_set(comp(Zhomesw_pos,Zcurrent_pos,Zhomesw_hyst)); +Ahomesw_out_set(comp(Ahomesw_pos,Acurrent_pos,Ahomesw_hyst)); +Uhomesw_out_set(comp(Uhomesw_pos,Ucurrent_pos,Uhomesw_hyst)); +Vhomesw_out_set(comp(Vhomesw_pos,Vcurrent_pos,Vhomesw_hyst)); int homing = Xhoming || X2homing || Yhoming || Y2homing || Zhoming || Ahoming || Uhoming || Vhoming; -homesw_all = (Xhomesw_out || X2homesw_out || Yhomesw_out || Y2homesw_out || - Zhomesw_out || Ahomesw_out || Uhomesw_out || Vhomesw_out) && homing; +homesw_all_set((Xhomesw_out || X2homesw_out || Yhomesw_out || Y2homesw_out || + Zhomesw_out || Ahomesw_out || Uhomesw_out || Vhomesw_out) && homing); /* set limit switches */ -Xmaxsw_out = wcomp(Xcurrent_pos,Xmaxsw_upper,Xmaxsw_lower+limit_offset); -Xminsw_out = wcomp(Xcurrent_pos,Xminsw_upper-limit_offset,Xminsw_lower); -Xbothsw_out = (Xmaxsw_out || Xminsw_out) && !homing; +Xmaxsw_out_set(wcomp(Xcurrent_pos,Xmaxsw_upper,Xmaxsw_lower+limit_offset)); +Xminsw_out_set(wcomp(Xcurrent_pos,Xminsw_upper-limit_offset,Xminsw_lower)); +Xbothsw_out_set((Xmaxsw_out || Xminsw_out) && !homing); -X2maxsw_out = wcomp(X2current_pos,X2maxsw_upper,X2maxsw_lower+limit_offset); -X2minsw_out = wcomp(X2current_pos,X2minsw_upper-limit_offset,X2minsw_lower); -X2bothsw_out = (X2maxsw_out || X2minsw_out) && !homing; +X2maxsw_out_set(wcomp(X2current_pos,X2maxsw_upper,X2maxsw_lower+limit_offset)); +X2minsw_out_set(wcomp(X2current_pos,X2minsw_upper-limit_offset,X2minsw_lower)); +X2bothsw_out_set((X2maxsw_out || X2minsw_out) && !homing); -Ymaxsw_out = wcomp(Ycurrent_pos,Ymaxsw_upper,Ymaxsw_lower+limit_offset); -Yminsw_out = wcomp(Ycurrent_pos,Yminsw_upper-limit_offset,Yminsw_lower); -Ybothsw_out = (Ymaxsw_out || Yminsw_out) && !homing; +Ymaxsw_out_set(wcomp(Ycurrent_pos,Ymaxsw_upper,Ymaxsw_lower+limit_offset)); +Yminsw_out_set(wcomp(Ycurrent_pos,Yminsw_upper-limit_offset,Yminsw_lower)); +Ybothsw_out_set((Ymaxsw_out || Yminsw_out) && !homing); -Y2maxsw_out = wcomp(Y2current_pos,Y2maxsw_upper,Y2maxsw_lower+limit_offset); -Y2minsw_out = wcomp(Y2current_pos,Y2minsw_upper-limit_offset,Y2minsw_lower); -Y2bothsw_out = (Y2maxsw_out || Y2minsw_out) && !homing; +Y2maxsw_out_set(wcomp(Y2current_pos,Y2maxsw_upper,Y2maxsw_lower+limit_offset)); +Y2minsw_out_set(wcomp(Y2current_pos,Y2minsw_upper-limit_offset,Y2minsw_lower)); +Y2bothsw_out_set((Y2maxsw_out || Y2minsw_out) && !homing); -Zmaxsw_out = wcomp(Zcurrent_pos,Zmaxsw_upper,Zmaxsw_lower+limit_offset); -Zminsw_out = wcomp(Zcurrent_pos,Zminsw_upper-limit_offset,Zminsw_lower); -Zbothsw_out = (Zmaxsw_out || Zminsw_out) && !homing; +Zmaxsw_out_set(wcomp(Zcurrent_pos,Zmaxsw_upper,Zmaxsw_lower+limit_offset)); +Zminsw_out_set(wcomp(Zcurrent_pos,Zminsw_upper-limit_offset,Zminsw_lower)); +Zbothsw_out_set((Zmaxsw_out || Zminsw_out) && !homing); -Amaxsw_out = wcomp(Acurrent_pos,Amaxsw_upper,Amaxsw_lower+limit_offset); -Aminsw_out = wcomp(Acurrent_pos,Aminsw_upper-limit_offset,Aminsw_lower); -Abothsw_out = (Amaxsw_out || Aminsw_out) && !homing; +Amaxsw_out_set(wcomp(Acurrent_pos,Amaxsw_upper,Amaxsw_lower+limit_offset)); +Aminsw_out_set(wcomp(Acurrent_pos,Aminsw_upper-limit_offset,Aminsw_lower)); +Abothsw_out_set((Amaxsw_out || Aminsw_out) && !homing); -Umaxsw_out = wcomp(Ucurrent_pos,Umaxsw_upper,Umaxsw_lower+limit_offset); -Uminsw_out = wcomp(Ucurrent_pos,Uminsw_upper-limit_offset,Uminsw_lower); -Ubothsw_out = (Umaxsw_out || Uminsw_out) && !homing; +Umaxsw_out_set(wcomp(Ucurrent_pos,Umaxsw_upper,Umaxsw_lower+limit_offset)); +Uminsw_out_set(wcomp(Ucurrent_pos,Uminsw_upper-limit_offset,Uminsw_lower)); +Ubothsw_out_set((Umaxsw_out || Uminsw_out) && !homing); -Vmaxsw_out = wcomp(Vcurrent_pos,Vmaxsw_upper,Vmaxsw_lower+limit_offset); -Vminsw_out = wcomp(Vcurrent_pos,Vminsw_upper-limit_offset,Vminsw_lower); -Vbothsw_out = (Vmaxsw_out || Vminsw_out) && !homing; +Vmaxsw_out_set(wcomp(Vcurrent_pos,Vmaxsw_upper,Vmaxsw_lower+limit_offset)); +Vminsw_out_set(wcomp(Vcurrent_pos,Vminsw_upper-limit_offset,Vminsw_lower)); +Vbothsw_out_set((Vmaxsw_out || Vminsw_out) && !homing); -limitsw_all = (Xbothsw_out || X2bothsw_out || Ybothsw_out || Y2bothsw_out +limitsw_all_set(Xbothsw_out || X2bothsw_out || Ybothsw_out || Y2bothsw_out || Zbothsw_out || Abothsw_out || Ubothsw_out || Vbothsw_out); /* set limit and home switches */ -limitsw_homesw_all = (homesw_all || limitsw_all); -Xmaxsw_homesw_out = (Xmaxsw_out || Xhomesw_out); -Xminsw_homesw_out = (Xminsw_out || Xhomesw_out); -Xbothsw_homesw_out = (Xbothsw_out || Xhomesw_out); - -X2maxsw_homesw_out = (X2maxsw_out || X2homesw_out); -X2minsw_homesw_out = (X2minsw_out || X2homesw_out); -X2bothsw_homesw_out = (X2bothsw_out || X2homesw_out); - -Ymaxsw_homesw_out = (Ymaxsw_out || Yhomesw_out); -Yminsw_homesw_out = (Yminsw_out || Yhomesw_out); -Ybothsw_homesw_out = (Ybothsw_out || Yhomesw_out); - -Y2maxsw_homesw_out = (Y2maxsw_out || Y2homesw_out); -Y2minsw_homesw_out = (Y2minsw_out || Y2homesw_out); -Y2bothsw_homesw_out = (Y2bothsw_out || Y2homesw_out); - -Zmaxsw_homesw_out = (Zmaxsw_out || Zhomesw_out); -Zminsw_homesw_out = (Zminsw_out || Zhomesw_out); -Zbothsw_homesw_out = (Zbothsw_out || Zhomesw_out); - -Umaxsw_homesw_out = (Umaxsw_out || Uhomesw_out); -Uminsw_homesw_out = (Uminsw_out || Uhomesw_out); -Ubothsw_homesw_out = (Ubothsw_out || Uhomesw_out); - -Vmaxsw_homesw_out = (Vmaxsw_out || Vhomesw_out); -Vminsw_homesw_out = (Vminsw_out || Vhomesw_out); -Vbothsw_homesw_out = (Vbothsw_out || Vhomesw_out); +limitsw_homesw_all_set((homesw_all || limitsw_all)); +Xmaxsw_homesw_out_set((Xmaxsw_out || Xhomesw_out)); +Xminsw_homesw_out_set((Xminsw_out || Xhomesw_out)); +Xbothsw_homesw_out_set((Xbothsw_out || Xhomesw_out)); + +X2maxsw_homesw_out_set((X2maxsw_out || X2homesw_out)); +X2minsw_homesw_out_set((X2minsw_out || X2homesw_out)); +X2bothsw_homesw_out_set((X2bothsw_out || X2homesw_out)); + +Ymaxsw_homesw_out_set((Ymaxsw_out || Yhomesw_out)); +Yminsw_homesw_out_set((Yminsw_out || Yhomesw_out)); +Ybothsw_homesw_out_set((Ybothsw_out || Yhomesw_out)); + +Y2maxsw_homesw_out_set((Y2maxsw_out || Y2homesw_out)); +Y2minsw_homesw_out_set((Y2minsw_out || Y2homesw_out)); +Y2bothsw_homesw_out_set((Y2bothsw_out || Y2homesw_out)); + +Zmaxsw_homesw_out_set((Zmaxsw_out || Zhomesw_out)); +Zminsw_homesw_out_set((Zminsw_out || Zhomesw_out)); +Zbothsw_homesw_out_set((Zbothsw_out || Zhomesw_out)); + +Umaxsw_homesw_out_set((Umaxsw_out || Uhomesw_out)); +Uminsw_homesw_out_set((Uminsw_out || Uhomesw_out)); +Ubothsw_homesw_out_set((Ubothsw_out || Uhomesw_out)); + +Vmaxsw_homesw_out_set((Vmaxsw_out || Vhomesw_out)); +Vminsw_homesw_out_set((Vminsw_out || Vhomesw_out)); +Vbothsw_homesw_out_set((Vbothsw_out || Vhomesw_out)); } diff --git a/src/hal/components/sim_encoder.c b/src/hal/components/sim_encoder.c index 6a9a133383c..0351b835ece 100644 --- a/src/hal/components/sim_encoder.c +++ b/src/hal/components/sim_encoder.c @@ -90,13 +90,13 @@ typedef struct { unsigned long accum; /* frequency generator accumulator */ signed char state; /* current quadrature state */ long cycle; /* current cycle */ - hal_bit_t *phaseA; /* pins for output signals */ - hal_bit_t *phaseB; /* pins for output signals */ - hal_bit_t *phaseZ; /* pins for output signals */ - hal_u32_t *ppr; /* pin: pulses per revolution */ - hal_float_t *scale; /* pin: pulses per revolution */ - hal_float_t *speed; /* pin: speed in revs/second */ - hal_s32_t *rawcounts; /* pin: raw counts */ + hal_bool_t phaseA; /* pins for output signals */ + hal_bool_t phaseB; /* pins for output signals */ + hal_bool_t phaseZ; /* pins for output signals */ + hal_uint_t ppr; /* pin: pulses per revolution */ + hal_real_t scale; /* pin: pulses per revolution */ + hal_real_t speed; /* pin: speed in revs/second */ + hal_sint_t rawcounts; /* pin: raw counts */ double old_scale; /* internal, used to detect changes */ double scale_mult; /* internal, reciprocal of scale */ } sim_enc_t; @@ -257,7 +257,7 @@ static void make_pulses(void *arg, long period) /* get direction bit, 1 if negative, 0 if positive */ dir = sim_enc->addval >> 31; if ( dir ) { - (*sim_enc->rawcounts) --; + hal_set_si32(sim_enc->rawcounts, hal_get_si32(sim_enc->rawcounts) - 1); /* negative rotation, decrement state, detect underflow */ if (--(sim_enc->state) < 0) { /* state underflow, roll over */ @@ -265,19 +265,19 @@ static void make_pulses(void *arg, long period) /* decrement cycle, detect underflow */ if (--(sim_enc->cycle) < 0) { /* cycle underflow, roll over */ - sim_enc->cycle += *(sim_enc->ppr); + sim_enc->cycle += hal_get_ui32(sim_enc->ppr); } } } else { - (*sim_enc->rawcounts) ++; + hal_set_si32(sim_enc->rawcounts, hal_get_si32(sim_enc->rawcounts) + 1); /* positive rotation, increment state, detect overflow */ if (++(sim_enc->state) > 3) { /* state overflow, roll over */ sim_enc->state = 0; /* increment cycle, detect overflow */ - if (++(sim_enc->cycle) >= *(sim_enc->ppr)) { + if (++(sim_enc->cycle) >= hal_get_ui32(sim_enc->ppr)) { /* cycle overflow, roll over */ - sim_enc->cycle -= *(sim_enc->ppr); + sim_enc->cycle -= hal_get_ui32(sim_enc->ppr); } } } @@ -285,30 +285,26 @@ static void make_pulses(void *arg, long period) /* generate outputs */ switch (sim_enc->state) { case 0: - *(sim_enc->phaseA) = 1; - *(sim_enc->phaseB) = 0; + hal_set_bool(sim_enc->phaseA, 1); + hal_set_bool(sim_enc->phaseB, 0); break; case 1: - *(sim_enc->phaseA) = 1; - *(sim_enc->phaseB) = 1; + hal_set_bool(sim_enc->phaseA, 1); + hal_set_bool(sim_enc->phaseB, 1); break; case 2: - *(sim_enc->phaseA) = 0; - *(sim_enc->phaseB) = 1; + hal_set_bool(sim_enc->phaseA, 0); + hal_set_bool(sim_enc->phaseB, 1); break; case 3: - *(sim_enc->phaseA) = 0; - *(sim_enc->phaseB) = 0; + hal_set_bool(sim_enc->phaseA, 0); + hal_set_bool(sim_enc->phaseB, 0); break; default: /* illegal state, reset to legal one */ sim_enc->state = 0; } - if ((sim_enc->state == 0) && (sim_enc->cycle == 0)) { - *(sim_enc->phaseZ) = 1; - } else { - *(sim_enc->phaseZ) = 0; - } + hal_set_bool(sim_enc->phaseZ, (sim_enc->state == 0) && (sim_enc->cycle == 0)); /* move on to next 'encoder' */ sim_enc++; } @@ -337,21 +333,22 @@ static void update_speed(void *arg, long period) sim_enc = arg; for (n = 0; n < howmany; n++) { /* check for change in scale value */ - if ( *(sim_enc->scale) != sim_enc->old_scale ) { + rtapi_real scale = hal_get_real(sim_enc->scale); + if ( scale != sim_enc->old_scale ) { /* save new scale to detect future changes */ - sim_enc->old_scale = *(sim_enc->scale); + sim_enc->old_scale = scale; /* scale value has changed, test and update it */ - if ((*(sim_enc->scale) < 1e-20) && (*(sim_enc->scale) > -1e-20)) { + if ((scale < 1e-20) && (scale > -1e-20)) { /* value too small, divide by zero is a bad thing */ - *(sim_enc->scale) = 1.0; + scale = hal_set_real(sim_enc->scale, 1.0); } /* we actually want the reciprocal */ - sim_enc->scale_mult = 1.0 / *(sim_enc->scale); + sim_enc->scale_mult = 1.0 / scale; } /* convert speed command (user units) to revs/sec */ - rev_sec = *(sim_enc->speed) * sim_enc->scale_mult; + rev_sec = hal_get_real(sim_enc->speed) * sim_enc->scale_mult; /* convert speed command (revs per sec) to counts/sec */ - freq = rev_sec * (*(sim_enc->ppr)) * 4.0; + freq = rev_sec * (hal_get_ui32(sim_enc->ppr)) * 4.0; /* limit the commanded frequency */ if (freq > maxf) { freq = maxf; @@ -380,48 +377,45 @@ static int export_sim_enc(sim_enc_t * addr, char *prefix) msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); /* export param variable for pulses per rev */ - retval = hal_pin_u32_newf(HAL_IO, &(addr->ppr), comp_id, + retval = hal_pin_new_ui32(comp_id, HAL_IO, &(addr->ppr), 100, "%s.ppr", prefix); if (retval != 0) { return retval; } /* export param variable for scaling */ - retval = hal_pin_float_newf(HAL_IO, &(addr->scale), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->scale), 1.0, "%s.scale", prefix); if (retval != 0) { return retval; } /* export pin for speed command */ - retval = hal_pin_float_newf(HAL_IN, &(addr->speed), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->speed), 0.0, "%s.speed", prefix); if (retval != 0) { return retval; } /* export pins for output phases */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phaseA), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phaseA), 0, "%s.phase-A", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phaseB), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phaseB), 0, "%s.phase-B", prefix); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phaseZ), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phaseZ), 0, "%s.phase-Z", prefix); if (retval != 0) { return retval; } /* export pin for rawcounts */ - retval = hal_pin_s32_newf(HAL_IN, &(addr->rawcounts), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_IN, &(addr->rawcounts), 0, "%s.rawcounts", prefix); if (retval != 0) { return retval; } - /* init parameters */ - *(addr->ppr) = 100; - *(addr->scale) = 1.0; /* init internal vars */ addr->old_scale = 0.0; addr->scale_mult = 1.0; @@ -430,10 +424,6 @@ static int export_sim_enc(sim_enc_t * addr, char *prefix) addr->addval = 0; addr->state = 0; addr->cycle = 0; - /* init the outputs */ - *(addr->phaseA) = 0; - *(addr->phaseB) = 0; - *(addr->phaseZ) = 0; /* restore saved message level */ rtapi_set_msg_level(msg); return 0; diff --git a/src/hal/components/sim_home_switch.comp b/src/hal/components/sim_home_switch.comp index b819644c6d1..0a0ce092164 100644 --- a/src/hal/components/sim_home_switch.comp +++ b/src/hal/components/sim_home_switch.comp @@ -8,16 +8,16 @@ A pin (index-enable) is provided for use when *[JOINT_n]HOME_USE_INDEX* is specified to reset the I/O pin *joint.N.index-enable*. """; -pin in float cur_pos "Current position (typically: joint.n.motor-pos-fb)"; -pin in float home_pos = 1 "Home switch position"; -pin in float hysteresis = 0.1"Travel required to backoff (hysteresis)"; -pin out bit home_sw"Home switch activated"; +pin in real cur_pos "Current position (typically: joint.n.motor-pos-fb)"; +pin in real home_pos = 1 "Home switch position"; +pin in real hysteresis = 0.1"Travel required to backoff (hysteresis)"; +pin out bool home_sw"Home switch activated"; -pin io bit index_enable "typ: connect to joint.N.index-enable"; -pin in float index_delay_ms = 10 "delay in msec to reset index-enable"; +pin io bool index_enable "typ: connect to joint.N.index-enable"; +pin in real index_delay_ms = 10 "delay in msec to reset index-enable"; variable int old_index_enable; -variable double index_timer_ms; +variable rtapi_real index_timer_ms; function _; license "GPL"; @@ -29,30 +29,30 @@ FUNCTION(_) { if (home_pos >= 0) { // home switch is on positive side if (cur_pos >= home_pos) { - home_sw = 1; + home_sw_set(1); } else { if (cur_pos <= (home_pos - hysteresis) ) { - home_sw = 0; + home_sw_set(0); } else { if (home_sw) { - home_sw = 1; + home_sw_set(1); } else { - home_sw = 0; + home_sw_set(0); } } } } else { // negative home switch location if (cur_pos <= home_pos) { - home_sw = 1; + home_sw_set(1); } else { if (cur_pos >= (home_pos + hysteresis) ) { - home_sw = 0; + home_sw_set(0); } else { if (home_sw) { - home_sw = 1; + home_sw_set(1); } else { - home_sw = 0; + home_sw_set(0); } } } @@ -63,7 +63,7 @@ FUNCTION(_) { index_timer_ms -= period * 1e-6; // period is in nS if (index_timer_ms <= 0) { index_timer_ms = 0; - index_enable = 0; + index_enable_set(0); return; } } diff --git a/src/hal/components/sim_matrix_kb.comp b/src/hal/components/sim_matrix_kb.comp index 912e1676324..aabe7915b4f 100644 --- a/src/hal/components/sim_matrix_kb.comp +++ b/src/hal/components/sim_matrix_kb.comp @@ -1,15 +1,15 @@ component sim_matrix_kb "convert HAL pin inputs to keycodes"; -pin out u32 out "pin that outputs the Keycode"; +pin out ui32 out "pin that outputs the Keycode"; -pin in bit button.c00.r##[8] "array of inputs"; -pin in bit button.c01.r##[8] "array of inputs"; -pin in bit button.c02.r##[8] "array of inputs"; -pin in bit button.c03.r##[8] "array of inputs"; -pin in bit button.c04.r##[8] "array of inputs"; -pin in bit button.c05.r##[8] "array of inputs"; -pin in bit button.c06.r##[8] "array of inputs"; -pin in bit button.c07.r##[8] "array of inputs"; +pin in bool button.c00.r##[8] "array of inputs"; +pin in bool button.c01.r##[8] "array of inputs"; +pin in bool button.c02.r##[8] "array of inputs"; +pin in bool button.c03.r##[8] "array of inputs"; +pin in bool button.c04.r##[8] "array of inputs"; +pin in bool button.c05.r##[8] "array of inputs"; +pin in bool button.c06.r##[8] "array of inputs"; +pin in bool button.c07.r##[8] "array of inputs"; variable int keydown = 0xC0; variable int keyup = 0x80; @@ -44,19 +44,19 @@ FUNCTION(_) { rtapi_print("row: %d column: %d code: %d\n",r,c,num); last[num] = cur_button; if (cur_button == 1){ - out = num | keydown; + out_set(num | keydown); return; }else{ - out = num | keyup; + out_set(num | keyup); return; } } } } if (allup_flag){ - out = 0; + out_set(0); }else{ - out = nokeychange; + out_set(nokeychange); } } diff --git a/src/hal/components/sim_parport.comp b/src/hal/components/sim_parport.comp index 44e44486ffa..a8f6ea5a46d 100644 --- a/src/hal/components/sim_parport.comp +++ b/src/hal/components/sim_parport.comp @@ -28,101 +28,101 @@ The read and write functions pass the logic from pins to fake pins or vice vera The reset function is a no operation. """; -pin in bit pin_01_out; -pin in bit pin_02_out; -pin in bit pin_03_out; -pin in bit pin_04_out; -pin in bit pin_05_out; -pin in bit pin_06_out; -pin in bit pin_07_out; -pin in bit pin_08_out; -pin in bit pin_09_out; -pin in bit pin_14_out; -pin in bit pin_16_out; -pin in bit pin_17_out; - -pin out bit pin_01_out_fake; -pin out bit pin_02_out_fake; -pin out bit pin_03_out_fake; -pin out bit pin_04_out_fake; -pin out bit pin_05_out_fake; -pin out bit pin_06_out_fake; -pin out bit pin_07_out_fake; -pin out bit pin_08_out_fake; -pin out bit pin_09_out_fake; -pin out bit pin_14_out_fake; -pin out bit pin_16_out_fake; -pin out bit pin_17_out_fake; - -param rw bit pin_01_out_invert; -param rw bit pin_02_out_invert; -param rw bit pin_03_out_invert; -param rw bit pin_04_out_invert; -param rw bit pin_05_out_invert; -param rw bit pin_06_out_invert; -param rw bit pin_07_out_invert; -param rw bit pin_08_out_invert; -param rw bit pin_09_out_invert; -param rw bit pin_14_out_invert; -param rw bit pin_16_out_invert; -param rw bit pin_17_out_invert; - -param rw bit pin_01_out_reset; -param rw bit pin_02_out_reset; -param rw bit pin_03_out_reset; -param rw bit pin_04_out_reset; -param rw bit pin_05_out_reset; -param rw bit pin_06_out_reset; -param rw bit pin_07_out_reset; -param rw bit pin_08_out_reset; -param rw bit pin_09_out_reset; -param rw bit pin_14_out_reset; -param rw bit pin_16_out_reset; -param rw bit pin_17_out_reset; - -pin out bit pin_02_in; -pin out bit pin_03_in; -pin out bit pin_04_in; -pin out bit pin_05_in; -pin out bit pin_06_in; -pin out bit pin_07_in; -pin out bit pin_08_in; -pin out bit pin_09_in; -pin out bit pin_10_in; -pin out bit pin_11_in; -pin out bit pin_12_in; -pin out bit pin_13_in; -pin out bit pin_15_in; - -pin in bit pin_02_in_fake; -pin in bit pin_03_in_fake; -pin in bit pin_04_in_fake; -pin in bit pin_05_in_fake; -pin in bit pin_06_in_fake; -pin in bit pin_07_in_fake; -pin in bit pin_08_in_fake; -pin in bit pin_09_in_fake; -pin in bit pin_10_in_fake; -pin in bit pin_11_in_fake; -pin in bit pin_12_in_fake; -pin in bit pin_13_in_fake; -pin in bit pin_15_in_fake; - -pin out bit pin_02_in_not; -pin out bit pin_03_in_not; -pin out bit pin_04_in_not; -pin out bit pin_05_in_not; -pin out bit pin_06_in_not; -pin out bit pin_07_in_not; -pin out bit pin_08_in_not; -pin out bit pin_09_in_not; -pin out bit pin_10_in_not; -pin out bit pin_11_in_not; -pin out bit pin_12_in_not; -pin out bit pin_13_in_not; -pin out bit pin_15_in_not; - -pin in float reset_time; +pin in bool pin_01_out; +pin in bool pin_02_out; +pin in bool pin_03_out; +pin in bool pin_04_out; +pin in bool pin_05_out; +pin in bool pin_06_out; +pin in bool pin_07_out; +pin in bool pin_08_out; +pin in bool pin_09_out; +pin in bool pin_14_out; +pin in bool pin_16_out; +pin in bool pin_17_out; + +pin out bool pin_01_out_fake; +pin out bool pin_02_out_fake; +pin out bool pin_03_out_fake; +pin out bool pin_04_out_fake; +pin out bool pin_05_out_fake; +pin out bool pin_06_out_fake; +pin out bool pin_07_out_fake; +pin out bool pin_08_out_fake; +pin out bool pin_09_out_fake; +pin out bool pin_14_out_fake; +pin out bool pin_16_out_fake; +pin out bool pin_17_out_fake; + +param rw bool pin_01_out_invert; +param rw bool pin_02_out_invert; +param rw bool pin_03_out_invert; +param rw bool pin_04_out_invert; +param rw bool pin_05_out_invert; +param rw bool pin_06_out_invert; +param rw bool pin_07_out_invert; +param rw bool pin_08_out_invert; +param rw bool pin_09_out_invert; +param rw bool pin_14_out_invert; +param rw bool pin_16_out_invert; +param rw bool pin_17_out_invert; + +param rw bool pin_01_out_reset; +param rw bool pin_02_out_reset; +param rw bool pin_03_out_reset; +param rw bool pin_04_out_reset; +param rw bool pin_05_out_reset; +param rw bool pin_06_out_reset; +param rw bool pin_07_out_reset; +param rw bool pin_08_out_reset; +param rw bool pin_09_out_reset; +param rw bool pin_14_out_reset; +param rw bool pin_16_out_reset; +param rw bool pin_17_out_reset; + +pin out bool pin_02_in; +pin out bool pin_03_in; +pin out bool pin_04_in; +pin out bool pin_05_in; +pin out bool pin_06_in; +pin out bool pin_07_in; +pin out bool pin_08_in; +pin out bool pin_09_in; +pin out bool pin_10_in; +pin out bool pin_11_in; +pin out bool pin_12_in; +pin out bool pin_13_in; +pin out bool pin_15_in; + +pin in bool pin_02_in_fake; +pin in bool pin_03_in_fake; +pin in bool pin_04_in_fake; +pin in bool pin_05_in_fake; +pin in bool pin_06_in_fake; +pin in bool pin_07_in_fake; +pin in bool pin_08_in_fake; +pin in bool pin_09_in_fake; +pin in bool pin_10_in_fake; +pin in bool pin_11_in_fake; +pin in bool pin_12_in_fake; +pin in bool pin_13_in_fake; +pin in bool pin_15_in_fake; + +pin out bool pin_02_in_not; +pin out bool pin_03_in_not; +pin out bool pin_04_in_not; +pin out bool pin_05_in_not; +pin out bool pin_06_in_not; +pin out bool pin_07_in_not; +pin out bool pin_08_in_not; +pin out bool pin_09_in_not; +pin out bool pin_10_in_not; +pin out bool pin_11_in_not; +pin out bool pin_12_in_not; +pin out bool pin_13_in_not; +pin out bool pin_15_in_not; + +pin in real reset_time; option period no; function read; @@ -134,50 +134,50 @@ author "Chris S Morley"; FUNCTION(read) { -pin_02_in = pin_02_in_fake; -pin_03_in = pin_03_in_fake; -pin_04_in = pin_04_in_fake; -pin_05_in = pin_05_in_fake; -pin_06_in = pin_06_in_fake; -pin_07_in = pin_07_in_fake; -pin_08_in = pin_08_in_fake; -pin_09_in = pin_09_in_fake; -pin_10_in = pin_10_in_fake; -pin_11_in = pin_11_in_fake; -pin_12_in = pin_12_in_fake; -pin_13_in = pin_13_in_fake; -pin_15_in = pin_15_in_fake; - -pin_02_in_not = ! pin_02_in_fake; -pin_03_in_not = ! pin_03_in_fake; -pin_04_in_not = ! pin_04_in_fake; -pin_05_in_not = ! pin_05_in_fake; -pin_06_in_not = ! pin_06_in_fake; -pin_07_in_not = ! pin_07_in_fake; -pin_08_in_not = ! pin_08_in_fake; -pin_09_in_not = ! pin_09_in_fake; -pin_10_in_not = ! pin_10_in_fake; -pin_11_in_not = ! pin_11_in_fake; -pin_12_in_not = ! pin_12_in_fake; -pin_13_in_not = ! pin_13_in_fake; -pin_15_in_not = ! pin_15_in_fake; +pin_02_in_set(pin_02_in_fake); +pin_03_in_set(pin_03_in_fake); +pin_04_in_set(pin_04_in_fake); +pin_05_in_set(pin_05_in_fake); +pin_06_in_set(pin_06_in_fake); +pin_07_in_set(pin_07_in_fake); +pin_08_in_set(pin_08_in_fake); +pin_09_in_set(pin_09_in_fake); +pin_10_in_set(pin_10_in_fake); +pin_11_in_set(pin_11_in_fake); +pin_12_in_set(pin_12_in_fake); +pin_13_in_set(pin_13_in_fake); +pin_15_in_set(pin_15_in_fake); + +pin_02_in_not_set(! pin_02_in_fake); +pin_03_in_not_set(! pin_03_in_fake); +pin_04_in_not_set(! pin_04_in_fake); +pin_05_in_not_set(! pin_05_in_fake); +pin_06_in_not_set(! pin_06_in_fake); +pin_07_in_not_set(! pin_07_in_fake); +pin_08_in_not_set(! pin_08_in_fake); +pin_09_in_not_set(! pin_09_in_fake); +pin_10_in_not_set(! pin_10_in_fake); +pin_11_in_not_set(! pin_11_in_fake); +pin_12_in_not_set(! pin_12_in_fake); +pin_13_in_not_set(! pin_13_in_fake); +pin_15_in_not_set(! pin_15_in_fake); } FUNCTION(write) { - pin_01_out_fake = pin_01_out ^ pin_01_out_invert; - pin_02_out_fake = pin_02_out ^ pin_02_out_invert; - pin_03_out_fake = pin_03_out ^ pin_03_out_invert; - pin_04_out_fake = pin_04_out ^ pin_04_out_invert; - pin_05_out_fake = pin_05_out ^ pin_05_out_invert; - pin_06_out_fake = pin_06_out ^ pin_06_out_invert; - pin_07_out_fake = pin_07_out ^ pin_07_out_invert; - pin_08_out_fake = pin_08_out ^ pin_08_out_invert; - pin_09_out_fake = pin_09_out ^ pin_09_out_invert; - pin_14_out_fake = pin_14_out ^ pin_14_out_invert; - pin_16_out_fake = pin_16_out ^ pin_16_out_invert; - pin_17_out_fake = pin_17_out ^ pin_17_out_invert; + pin_01_out_fake_set(pin_01_out ^ pin_01_out_invert); + pin_02_out_fake_set(pin_02_out ^ pin_02_out_invert); + pin_03_out_fake_set(pin_03_out ^ pin_03_out_invert); + pin_04_out_fake_set(pin_04_out ^ pin_04_out_invert); + pin_05_out_fake_set(pin_05_out ^ pin_05_out_invert); + pin_06_out_fake_set(pin_06_out ^ pin_06_out_invert); + pin_07_out_fake_set(pin_07_out ^ pin_07_out_invert); + pin_08_out_fake_set(pin_08_out ^ pin_08_out_invert); + pin_09_out_fake_set(pin_09_out ^ pin_09_out_invert); + pin_14_out_fake_set(pin_14_out ^ pin_14_out_invert); + pin_16_out_fake_set(pin_16_out ^ pin_16_out_invert); + pin_17_out_fake_set(pin_17_out ^ pin_17_out_invert); } FUNCTION(reset) { diff --git a/src/hal/components/sim_spindle.comp b/src/hal/components/sim_spindle.comp index 074bc715918..29f6e0aa23b 100644 --- a/src/hal/components/sim_spindle.comp +++ b/src/hal/components/sim_spindle.comp @@ -1,9 +1,9 @@ component sim_spindle "Simulated spindle with index pulse"; -pin in float velocity-cmd "Commanded speed"; -pin out float position-fb "Feedback position, in revolutions"; -pin io bit index-enable "Reset *position-fb* to 0 at the next full rotation"; -param rw float scale = 1.0 +pin in real velocity-cmd "Commanded speed"; +pin out real position-fb "Feedback position, in revolutions"; +pin io bool index-enable "Reset *position-fb* to 0 at the next full rotation"; +param rw real scale = 1.0 """factor applied to *velocity-cmd*. The result of '*velocity-cmd* * *scale*' be in revolutions per second. @@ -20,16 +20,16 @@ function _; FUNCTION(_) { - double old_position = position_fb; - double new_position = position_fb + velocity_cmd * fperiod * scale; + rtapi_real old_position = position_fb; + rtapi_real new_position = position_fb + velocity_cmd * fperiod * scale; if(index_enable && (floor(old_position) != floor(new_position))) { - index_enable = false; + index_enable_set(false); if(velocity_cmd < 0) new_position = new_position - ceil(new_position); else new_position = new_position - floor(new_position); } - position_fb = new_position; + position_fb_set(new_position); } diff --git a/src/hal/components/simple_tp.comp b/src/hal/components/simple_tp.comp index 29d0c284415..aad6fd529bf 100644 --- a/src/hal/components/simple_tp.comp +++ b/src/hal/components/simple_tp.comp @@ -21,23 +21,23 @@ component simple_tp """\ This component is a single axis simple trajectory planner, same as used for jogging in LinuxCNC. Used by PNCconf to allow testing of acceleration and velocity values for an axis."""; -pin in float target-pos "target position to plan for."; -pin in float maxvel "Maximum velocity"; -pin in float maxaccel "Acceleration rate"; -pin in bit enable "If disabled, planner sets velocity to zero immediately."; +pin in real target-pos "target position to plan for."; +pin in real maxvel "Maximum velocity"; +pin in real maxaccel "Acceleration rate"; +pin in bool enable "If disabled, planner sets velocity to zero immediately."; -pin out float current-pos "position commanded at this point in time."; -pin out float current-vel "velocity commanded at this moment in time."; -pin out bit active "if active is true, the planner is requesting movement."; +pin out real current-pos "position commanded at this point in time."; +pin out real current-vel "velocity commanded at this moment in time."; +pin out bool active "if active is true, the planner is requesting movement."; function update; license "GPL"; author "Chris S Morley"; ;; #include FUNCTION(update) { - double max_dv, tiny_dp, pos_err, vel_req; + rtapi_real max_dv, tiny_dp, pos_err, vel_req; - active = 0; + active_set(0); /* compute max change in velocity per servo period */ max_dv = maxaccel * fperiod; /* compute a tiny position range, to be treated as zero */ @@ -54,12 +54,12 @@ FUNCTION(update) { vel_req = -max_dv + sqrt(2.0 * maxaccel * pos_err + max_dv * max_dv); /* mark planner as active */ - active = 1; + active_set(1); } else if (pos_err < -tiny_dp) { vel_req = max_dv - sqrt(-2.0 * maxaccel * pos_err + max_dv * max_dv); /* mark planner as active */ - active = 1; + active_set(1); } else { /* within 'tiny_dp' of desired pos, no need to move */ vel_req = 0.0; @@ -76,18 +76,18 @@ FUNCTION(update) { } /* ramp velocity toward request at accel limit */ if (vel_req > current_vel + max_dv) { - current_vel += max_dv; + current_vel_set(current_vel + max_dv); } else if (vel_req < current_vel - max_dv) { - current_vel -= max_dv; + current_vel_set(current_vel - max_dv); } else { - current_vel = vel_req; + current_vel_set(vel_req); } /* check for still moving */ if (current_vel != 0.0) { /* yes, mark planner active */ - active = 1; + active_set(1); } /* integrate velocity to get new position */ - current_pos += current_vel * fperiod; + current_pos_set(current_pos + current_vel * fperiod); } diff --git a/src/hal/components/sphereprobe.comp b/src/hal/components/sphereprobe.comp index 7cba0924f97..1b20485857b 100644 --- a/src/hal/components/sphereprobe.comp +++ b/src/hal/components/sphereprobe.comp @@ -2,16 +2,16 @@ component sphereprobe "Probe a pretend hemisphere"; author "Jeff Epler"; license "GPL"; -pin in signed px; -pin in signed py; -pin in signed pz "*rawcounts* position from software encoder"; +pin in si32 px; +pin in si32 py; +pin in si32 pz "*rawcounts* position from software encoder"; -pin in signed cx; -pin in signed cy; -pin in signed cz "Center of sphere in counts"; -pin in signed r "Radius of hemisphere in counts"; +pin in si32 cx; +pin in si32 cy; +pin in si32 cz "Center of sphere in counts"; +pin in si32 r "Radius of hemisphere in counts"; -pin out bit probe-out; +pin out bool probe-out; option period no; function _ "update probe-out based on inputs"; @@ -24,9 +24,9 @@ FUNCTION(_) { rtapi_u64 d2 = dx*dx + dy*dy; rtapi_u64 r2 = (rtapi_s64)r*(rtapi_s64)r; if(d2 > r2) { - probe_out = pz < cz; + probe_out_set(pz < cz); } else { d2 += dz*dz; - probe_out = d2 <= r2; + probe_out_set(d2 <= r2); } } diff --git a/src/hal/components/spindle.comp b/src/hal/components/spindle.comp index 39fa227e1d3..11cc86faa9e 100644 --- a/src/hal/components/spindle.comp +++ b/src/hal/components/spindle.comp @@ -50,30 +50,30 @@ Each gear has individual control of speeds, acceleration, driver gain and direct see_also "*motion*(9)"; -pin in unsigned select-gear +pin in ui32 select-gear """Select a gear. Must be in the range 0 -> number of available gears -1. If you use this, do not use the select.x input pins."""; -pin in float commanded-speed "Commanded spindle speed (in RPM)"; -pin in float actual-speed """Actual spindle speed from a spindle encoder (in RPS). +pin in real commanded-speed "Commanded spindle speed (in RPM)"; +pin in real actual-speed """Actual spindle speed from a spindle encoder (in RPS). If you do not have a spindle encoder set the simulate_encoder parameter to 1."""; -pin in bit simulate-encoder "If you do not have an encoder, set this to 1."; -pin in bit enable "If FALSE, the spindle is stopped at the gear's maximum deceleration."; -pin in float spindle-lpf """Smooth the spindle-rpm-abs output when at speed, 0 = disabled. +pin in bool simulate-encoder "If you do not have an encoder, set this to 1."; +pin in bool enable "If FALSE, the spindle is stopped at the gear's maximum deceleration."; +pin in real spindle-lpf """Smooth the spindle-rpm-abs output when at speed, 0 = disabled. Suitable values are probably between 1 and 20 depending on how stable your spindle is."""; -pin out float spindle-rpm """Current spindle speed in RPM.+ve = forward, -ve = reverse. +pin out real spindle-rpm """Current spindle speed in RPM.+ve = forward, -ve = reverse. Uses the encoder input if available. If not, uses a simulated encoder speed."""; -pin out float spindle-rpm-abs "Absolute spindle speed in RPM. Useful for spindle speed displays."; -pin out float output "Scaled output"; -pin out unsigned current-gear "Currently selected gear."; +pin out real spindle-rpm-abs "Absolute spindle speed in RPM. Useful for spindle speed displays."; +pin out real output "Scaled output"; +pin out ui32 current-gear "Currently selected gear."; -pin out bit at-speed "TRUE when the spindle is at speed"; -pin out bit forward "TRUE for forward rotation"; -pin out bit reverse "TRUE for reverse rotation. Both forward and reverse are false when the spindle is stopped."; -pin out bit brake "TRUE when decelerating"; -pin out bit zero-speed "TRUE when the spindle is stationary"; -pin out bit limited """TRUE when the commanded spindle speed is >max or max or 0) && forward; - reverse = (curspeed <0) && forward; + forward_set((curspeed > 0) && forward); + reverse_set((curspeed < 0) && forward); } if(curspeed < 0) curspeed = -curspeed; - output = (curspeed + (*(thisgear->offset))) * (*(thisgear->scale)); - limited = limit; + output_set((curspeed + (hal_get_real(thisgear->offset))) * (hal_get_real(thisgear->scale))); + limited_set(limit); } EXTRA_SETUP(){ @@ -278,7 +278,7 @@ EXTRA_SETUP(){ if(r != 0) return r; } if(ngears ==1){ - *(gears[0].select) = true; + hal_set_bool(gears[0].select, true); } return(0); } @@ -286,49 +286,40 @@ EXTRA_SETUP(){ int add_gear(int index, char *prefix, gear_t * g) { int r; - r = hal_pin_float_newf(HAL_IN, &(g->scale), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->scale), 1.0, "%s.scale.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->min), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->min), 0.0, "%s.min.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->max), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->max), 0.0, "%s.max.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->accel), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->accel), 0.0, "%s.accel.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->decel), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->decel), 0.0, "%s.decel.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->speed_tolerance), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->speed_tolerance), 20.0, "%s.speed-tolerance.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->zero_tolerance), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->zero_tolerance), 20.0, "%s.zero-tolerance.%i", prefix,index); if(r != 0) return r; - r = hal_pin_float_newf(HAL_IN, &(g->offset), comp_id, + r = hal_pin_new_real(comp_id, HAL_IN, &(g->offset), 0.0, "%s.offset.%i", prefix,index); if(r != 0) return r; - r = hal_pin_bit_newf(HAL_IN, &(g->select), comp_id, + r = hal_pin_new_bool(comp_id, HAL_IN, &(g->select), false, "%s.select.%i", prefix,index); if(r != 0) return r; - *g->scale = 1; - *g->min = 0; - *g->max = 0; - *g->accel = 0; - *g->decel = 0; - *g->speed_tolerance = 20; - *g->zero_tolerance = 20; - *g->offset = 0; - *g->select = false; return(0); } diff --git a/src/hal/components/spindle.h b/src/hal/components/spindle.h index 49aee824cad..5f3ad2b5f7e 100644 --- a/src/hal/components/spindle.h +++ b/src/hal/components/spindle.h @@ -10,13 +10,13 @@ ********************************************************************/ typedef struct { - hal_float_t *scale; - hal_float_t *min; - hal_float_t *max; - hal_float_t *accel; - hal_float_t *decel; - hal_float_t *speed_tolerance; - hal_float_t *zero_tolerance; - hal_float_t *offset; - hal_bit_t *select; + hal_real_t scale; + hal_real_t min; + hal_real_t max; + hal_real_t accel; + hal_real_t decel; + hal_real_t speed_tolerance; + hal_real_t zero_tolerance; + hal_real_t offset; + hal_bool_t select; } gear_t; diff --git a/src/hal/components/spindle_monitor.comp b/src/hal/components/spindle_monitor.comp index 829323c5a9d..bfa65e98acb 100644 --- a/src/hal/components/spindle_monitor.comp +++ b/src/hal/components/spindle_monitor.comp @@ -1,13 +1,13 @@ component spindle_monitor "spindle at-speed and underspeed detection"; -pin in bit spindle-is-on; -pin in float spindle-command; -pin in float spindle-feedback; +pin in bool spindle-is-on; +pin in real spindle-command; +pin in real spindle-feedback; -pin out bit spindle-at-speed; -pin out bit spindle-underspeed; +pin out bool spindle-at-speed; +pin out bool spindle-underspeed; -param rw unsigned level "state machine state"; -param rw float threshold; +param rw ui32 level "state machine state"; +param rw real threshold; option period no; function _; @@ -22,28 +22,28 @@ FUNCTION(_) { switch (level){ case 0: // idle - spindle_at_speed = 0; - spindle_underspeed = 0; - if (spindle_is_on) level = 1; + spindle_at_speed_set(0); + spindle_underspeed_set(0); + if (spindle_is_on) level_set(1); break; case 1: // waiting for spindle-at-speed if ( ! spindle_is_on ) { - level = 0; + level_set(0); return; } if (fabs(spindle_command - spindle_feedback) < threshold) { - level = 2; - spindle_at_speed = 1; + level_set(2); + spindle_at_speed_set(1); return; } break; case 2: // monitoring speed if ( ! spindle_is_on ) { - level = 0; + level_set(0); return; } if ((spindle_command - spindle_feedback) > threshold) { - spindle_underspeed = 1; } + spindle_underspeed_set(1); } break; default: // not sure how we got here, but fix the situation - level = 0; + level_set(0); } } diff --git a/src/hal/components/stepgen.c b/src/hal/components/stepgen.c index bcc4d878f33..f10612c2581 100644 --- a/src/hal/components/stepgen.c +++ b/src/hal/components/stepgen.c @@ -337,39 +337,39 @@ typedef struct { int hold_dds; /* prevents accumulator from updating */ long addval; /* actual frequency generator add value */ volatile long long accum; /* frequency generator accumulator */ - hal_s32_t rawcount; /* param: position feedback in counts */ + hal_sint_t rawcount; /* param: position feedback in counts */ int curr_dir; /* current direction */ int state; /* current position in state table */ /* stuff that is read but not written by makepulses */ - hal_bit_t *enable; /* pin for enable stepgen */ + hal_bool_t enable; /* pin for enable stepgen */ long target_addval; /* desired freq generator add value */ long deltalim; /* max allowed change per period */ - hal_u32_t step_len; /* parameter: step pulse length */ - hal_u32_t dir_hold_dly; /* param: direction hold time or delay */ - hal_u32_t dir_setup; /* param: direction setup time */ + hal_uint_t step_len; /* param: step pulse length */ + hal_uint_t dir_hold_dly; /* param: direction hold time or delay */ + hal_uint_t dir_setup; /* param: direction setup time */ int step_type; /* stepping type - see list above */ int cycle_max; /* cycle length for step types 2 and up */ int num_phases; /* number of phases for types 2 and up */ - hal_bit_t *phase[5]; /* pins for output signals */ + hal_bool_t phase[5]; /* pins for output signals */ const unsigned char *lut; /* pointer to state lookup table */ /* stuff that is not accessed by makepulses */ int pos_mode; /* 1 = position mode, 0 = velocity mode */ - hal_u32_t step_space; /* parameter: min step pulse spacing */ + hal_uint_t step_space; /* param: min step pulse spacing */ double old_pos_cmd; /* previous position command (counts) */ - hal_s32_t *count; /* pin: captured feedback in counts */ - hal_float_t pos_scale; /* param: steps per position unit */ + hal_sint_t count; /* pin: captured feedback in counts */ + hal_real_t pos_scale; /* param: steps per position unit */ double old_scale; /* stored scale value */ double scale_recip; /* reciprocal value used for scaling */ - hal_float_t *vel_cmd; /* pin: velocity command (pos units/sec) */ - hal_float_t *pos_cmd; /* pin: position command (position units) */ - hal_float_t *pos_fb; /* pin: position feedback (position units) */ - hal_float_t freq; /* param: frequency command */ - hal_float_t maxvel; /* param: max velocity, (pos units/sec) */ - hal_float_t maxaccel; /* param: max accel (pos units/sec^2) */ - hal_u32_t old_step_len; /* used to detect parameter changes */ - hal_u32_t old_step_space; - hal_u32_t old_dir_hold_dly; - hal_u32_t old_dir_setup; + hal_real_t vel_cmd; /* pin: velocity command (pos units/sec) */ + hal_real_t pos_cmd; /* pin: position command (position units) */ + hal_real_t pos_fb; /* pin: position feedback (position units) */ + hal_real_t freq; /* param: frequency command */ + hal_real_t maxvel; /* param: max velocity, (pos units/sec) */ + hal_real_t maxaccel; /* param: max accel (pos units/sec^2) */ + rtapi_u32 old_step_len; /* used to detect parameter changes */ + rtapi_u32 old_step_space; + rtapi_u32 old_dir_hold_dly; + rtapi_u32 old_dir_setup; int printed_error; /* flag to avoid repeated printing */ } stepgen_t; @@ -592,7 +592,7 @@ static void make_pulses(void *arg, long period) stepgen->hold_dds = 0; } } - if ( !stepgen->hold_dds && *(stepgen->enable) ) { + if ( !stepgen->hold_dds && hal_get_bool(stepgen->enable) ) { /* update addval (ramping) */ old_addval = stepgen->addval; target_addval = stepgen->target_addval; @@ -625,7 +625,7 @@ static void make_pulses(void *arg, long period) } } /* update DDS */ - if ( !stepgen->hold_dds && *(stepgen->enable) ) { + if ( !stepgen->hold_dds && hal_get_bool(stepgen->enable) ) { /* save current value of low half of accum */ step_now = stepgen->accum; /* update the accumulator */ @@ -635,7 +635,7 @@ static void make_pulses(void *arg, long period) /* we only care about the pickoff bit */ step_now &= (1L << PICKOFF); /* update rawcounts parameter */ - stepgen->rawcount = stepgen->accum >> PICKOFF; + hal_set_si32(stepgen->rawcount, stepgen->accum >> PICKOFF); } else { /* DDS is in hold, no steps */ step_now = 0; @@ -651,11 +651,11 @@ static void make_pulses(void *arg, long period) if ( step_now ) { /* (re)start various timers */ /* timer 1 = time till end of step pulse */ - stepgen->timer1 = stepgen->step_len; + stepgen->timer1 = hal_get_ui32(stepgen->step_len); /* timer 2 = time till allowed to change dir pin */ - stepgen->timer2 = stepgen->timer1 + stepgen->dir_hold_dly; + stepgen->timer2 = stepgen->timer1 + hal_get_ui32(stepgen->dir_hold_dly); /* timer 3 = time till allowed to step the other way */ - stepgen->timer3 = stepgen->timer2 + stepgen->dir_setup; + stepgen->timer3 = stepgen->timer2 + hal_get_ui32(stepgen->dir_setup); if ( stepgen->step_type >= 2 ) { /* update state */ stepgen->state += stepgen->curr_dir; @@ -669,29 +669,21 @@ static void make_pulses(void *arg, long period) /* generate output, based on stepping type */ if (stepgen->step_type == 0) { /* step/dir output */ - if ( stepgen->timer1 != 0 ) { - *(stepgen->phase[STEP_PIN]) = 1; - } else { - *(stepgen->phase[STEP_PIN]) = 0; - } - if ( stepgen->curr_dir < 0 ) { - *(stepgen->phase[DIR_PIN]) = 1; - } else { - *(stepgen->phase[DIR_PIN]) = 0; - } + hal_set_bool(stepgen->phase[STEP_PIN], stepgen->timer1 != 0); + hal_set_bool(stepgen->phase[DIR_PIN], stepgen->curr_dir < 0); } else if (stepgen->step_type == 1) { /* up/down */ if ( stepgen->timer1 != 0 ) { if ( stepgen->curr_dir < 0 ) { - *(stepgen->phase[UP_PIN]) = 0; - *(stepgen->phase[DOWN_PIN]) = 1; + hal_set_bool(stepgen->phase[UP_PIN], 0); + hal_set_bool(stepgen->phase[DOWN_PIN], 1); } else { - *(stepgen->phase[UP_PIN]) = 1; - *(stepgen->phase[DOWN_PIN]) = 0; + hal_set_bool(stepgen->phase[UP_PIN], 1); + hal_set_bool(stepgen->phase[DOWN_PIN], 0); } } else { - *(stepgen->phase[UP_PIN]) = 0; - *(stepgen->phase[DOWN_PIN]) = 0; + hal_set_bool(stepgen->phase[UP_PIN], 0); + hal_set_bool(stepgen->phase[DOWN_PIN], 0); } } else { /* step type 2 or greater */ @@ -700,7 +692,7 @@ static void make_pulses(void *arg, long period) /* now output the phase bits */ for (p = 0; p < stepgen->num_phases; p++) { /* output one phase */ - *(stepgen->phase[p]) = outbits & 1; + hal_set_bool(stepgen->phase[p], outbits & 1); /* move to the next phase */ outbits >>= 1; } @@ -729,24 +721,25 @@ static void update_pos(void *arg, long period) accum_b = stepgen->accum; } while ( accum_a != accum_b ); /* compute integer counts */ - *(stepgen->count) = accum_a >> PICKOFF; + hal_set_si32(stepgen->count, accum_a >> PICKOFF); /* check for change in scale value */ - if (stepgen->pos_scale != stepgen->old_scale) { + rtapi_real pos_scale = hal_get_real(stepgen->pos_scale); + if (pos_scale != stepgen->old_scale) { /* get ready to detect future scale changes */ - stepgen->old_scale = stepgen->pos_scale; + stepgen->old_scale = pos_scale; /* validate the new scale value */ - if ((stepgen->pos_scale < 1e-20) - && (stepgen->pos_scale > -1e-20)) { + if ((pos_scale < 1e-20) + && (pos_scale > -1e-20)) { /* value too small, divide by zero is a bad thing */ - stepgen->pos_scale = 1.0; + pos_scale = hal_set_real(stepgen->pos_scale, 1.0); } /* we will need the reciprocal, and the accum is fixed point with fractional bits, so we precalc some stuff */ - stepgen->scale_recip = (1.0 / (1L << PICKOFF)) / stepgen->pos_scale; + stepgen->scale_recip = (1.0 / (1L << PICKOFF)) / pos_scale; } /* scale accumulator to make floating point position, after removing the one-half count offset */ - *(stepgen->pos_fb) = (double)(accum_a-(1<< (PICKOFF-1))) * stepgen->scale_recip; + hal_set_real(stepgen->pos_fb, (double)(accum_a-(1<< (PICKOFF-1))) * stepgen->scale_recip); /* move on to next channel */ stepgen++; } @@ -810,18 +803,19 @@ static void update_freq(void *arg, long period) /* loop thru generators */ for (n = 0; n < num_chan; n++) { /* check for scale change */ - if (stepgen->pos_scale != stepgen->old_scale) { + rtapi_real pos_scale = hal_get_real(stepgen->pos_scale); + if (pos_scale != stepgen->old_scale) { /* get ready to detect future scale changes */ - stepgen->old_scale = stepgen->pos_scale; + stepgen->old_scale = pos_scale; /* validate the new scale value */ - if ((stepgen->pos_scale < 1e-20) - && (stepgen->pos_scale > -1e-20)) { + if ((pos_scale < 1e-20) + && (pos_scale > -1e-20)) { /* value too small, divide by zero is a bad thing */ - stepgen->pos_scale = 1.0; + pos_scale = hal_set_real(stepgen->pos_scale, 1.0); } /* we will need the reciprocal, and the accum is fixed point with fractional bits, so we precalc some stuff */ - stepgen->scale_recip = (1.0 / (1L << PICKOFF)) / stepgen->pos_scale; + stepgen->scale_recip = (1.0 / (1L << PICKOFF)) / pos_scale; } if ( newperiod ) { /* period changed, force recalc of timing parameters */ @@ -831,43 +825,43 @@ static void update_freq(void *arg, long period) stepgen->old_dir_setup = ~0; } /* process timing parameters */ - if ( stepgen->step_len != stepgen->old_step_len ) { + if ( hal_get_ui32(stepgen->step_len) != stepgen->old_step_len ) { /* must be non-zero */ - if ( stepgen->step_len == 0 ) { - stepgen->step_len = 1; + if ( hal_get_ui32(stepgen->step_len) == 0 ) { + hal_set_ui32(stepgen->step_len, 1); } /* make integer multiple of periodns */ - stepgen->old_step_len = ulceil(stepgen->step_len, periodns); - stepgen->step_len = stepgen->old_step_len; + stepgen->old_step_len = ulceil(hal_get_ui32(stepgen->step_len), periodns); + hal_set_ui32(stepgen->step_len, stepgen->old_step_len); } - if ( stepgen->step_space != stepgen->old_step_space ) { + if ( hal_get_ui32(stepgen->step_space) != stepgen->old_step_space ) { /* make integer multiple of periodns */ - stepgen->old_step_space = ulceil(stepgen->step_space, periodns); - stepgen->step_space = stepgen->old_step_space; + stepgen->old_step_space = ulceil(hal_get_ui32(stepgen->step_space), periodns); + hal_set_ui32(stepgen->step_space, stepgen->old_step_space); } - if ( stepgen->dir_setup != stepgen->old_dir_setup ) { + if ( hal_get_ui32(stepgen->dir_setup) != stepgen->old_dir_setup ) { /* make integer multiple of periodns */ - stepgen->old_dir_setup = ulceil(stepgen->dir_setup, periodns); - stepgen->dir_setup = stepgen->old_dir_setup; + stepgen->old_dir_setup = ulceil(hal_get_ui32(stepgen->dir_setup), periodns); + hal_set_ui32(stepgen->dir_setup, stepgen->old_dir_setup); } - if ( stepgen->dir_hold_dly != stepgen->old_dir_hold_dly ) { - if ( (stepgen->dir_hold_dly + stepgen->dir_setup) == 0 ) { + if ( hal_get_ui32(stepgen->dir_hold_dly) != stepgen->old_dir_hold_dly ) { + if ( (hal_get_ui32(stepgen->dir_hold_dly) + hal_get_ui32(stepgen->dir_setup)) == 0 ) { /* dirdelay must be non-zero step types 0 and 1 */ if ( stepgen->step_type < 2 ) { - stepgen->dir_hold_dly = 1; + hal_set_ui32(stepgen->dir_hold_dly, 1); } } - stepgen->old_dir_hold_dly = ulceil(stepgen->dir_hold_dly, periodns); - stepgen->dir_hold_dly = stepgen->old_dir_hold_dly; + stepgen->old_dir_hold_dly = ulceil(hal_get_ui32(stepgen->dir_hold_dly), periodns); + hal_set_ui32(stepgen->dir_hold_dly, stepgen->old_dir_hold_dly); } /* test for disabled stepgen */ - if (*stepgen->enable == 0) { + if (hal_get_bool(stepgen->enable) == 0) { /* disabled: keep updating old_pos_cmd (if in pos ctrl mode) */ if ( stepgen->pos_mode ) { - stepgen->old_pos_cmd = *stepgen->pos_cmd * stepgen->pos_scale; + stepgen->old_pos_cmd = hal_get_real(stepgen->pos_cmd) * pos_scale; } /* set velocity to zero */ - stepgen->freq = 0; + hal_set_real(stepgen->freq, 0); stepgen->addval = 0; stepgen->target_addval = 0; /* and skip to next one */ @@ -875,15 +869,15 @@ static void update_freq(void *arg, long period) continue; } /* calculate frequency limit */ - min_step_period = stepgen->step_len + stepgen->step_space; + min_step_period = hal_get_ui32(stepgen->step_len) + hal_get_ui32(stepgen->step_space); max_freq = 1.0 / (min_step_period * 0.000000001); /* check for user specified frequency limit parameter */ - if (stepgen->maxvel <= 0.0) { + if (hal_get_real(stepgen->maxvel) <= 0.0) { /* set to zero if negative */ - stepgen->maxvel = 0.0; + hal_set_real(stepgen->maxvel, 0.0); } else { /* parameter is non-zero, compare to max_freq */ - desired_freq = stepgen->maxvel * fabs(stepgen->pos_scale); + desired_freq = hal_get_real(stepgen->maxvel) * fabs(pos_scale); if (desired_freq > max_freq) { /* parameter is too high, complain about it */ if(!stepgen->printed_error) { @@ -896,34 +890,34 @@ static void update_freq(void *arg, long period) stepgen->printed_error = 1; } /* parameter is too high, limit it */ - stepgen->maxvel = max_freq / fabs(stepgen->pos_scale); + hal_set_real(stepgen->maxvel, max_freq / fabs(pos_scale)); } else { /* lower max_freq to match parameter */ - max_freq = stepgen->maxvel * fabs(stepgen->pos_scale); + max_freq = hal_get_real(stepgen->maxvel) * fabs(pos_scale); } } /* set internal accel limit to its absolute max, which is zero to full speed in one thread period */ max_ac = max_freq * recip_dt; /* check for user specified accel limit parameter */ - if (stepgen->maxaccel <= 0.0) { + if (hal_get_real(stepgen->maxaccel) <= 0.0) { /* set to zero if negative */ - stepgen->maxaccel = 0.0; + hal_set_real(stepgen->maxaccel, 0.0); } else { /* parameter is non-zero, compare to max_ac */ - if ((stepgen->maxaccel * fabs(stepgen->pos_scale)) > max_ac) { + if ((hal_get_real(stepgen->maxaccel) * fabs(pos_scale)) > max_ac) { /* parameter is too high, lower it */ - stepgen->maxaccel = max_ac / fabs(stepgen->pos_scale); + hal_set_real(stepgen->maxaccel, max_ac / fabs(pos_scale)); } else { /* lower limit to match parameter */ - max_ac = stepgen->maxaccel * fabs(stepgen->pos_scale); + max_ac = hal_get_real(stepgen->maxaccel) * fabs(pos_scale); } } /* at this point, all scaling, limits, and other parameter changes have been handled - time for the main control */ if ( stepgen->pos_mode ) { /* calculate position command in counts */ - pos_cmd = *stepgen->pos_cmd * stepgen->pos_scale; + pos_cmd = hal_get_real(stepgen->pos_cmd) * pos_scale; /* calculate velocity command in counts/sec */ vel_cmd = (pos_cmd - stepgen->old_pos_cmd) * recip_dt; stepgen->old_pos_cmd = pos_cmd; @@ -938,7 +932,7 @@ static void update_freq(void *arg, long period) the one-half step offset */ curr_pos = (accum_a-(1<< (PICKOFF-1))) * (1.0 / (1L << PICKOFF)); /* get velocity in counts/sec */ - curr_vel = stepgen->freq; + curr_vel = hal_get_real(stepgen->freq); /* At this point we have good values for pos_cmd, curr_pos, vel_cmd, curr_vel, max_freq and max_ac, all in counts, counts/sec, or counts/sec^2. Now we just have to do @@ -996,7 +990,7 @@ static void update_freq(void *arg, long period) } else { /* velocity mode is simpler */ /* calculate velocity command in counts/sec */ - vel_cmd = *(stepgen->vel_cmd) * stepgen->pos_scale; + vel_cmd = hal_get_real(stepgen->vel_cmd) * pos_scale; /* apply frequency limit */ if (vel_cmd > max_freq) { vel_cmd = max_freq; @@ -1006,18 +1000,18 @@ static void update_freq(void *arg, long period) /* calc max change in frequency in one period */ dv = max_ac * dt; /* apply accel limit */ - if ( vel_cmd > (stepgen->freq + dv) ) { - new_vel = stepgen->freq + dv; - } else if ( vel_cmd < (stepgen->freq - dv) ) { - new_vel = stepgen->freq - dv; + if ( vel_cmd > (hal_get_real(stepgen->freq) + dv) ) { + new_vel = hal_get_real(stepgen->freq) + dv; + } else if ( vel_cmd < (hal_get_real(stepgen->freq) - dv) ) { + new_vel = hal_get_real(stepgen->freq) - dv; } else { new_vel = vel_cmd; } /* end of velocity mode */ } - stepgen->freq = new_vel; + hal_set_real(stepgen->freq, new_vel); /* calculate new addval */ - stepgen->target_addval = stepgen->freq * freqscale; + stepgen->target_addval = hal_get_real(stepgen->freq) * freqscale; /* calculate new deltalim */ stepgen->deltalim = max_ac * accelscale; /* move on to next channel */ @@ -1042,124 +1036,108 @@ static int export_stepgen(int num, stepgen_t * addr, int step_type, int pos_mode rtapi_set_msg_level(RTAPI_MSG_WARN); /* export param variable for raw counts */ - retval = hal_param_s32_newf(HAL_RO, &(addr->rawcount), comp_id, + retval = hal_param_new_si32(comp_id, HAL_RO, &(addr->rawcount), 0, "stepgen.%d.rawcounts", num); if (retval != 0) { return retval; } /* export pin for counts captured by update() */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->count), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->count), 0, "stepgen.%d.counts", num); if (retval != 0) { return retval; } /* export parameter for position scaling */ - retval = hal_param_float_newf(HAL_RW, &(addr->pos_scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(addr->pos_scale), 1.0, "stepgen.%d.position-scale", num); if (retval != 0) { return retval; } /* export pin for command */ if ( pos_mode ) { - retval = hal_pin_float_newf(HAL_IN, &(addr->pos_cmd), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->pos_cmd), 0.0, "stepgen.%d.position-cmd", num); } else { - retval = hal_pin_float_newf(HAL_IN, &(addr->vel_cmd), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(addr->vel_cmd), 0.0, "stepgen.%d.velocity-cmd", num); } if (retval != 0) { return retval; } /* export pin for enable command */ - retval = hal_pin_bit_newf(HAL_IN, &(addr->enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->enable), 0, "stepgen.%d.enable", num); if (retval != 0) { return retval; } /* export pin for scaled position captured by update() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos_fb), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->pos_fb), 0.0, "stepgen.%d.position-fb", num); if (retval != 0) { return retval; } /* export param for scaled velocity (frequency in Hz) */ - retval = hal_param_float_newf(HAL_RO, &(addr->freq), comp_id, + retval = hal_param_new_real(comp_id, HAL_RO, &(addr->freq), 0.0, "stepgen.%d.frequency", num); if (retval != 0) { return retval; } /* export parameter for max frequency */ - retval = hal_param_float_newf(HAL_RW, &(addr->maxvel), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(addr->maxvel), 0.0, "stepgen.%d.maxvel", num); if (retval != 0) { return retval; } /* export parameter for max accel/decel */ - retval = hal_param_float_newf(HAL_RW, &(addr->maxaccel), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(addr->maxaccel), 0.0, "stepgen.%d.maxaccel", num); if (retval != 0) { return retval; } /* every step type uses steplen */ - retval = hal_param_u32_newf(HAL_RW, &(addr->step_len), comp_id, + retval = hal_param_new_ui32(comp_id, HAL_RW, &(addr->step_len), 1, "stepgen.%d.steplen", num); if (retval != 0) { return retval; } if (step_type < 2) { /* step/dir and up/down use 'stepspace' */ - retval = hal_param_u32_newf(HAL_RW, &(addr->step_space), - comp_id, "stepgen.%d.stepspace", num); + retval = hal_param_new_ui32(comp_id, HAL_RW, &(addr->step_space), + 1, "stepgen.%d.stepspace", num); + if (retval != 0) { return retval; } + } else { + /* Ensure accessible and zeroed target memory when parameter not used */ + retval = hal_param_new_fake(comp_id, (hal_refs_u *)&(addr->step_space)); if (retval != 0) { return retval; } } if ( step_type == 0 ) { /* step/dir is the only one that uses dirsetup and dirhold */ - retval = hal_param_u32_newf(HAL_RW, &(addr->dir_setup), - comp_id, "stepgen.%d.dirsetup", num); + retval = hal_param_new_ui32(comp_id, HAL_RW, &(addr->dir_setup), + 1, "stepgen.%d.dirsetup", num); if (retval != 0) { return retval; } - retval = hal_param_u32_newf(HAL_RW, &(addr->dir_hold_dly), - comp_id, "stepgen.%d.dirhold", num); + retval = hal_param_new_ui32(comp_id, HAL_RW, &(addr->dir_hold_dly), + 1, "stepgen.%d.dirhold", num); if (retval != 0) { return retval; } } else { + /* Ensure accessible and zeroed target memory when parameter not used */ + retval = hal_param_new_fake(comp_id, (hal_refs_u *)&(addr->dir_setup)); + if (retval != 0) { return retval; } /* the others use dirdelay */ - retval = hal_param_u32_newf(HAL_RW, &(addr->dir_hold_dly), - comp_id, "stepgen.%d.dirdelay", num); + retval = hal_param_new_ui32(comp_id, HAL_RW, &(addr->dir_hold_dly), + 1, "stepgen.%d.dirdelay", num); if (retval != 0) { return retval; } } /* export output pins */ if ( step_type == 0 ) { /* step and direction */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phase[STEP_PIN]), - comp_id, "stepgen.%d.step", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phase[STEP_PIN]), + 0, "stepgen.%d.step", num); if (retval != 0) { return retval; } - *(addr->phase[STEP_PIN]) = 0; - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phase[DIR_PIN]), - comp_id, "stepgen.%d.dir", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phase[DIR_PIN]), + 0, "stepgen.%d.dir", num); if (retval != 0) { return retval; } - *(addr->phase[DIR_PIN]) = 0; } else if (step_type == 1) { /* up and down */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phase[UP_PIN]), - comp_id, "stepgen.%d.up", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phase[UP_PIN]), + 0, "stepgen.%d.up", num); if (retval != 0) { return retval; } - *(addr->phase[UP_PIN]) = 0; - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phase[DOWN_PIN]), - comp_id, "stepgen.%d.down", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phase[DOWN_PIN]), + 0, "stepgen.%d.down", num); if (retval != 0) { return retval; } - *(addr->phase[DOWN_PIN]) = 0; } else { /* stepping types 2 and higher use a varying number of phase pins */ addr->num_phases = num_phases_lut[step_type - 2]; for (n = 0; n < addr->num_phases; n++) { - retval = hal_pin_bit_newf(HAL_OUT, &(addr->phase[n]), - comp_id, "stepgen.%d.phase-%c", num, n + 'A'); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->phase[n]), + 0, "stepgen.%d.phase-%c", num, n + 'A'); if (retval != 0) { return retval; } - *(addr->phase[n]) = 0; } } /* set default parameter values */ - addr->pos_scale = 1.0; addr->old_scale = 0.0; addr->scale_recip = 0.0; - addr->freq = 0.0; - addr->maxvel = 0.0; - addr->maxaccel = 0.0; addr->step_type = step_type; addr->pos_mode = pos_mode; - /* timing parameter defaults depend on step type */ - addr->step_len = 1; - if ( step_type < 2 ) { - addr->step_space = 1; - } else { - addr->step_space = 0; - } - if ( step_type == 0 ) { - addr->dir_hold_dly = 1; - addr->dir_setup = 1; - } else { - addr->dir_hold_dly = 1; - addr->dir_setup = 0; - } /* set 'old' values to make update_freq validate the timing params */ addr->old_step_len = ~0; addr->old_step_space = ~0; @@ -1179,23 +1157,13 @@ static int export_stepgen(int num, stepgen_t * addr, int step_type, int pos_mode /* accumulator gets a half step offset, so it will step half way between integer positions, not at the integer positions */ addr->accum = 1 << (PICKOFF-1); - addr->rawcount = 0; addr->curr_dir = 0; addr->state = 0; - *(addr->enable) = 0; addr->target_addval = 0; addr->deltalim = 0; /* other init */ addr->printed_error = 0; addr->old_pos_cmd = 0.0; - /* set initial pin values */ - *(addr->count) = 0; - *(addr->pos_fb) = 0.0; - if ( pos_mode ) { - *(addr->pos_cmd) = 0.0; - } else { - *(addr->vel_cmd) = 0.0; - } /* restore saved message level */ rtapi_set_msg_level(msg); return 0; diff --git a/src/hal/components/steptest.comp b/src/hal/components/steptest.comp index 364852d72fc..422b4e1a45c 100644 --- a/src/hal/components/steptest.comp +++ b/src/hal/components/steptest.comp @@ -1,46 +1,46 @@ component steptest """\ Used by Stepconf to allow testing of acceleration and velocity values for an axis."""; -pin in bit jog-minus "Drive TRUE to jog the axis in its minus direction"; -pin in bit jog-plus "Drive TRUE to jog the axis in its positive direction"; -pin in bit run "Drive TRUE to run the axis near its current position_fb with a trapezoidal velocity profile"; -pin in float maxvel "Maximum velocity"; -pin in float maxaccel "Permitted Acceleration"; -pin in float amplitude "Approximate amplitude of positions to command during 'run'"; -pin in s32 dir "Direction from central point to test: 0 = both, 1 = positive, 2 = negative"; -pin out float position-cmd; -pin in float position-fb; -pin out bit running; -pin out float run-target; -pin out float run-start; -pin out float run-low; -pin out float run-high; -pin in s32 pause = 0 "pause time for each end of run in seconds"; -param rw float epsilon = .001; -variable double timer; -param r float elapsed "Current value of the internal timer"; +pin in bool jog-minus "Drive TRUE to jog the axis in its minus direction"; +pin in bool jog-plus "Drive TRUE to jog the axis in its positive direction"; +pin in bool run "Drive TRUE to run the axis near its current position_fb with a trapezoidal velocity profile"; +pin in real maxvel "Maximum velocity"; +pin in real maxaccel "Permitted Acceleration"; +pin in real amplitude "Approximate amplitude of positions to command during 'run'"; +pin in si32 dir "Direction from central point to test: 0 = both, 1 = positive, 2 = negative"; +pin out real position-cmd; +pin in real position-fb; +pin out bool running; +pin out real run-target; +pin out real run-start; +pin out real run-low; +pin out real run-high; +pin in si32 pause = 0 "pause time for each end of run in seconds"; +param rw real epsilon = .001; +variable rtapi_real timer; +param r real elapsed "Current value of the internal timer"; variable int timer_on; function _; license "GPL"; author "Jeff Epler"; +include ; ;; -extern double fabs(double); if (timer_on) { timer += fperiod; } -elapsed = timer; +elapsed_set(timer); if(run) { if(!running) { - running = 1; - run_start = position_fb; + running_set(1); + run_start_set(position_fb); - if(dir == 2) run_high = run_start; - else run_high = run_start + amplitude; + if(dir == 2) run_high_set(run_start); + else run_high_set(run_start + amplitude); - if(dir == 1) run_low = run_start; - else run_low = run_start - amplitude; + if(dir == 1) run_low_set(run_start); + else run_low_set(run_start - amplitude); - position_cmd = run_low; + position_cmd_set(run_low); } if(fabs(position_fb - position_cmd) < epsilon) { @@ -51,29 +51,29 @@ if(run) { } else if (timer >= pause) { timer_on = false; if(position_cmd == run_low) { - position_cmd = run_high; + position_cmd_set(run_high); } else { - position_cmd = run_low; + position_cmd_set(run_low); } } } } } else if(running) { - position_cmd = run_start; + position_cmd_set(run_start); if(fabs(position_fb - run_start) < epsilon) { - running = 0; + running_set(0); timer_on = false; } } else { if(jog_minus) { - position_cmd = position_fb - 2 * maxvel * fperiod; + position_cmd_set(position_fb - 2 * maxvel * fperiod); } else if(jog_plus) { - position_cmd = position_fb + 2 * maxvel * fperiod; + position_cmd_set(position_fb + 2 * maxvel * fperiod); } else { // Let the command track the feedback while the stepgen decelerates // to a halt, then keep the command constant there. if (fabs(position_fb - position_cmd) > (0.001 * maxvel * fperiod)) { - position_cmd = position_fb; + position_cmd_set(position_fb); } } } diff --git a/src/hal/components/streamer.c b/src/hal/components/streamer.c index 9ba349ae837..7c1d7714f52 100644 --- a/src/hal/components/streamer.c +++ b/src/hal/components/streamer.c @@ -6,7 +6,7 @@ * * Author: John Kasunich * License: GPL Version 2 -* +* * Copyright (c) 2006 All rights reserved. * ********************************************************************/ @@ -14,8 +14,8 @@ that allows numbers stored in a file to be "streamed" onto HAL pins at a uniform realtime sample rate. When the realtime module is loaded, it creates a fifo in shared memory. Then, the user - space program 'hal_streamer' is invoked. 'hal_streamer' takes - input from stdin and writes it to the fifo, and this component + space program 'hal_streamer' is invoked. 'hal_streamer' takes + input from stdin and writes it to the fifo, and this component transfers the data from the fifo to HAL pins. Loading: @@ -89,14 +89,14 @@ RTAPI_MP_ARRAY_INT(depth,MAX_STREAMERS,"fifo depth"); typedef struct { hal_stream_t fifo; /* pointer to user/RT fifo */ - hal_s32_t *curr_depth; /* pin: current fifo depth */ - hal_bit_t *empty; /* pin: underrun flag */ - hal_bit_t *enable; /* pin: enable streaming */ - hal_s32_t *underruns; /* pin: number of underruns */ - hal_bit_t *clock; /* pin: clock input */ - hal_s32_t *clock_mode; /* pin: clock mode */ + hal_sint_t curr_depth; /* pin: current fifo depth */ + hal_bool_t empty; /* pin: underrun flag */ + hal_bool_t enable; /* pin: enable streaming */ + hal_sint_t underruns; /* pin: number of underruns */ + hal_bool_t clock; /* pin: clock input */ + hal_sint_t clock_mode; /* pin: clock mode */ + hal_refs_u pins[HAL_STREAM_MAX_PINS]; int myclockedge; /* clock edge detector */ - pin_data_t pins[HAL_STREAM_MAX_PINS]; } streamer_t; /* other globals */ @@ -168,192 +168,135 @@ void rtapi_app_exit(void) static void update(void *arg, long period) { (void)period; - streamer_t *str; - pin_data_t *pptr; - int n, doclk; + streamer_t *str = (streamer_t *)arg; /* point at streamer struct in HAL shmem */ + int doclk = 0; - /* point at streamer struct in HAL shmem */ - str = arg; /* keep last two clock states to get all possible clock edges */ - int myclockedge = - str->myclockedge=((str->myclockedge<<1) | (*(str->clock) & 1)) & 3; + int myclockedge = str->myclockedge=((str->myclockedge<<1) | (hal_get_bool(str->clock) & 1)) & 3; /* are we enabled? - generate doclock if enabled and right mode */ - doclk=0; - if ( *(str->enable) ) { - doclk=1; - switch (*str->clock_mode) { - /* clock-mode 0 means do clock if enabled */ - case 0: - break; - /* clock-mode 1 means enabled & falling edge */ - case 1: - if ( myclockedge!=2) { - doclk=0; - } - break; - /* clock-mode 2 means enabled & rising edge */ - case 2: - if ( myclockedge!=1) { - doclk=0; - } - break; - /* clock-mode 3 means enabled & both edges */ - case 3: - if ((myclockedge==0) | ( myclockedge==3)) { - doclk=0; - } - break; - default: - break; - } + if (hal_get_bool(str->enable)) { + doclk = 1; + switch (hal_get_si32(str->clock_mode)) { + /* clock-mode 0 means do clock if enabled */ + case 0: + break; + /* clock-mode 1 means enabled & falling edge */ + case 1: + if (2 != myclockedge) { + doclk = 0; + } + break; + /* clock-mode 2 means enabled & rising edge */ + case 2: + if (1 != myclockedge) { + doclk = 0; + } + break; + /* clock-mode 3 means enabled & both edges */ + case 3: + if (0 == myclockedge || 3 == myclockedge) { + doclk = 0; + } + break; + default: + break; + } } - /* pint at HAL pins */ - pptr = str->pins; /* point at user/RT fifo in other shmem */ int depth = hal_stream_depth(&str->fifo); - *(str->curr_depth) = depth; - *(str->empty) = depth == 0; + hal_set_si32(str->curr_depth, depth); + hal_set_bool(str->empty, depth == 0); if(!doclk) - /* done - output pins retain current values */ - return; + return; /* done - output pins retain current values */ if(depth == 0) { - /* increase underrun only for valid clock*/ - (*str->underruns)++; - return; + /* increase underrun only for valid clock*/ + hal_set_si32(str->underruns, hal_get_si32(str->underruns) + 1); + return; } union hal_stream_data data[HAL_STREAM_MAX_PINS]; - if(hal_stream_read(&str->fifo, data, NULL) < 0) - { + if(hal_stream_read(&str->fifo, data, NULL) < 0) { /* should not happen (single reader invariant) */ - (*str->underruns)++; - return; + hal_set_si32(str->underruns, hal_get_si32(str->underruns) + 1); + return; } - union hal_stream_data *dptr = data; int num_pins = hal_stream_element_count(&str->fifo); /* copy data from fifo to HAL pins */ - for ( n = 0 ; n < num_pins ; n++ ) { - switch ( hal_stream_element_type(&str->fifo, n) ) { - case HAL_FLOAT: - *(pptr->hfloat) = dptr->f; - break; - case HAL_BIT: - if ( dptr->b ) { - *(pptr->hbit) = 1; - } else { - *(pptr->hbit) = 0; - } - break; - case HAL_U32: - *(pptr->hu32) = dptr->u; - break; - case HAL_S32: - *(pptr->hs32) = dptr->s; - break; - default: - break; - } - dptr++; - pptr++; + for (int n = 0; n < num_pins; n++) { + switch ( hal_stream_element_type(&str->fifo, n) ) { + case HAL_REAL: hal_set_real(str->pins[n].r, data[n].f); break; + case HAL_S32: hal_set_si32(str->pins[n].s, data[n].s); break; + case HAL_U32: hal_set_ui32(str->pins[n].u, data[n].u); break; + case HAL_SINT: hal_set_sint(str->pins[n].s, data[n].l); break; + case HAL_UINT: hal_set_uint(str->pins[n].u, data[n].k); break; + case HAL_BOOL: hal_set_bool(str->pins[n].b, data[n].b); break; + default: + break; + } } } static int init_streamer(int num, streamer_t *str) { - int retval, n, usefp; - pin_data_t *pptr; - char buf[HAL_NAME_LEN + 1]; - + int retval; + static const char strbase[] = "streamer."; /* export "standard" pins and params */ - retval = hal_pin_bit_newf(HAL_OUT, &(str->empty), comp_id, - "streamer.%d.empty", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &str->empty, 1, "%s%d.empty", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'empty' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'empty' pin export failed\n"); + return -EIO; } - retval = hal_pin_bit_newf(HAL_IN, &(str->enable), comp_id, - "streamer.%d.enable", num); + retval = hal_pin_new_bool(comp_id, HAL_IN, &str->enable, 1, "%s%d.enable", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'enable' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'enable' pin export failed\n"); + return -EIO; } - retval = hal_pin_s32_newf(HAL_OUT, &(str->curr_depth), comp_id, - "streamer.%d.curr-depth", num); + retval = hal_pin_new_si32(comp_id, HAL_OUT, &str->curr_depth, 0, "%s%d.curr-depth", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'curr_depth' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'curr_depth' pin export failed\n"); + return -EIO; } - retval = hal_pin_s32_newf(HAL_IO, &(str->underruns), comp_id, - "streamer.%d.underruns", num); + retval = hal_pin_new_si32(comp_id, HAL_IO, &str->underruns, 0, "%s%d.underruns", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'underruns' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'underruns' pin export failed\n"); + return -EIO; } - - retval = hal_pin_bit_newf(HAL_IN, &(str->clock), comp_id, - "streamer.%d.clock", num); + retval = hal_pin_new_bool(comp_id, HAL_IN, &str->clock, 0, "%s%d.clock", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'clock' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'clock' pin export failed\n"); + return -EIO; } - - retval = hal_pin_s32_newf(HAL_IN, &(str->clock_mode), comp_id, - "streamer.%d.clock-mode", num); + retval = hal_pin_new_si32(comp_id, HAL_IN, &str->clock_mode, 0, "%s%d.clock-mode", strbase, num); if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: 'clock_mode' pin export failed\n"); - return -EIO; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: 'clock_mode' pin export failed\n"); + return -EIO; } - /* init the standard pins and params */ - *(str->empty) = 1; - *(str->enable) = 1; - *(str->curr_depth) = 0; - *(str->underruns) = 0; - *(str->clock_mode) = 0; - pptr = str->pins; - usefp = 0; /* export user specified pins (the ones that stream data) */ - for ( n = 0 ; n < hal_stream_element_count(&str->fifo); n++ ) { - rtapi_snprintf(buf, sizeof(buf), "streamer.%d.pin.%d", num, n); - retval = hal_pin_new(buf, hal_stream_element_type(&str->fifo, n), HAL_OUT, (void **)pptr, comp_id ); - if (retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: pin '%s' export failed\n", buf); - return -EIO; - } - /* init the pin value */ - switch ( hal_stream_element_type(&str->fifo, n) ) { - case HAL_FLOAT: - *(pptr->hfloat) = 0.0; - usefp = 1; - break; - case HAL_BIT: - *(pptr->hbit) = 0; - break; - case HAL_U32: - *(pptr->hu32) = 0; - break; - case HAL_S32: - *(pptr->hs32) = 0; - break; - default: - break; - } - pptr++; + for (int n = 0; n < hal_stream_element_count(&str->fifo); n++) { + static const char pstr[] = "streamer.%d.pin.%d"; + int type; + switch(type = hal_stream_element_type(&str->fifo, n)) { + case HAL_REAL: retval = hal_pin_new_real(comp_id, HAL_OUT, &str->pins[n].r, 0.0, pstr, num, n); break; + case HAL_S32: retval = hal_pin_new_si32(comp_id, HAL_OUT, &str->pins[n].s, 0, pstr, num, n); break; + case HAL_U32: retval = hal_pin_new_ui32(comp_id, HAL_OUT, &str->pins[n].u, 0, pstr, num, n); break; + case HAL_SINT: retval = hal_pin_new_sint(comp_id, HAL_OUT, &str->pins[n].s, 0, pstr, num, n); break; + case HAL_UINT: retval = hal_pin_new_uint(comp_id, HAL_OUT, &str->pins[n].u, 0, pstr, num, n); break; + case HAL_BOOL: retval = hal_pin_new_bool(comp_id, HAL_OUT, &str->pins[n].b, 0, pstr, num, n); break; + default: + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: stream type for pin %d has bad type %d\n", n, type); + return -EIO; + } + if (retval != 0 ) { + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: pin '%d' export failed\n", n); + return -EIO; + } } /* export update function */ - retval = hal_export_functf(update, str, usefp, 0, comp_id, "streamer.%d", num); + retval = hal_export_functf(update, str, 1, 0, comp_id, "%s%d", strbase, num); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "STREAMER: ERROR: function export failed\n"); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "STREAMER: ERROR: function export failed\n"); + return retval; } return 0; } - diff --git a/src/hal/components/streamer.h b/src/hal/components/streamer.h index 656df5095ba..b0ab01c1c59 100644 --- a/src/hal/components/streamer.h +++ b/src/hal/components/streamer.h @@ -10,19 +10,12 @@ * ********************************************************************/ +#ifndef __HAL_COMPONENT_STREAMER_H +#define __HAL_COMPONENT_STREAMER_H + #define MAX_STREAMERS 8 #define MAX_SAMPLERS 8 -#define MAX_PINS 20 -#define MAX_SHMEM 128000 #define STREAMER_SHMEM_KEY 0x48535430 #define SAMPLER_SHMEM_KEY 0x48534130 -/* this struct lives in HAL shared memory */ - -typedef union { - hal_bit_t *hbit; - hal_float_t *hfloat; - hal_u32_t *hu32; - hal_s32_t *hs32; -} pin_data_t; - +#endif diff --git a/src/hal/components/streamer_usr.c b/src/hal/components/streamer_usr.c index 866a3f560e0..c6864e1a0e0 100644 --- a/src/hal/components/streamer_usr.c +++ b/src/hal/components/streamer_usr.c @@ -207,6 +207,12 @@ int main(int argc, char **argv) case HAL_S32: dptr->s = strtol(cp, &cp2, 10); break; + case HAL_U64: + dptr->k = strtoull(cp, &cp2, 10); + break; + case HAL_S64: + dptr->l = strtoll(cp, &cp2, 10); + break; default: /* better not happen */ goto out; diff --git a/src/hal/components/sum2.comp b/src/hal/components/sum2.comp index cfeab4792ac..387ac548572 100644 --- a/src/hal/components/sum2.comp +++ b/src/hal/components/sum2.comp @@ -1,16 +1,16 @@ component sum2 "Sum of two inputs (each with a gain) and an offset"; see_also "scaled_s32_sums(9), weighted_sum(9)"; -pin in float in0; -pin in float in1; -param rw float gain0 = 1.0; -param rw float gain1 = 1.0; -param rw float offset; -pin out float out "out = in0 * gain0 + in1 * gain1 + offset"; +pin in real in0; +pin in real in1; +param rw real gain0 = 1.0; +param rw real gain1 = 1.0; +param rw real offset; +pin out real out "out = in0 * gain0 + in1 * gain1 + offset"; option period no; function _; license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - out = in0 * gain0 + in1 * gain1 + offset; + out_set(in0 * gain0 + in1 * gain1 + offset); } diff --git a/src/hal/components/supply.c b/src/hal/components/supply.c index 112d9fac7e6..8591cbe865f 100644 --- a/src/hal/components/supply.c +++ b/src/hal/components/supply.c @@ -63,12 +63,12 @@ RTAPI_MP_INT(num_chan, "number of channels"); */ typedef struct { - hal_bit_t *q; /* pin: q output of simulated flip-flop */ - hal_bit_t *_q; /* pin: /q output of simulated flip-flop */ - hal_float_t *variable; /* pin: output set by param "value" */ - hal_float_t *_variable; /* pin: output set by param "value" * -1.0 */ - hal_bit_t *d; /* pin: d input to simulated flip-flop */ - hal_float_t *value; /* pin: value of float pin "variable" */ + hal_bool_t q; /* pin: q output of simulated flip-flop */ + hal_bool_t _q; /* pin: /q output of simulated flip-flop */ + hal_real_t variable; /* pin: output set by param "value" */ + hal_real_t _variable; /* pin: output set by param "value" * -1.0 */ + hal_bool_t d; /* pin: d input to simulated flip-flop */ + hal_real_t value; /* pin: value of float pin "variable" */ } hal_supply_t; /* pointer to supply_t struct */ @@ -141,15 +141,16 @@ void rtapi_app_exit(void) static void update_supply(void *arg, long l) { (void)l; - hal_supply_t *supply; - /* point to the data */ - supply = arg; + hal_supply_t *supply = arg; + /* set pin = param */ - *(supply->q) = *(supply->d); - *(supply->_q) = !(*(supply->d)); - *(supply->variable) = *(supply->value); - *(supply->_variable) = *(supply->value) * -1.0; + rtapi_bool d = hal_get_bool(supply->d); + hal_set_bool(supply->q, d); + hal_set_bool(supply->_q, !d); + rtapi_real value = hal_get_real(supply->value); + hal_set_real(supply->variable, value); + hal_set_real(supply->_variable, value * -1.0); /* done */ } @@ -162,38 +163,31 @@ static int export_supply(int num, hal_supply_t * addr) int retval; /* export pins */ - retval = hal_pin_bit_newf(HAL_OUT, &(addr->q), comp_id, "supply.%d.q", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->q), 0, "supply.%d.q", num); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(addr->_q), comp_id, "supply.%d._q", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(addr->_q), 1, "supply.%d._q", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->variable), comp_id,"supply.%d.variable", num); + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->variable), 0.0,"supply.%d.variable", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(addr->_variable), comp_id, "supply.%d._variable", num); + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->_variable), 0.0, "supply.%d._variable", num); if (retval != 0) { return retval; } /* export parameters */ - retval = hal_pin_bit_newf(HAL_IO, &(addr->d), comp_id, "supply.%d.d", num); + retval = hal_pin_new_bool(comp_id, HAL_IO, &(addr->d), 0, "supply.%d.d", num); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_IO, &(addr->value), comp_id, "supply.%d.value", num); + retval = hal_pin_new_real(comp_id, HAL_IO, &(addr->value), 0.0, "supply.%d.value", num); if (retval != 0) { return retval; } - /* init all structure members */ - *(addr->q) = 0; - *(addr->_q) = 1; - *(addr->variable) = 0.0; - *(addr->_variable) = 0.0; - *(addr->d) = 0; - *(addr->value) = 0.0; /* export function for this loop */ retval = hal_export_functf(update_supply, &(supply_array[num]), 1, 0, diff --git a/src/hal/components/thc.comp b/src/hal/components/thc.comp index 42341dedbae..41adf2d69c5 100644 --- a/src/hal/components/thc.comp +++ b/src/hal/components/thc.comp @@ -59,33 +59,33 @@ license "GPLv2 or greater"; option singleton yes; // Input Pins -pin in float encoder_vel "Connect to hm2_5i20.0.encoder.00.velocity"; -pin in float current_vel "Connect to motion.current-vel"; -pin in float requested_vel "Connect to motion.requested-vel"; -pin in float volts_requested "Tip Volts current_vel >= min_velocity requested"; -pin in float vel_tol "Velocity Tolerance (Corner Lock)"; -pin in bit torch_on "Connect to spindle.N.on"; -pin in bit arc_ok "Arc OK from Plasma Torch"; -pin in bit enable "Enable the THC, if not enabled Z position is passed through"; -pin in float z_pos_in "Z Motor Position Command in from axis.n.motor-pos-cmd"; +pin in real encoder_vel "Connect to hm2_5i20.0.encoder.00.velocity"; +pin in real current_vel "Connect to motion.current-vel"; +pin in real requested_vel "Connect to motion.requested-vel"; +pin in real volts_requested "Tip Volts current_vel >= min_velocity requested"; +pin in real vel_tol "Velocity Tolerance (Corner Lock)"; +pin in bool torch_on "Connect to spindle.N.on"; +pin in bool arc_ok "Arc OK from Plasma Torch"; +pin in bool enable "Enable the THC, if not enabled Z position is passed through"; +pin in real z_pos_in "Z Motor Position Command in from axis.n.motor-pos-cmd"; // Output Pins -pin out float z_pos_out "Z Motor Position Command Out"; -pin out float z_fb_out "Z Position Feedback to Axis"; -pin out float volts "The Calculated Volts"; -pin out bit vel_status "When the THC thinks we are at requested speed"; -pin out float offset_value "The Current Offset"; +pin out real z_pos_out "Z Motor Position Command Out"; +pin out real z_fb_out "Z Position Feedback to Axis"; +pin out real volts "The Calculated Volts"; +pin out bool vel_status "When the THC thinks we are at requested speed"; +pin out real offset_value "The Current Offset"; // Parameters -param rw float vel_scale "The scale to convert the Velocity signal to Volts"; -param rw float scale_offset "The offset of the velocity input at 0 volts"; -param rw float velocity_tol "The deviation percent from planned velocity"; -param rw float voltage_tol "The deviation of Tip Voltage before correction takes place"; -param rw float correction_vel "The amount of change in user units per period to move Z to correct"; +param rw real vel_scale "The scale to convert the Velocity signal to Volts"; +param rw real scale_offset "The offset of the velocity input at 0 volts"; +param rw real velocity_tol "The deviation percent from planned velocity"; +param rw real voltage_tol "The deviation of Tip Voltage before correction takes place"; +param rw real correction_vel "The amount of change in user units per period to move Z to correct"; // Global Variables -variable float offset; -variable float last_z_in; +variable rtapi_real offset; +variable rtapi_real last_z_in; option period no; function _; @@ -96,14 +96,14 @@ function _; FUNCTION(_) { // convert encoder velocity to volts - volts = (encoder_vel - scale_offset) * vel_scale; - if(volts < 0){volts = 0;} // make sure volts is not negative - offset_value = offset; + volts_set((encoder_vel - scale_offset) * vel_scale); + if(volts < 0){volts_set(0);} // make sure volts is not negative + offset_value_set(offset); if(enable){ - float min_velocity = requested_vel -(requested_vel*(velocity_tol*0.01)); - if(current_vel > 0 && current_vel >= min_velocity){vel_status = 1;} - else {vel_status =0;} + rtapi_real min_velocity = requested_vel -(requested_vel*(velocity_tol*0.01)); + if(current_vel > 0 && current_vel >= min_velocity){vel_status_set(1);} + else {vel_status_set(0);} if(torch_on && arc_ok && vel_status){ // allow correction if((volts + voltage_tol) > volts_requested){ @@ -115,7 +115,7 @@ FUNCTION(_) { last_z_in = 0; } if(!torch_on){ // remove any offset - float z_diff; + rtapi_real z_diff; z_diff = z_pos_in - last_z_in; if(z_diff > 0 && offset != 0){ // torch is moving up if(offset > 0){ // positive offset @@ -133,12 +133,12 @@ FUNCTION(_) { } last_z_in = z_pos_in; } - z_pos_out = z_pos_in + offset; - z_fb_out = z_pos_in; // keep axis motor position fb from being confused + z_pos_out_set(z_pos_in + offset); + z_fb_out_set(z_pos_in); // keep axis motor position fb from being confused } if(!enable){ - z_pos_out = z_pos_in; - z_fb_out = z_pos_in; // keep axis motor position fb from being confused + z_pos_out_set(z_pos_in); + z_fb_out_set(z_pos_in); // keep axis motor position fb from being confused } } diff --git a/src/hal/components/thcud.comp b/src/hal/components/thcud.comp index ce9938efda0..cdfdd169408 100644 --- a/src/hal/components/thcud.comp +++ b/src/hal/components/thcud.comp @@ -69,28 +69,28 @@ license "GPLv2 or greater"; option singleton yes; // Input Pins -pin in bit torch_up "Connect to an input pin"; -pin in bit torch_down "Connect to input pin"; -pin in float current_vel "Connect to motion.current-vel"; -pin in float requested_vel "Connect to motion.requested-vel"; -pin in bit torch_on "Connect to spindle.N.on"; -pin in bit arc_ok "Arc Ok from Plasma Torch"; -pin in bit enable "Enable the THC, if not enabled Z position is passed through"; -pin in float z_pos_in "Z Motor Position Command in from axis.n.motor-pos-cmd"; +pin in bool torch_up "Connect to an input pin"; +pin in bool torch_down "Connect to input pin"; +pin in real current_vel "Connect to motion.current-vel"; +pin in real requested_vel "Connect to motion.requested-vel"; +pin in bool torch_on "Connect to spindle.N.on"; +pin in bool arc_ok "Arc Ok from Plasma Torch"; +pin in bool enable "Enable the THC, if not enabled Z position is passed through"; +pin in real z_pos_in "Z Motor Position Command in from axis.n.motor-pos-cmd"; // Output Pins -pin out float z_pos_out "Z Motor Position Command Out"; -pin out float z_fb_out "Z Position Feedback to Axis"; -pin out float cur_offset "The Current Offset"; -pin out bit vel_status "When the THC thinks we are at requested speed"; -pin out bit removing_offset "Pin for testing"; -pin in float correction_vel "The Velocity to move Z to correct"; +pin out real z_pos_out "Z Motor Position Command Out"; +pin out real z_fb_out "Z Position Feedback to Axis"; +pin out real cur_offset "The Current Offset"; +pin out bool vel_status "When the THC thinks we are at requested speed"; +pin out bool removing_offset "Pin for testing"; +pin in real correction_vel "The Velocity to move Z to correct"; // Parameters -param rw float velocity_tol "The deviation percent from planned velocity"; +param rw real velocity_tol "The deviation percent from planned velocity"; // Global Variables -variable float last_z_in; +variable rtapi_real last_z_in; option period no; function _; @@ -101,46 +101,46 @@ function _; FUNCTION(_) { if(enable){ - float min_velocity = requested_vel -(requested_vel*(velocity_tol*0.01)); - if(current_vel > 0 && current_vel >= min_velocity){vel_status = 1;} - else {vel_status =0;} + rtapi_real min_velocity = requested_vel -(requested_vel*(velocity_tol*0.01)); + if(current_vel > 0 && current_vel >= min_velocity){vel_status_set(1);} + else {vel_status_set(0);} if(torch_on && arc_ok && vel_status){ // allow correction if(torch_down){ - cur_offset -= correction_vel; + cur_offset_set(cur_offset - correction_vel); } if(torch_up){ - cur_offset += correction_vel; + cur_offset_set(cur_offset + correction_vel); } last_z_in = 0; } if(!torch_on){ // remove any offset - float z_diff; + rtapi_real z_diff; z_diff = z_pos_in - last_z_in; if(z_diff > 0 && cur_offset != 0){ // torch is moving up - removing_offset = 1; + removing_offset_set(1); if(cur_offset > 0){ // positive offset if(cur_offset > z_diff){ // remove some - cur_offset -= z_diff; + cur_offset_set(cur_offset - z_diff); } - else {cur_offset = 0;} + else {cur_offset_set(0);} } if(cur_offset < 0){ // negative offset if(cur_offset < z_diff){ // remove some - cur_offset += z_diff; + cur_offset_set(cur_offset + z_diff); } - else {cur_offset = 0;} + else {cur_offset_set(0);} } } - else {removing_offset = 0;} + else {removing_offset_set(0);} last_z_in = z_pos_in; } - z_pos_out = z_pos_in + cur_offset; - z_fb_out = z_pos_in; // keep axis motor position fb from being confused + z_pos_out_set(z_pos_in + cur_offset); + z_fb_out_set(z_pos_in); // keep axis motor position fb from being confused } if(!enable){ - z_pos_out = z_pos_in + cur_offset; - z_fb_out = z_pos_in; // keep axis motor position fb from being confused + z_pos_out_set(z_pos_in + cur_offset); + z_fb_out_set(z_pos_in); // keep axis motor position fb from being confused } } diff --git a/src/hal/components/threadtest.comp b/src/hal/components/threadtest.comp index 30e42641917..50c20772ca6 100644 --- a/src/hal/components/threadtest.comp +++ b/src/hal/components/threadtest.comp @@ -1,5 +1,5 @@ component threadtest "LinuxCNC HAL component for testing thread behavior"; -pin out unsigned count; +pin out ui32 count; option period no; function increment; function reset; @@ -8,5 +8,5 @@ author "Jeff Epler"; ;; -FUNCTION(increment) { count++; } -FUNCTION(reset) { count=0; } +FUNCTION(increment) { count_set(count + 1); } +FUNCTION(reset) { count_set(0); } diff --git a/src/hal/components/time.comp b/src/hal/components/time.comp index ef6c6f309d3..532cf097591 100644 --- a/src/hal/components/time.comp +++ b/src/hal/components/time.comp @@ -100,16 +100,16 @@ author "John Thornton, itaib, Moses McKnight"; license "GPL"; // Input Pins -pin in bit start "Timer On"; -pin in bit pause = 0 "Pause"; +pin in bool start "Timer On"; +pin in bool pause = 0 "Pause"; // Output Pins -pin out u32 seconds "Seconds"; -pin out u32 minutes "Minutes"; -pin out u32 hours "Hours"; +pin out ui32 seconds "Seconds"; +pin out ui32 minutes "Minutes"; +pin out ui32 hours "Hours"; // Global Variables -variable double totalnsec; +variable rtapi_real totalnsec; variable int old_start; function _; @@ -120,16 +120,16 @@ function _; FUNCTION(_) { rtapi_u32 totalseconds; - int running = start | pause; + int running = start || pause; if(running && !old_start) totalnsec = 0; if(start && !pause){ - totalnsec = totalnsec + period; - totalseconds = totalnsec * 0.000000001; - seconds = totalseconds % 60; - minutes = (totalseconds / 60) % 60; - hours = (totalseconds / 3600); - } - old_start = running; + totalnsec = totalnsec + period; + totalseconds = totalnsec * 0.000000001; + seconds_set(totalseconds % 60); + minutes_set((totalseconds / 60) % 60); + hours_set((totalseconds / 3600)); + } + old_start = running; } diff --git a/src/hal/components/timedelay.comp b/src/hal/components/timedelay.comp index 1459f2f0bb6..62c9896b61c 100644 --- a/src/hal/components/timedelay.comp +++ b/src/hal/components/timedelay.comp @@ -1,34 +1,34 @@ component timedelay "The equivalent of a time-delay relay"; -pin in bit in; -pin out bit out """Follows the value of *in* after applying the delays +pin in bool in; +pin out bool out """Follows the value of *in* after applying the delays *on-delay* and *off-delay*."""; -pin in float on-delay = 0.5 """The time, in seconds, for which *in* must be +pin in real on-delay = 0.5 """The time, in seconds, for which *in* must be *true* before *out* becomes *true*"""; -pin in float off-delay = 0.5 """The time, in seconds, for which *in* must be +pin in real off-delay = 0.5 """The time, in seconds, for which *in* must be *false* before *out* becomes *false*"""; -pin out float elapsed "Current value of the internal timer"; -variable double timer; +pin out real elapsed "Current value of the internal timer"; +variable rtapi_real timer; function _; license "GPL"; author "Jeff Epler, based on works by Stephen Wille Padnos and John Kasunich"; ;; -hal_bit_t in_ = in; +rtapi_bool in_ = in; if(in_ != out) { timer += fperiod; - elapsed = timer; + elapsed_set(timer); if(in_) { if(timer >= on_delay) { - out = 1; + out_set(1); timer = 0.0; } } else { if(timer >= off_delay) { - out = 0; + out_set(0); timer = 0.0; } } diff --git a/src/hal/components/timedelta.comp b/src/hal/components/timedelta.comp index 19fabe45e8b..c43fcc58b18 100644 --- a/src/hal/components/timedelta.comp +++ b/src/hal/components/timedelta.comp @@ -1,22 +1,22 @@ component timedelta "LinuxCNC HAL component that measures thread scheduling timing behavior"; -pin out s32 jitter=0 "Worst-case scheduling error (in ns). This is the largest discrepancy between ideal thread period, and actual time between sequential runs of this component. This uses the absolute value of the error, so 'got run too early' and 'got run too late' both show up as positive jitter."; +pin out si32 jitter=0 "Worst-case scheduling error (in ns). This is the largest discrepancy between ideal thread period, and actual time between sequential runs of this component. This uses the absolute value of the error, so 'got run too early' and 'got run too late' both show up as positive jitter."; -pin out s32 current_jitter=0 "Scheduling error (in ns) of the current invocation. This is the discrepancy between ideal thread period, and actual time since the previous run of this component. This uses the absolute value of the error, so 'got run too early' and 'got run too late' both show up as positive jitter."; +pin out si32 current_jitter=0 "Scheduling error (in ns) of the current invocation. This is the discrepancy between ideal thread period, and actual time since the previous run of this component. This uses the absolute value of the error, so 'got run too early' and 'got run too late' both show up as positive jitter."; -pin out s32 current_error=0 "Scheduling error (in ns) of the current invocation. This is the discrepancy between ideal thread period, and actual time since the previous run of this component. This does not use the absolute value of the error, so 'got run too early' shows up as negative error and 'got run too late' shows up as positive error."; +pin out si32 current_error=0 "Scheduling error (in ns) of the current invocation. This is the discrepancy between ideal thread period, and actual time since the previous run of this component. This does not use the absolute value of the error, so 'got run too early' shows up as negative error and 'got run too late' shows up as positive error."; -pin out s32 min_=0 "Minimum time (in ns) between sequential runs of this component."; +pin out si32 min_=0 "Minimum time (in ns) between sequential runs of this component."; -pin out s32 max_=0 "Maximum time (in ns) between sequential runs of this component."; +pin out si32 max_=0 "Maximum time (in ns) between sequential runs of this component."; -pin in bit reset "Set this pin to True, then back to False, to reset some of the statistics."; +pin in bool reset "Set this pin to True, then back to False, to reset some of the statistics."; -pin out s32 out "Time (in ns) since the previous run of this component. This should ideally be equal to the thread period."; +pin out si32 out "Time (in ns) since the previous run of this component. This should ideally be equal to the thread period."; -pin out s32 err=0 "Cumulative time error (in ns). Probably not useful."; +pin out si32 err=0 "Cumulative time error (in ns). Probably not useful."; -pin out float avg_err=0 "The average scheduling error (in ns)."; +pin out real avg_err=0 "The average scheduling error (in ns)."; function _; @@ -32,23 +32,31 @@ rtapi_s64 now = rtapi_get_time(); if(last != 0) { rtapi_s64 del = (now - last); - out = del; + out_set(del); - err = err + del - period; + err_set(err + del - period); if(first) { first = 0; - min_ = max_ = del; - jitter = 0; + min__set(del); + max__set(del); + jitter_set(0); } else { - if(del < min_) min_ = del; - if(del > max_) max_ = del; - jitter = max(max_ - period, period - min_); - current_jitter = max(del - period, period - del); - current_error = del - period; + if(del < min_) min__set(del); + if(del > max_) max__set(del); + jitter_set(max(max_ - period, period - min_)); + current_jitter_set(max(del - period, period - del)); + current_error_set(del - period); } count++; - avg_err = err / (double)count; + avg_err_set(err / (double)count); } -if(reset) { first = 1; last = 0; out = 0; jitter = 0; max_ = 0; } -else last = now; +if(reset) { + first = 1; + last = 0; + out_set(0); + jitter_set(0); + max__set(0); +} else { + last = now; +} diff --git a/src/hal/components/tof.comp b/src/hal/components/tof.comp index c942bb1695b..1afba81b9f6 100644 --- a/src/hal/components/tof.comp +++ b/src/hal/components/tof.comp @@ -18,11 +18,11 @@ * ********************************************************************/ component tof "IEC TOF timer - delay falling edge on a signal"; -pin in bit in "Input signal"; -pin out bit q "Output signal"; -pin out float et "Elapsed time since falling edge in seconds"; +pin in bool in "Input signal"; +pin out bool q "Output signal"; +pin out real et "Elapsed time since falling edge in seconds"; -param rw float pt "Delay time in seconds"; +param rw real pt "Delay time in seconds"; function _ "Update the timer"; license "GPL"; @@ -30,12 +30,12 @@ author "Chad Woitas"; ;; FUNCTION(_) { if(pt < 0) { - pt = 0; + pt_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "tof: Delay time must be positive, resetting to 0"); } if(et < 0) { - et = 0; + et_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "tof: Elapsed time rolled over, resetting to 0"); } @@ -43,16 +43,16 @@ FUNCTION(_) { // Check timers if(in){ // Reset Variables - q = 1; - et = 0; + q_set(1); + et_set(0); } else{ // Update outputs if(et >= pt){ - q = 0; + q_set(0); } else{ - et += fperiod; + et_set(et + fperiod); } } } diff --git a/src/hal/components/toggle.comp b/src/hal/components/toggle.comp index d533844b165..f8dbb86628c 100644 --- a/src/hal/components/toggle.comp +++ b/src/hal/components/toggle.comp @@ -12,9 +12,9 @@ out: └─────┘           └───── """; -pin in bit in "button input"; -pin io bit out "on/off output"; -param rw u32 debounce = 2 "debounce delay in periods"; +pin in bool in "button input"; +pin io bool out "on/off output"; +param rw ui32 debounce = 2 "debounce delay in periods"; option data toggle_data; option period no; @@ -29,19 +29,19 @@ typedef struct { } toggle_data; FUNCTION(_) { - - if (( debounce < 1 ) || ( debounce > 10000 )) { + rtapi_u32 deb = debounce; + if (( deb < 1 ) || ( deb > 10000 )) { /* set a sane value, we don't want 2 million second delays */ - debounce = 2; + debounce_set(deb = 2); } if ( in ) { /* pressed */ data.debounce_cntr++; - if ( data.debounce_cntr >= (int)debounce ) { - data.debounce_cntr = debounce; + if ( data.debounce_cntr >= (int)deb ) { + data.debounce_cntr = deb; if ( data.debounced == 0 ) { /* toggle output */ - out = !out; + out_set(!out); } data.debounced = 1; } diff --git a/src/hal/components/toggle2nist.comp b/src/hal/components/toggle2nist.comp index df002e2bf36..6d723121369 100644 --- a/src/hal/components/toggle2nist.comp +++ b/src/hal/components/toggle2nist.comp @@ -26,13 +26,13 @@ is-on: └─────────────────┘        """; -pin in bit in "momentary button in"; -pin in bit is_on "current state of device"; -pin in unsigned debounce = 2 "debounce delay for 'in'-pin in cycles"; -pin out bit on "turn device on"; -pin out bit off "turn device off"; +pin in bool in "momentary button in"; +pin in bool is_on "current state of device"; +pin in ui32 debounce = 2 "debounce delay for 'in'-pin in cycles"; +pin out bool on "turn device on"; +pin out bool off "turn device off"; variable int debounce_cntr; -variable unsigned debounce_set; +variable unsigned debounce_val; variable int state; option period no; @@ -43,33 +43,33 @@ author "Anders Wallin, David Mueller"; FUNCTION(_) { if (( debounce < 1 ) || ( debounce > 10000 )) { - debounce_set = 2; /* set a sane value */ + debounce_val = 2; /* set a sane value */ } else { - debounce_set = debounce; + debounce_val = debounce; } if (in && state == 0 ) { /* input has changed from debounced 0 -> 1 */ debounce_cntr++; - if ( debounce_cntr >= (int)debounce_set ) { + if ( debounce_cntr >= (int)debounce_val ) { if (!is_on) { /* turn ON if it's off */ - on=1; - off=0; + on_set(1); + off_set(0); } else { /* turn OFF if it's on */ - on=0; - off=1; + on_set(0); + off_set(1); } state = 1; debounce_cntr = 0; } } else if (!in && state == 1) { /* input has changed from debounced 1 -> 0 */ debounce_cntr++; - if ( debounce_cntr >= (int)debounce_set ) { + if ( debounce_cntr >= (int)debounce_val ) { state = 0; debounce_cntr = 0; } } else if ((!is_on && off) || (is_on && on)) { /* reset outputs once device has switched*/ - on = 0; - off = 0; + on_set(0); + off_set(0); debounce_cntr = 0; } else { debounce_cntr = 0; diff --git a/src/hal/components/ton.comp b/src/hal/components/ton.comp index 90974f48b07..327e0779450 100644 --- a/src/hal/components/ton.comp +++ b/src/hal/components/ton.comp @@ -18,11 +18,11 @@ * ********************************************************************/ component ton "IEC TON timer - delay rising edge on a signal"; -pin in bit in "Input signal"; -pin out bit q "Output signal"; -pin out float et "Elapsed time since rising edge in seconds"; +pin in bool in "Input signal"; +pin out bool q "Output signal"; +pin out real et "Elapsed time since rising edge in seconds"; -param rw float pt "Delay time in seconds"; +param rw real pt "Delay time in seconds"; function _ "Update the timer"; license "GPL"; @@ -30,12 +30,12 @@ author "Chad Woitas"; ;; FUNCTION(_) { if(pt < 0) { - pt = 0; + pt_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "ton: Delay time must be positive, resetting to 0"); } if(et < 0) { - et = 0; + et_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "ton: Elapsed time rolled over, resetting to 0"); } @@ -44,15 +44,15 @@ FUNCTION(_) { if(in){ // Update outputs if(et >= pt){ - q = 1; + q_set(1); } else{ - et += fperiod; + et_set(et + fperiod); } } else{ // Reset Variables - et = 0; - q = 0; + et_set(0); + q_set(0); } } diff --git a/src/hal/components/tp.comp b/src/hal/components/tp.comp index 5d202f9f748..22b8e9b7f08 100644 --- a/src/hal/components/tp.comp +++ b/src/hal/components/tp.comp @@ -18,11 +18,11 @@ * ********************************************************************/ component tp "IEC TP timer - generate a high pulse of defined duration on rising edge"; -pin in bit in "Input signal"; -pin out bit q "Output signal"; -pin out float et "Elapsed time since start of pulse in seconds"; +pin in bool in "Input signal"; +pin out bool q "Output signal"; +pin out real et "Elapsed time since start of pulse in seconds"; -param rw float pt "Pulse time in seconds"; +param rw real pt "Pulse time in seconds"; variable int in_old; // Value of in on last cycle, for rising edge detection @@ -32,12 +32,12 @@ author "Chad Woitas"; ;; FUNCTION(_) { if(pt < 0) { - pt = 0; + pt_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "tp: Pulse time must be positive, resetting to 0"); } if(et < 0) { - et = 0; + et_set(0); rtapi_print_msg(RTAPI_MSG_WARN, "tp: Elapsed time rolled over, resetting to 0"); } @@ -46,17 +46,17 @@ FUNCTION(_) { if((in && !in_old) || q){ // Update outputs if(et < pt){ - q = 1; - et += fperiod; + q_set(1); + et_set(et + fperiod); } else{ - q = 0; + q_set(0); } } else{ // Reset Variables - et = 0; - q = 0; + et_set(0); + q_set(0); } in_old = in; } diff --git a/src/hal/components/tpcomp.comp b/src/hal/components/tpcomp.comp index 208c23444c8..abc0a84ca2c 100644 --- a/src/hal/components/tpcomp.comp +++ b/src/hal/components/tpcomp.comp @@ -37,7 +37,7 @@ https://github.com/LinuxCNC/linuxcnc/blob/BRANCHNAME/src/hal/components/tpcomp.c """; -pin out bit is_module=1; //one pin is required to use halcompile) +pin out bool is_module=1; //one pin is required to use halcompile) license "GPL"; author "Dewey Garrett"; diff --git a/src/hal/components/tristate_bit.comp b/src/hal/components/tristate_bit.comp index 9bcbeb04cb9..993cdee7935 100644 --- a/src/hal/components/tristate_bit.comp +++ b/src/hal/components/tristate_bit.comp @@ -1,12 +1,12 @@ component tristate_bit "Place a signal on an I/O pin only when enabled, similar to a tristate buffer in electronics"; -pin in bit in_ "Input value"; -pin io bit out "Output value"; -pin in bit enable "When TRUE, copy in to out"; +pin in bool in_ "Input value"; +pin io bool out "Output value"; +pin in bool enable "When TRUE, copy in to out"; option period no; function _ "If *enable* is TRUE, copy *in* to *out*."; license "GPL"; author "Jeff Epler"; ;; -if(enable) out = in_; +if(enable) out_set(in_); diff --git a/src/hal/components/tristate_float.comp b/src/hal/components/tristate_float.comp index 72c484d20ab..0414f1f44cb 100644 --- a/src/hal/components/tristate_float.comp +++ b/src/hal/components/tristate_float.comp @@ -1,8 +1,8 @@ component tristate_float "Place a signal on an I/O pin only when enabled, similar to a tristate buffer in electronics"; -pin in float in_ "Input value"; -pin io float out "Output value"; -pin in bit enable "When TRUE, copy in to out"; +pin in real in_ "Input value"; +pin io real out "Output value"; +pin in bool enable "When TRUE, copy in to out"; option period no; function _ "If *enable* is TRUE, copy *in* to *out*."; @@ -10,4 +10,4 @@ license "GPL"; author "Jeff Epler"; ;; -FUNCTION(_) { if(enable) out = in_; } +FUNCTION(_) { if(enable) out_set(in_); } diff --git a/src/hal/components/updown.comp b/src/hal/components/updown.comp index 45b059f15be..51bea6764be 100644 --- a/src/hal/components/updown.comp +++ b/src/hal/components/updown.comp @@ -1,12 +1,12 @@ component updown "Counts up or down, with optional limits and wraparound behavior"; -pin in bit countup "Increment count when this pin goes from 0 to 1"; -pin in bit countdown "Decrement count when this pin goes from 0 to 1"; -pin in bit reset "Reset count when this pin goes from 0 to 1"; -pin out s32 count "The current count"; -param rw bit clamp "If TRUE, then clamp the output to the min and max parameters."; -param rw bit wrap "If TRUE, then wrap around when the count goes above or below the min and max parameters. Note that wrap implies (and overrides) clamp."; -param rw s32 max = 0x7FFFFFFF "If clamp or wrap is set, count will never exceed this number"; -param rw s32 min "If clamp or wrap is set, count will never be less than this number"; +pin in bool countup "Increment count when this pin goes from 0 to 1"; +pin in bool countdown "Decrement count when this pin goes from 0 to 1"; +pin in bool reset "Reset count when this pin goes from 0 to 1"; +pin out si32 count "The current count"; +param rw bool clamp_ "If TRUE, then clamp the output to the min and max parameters."; +param rw bool wrap "If TRUE, then wrap around when the count goes above or below the min and max parameters. Note that wrap implies (and overrides) clamp."; +param rw si32 max_ = 0x7FFFFFFF "If clamp or wrap is set, count will never exceed this number"; +param rw si32 min_ "If clamp or wrap is set, count will never be less than this number"; variable int oldup; variable int olddown; variable int first = 1; @@ -18,7 +18,7 @@ author "Stephen Wille Padnos"; ;; FUNCTION(_) { - hal_s32_t temp_count = count; + rtapi_s32 temp_count = count; if (first) { oldup=countup; olddown=countdown; @@ -34,17 +34,17 @@ FUNCTION(_) { temp_count=0; } if (wrap) { - if (temp_count > max) - temp_count = min; - else if (temp_count < min) - temp_count = max; - } else if (clamp) { - if (temp_count > max) - temp_count = max; - else if (temp_count < min) - temp_count = min; + if (temp_count > max_) + temp_count = min_; + else if (temp_count < min_) + temp_count = max_; + } else if (clamp_) { + if (temp_count > max_) + temp_count = max_; + else if (temp_count < min_) + temp_count = min_; } - count = temp_count; + count_set(temp_count); oldup = countup; olddown = countdown; } diff --git a/src/hal/components/userkins.comp b/src/hal/components/userkins.comp index 427e98fdb34..85e8800c02a 100644 --- a/src/hal/components/userkins.comp +++ b/src/hal/components/userkins.comp @@ -59,7 +59,7 @@ change all instances of `userkins` to `mykins`. """; // The fpin pin is not accessible in kinematics functions. // Use the *_setup() function for pins and params used by kinematics. -pin out s32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; +pin out si32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; option period no; function fdemo; license "GPL"; @@ -71,17 +71,17 @@ author "Dewey Garrett"; static struct haldata { // Example pin pointers - hal_u32_t *in; - hal_u32_t *out; + hal_uint_t in; + hal_uint_t out; // Example parameters - hal_float_t param_rw; - hal_float_t param_ro; + hal_real_t param_rw; + hal_real_t param_ro; } *haldata; // hal pin/param types: -// hal_bit_t bit -// hal_u32_t unsigned 32bit integer -// hal_s32_t signed 32bit integer -// hal_float_t float (double precision) +// hal_bool_t boolean bit +// hal_uint_t unsigned integer +// hal_sint_t signed integer +// hal_real_t floating point (double precision) FUNCTION(fdemo) { // This function can be added to a thread (addf) for @@ -89,7 +89,7 @@ FUNCTION(fdemo) { if (fpin == 0) { rtapi_print("fdemo function added to thread\n"); } - fpin++; + fpin_set(fpin + 1); } static int userkins_setup(void) { @@ -105,12 +105,12 @@ static int userkins_setup(void) { if (!haldata) goto error; // hal pin examples: - res += hal_pin_u32_newf(HAL_IN ,&(haldata->in) ,comp_id,"%s.in" ,HAL_PREFIX); - res += hal_pin_u32_newf(HAL_OUT,&(haldata->out),comp_id,"%s.out",HAL_PREFIX); + res += hal_pin_new_ui32(comp_id, HAL_IN , &(haldata->in) , 0, "%s.in" , HAL_PREFIX); + res += hal_pin_new_ui32(comp_id, HAL_OUT, &(haldata->out), 0, "%s.out", HAL_PREFIX); // hal parameter examples: - res += hal_param_float_newf(HAL_RW, &haldata->param_rw,comp_id,"%s.param-rw",HAL_PREFIX); - res += hal_param_float_newf(HAL_RO, &haldata->param_ro,comp_id,"%s.param-ro",HAL_PREFIX); + res += hal_param_new_real(comp_id, HAL_RW, &haldata->param_rw, 0.0, "%s.param-rw", HAL_PREFIX); + res += hal_param_new_real(comp_id, HAL_RO, &haldata->param_ro, 0.0, "%s.param-ro", HAL_PREFIX); if (res) goto error; hal_ready(comp_id); @@ -160,7 +160,7 @@ int kinematicsForward(const double *j, pos->v = 0; pos->w = 0; - if (*haldata->in && !is_ready && !gave_msg) { + if (hal_get_ui32(haldata->in) && !is_ready && !gave_msg) { rtapi_print_msg(RTAPI_MSG_ERR, "%s The 'in' pin not echoed until Inverse called\n", __FILE__); @@ -190,8 +190,8 @@ int kinematicsInverse(const EmcPose * pos, j[2] = pos->tran.z; // joint 2 //example hal pin update (homing reqd before kinematicsInverse) - *haldata->out = *haldata->in; //dereference - //read from param example: *haldata->out = haldata->param_rw; + hal_set_ui32(haldata->out, hal_get_ui32(haldata->in)); //dereference + //read from param example: hal_set_ui32(haldata->out, hal_get_real(haldata->param_rw)); return 0; } // kinematicsInverse() diff --git a/src/hal/components/watchdog.c b/src/hal/components/watchdog.c index 943e6d91c47..13184352209 100644 --- a/src/hal/components/watchdog.c +++ b/src/hal/components/watchdog.c @@ -38,27 +38,27 @@ RTAPI_MP_INT(num_inputs, "Number of inputs"); /* Data needed for each input */ typedef struct { - hal_bit_t *input; /* pin: the input bit HAL pin */ - hal_float_t timeout; /* param: maximum alloewd timeb without a transition on bit */ - hal_float_t oldtimeout; /* internal: used to determine whether the timeout has changed */ - hal_s32_t c_secs, c_nsecs; /* internal: elapsed seconds and nanoseconds */ - hal_s32_t t_secs, t_nsecs; /* internal: seconds and nanoseconds for timeout */ - hal_bit_t last; /* internal: last value of the input pin */ + hal_bool_t input; /* pin: the input bit HAL pin */ + hal_real_t timeout; /* param: maximum alloewd timeb without a transition on bit */ + rtapi_real oldtimeout; /* internal: used to determine whether the timeout has changed */ + rtapi_s32 c_secs, c_nsecs; /* internal: elapsed seconds and nanoseconds */ + rtapi_s32 t_secs, t_nsecs; /* internal: seconds and nanoseconds for timeout */ + rtapi_bool last; /* internal: last value of the input pin */ } watchdog_input_t; #define MAX_INPUTS 32 /* Base data for a weighted summer. */ typedef struct { - hal_bit_t *output; /* output pin: high if all inputs are toggling, low otherwise */ - hal_bit_t *enable; /* pin: only runs while this is high (kind of like an enable) */ + hal_bool_t output; /* output pin: high if all inputs are toggling, low otherwise */ + hal_bool_t enable; /* pin: only runs while this is high (kind of like an enable) */ } watchdog_data_t; /* other globals */ static int comp_id; /* component ID */ watchdog_input_t *inputs; /* internal: pointer to the input bits and weights */ watchdog_data_t *data; /* common data */ -hal_bit_t old_enable; +rtapi_bool old_enable; /*********************************************************************** * LOCAL FUNCTION DECLARATIONS * ************************************************************************/ @@ -96,7 +96,7 @@ int rtapi_app_main(void) } /* allocate shared memory for watchdog global and pin info */ - data = hal_malloc(sizeof(watchdog_data_t)); + data = hal_malloc(sizeof(*data)); if (data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: hal_malloc() for common data failed\n"); @@ -104,7 +104,7 @@ int rtapi_app_main(void) goto err; } - inputs = hal_malloc(num_inputs * sizeof(watchdog_input_t)); + inputs = hal_malloc(num_inputs * sizeof(*inputs)); if (inputs == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: hal_malloc() for input pins failed\n"); @@ -114,34 +114,33 @@ int rtapi_app_main(void) /* export pins/params for all inputs */ for (n = 0; n < num_inputs; n++) { - retval=hal_pin_bit_newf(HAL_IN, &(inputs[n].input), comp_id, "watchdog.input-%d", n); + retval=hal_pin_new_bool(comp_id, HAL_IN, &(inputs[n].input), 0, "watchdog.input-%d", n); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: couldn't create input pin watchdog.input-%d\n", n); goto err; } - retval=hal_param_float_newf(HAL_RW, &(inputs[n].timeout), comp_id, "watchdog.timeout-%d", n); + retval=hal_param_new_real(comp_id, HAL_RW, &(inputs[n].timeout), 0.0, "watchdog.timeout-%d", n); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: couldn't create input parameter watchdog.timeout-%d\n", n); goto err; } - inputs[n].timeout=0; inputs[n].oldtimeout=-1; inputs[n].c_secs = inputs[n].t_secs = 0; inputs[n].c_nsecs = inputs[n].t_nsecs = 0; - inputs[n].last = *(inputs[n].input); + inputs[n].last = hal_get_bool(inputs[n].input); } /* export "global" pins */ - retval=hal_pin_bit_newf(HAL_OUT, &(data->output), comp_id, "watchdog.ok-out"); + retval=hal_pin_new_bool(comp_id, HAL_OUT, &(data->output), 0, "watchdog.ok-out"); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: couldn't create output pin watchdog.ok-out\n"); goto err; } - retval=hal_pin_bit_newf(HAL_IN, &(data->enable), comp_id, "watchdog.enable-in"); + retval=hal_pin_new_bool(comp_id, HAL_IN, &(data->enable), 0, "watchdog.enable-in"); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, "WATCHDOG: ERROR: couldn't create input pin watchdog.enable-in\n"); @@ -194,9 +193,9 @@ static void process(void *arg, long period) int i, fault=0; // set_timeouts has to turn on the output when it detects a valid // transition on enable - if (!(*data->enable) || (!(*data->output))) return; + if (!hal_get_bool(data->enable) || (!hal_get_bool(data->output))) return; for (i=0;ioutput)=0; + if (fault) hal_set_bool(data->output, 0); } static void set_timeouts(void *arg, long period) @@ -221,10 +220,10 @@ static void set_timeouts(void *arg, long period) (void)arg; (void)period; int i; - hal_float_t temp; + rtapi_real temp; for (i=0;ioutput)) { - if (*(data->enable) && !old_enable) { + if (!hal_get_bool(data->output)) { + if (hal_get_bool(data->enable) && !old_enable) { // rising edge on enable, so we can restart for (i=0;ioutput) = 1; + hal_set_bool(data->output, 1); } } - old_enable=*(data->enable); + old_enable=hal_get_bool(data->enable); } /*********************************************************************** * LOCAL FUNCTION DEFINITIONS * diff --git a/src/hal/components/wcomp.comp b/src/hal/components/wcomp.comp index 6df1b8494a6..be83b4f751a 100644 --- a/src/hal/components/wcomp.comp +++ b/src/hal/components/wcomp.comp @@ -1,10 +1,10 @@ component wcomp "Window comparator"; -pin in float in "Value being compared"; -pin in float min_ "Low boundary for comparison"; -pin in float max_ "High boundary for comparison"; -pin out bit out "True if *in* is strictly between *min* and *max*"; -pin out bit under "True if *in* is less than or equal to *min*"; -pin out bit over "True if *in* is greater than or equal to *max*"; +pin in real in "Value being compared"; +pin in real min_ "Low boundary for comparison"; +pin in real max_ "High boundary for comparison"; +pin out bool out "True if *in* is strictly between *min* and *max*"; +pin out bool under "True if *in* is less than or equal to *min*"; +pin out bool over "True if *in* is greater than or equal to *max*"; notes "If *max* <= *min* then the behavior is undefined."; option period no; @@ -13,8 +13,10 @@ license "GPL"; author "Jeff Epler"; ;; FUNCTION(_) { - double tmp = in; - under = (tmp <= min_); - over = (tmp >= max_); - out = !(over || under); + rtapi_real tmp = in; + rtapi_bool u = tmp <= min_; + rtapi_bool o= tmp >= max_; + under_set(u); + over_set(o); + out_set(!(o || u)); } diff --git a/src/hal/components/weighted_sum.c b/src/hal/components/weighted_sum.c index f17dc3d7c9b..d28b2aa0a26 100644 --- a/src/hal/components/weighted_sum.c +++ b/src/hal/components/weighted_sum.c @@ -48,17 +48,17 @@ RTAPI_MP_ARRAY_INT(wsum_sizes, MAX_SUMMERS, "Sizes of up to 8 weighted summers") /* Data needed for each bit of a weighted summer */ typedef struct { - hal_bit_t *bit; /* pin: the input bit HAL pin */ - hal_s32_t *weight; /* pin: the numeric weight of this pin */ + hal_bool_t bit; /* pin: the input bit HAL pin */ + hal_sint_t weight; /* pin: the numeric weight of this pin */ } wsum_bit_t; /* Base data for a weighted summer. */ typedef struct { - hal_s32_t *sum; /* output pin: the calculated sum */ - hal_s32_t *offset; /* pin: offset for this summer */ - hal_bit_t *hold; /* input pin: hold value if 1, update if 0 */ - int num_bits; /* internal: How many bits are in this summer */ - wsum_bit_t *bits; /* internal: pointer to the input bits and weights */ + hal_sint_t sum; /* output pin: the calculated sum */ + hal_sint_t offset; /* pin: offset for this summer */ + hal_bool_t hold; /* input pin: hold value if 1, update if 0 */ + int num_bits; /* internal: How many bits are in this summer */ + wsum_bit_t *bits; /* internal: pointer to the input bits and weights */ } wsum_t; /* pointer to array of wsum structs in shmem */ @@ -179,17 +179,17 @@ static void process_wsums(void *arg, long period) wsums = (wsum_t *)arg; for (n=0 ; nhold)) continue; - else { - running_total = *(thissum->offset); - for (b=0 ; bnum_bits ; b++) { - if (*(thissum->bits[b].bit)) { - running_total += *(thissum->bits[b].weight); - } - } - } - *(thissum->sum) = running_total; + thissum = &(wsums[n]); + if (hal_get_bool(thissum->hold)) continue; + else { + running_total = hal_get_si32(thissum->offset); + for (b=0 ; bnum_bits ; b++) { + if (hal_get_bool(thissum->bits[b].bit)) { + running_total += hal_get_si32(thissum->bits[b].weight); + } + } + } + hal_set_si32(thissum->sum, running_total); } } @@ -200,34 +200,28 @@ static void process_wsums(void *arg, long period) static int export_wsum(int num, int num_bits, wsum_t *addr, wsum_bit_t *bitaddr) { int retval, i, w; - char buf[HAL_NAME_LEN+1], base[HAL_NAME_LEN+1]; + char base[HAL_NAME_LEN+1]; - rtapi_snprintf(base, sizeof(base), "wsum.%d", num); /* export pin for offset (input) */ - rtapi_snprintf(buf, sizeof(buf), "%s.offset", base); - retval = hal_pin_s32_new(buf, HAL_IO, &(addr->offset), comp_id); + rtapi_snprintf(base, sizeof(base), "wsum.%d", num); + retval = hal_pin_new_si32(comp_id, HAL_IO, &(addr->offset), 0, "%s.offset", base); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "WEIGHTED_SUM: ERROR: '%s' param export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "WEIGHTED_SUM: ERROR: '%s.offset' param export failed\n", base); + return retval; } /* export pin for output sum */ - rtapi_snprintf(buf, sizeof(buf), "%s.sum", base); - retval = hal_pin_s32_new(buf, HAL_OUT, &(addr->sum), comp_id); + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->sum), 0, "%s.sum", base); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "WEIGHTED_SUM: ERROR: '%s' pin export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "WEIGHTED_SUM: ERROR: '%s.sum' pin export failed\n", base); + return retval; } /* export pin for update hold */ - rtapi_snprintf(buf, sizeof(buf), "%s.hold", base); - retval = hal_pin_bit_new(buf, HAL_IN, &(addr->hold), comp_id); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->hold), 0, "%s.hold", base); if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "WEIGHTED_SUM: ERROR: '%s' pin export failed\n", buf); - return retval; + rtapi_print_msg(RTAPI_MSG_ERR, "WEIGHTED_SUM: ERROR: '%s.hold' pin export failed\n", base); + return retval; } addr->bits = bitaddr; @@ -235,26 +229,17 @@ static int export_wsum(int num, int num_bits, wsum_t *addr, wsum_bit_t *bitaddr) /* export the input bits and weight parameters, and set the default weights */ w = 1; for (i=0;ibits[i].bit), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "WEIGHTED_SUM: ERROR: '%s' pin export failed\n", buf); - return retval; - } - rtapi_snprintf(buf, sizeof(buf), "%s.bit.%d.weight", base, i); - retval = hal_pin_s32_new(buf, HAL_IO, &(addr->bits[i].weight), comp_id); - if (retval != 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "WEIGHTED_SUM: ERROR: '%s' param export failed\n", buf); - return retval; - } - *(addr->bits[i].weight) = w; - w <<= 1; + retval = hal_pin_new_bool(comp_id, HAL_IN, &(addr->bits[i].bit), 0, "%s.bit.%d.in", base, i); + if (retval != 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "WEIGHTED_SUM: ERROR: '%s.bit.%d.in' pin export failed\n", base, i); + return retval; + } + retval = hal_pin_new_si32(comp_id, HAL_IO, &(addr->bits[i].weight), w, "%s.bit.%d.weight", base, i); + if (retval != 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "WEIGHTED_SUM: ERROR: '%s.bit.%d.weight' param export failed\n", base, i); + return retval; + } + w <<= 1; } - - /* set initial parameter and pin values */ - *(addr->offset) = 0; - *(addr->sum) = 0; return 0; } diff --git a/src/hal/components/xhc_hb04_util.comp b/src/hal/components/xhc_hb04_util.comp index abd1c3df9d3..f52a4d04d73 100644 --- a/src/hal/components/xhc_hb04_util.comp +++ b/src/hal/components/xhc_hb04_util.comp @@ -8,43 +8,43 @@ calculating the filter time constant ($ man lowpass). """; -pin in bit start_or_pause; -pin in bit is_paused; -pin in bit is_idle; -pin in bit is_running; -pin out bit pause; -pin out bit resume; -pin out bit run; +pin in bool start_or_pause; +pin in bool is_paused; +pin in bool is_idle; +pin in bool is_running; +pin out bool pause; +pin out bool resume; +pin out bool run; // integer low pass filters (see ilowpass.comp) -pin in s32 in0; -pin in s32 in1; -pin in s32 in2; -pin in s32 in3; -pin out s32 out0; -pin out s32 out1; -pin out s32 out2; -pin out s32 out3; -pin in float scale0 = 1.0; -pin in float scale1 = 1.0; -pin in float scale2 = 1.0; -pin in float scale3 = 1.0; -pin in float coef0 = 1.0; -pin in float coef1 = 1.0; -pin in float coef2 = 1.0; -pin in float coef3 = 1.0; +pin in si32 in0; +pin in si32 in1; +pin in si32 in2; +pin in si32 in3; +pin out si32 out0; +pin out si32 out1; +pin out si32 out2; +pin out si32 out3; +pin in real scale0 = 1.0; +pin in real scale1 = 1.0; +pin in real scale2 = 1.0; +pin in real scale3 = 1.0; +pin in real coef0 = 1.0; +pin in real coef1 = 1.0; +pin in real coef2 = 1.0; +pin in real coef3 = 1.0; -pin in float divide_by_k_in; -pin out float divide_by_k_out; -pin in float k = 1.0; +pin in real divide_by_k_in; +pin out real divide_by_k_out; +pin in real k = 1.0; option data xhc_data; option period no; -variable double value0; -variable double value1; -variable double value2; -variable double value3; +variable rtapi_real value0; +variable rtapi_real value1; +variable rtapi_real value2; +variable rtapi_real value3; function _; license "GPL"; @@ -57,9 +57,9 @@ typedef struct { int old_start_or_pause; } xhc_data; FUNCTION(_) { if (k == 0) { - divide_by_k_out = 1e99; + divide_by_k_out_set(1e99); } else { - divide_by_k_out = divide_by_k_in / k; + divide_by_k_out_set(divide_by_k_in / k); } // protect so that 0 <= coef <= 1 @@ -68,18 +68,18 @@ FUNCTION(_) { value2 += (in2 - value2) * (fabs(coef2) < 1 ? fabs(coef2) : 1); value3 += (in3 - value3) * (fabs(coef3) < 1 ? fabs(coef3) : 1); - out0 = ceil(value0 * scale0 - .5); - out1 = ceil(value1 * scale1 - .5); - out2 = ceil(value2 * scale2 - .5); - out3 = ceil(value3 * scale3 - .5); + out0_set(ceil(value0 * scale0 - .5)); + out1_set(ceil(value1 * scale1 - .5)); + out2_set(ceil(value2 * scale2 - .5)); + out3_set(ceil(value3 * scale3 - .5)); if (data.old_start_or_pause == start_or_pause) return; data.old_start_or_pause = start_or_pause; if (!start_or_pause) { - pause = run = resume = 0; + pause_set(0); run_set(0); resume_set(0); return; } - if (is_paused) {pause = 0; run = 0; resume = 1; } - if (is_running) {pause = 1; run = 0; resume = 0; } - if (is_idle) {pause = 0; run = 1; resume = 0; } + if (is_paused) {pause_set(0); run_set(0); resume_set(1); } + if (is_running) {pause_set(1); run_set(0); resume_set(0); } + if (is_idle) {pause_set(0); run_set(1); resume_set(0); } } diff --git a/src/hal/components/xor2.comp b/src/hal/components/xor2.comp index b2b2fb3d88c..e8a1e6ba088 100644 --- a/src/hal/components/xor2.comp +++ b/src/hal/components/xor2.comp @@ -1,7 +1,7 @@ component xor2 "Two-input XOR (exclusive OR) gate"; -pin in bit in0 "First input"; -pin in bit in1 "Second input"; -pin out bit out "Output"; +pin in bool in0 "First input"; +pin in bool in1 "Second input"; +pin out bool out "Output"; description """ The *out* pin is computed from the value of the *in0* and *in1* pins according @@ -33,10 +33,6 @@ author "John Kasunich"; option period no; ;; FUNCTION(_) { - if (( in0 && !in1 ) || ( in1 && !in0 )) { - out = 1; - } else { - out = 0; - } + out_set((int)in0 ^ (int)in1); } diff --git a/src/hal/components/xyzab_tdr_kins.comp b/src/hal/components/xyzab_tdr_kins.comp index 210606c95c9..ea9e39839a0 100644 --- a/src/hal/components/xyzab_tdr_kins.comp +++ b/src/hal/components/xyzab_tdr_kins.comp @@ -30,7 +30,7 @@ chapter (docs/src/motion/switchkins.txt) """; -pin out s32 dummy=0"one pin needed to satisfy halcompile requirement"; +pin out si32 dummy=0"one pin needed to satisfy halcompile requirement"; license "GPL"; author "David Mueller"; @@ -42,16 +42,16 @@ author "David Mueller"; static struct haldata { // Declare hal pin pointers used for xyzab_tdr kinematics: - hal_float_t *tool_offset_z; - hal_float_t *x_offset; - hal_float_t *z_offset; - hal_float_t *x_rot_point; - hal_float_t *y_rot_point; - hal_float_t *z_rot_point; + hal_real_t tool_offset_z; + hal_real_t x_offset; + hal_real_t z_offset; + hal_real_t x_rot_point; + hal_real_t y_rot_point; + hal_real_t z_rot_point; //Declare hal pin pointers used for switchable kinematics - hal_bit_t *kinstype_is_0; - hal_bit_t *kinstype_is_1; + hal_bool_t kinstype_is_0; + hal_bool_t kinstype_is_1; } *haldata; static int xyzab_tdr_setup(void) { @@ -62,24 +62,22 @@ static int xyzab_tdr_setup(void) { // set unready to allow creation of pins if (hal_set_unready(comp_id)) goto error; - haldata = hal_malloc(sizeof(struct haldata)); + haldata = hal_malloc(sizeof(*haldata)); if (!haldata) goto error; // hal pins required for xyzab_tdr kinematics: - res += hal_pin_float_newf(HAL_IN ,&(haldata->tool_offset_z) ,comp_id,"%s.tool-offset-z" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->x_offset) ,comp_id,"%s.x-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->z_offset) ,comp_id,"%s.z-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&haldata->x_rot_point ,comp_id,"%s.x-rot-point" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&haldata->y_rot_point ,comp_id,"%s.y-rot-point" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&haldata->z_rot_point ,comp_id,"%s.z-rot-point" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->tool_offset_z, 0.0, "%s.tool-offset-z", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_offset, 0.0, "%s.x-offset", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_offset, 0.0, "%s.z-offset", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_rot_point, 0.0, "%s.x-rot-point", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->y_rot_point, 0.0, "%s.y-rot-point", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_rot_point, 0.0, "%s.z-rot-point", HAL_PREFIX); // hal pins required for switchable kinematics: - res += hal_pin_bit_new("kinstype.is-0", HAL_OUT, &(haldata->kinstype_is_0), comp_id); - res += hal_pin_bit_new("kinstype.is-1", HAL_OUT, &(haldata->kinstype_is_1), comp_id); - - // define default kinematics at startup for switchable kinematics - *haldata->kinstype_is_0 = 1; //default at startup -> identity kinematics - *haldata->kinstype_is_1 = 0; //-> XYZAB TCP + //default at startup -> identity kinematics + //-> XYZAB TCP + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_0, 1, "kinstype.is-0"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_1, 0, "kinstype.is-1"); if (res) goto error; hal_ready(comp_id); @@ -97,7 +95,7 @@ EXPORT_SYMBOL(kinematicsSwitch); EXPORT_SYMBOL(kinematicsInverse); EXPORT_SYMBOL(kinematicsForward); -static hal_u32_t switchkins_type; +static rtapi_u32 switchkins_type; int kinematicsSwitchable() {return 1;} @@ -109,19 +107,19 @@ int kinematicsSwitch(int new_switchkins_type) switch (switchkins_type) { case 0: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE0\n"); - *haldata->kinstype_is_0 = 1; - *haldata->kinstype_is_1 = 0; + hal_set_bool(haldata->kinstype_is_0, 1); + hal_set_bool(haldata->kinstype_is_1, 0); break; case 1: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 1; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 1); break; default: rtapi_print_msg(RTAPI_MSG_ERR, "kinematicsSwitch:BAD VALUE <%d>\n", switchkins_type); - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_0 = 0; + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_0, 0); return -1; // FAIL } return 0; // ok @@ -145,12 +143,12 @@ int kinematicsForward(const double *j, { (void)fflags; (void)iflags; - double x_rot_point = *(haldata->x_rot_point); - double y_rot_point = *(haldata->y_rot_point); - double z_rot_point = *(haldata->z_rot_point); + double x_rot_point = hal_get_real(haldata->x_rot_point); + double y_rot_point = hal_get_real(haldata->y_rot_point); + double z_rot_point = hal_get_real(haldata->z_rot_point); - double dz = *(haldata->z_offset); - double dt = *(haldata->tool_offset_z); + double dz = hal_get_real(haldata->z_offset); + double dt = hal_get_real(haldata->tool_offset_z); // substitutions as used in mathematical documentation // including degree -> radians angle conversion @@ -209,13 +207,13 @@ int kinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - double x_rot_point = *(haldata->x_rot_point); - double y_rot_point = *(haldata->y_rot_point); - double z_rot_point = *(haldata->z_rot_point); + double x_rot_point = hal_get_real(haldata->x_rot_point); + double y_rot_point = hal_get_real(haldata->y_rot_point); + double z_rot_point = hal_get_real(haldata->z_rot_point); - double dx = *(haldata->x_offset); - double dz = *(haldata->z_offset); - double dt = *(haldata->tool_offset_z); + double dx = hal_get_real(haldata->x_offset); + double dz = hal_get_real(haldata->z_offset); + double dt = hal_get_real(haldata->tool_offset_z); // substitutions as used in mathematical documentation // including degree -> radians angle conversion diff --git a/src/hal/components/xyzacb_trsrn.comp b/src/hal/components/xyzacb_trsrn.comp index 3f0ed80da70..dfbe4466ace 100644 --- a/src/hal/components/xyzacb_trsrn.comp +++ b/src/hal/components/xyzacb_trsrn.comp @@ -5,11 +5,8 @@ description FIXME """; -// The fpin pin is not accessible in kinematics functions. -// Use the *_setup() function for pins and params used by kinematics. -pin out s32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; +pin out si32 dummy=0 "dummy pin to satisfy halcompile"; option period no; -function fdemo; license "GPL"; author "David Mueller"; @@ -20,53 +17,36 @@ author "David Mueller"; static struct haldata { - // Example pin pointers: - hal_u32_t *in; - hal_u32_t *out; // these should be parameters really but we want to be able to // change them for demonstration purposes - hal_float_t *y_pivot; - hal_float_t *z_pivot; - hal_float_t *x_offset; - hal_float_t *y_offset; - hal_float_t *y_rot_axis; - hal_float_t *z_rot_axis; - hal_float_t *pre_rot; - hal_float_t *nut_angle; - hal_float_t *prim_angle; - hal_float_t *sec_angle; - - - // Example parameters: - // hal_float_t param_rw; - // hal_float_t param_ro; + hal_real_t y_pivot; + hal_real_t z_pivot; + hal_real_t x_offset; + hal_real_t y_offset; + hal_real_t y_rot_axis; + hal_real_t z_rot_axis; + hal_real_t pre_rot; + hal_real_t nut_angle; + hal_real_t prim_angle; + hal_real_t sec_angle; // Parameters used for xyzacb_trsrn kinematics: // Declare hal pin pointers used for xyzacb_trsrn kinematics: - hal_float_t *tool_offset_z; + hal_real_t tool_offset_z; //Declare hal pin pointers used for switchable kinematics - hal_bit_t *kinstype_is_0; - hal_bit_t *kinstype_is_1; - hal_bit_t *kinstype_is_2; + hal_bool_t kinstype_is_0; + hal_bool_t kinstype_is_1; + hal_bool_t kinstype_is_2; } *haldata; -FUNCTION(fdemo) { - // This function can be added to a thread (addf) for - // purposes not related to the kinematics functions. - if (fpin == 0) { - rtapi_print("fdemo function added to thread\n"); - } - fpin++; -} - static int xyzacb_trsrn_setup(void) { #define HAL_PREFIX "xyzacb_trsrn_kins" int res=0; - // inbherit comp_id from rtapi_main() + // inherit comp_id from rtapi_main() if (comp_id < 0) goto error; // set unready to allow creation of pins if (hal_set_unready(comp_id)) goto error; @@ -74,37 +54,26 @@ static int xyzacb_trsrn_setup(void) { haldata = hal_malloc(sizeof(struct haldata)); if (!haldata) goto error; - // hal pin examples: - res += hal_pin_u32_newf(HAL_IN ,&(haldata->in) ,comp_id,"%s.in" ,HAL_PREFIX); - res += hal_pin_u32_newf(HAL_OUT,&(haldata->out),comp_id,"%s.out",HAL_PREFIX); - - // hal parameter examples: - // res += hal_param_float_newf(HAL_RW, &haldata->param_rw ,comp_id,"%s.param-rw",HAL_PREFIX); - // res += hal_param_float_newf(HAL_RO, &haldata->param_ro ,comp_id,"%s.param-ro",HAL_PREFIX); - // hal pins required for xyzacb_trsrn kinematics: - res += hal_pin_float_newf(HAL_IN ,&(haldata->tool_offset_z) - ,comp_id,"%s.tool-offset-z" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->y_pivot) ,comp_id,"%s.y-pivot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->z_pivot) ,comp_id,"%s.z-pivot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->x_offset) ,comp_id,"%s.x-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->y_offset) ,comp_id,"%s.y-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->y_rot_axis) ,comp_id,"%s.y-rot-axis" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->z_rot_axis) ,comp_id,"%s.z-rot-axis" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->pre_rot) ,comp_id,"%s.pre-rot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->nut_angle) ,comp_id,"%s.nut-angle" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->prim_angle) ,comp_id,"%s.primary-angle" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->sec_angle) ,comp_id,"%s.secondary-angle" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->tool_offset_z, 0.0, "%s.tool-offset-z" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->y_pivot, 0.0, "%s.y-pivot" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_pivot, 0.0, "%s.z-pivot" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_offset, 0.0, "%s.x-offset" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->y_offset, 0.0, "%s.y-offset" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->y_rot_axis, 0.0, "%s.y-rot-axis" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_rot_axis, 0.0, "%s.z-rot-axis" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->pre_rot, 0.0, "%s.pre-rot" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->nut_angle, 0.0, "%s.nut-angle" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->prim_angle, 0.0, "%s.primary-angle" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->sec_angle, 0.0, "%s.secondary-angle" ,HAL_PREFIX); // hal pins required for switchable kinematics: - res += hal_pin_bit_new("kinstype.is-0", HAL_OUT, &(haldata->kinstype_is_0), comp_id); - res += hal_pin_bit_new("kinstype.is-1", HAL_OUT, &(haldata->kinstype_is_1), comp_id); - res += hal_pin_bit_new("kinstype.is-2", HAL_OUT, &(haldata->kinstype_is_2), comp_id); - - // define default kinematics at startup for switchable kinematics - *haldata->kinstype_is_0 = 1; //default at startup -> identity kinematics - *haldata->kinstype_is_1 = 0; //-> xyzabc TCP - *haldata->kinstype_is_2 = 0; //-> xyzabc TOOL + //default at startup -> identity kinematics + //-> xyzabc TCP + //-> xyzabc TOOL + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_0, 1, "kinstype.is-0"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_1, 0, "kinstype.is-1"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_2, 0, "kinstype.is-2"); if (res) goto error; hal_ready(comp_id); @@ -122,7 +91,7 @@ EXPORT_SYMBOL(kinematicsSwitch); EXPORT_SYMBOL(kinematicsInverse); EXPORT_SYMBOL(kinematicsForward); -static hal_u32_t switchkins_type; +static rtapi_u32 switchkins_type; int kinematicsSwitchable() {return 1;} @@ -136,28 +105,28 @@ int kinematicsSwitch(int new_switchkins_type) switch (switchkins_type) { case 0: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE0\n"); - *haldata->kinstype_is_0 = 1; - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_0, 1); + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_2, 0); break; case 1: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 1; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 1); + hal_set_bool(haldata->kinstype_is_2, 0); break; case 2: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_2 = 1; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_2, 1); break; default: rtapi_print_msg(RTAPI_MSG_ERR, "kinematicsSwitch:BAD VALUE <%d>\n", switchkins_type); - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_2, 0); return -1; // FAIL } return 0; // ok @@ -174,9 +143,6 @@ static bool is_setup=0; } // kinematicsType() - -static bool is_ready=0; - int kinematicsForward(const double *j, EmcPose * pos, const KINEMATICS_FORWARD_FLAGS * fflags, @@ -184,24 +150,23 @@ int kinematicsForward(const double *j, { (void)fflags; (void)iflags; - static bool gave_msg; // START of custom variable declaration for Forward kinematics // geometric offsets of the universal spindle head as defined in the ini file - double Ly = *haldata->y_pivot; - double Lz = *haldata->z_pivot; - double Dx = *haldata->x_offset; - double Dy = *haldata->y_offset; - double Dray = *haldata->y_rot_axis - (Dy + Ly); - double Draz = *haldata->z_rot_axis - Lz; - double tc = *haldata->pre_rot; - double nu = *haldata->nut_angle; // degrees - double theta_1 = *haldata->prim_angle; // degrees - double theta_2 = *haldata->sec_angle; // degrees + double Ly = hal_get_real(haldata->y_pivot); + double Lz = hal_get_real(haldata->z_pivot); + double Dx = hal_get_real(haldata->x_offset); + double Dy = hal_get_real(haldata->y_offset); + double Dray = hal_get_real(haldata->y_rot_axis) - (Dy + Ly); + double Draz = hal_get_real(haldata->z_rot_axis) - Lz; + double tc = hal_get_real(haldata->pre_rot); + double nu = hal_get_real(haldata->nut_angle); // degrees + double theta_1 = hal_get_real(haldata->prim_angle); // degrees + double theta_2 = hal_get_real(haldata->sec_angle); // degrees // tool-length offset if G43 is used (offset as defined in the tool editor) - double Dt = *(haldata->tool_offset_z); + double Dt = hal_get_real(haldata->tool_offset_z); // variables used in both, TCP and TOOL kinematics double Sw = sin(j[3]*TO_RAD); @@ -335,14 +300,7 @@ int kinematicsForward(const double *j, pos->u = 0; pos->v = 0; pos->w = 0; - // pass the current position to the outside world - if (*haldata->in && !is_ready && !gave_msg) { - rtapi_print_msg(RTAPI_MSG_ERR, - "%s in pin not echoed until Inverse called\n", - __FILE__); - gave_msg=1; - } return 0; } // kinematicsForward() @@ -353,24 +311,23 @@ int kinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - is_ready = 1; // Inverse is not called until homed for KINEMATICS_BOTH // START of custom variable declaration for Forward kinematics // geometric offsets of the universal spindle head as defined in the ini file - double Ly = *haldata->y_pivot; - double Lz = *haldata->z_pivot; - double Dx = *haldata->x_offset; - double Dy = *haldata->y_offset; - double Dray = *haldata->y_rot_axis - (Dy + Ly); - double Draz = *haldata->z_rot_axis - Lz; - double tc = *haldata->pre_rot; - double nu = *haldata->nut_angle; // degrees - double theta_1 = *haldata->prim_angle; // degrees - double theta_2 = *haldata->sec_angle; // degrees + double Ly = hal_get_real(haldata->y_pivot); + double Lz = hal_get_real(haldata->z_pivot); + double Dx = hal_get_real(haldata->x_offset); + double Dy = hal_get_real(haldata->y_offset); + double Dray = hal_get_real(haldata->y_rot_axis) - (Dy + Ly); + double Draz = hal_get_real(haldata->z_rot_axis) - Lz; + double tc = hal_get_real(haldata->pre_rot); + double nu = hal_get_real(haldata->nut_angle); // degrees + double theta_1 = hal_get_real(haldata->prim_angle); // degrees + double theta_2 = hal_get_real(haldata->sec_angle); // degrees // tool-length offset if G43 is used (offset as defined in the tool editor) - double Dt = *(haldata->tool_offset_z); + double Dt = hal_get_real(haldata->tool_offset_z); // substitutions as used in mathematical documentation // including degree -> radians angle conversion @@ -503,9 +460,5 @@ int kinematicsInverse(const EmcPose * pos, break; } - //example hal pin update (homing reqd before kinematicsInverse) - *haldata->out = *haldata->in; //dereference - //read from param example: *haldata->out = haldata->param_rw; - return 0; } // kinematicsInverse() diff --git a/src/hal/components/xyzbca_trsrn.comp b/src/hal/components/xyzbca_trsrn.comp index 39bcd54e8d7..b8f451c17f9 100644 --- a/src/hal/components/xyzbca_trsrn.comp +++ b/src/hal/components/xyzbca_trsrn.comp @@ -5,11 +5,8 @@ description FIXME """; -// The fpin pin is not accessible in kinematics functions. -// Use the *_setup() function for pins and params used by kinematics. -pin out s32 fpin=0"pin to demonstrate use of a conventional (non-kinematics) function fdemo"; +pin out si32 dummy=0 "dummy pin to satisfy halcompile"; option period no; -function fdemo; license "GPL"; author "David Mueller"; @@ -20,48 +17,32 @@ author "David Mueller"; static struct haldata { - // Example pin pointers: - hal_u32_t *in; - hal_u32_t *out; // these should be parameters really but we want to be able to // change them for demonstration purposes - hal_float_t *x_pivot; - hal_float_t *z_pivot; - hal_float_t *x_offset; - hal_float_t *y_offset; - hal_float_t *x_rot_axis; - hal_float_t *z_rot_axis; - hal_float_t *pre_rot; - hal_float_t *nut_angle; - hal_float_t *prim_angle; - hal_float_t *sec_angle; - - // Example parameters: - // hal_float_t param_rw; - // hal_float_t param_ro; + hal_real_t x_pivot; + hal_real_t z_pivot; + hal_real_t x_offset; + hal_real_t y_offset; + hal_real_t x_rot_axis; + hal_real_t z_rot_axis; + hal_real_t pre_rot; + hal_real_t nut_angle; + hal_real_t prim_angle; + hal_real_t sec_angle; // Parameters used for xyzbca_trsrn kinematics: // Declare hal pin pointers used for xyzbca_trsrn kinematics: - hal_float_t *tool_offset_z; + hal_real_t tool_offset_z; //Declare hal pin pointers used for switchable kinematics - hal_bit_t *kinstype_is_0; - hal_bit_t *kinstype_is_1; - hal_bit_t *kinstype_is_2; + hal_bool_t kinstype_is_0; + hal_bool_t kinstype_is_1; + hal_bool_t kinstype_is_2; } *haldata; -FUNCTION(fdemo) { - // This function can be added to a thread (addf) for - // purposes not related to the kinematics functions. - if (fpin == 0) { - rtapi_print("fdemo function added to thread\n"); - } - fpin++; -} - static int xyzbca_trsrn_setup(void) { #define HAL_PREFIX "xyzbca_trsrn_kins" int res=0; @@ -73,37 +54,26 @@ static int xyzbca_trsrn_setup(void) { haldata = hal_malloc(sizeof(struct haldata)); if (!haldata) goto error; - // hal pin examples: - res += hal_pin_u32_newf(HAL_IN ,&(haldata->in) ,comp_id,"%s.in" ,HAL_PREFIX); - res += hal_pin_u32_newf(HAL_OUT,&(haldata->out),comp_id,"%s.out",HAL_PREFIX); - - // hal parameter examples: - // res += hal_param_float_newf(HAL_RW, &haldata->param_rw ,comp_id,"%s.param-rw",HAL_PREFIX); - // res += hal_param_float_newf(HAL_RO, &haldata->param_ro ,comp_id,"%s.param-ro",HAL_PREFIX); - // hal pins required for xyzbca_trsrn kinematics: - res += hal_pin_float_newf(HAL_IN ,&(haldata->tool_offset_z) - ,comp_id,"%s.tool-offset-z" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->x_pivot) ,comp_id,"%s.x-pivot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->z_pivot) ,comp_id,"%s.z-pivot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->x_offset) ,comp_id,"%s.x-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->y_offset) ,comp_id,"%s.y-offset" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->x_rot_axis) ,comp_id,"%s.x-rot-axis" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->z_rot_axis) ,comp_id,"%s.z-rot-axis" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->pre_rot) ,comp_id,"%s.pre-rot" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->nut_angle) ,comp_id,"%s.nut-angle" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->prim_angle) ,comp_id,"%s.primary-angle" ,HAL_PREFIX); - res += hal_pin_float_newf(HAL_IN ,&(haldata->sec_angle) ,comp_id,"%s.secondary-angle" ,HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->tool_offset_z, 0.0, "%s.tool-offset-z", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_pivot, 0.0, "%s.x-pivot", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_pivot, 0.0, "%s.z-pivot", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_offset, 0.0, "%s.x-offset", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->y_offset, 0.0, "%s.y-offset", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->x_rot_axis, 0.0, "%s.x-rot-axis", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->z_rot_axis, 0.0, "%s.z-rot-axis", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->pre_rot, 0.0, "%s.pre-rot", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->nut_angle, 0.0, "%s.nut-angle", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->prim_angle, 0.0, "%s.primary-angle", HAL_PREFIX); + res += hal_pin_new_real(comp_id, HAL_IN, &haldata->sec_angle, 0.0, "%s.secondary-angle", HAL_PREFIX); // hal pins required for switchable kinematics: - res += hal_pin_bit_new("kinstype.is-0", HAL_OUT, &(haldata->kinstype_is_0), comp_id); - res += hal_pin_bit_new("kinstype.is-1", HAL_OUT, &(haldata->kinstype_is_1), comp_id); - res += hal_pin_bit_new("kinstype.is-2", HAL_OUT, &(haldata->kinstype_is_2), comp_id); - - // define default kinematics at startup for switchable kinematics - *haldata->kinstype_is_0 = 1; //default at startup -> identity kinematics - *haldata->kinstype_is_1 = 0; //-> xyzabc TCP - *haldata->kinstype_is_2 = 0; //-> xyzabc TOOL + //default at startup -> identity kinematics + //-> xyzabc TCP + //-> xyzabc TOOL + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_0, 1, "kinstype.is-0"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_1, 0, "kinstype.is-1"); + res += hal_pin_new_bool(comp_id, HAL_OUT, &haldata->kinstype_is_2, 0, "kinstype.is-2"); if (res) goto error; hal_ready(comp_id); @@ -121,7 +91,7 @@ EXPORT_SYMBOL(kinematicsSwitch); EXPORT_SYMBOL(kinematicsInverse); EXPORT_SYMBOL(kinematicsForward); -static hal_u32_t switchkins_type; +static rtapi_u32 switchkins_type; int kinematicsSwitchable() {return 1;} @@ -135,28 +105,28 @@ int kinematicsSwitch(int new_switchkins_type) switch (switchkins_type) { case 0: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE0\n"); - *haldata->kinstype_is_0 = 1; - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_0, 1); + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_2, 0); break; case 1: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 1; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 1); + hal_set_bool(haldata->kinstype_is_2, 0); break; case 2: rtapi_print_msg(RTAPI_MSG_INFO, "kinematicsSwitch:TYPE1\n"); - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_2 = 1; + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_2, 1); break; default: rtapi_print_msg(RTAPI_MSG_ERR, "kinematicsSwitch:BAD VALUE <%d>\n", switchkins_type); - *haldata->kinstype_is_1 = 0; - *haldata->kinstype_is_0 = 0; - *haldata->kinstype_is_2 = 0; + hal_set_bool(haldata->kinstype_is_1, 0); + hal_set_bool(haldata->kinstype_is_0, 0); + hal_set_bool(haldata->kinstype_is_2, 0); return -1; // FAIL } return 0; // ok @@ -173,9 +143,6 @@ static bool is_setup=0; } // kinematicsType() - -static bool is_ready=0; - int kinematicsForward(const double *j, EmcPose * pos, const KINEMATICS_FORWARD_FLAGS * fflags, @@ -183,24 +150,23 @@ int kinematicsForward(const double *j, { (void)fflags; (void)iflags; - static bool gave_msg; // START of custom variable declaration for Forward kinematics // geometric offsets of the universal spindle head as defined in the ini file - double Lx = *haldata->x_pivot; - double Lz = *haldata->z_pivot; - double Dx = *haldata->x_offset; - double Dy = *haldata->y_offset; - double Drax = *haldata->x_rot_axis - Lx- Dx; - double Draz = *haldata->z_rot_axis - Lz; - double tc = *haldata->pre_rot; - double nu = *haldata->nut_angle; // degrees - double theta_1 = *haldata->prim_angle; // degrees - double theta_2 = *haldata->sec_angle; // degrees + double Lx = hal_get_real(haldata->x_pivot); + double Lz = hal_get_real(haldata->z_pivot); + double Dx = hal_get_real(haldata->x_offset); + double Dy = hal_get_real(haldata->y_offset); + double Drax = hal_get_real(haldata->x_rot_axis) - Lx- Dx; + double Draz = hal_get_real(haldata->z_rot_axis) - Lz; + double tc = hal_get_real(haldata->pre_rot); + double nu = hal_get_real(haldata->nut_angle); // degrees + double theta_1 = hal_get_real(haldata->prim_angle); // degrees + double theta_2 = hal_get_real(haldata->sec_angle); // degrees // tool-length offset if G43 is used (offset as defined in the tool editor) - double Dt = *(haldata->tool_offset_z); + double Dt = hal_get_real(haldata->tool_offset_z); // variables used in both, TCP and TOOL kinematics double Sw = sin(j[4]*TO_RAD); @@ -339,14 +305,7 @@ int kinematicsForward(const double *j, pos->u = 0; pos->v = 0; pos->w = 0; - // pass the current position to the outside world - if (*haldata->in && !is_ready && !gave_msg) { - rtapi_print_msg(RTAPI_MSG_ERR, - "%s in pin not echoed until Inverse called\n", - __FILE__); - gave_msg=1; - } return 0; } // kinematicsForward() @@ -357,24 +316,23 @@ int kinematicsInverse(const EmcPose * pos, { (void)iflags; (void)fflags; - is_ready = 1; // Inverse is not called until homed for KINEMATICS_BOTH // START of custom variable declaration for Forward kinematics // geometric offsets of the universal spindle head as defined in the ini file - double Lx = *haldata->x_pivot; - double Lz = *haldata->z_pivot; - double Dx = *haldata->x_offset; - double Dy = *haldata->y_offset; - double Drax = *haldata->x_rot_axis - Lx - Dx; - double Draz = *haldata->z_rot_axis - Lz; - double tc = *haldata->pre_rot; - double nu = *haldata->nut_angle; // degrees - double theta_1 = *haldata->prim_angle; // degrees - double theta_2 = *haldata->sec_angle; // degrees + double Lx = hal_get_real(haldata->x_pivot); + double Lz = hal_get_real(haldata->z_pivot); + double Dx = hal_get_real(haldata->x_offset); + double Dy = hal_get_real(haldata->y_offset); + double Drax = hal_get_real(haldata->x_rot_axis) - Lx - Dx; + double Draz = hal_get_real(haldata->z_rot_axis) - Lz; + double tc = hal_get_real(haldata->pre_rot); + double nu = hal_get_real(haldata->nut_angle); // degrees + double theta_1 = hal_get_real(haldata->prim_angle); // degrees + double theta_2 = hal_get_real(haldata->sec_angle); // degrees // tool-length offset if G43 is used (offset as defined in the tool editor) - double Dt = *(haldata->tool_offset_z); + double Dt = hal_get_real(haldata->tool_offset_z); // variables used in both, TCP and TOOL kinematics double Sw = sin(j[4]*TO_RAD); @@ -505,9 +463,5 @@ int kinematicsInverse(const EmcPose * pos, break; } - //example hal pin update (homing reqd before kinematicsInverse) - *haldata->out = *haldata->in; //dereference - //read from param example: *haldata->out = haldata->param_rw; - return 0; } // kinematicsInverse() diff --git a/src/hal/drivers/gm.h b/src/hal/drivers/gm.h index 22496e7fcd6..0494d78cba0 100644 --- a/src/hal/drivers/gm.h +++ b/src/hal/drivers/gm.h @@ -32,53 +32,53 @@ #define notPresented 0x00000000 typedef struct { - hal_u32_t serialModulesDataOut[16][8]; // 0000 0000 - hal_u32_t serialModulesDataIn[16][8]; // 1000 0000 - - hal_u32_t moduleId[8]; //addr 0 0000 000 - - hal_u32_t card_status_reg; //addr 1 0001 000 // ... Estop_2 | Estop_1 | Pwr_fault | Bus_err | Wdt_err //Card status read resets wdt - hal_u32_t cardID; // 0001 001 - hal_u32_t card_control_reg; // 0001 010 // Wdt_period(16 bit)[us] | ... | EstopEn_2 | EstopEn_1 | power_enable | card_enable - hal_u32_t reserved_0; // 0001 011 - hal_u32_t gpio; // 0001 100 - hal_u32_t gpioDir; // 0001 101 - hal_u32_t StepGen_status; // 0001 110 - hal_u32_t PCI_clk_counter; // 0001 111 - - hal_u32_t ENC_control_reg; //addr 2 0010 000 - hal_u32_t CAN_status_reg; - hal_u32_t CAN_control_reg; - hal_u32_t DAC_0; //DAC AXIS 1-0 - hal_u32_t DAC_1; //DAC AXIS 3-2 - hal_u32_t DAC_2; //DAC AXIS 5-4 - hal_u32_t reserved_1[2]; - - hal_u32_t CAN_RX_buffer[4]; //addr 3 0011 000 - hal_u32_t CAN_TX_buffer[4]; - hal_u32_t reserved_2[8]; //addr 4 0100 000 - - hal_u32_t reserved_3[8]; //addr 5 0101 000 - - hal_u32_t reserved_4[8]; //addr 6 0110 000 - - hal_u32_t reserved_5[8]; //addr 7 0111 000 - - hal_s32_t ENC_counter[6]; //addr 8 1000 000 - hal_u32_t reserved_6[2]; - hal_s32_t ENC_period[6]; //addr 9 1001 000 - hal_u32_t reserved_7[2]; - hal_s32_t ENC_index_latch[6]; //addr 10 1010 000 - hal_u32_t reserved_8[2]; - hal_s32_t reserved_9[8]; //addr 11 1011 000 - - hal_s32_t StepGen_steprate[6]; //addr 12 1100 000 - hal_u32_t reserved_10[2]; - hal_u32_t StepGen_fb[6]; //addr 13 1101 000 - hal_u32_t reserved_11[2]; - hal_u32_t StepGen_time_params[6]; //addr 14 1110 000 - hal_u32_t reserved_12[2]; - hal_u32_t reserved_16[8]; //addr 15 1111 000 + volatile rtapi_u32 serialModulesDataOut[16][8]; // 0000 0000 + volatile rtapi_u32 serialModulesDataIn[16][8]; // 1000 0000 + + volatile rtapi_u32 moduleId[8]; //addr 0 0000 000 + + volatile rtapi_u32 card_status_reg; //addr 1 0001 000 // ... Estop_2 | Estop_1 | Pwr_fault | Bus_err | Wdt_err //Card status read resets wdt + volatile rtapi_u32 cardID; // 0001 001 + volatile rtapi_u32 card_control_reg; // 0001 010 // Wdt_period(16 bit)[us] | ... | EstopEn_2 | EstopEn_1 | power_enable | card_enable + volatile rtapi_u32 reserved_0; // 0001 011 + volatile rtapi_u32 gpio; // 0001 100 + volatile rtapi_u32 gpioDir; // 0001 101 + volatile rtapi_u32 StepGen_status; // 0001 110 + volatile rtapi_u32 PCI_clk_counter; // 0001 111 + + volatile rtapi_u32 ENC_control_reg; //addr 2 0010 000 + volatile rtapi_u32 CAN_status_reg; + volatile rtapi_u32 CAN_control_reg; + volatile rtapi_u32 DAC_0; //DAC AXIS 1-0 + volatile rtapi_u32 DAC_1; //DAC AXIS 3-2 + volatile rtapi_u32 DAC_2; //DAC AXIS 5-4 + volatile rtapi_u32 reserved_1[2]; + + volatile rtapi_u32 CAN_RX_buffer[4]; //addr 3 0011 000 + volatile rtapi_u32 CAN_TX_buffer[4]; + volatile rtapi_u32 reserved_2[8]; //addr 4 0100 000 + + volatile rtapi_u32 reserved_3[8]; //addr 5 0101 000 + + volatile rtapi_u32 reserved_4[8]; //addr 6 0110 000 + + volatile rtapi_u32 reserved_5[8]; //addr 7 0111 000 + + volatile rtapi_s32 ENC_counter[6]; //addr 8 1000 000 + volatile rtapi_u32 reserved_6[2]; + volatile rtapi_s32 ENC_period[6]; //addr 9 1001 000 + volatile rtapi_u32 reserved_7[2]; + volatile rtapi_s32 ENC_index_latch[6]; //addr 10 1010 000 + volatile rtapi_u32 reserved_8[2]; + volatile rtapi_s32 reserved_9[8]; //addr 11 1011 000 + + volatile rtapi_s32 StepGen_steprate[6]; //addr 12 1100 000 + volatile rtapi_u32 reserved_10[2]; + volatile rtapi_u32 StepGen_fb[6]; //addr 13 1101 000 + volatile rtapi_u32 reserved_11[2]; + volatile rtapi_u32 StepGen_time_params[6]; //addr 14 1110 000 + volatile rtapi_u32 reserved_12[2]; + volatile rtapi_u32 reserved_16[8]; //addr 15 1111 000 } volatile card; diff --git a/src/hal/drivers/hal_ax5214h.c b/src/hal/drivers/hal_ax5214h.c index 6eddfe16483..84dd3781d51 100644 --- a/src/hal/drivers/hal_ax5214h.c +++ b/src/hal/drivers/hal_ax5214h.c @@ -120,10 +120,10 @@ RTAPI_MP_STRING(cfg, "config string"); */ typedef struct { - hal_bit_t *data; /* basic pin for input or output */ + hal_bool_t data; /* basic pin for input or output */ union { - hal_bit_t *not; /* pin for inverted data (input only) */ - hal_bit_t invert; /* param for inversion (output only) */ + hal_bool_t not; /* pin for inverted data (input only) */ + hal_bool_t invert; /* param for inversion (output only) */ } io; } io_pin_t; @@ -295,12 +295,12 @@ static void split_input(unsigned char data, io_pin_t *dest, int num) for (b = 0 ; b < num ; b++ ) { if ( data & mask ) { /* input high, which means FALSE (active low) */ - *(dest->data) = 0; - *(dest->io.not) = 1; + hal_set_bool(dest->data, 0); + hal_set_bool(dest->io.not, 1); } else { /* input low, which means TRUE */ - *(dest->data) = 1; - *(dest->io.not) = 0; + hal_set_bool(dest->data, 1); + hal_set_bool(dest->io.not, 0); } mask <<= 1; dest++; @@ -361,12 +361,12 @@ unsigned char build_output(io_pin_t *src, int num) /* assemble output byte for data port from 'num' source variables */ for (b = 0; b < num; b++) { /* get the data, add to output byte */ - if ( *(src->data) ) { - if ( !(src->io.invert) ) { + if ( hal_get_bool(src->data) ) { + if ( !hal_get_bool(src->io.invert) ) { data |= mask; } } else { - if ( (src->io.invert) ) { + if ( hal_get_bool(src->io.invert) ) { data |= mask; } } @@ -644,17 +644,14 @@ static int export_input_pin(int boardnum, int pinnum, io_pin_t *pin) int retval; /* export read only HAL pin for input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->data), 0, "ax5214h.%d.in-%02d", boardnum, pinnum); if (retval != 0) { return retval; } /* export additional pin for inverted input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->io.not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->io.not), 1, "ax5214h.%d.in-%02d-not", boardnum, pinnum); - /* initialize HAL pins */ - *(pin->data) = 0; - *(pin->io.not) = 1; return retval; } @@ -663,16 +660,13 @@ static int export_output_pin(int boardnum, int pinnum, io_pin_t *pin) int retval; /* export read only HAL pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(pin->data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(pin->data), 0, "ax5214h.%d.out-%02d", boardnum, pinnum); if (retval != 0) { return retval; } /* export parameter for polarity */ - retval = hal_param_bit_newf(HAL_RW, &(pin->io.invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(pin->io.invert), 0, "ax5214h.%d.out-%02d-invert", boardnum, pinnum); - /* initialize HAL pin and param */ - *(pin->data) = 0; - pin->io.invert = 0; return retval; } diff --git a/src/hal/drivers/hal_bb_gpio.c b/src/hal/drivers/hal_bb_gpio.c index ca31e5ada72..e1a23f3a5e9 100644 --- a/src/hal/drivers/hal_bb_gpio.c +++ b/src/hal/drivers/hal_bb_gpio.c @@ -34,12 +34,12 @@ MODULE_LICENSE("GPL"); #define PINS_PER_HEADER 46 typedef struct { - hal_bit_t* led_pins[4]; - hal_bit_t* input_pins[1 + PINS_PER_HEADER * HEADERS]; // array of pointers to bivts - hal_bit_t* output_pins[1 + PINS_PER_HEADER * HEADERS]; // array of pointers to bits - hal_bit_t *led_inv[4]; - hal_bit_t *input_inv[1 + PINS_PER_HEADER * HEADERS]; - hal_bit_t *output_inv[1 + PINS_PER_HEADER * HEADERS]; + hal_bool_t led_pins[4]; + hal_bool_t input_pins[1 + PINS_PER_HEADER * HEADERS]; // array of pointers to bivts + hal_bool_t output_pins[1 + PINS_PER_HEADER * HEADERS]; // array of pointers to bits + hal_bool_t led_inv[4]; + hal_bool_t input_inv[1 + PINS_PER_HEADER * HEADERS]; + hal_bool_t output_inv[1 + PINS_PER_HEADER * HEADERS]; } port_data_t; static port_data_t *port_data; @@ -169,7 +169,7 @@ int rtapi_app_main(void) { } // Add HAL pin - retval = hal_pin_bit_newf(HAL_IN, &(port_data->led_pins[led]), comp_id, "bb_gpio.userled%d", led); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data->led_pins[led]), 0, "bb_gpio.userled%d", led); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: userled %d could not export pin, err: %d\n", modname, led, retval); @@ -178,7 +178,7 @@ int rtapi_app_main(void) { } // Add HAL pin - retval = hal_pin_bit_newf(HAL_IN, &(port_data->led_inv[led]), comp_id, "bb_gpio.userled%d-invert", led); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data->led_inv[led]), 0, "bb_gpio.userled%d-invert", led); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: userled %d could not export pin, err: %d\n", modname, led, retval); @@ -186,9 +186,6 @@ int rtapi_app_main(void) { return -1; } - // Initialize HAL pin - *(port_data->led_inv[led]) = 0; - int gpio_num = user_led_gpio_pins[led].port_num; // configure gpio port if necessary if(gpio_ports[gpio_num] == NULL) { @@ -241,7 +238,7 @@ int rtapi_app_main(void) { data = NULL; // after the first call, subsequent calls to strtok need to be on NULL // Add HAL pin - retval = hal_pin_bit_newf(HAL_OUT, &(port_data->input_pins[pin + (header - 8)*PINS_PER_HEADER]), comp_id, "bb_gpio.p%d.in-%02d", header, pin); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(port_data->input_pins[pin + (header - 8)*PINS_PER_HEADER]), 0, "bb_gpio.p%d.in-%02d", header, pin); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: pin p%d.%02d could not export pin, err: %d\n", modname, header, pin, retval); @@ -250,7 +247,7 @@ int rtapi_app_main(void) { } // Add HAL pin - retval = hal_pin_bit_newf(HAL_IN, &(port_data->input_inv[pin + (header - 8)*PINS_PER_HEADER]), comp_id, "bb_gpio.p%d.in-%02d-invert", header, pin); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data->input_inv[pin + (header - 8)*PINS_PER_HEADER]), 0, "bb_gpio.p%d.in-%02d-invert", header, pin); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: pin p%d.%02d could not export pin, err: %d\n", modname, header, pin, retval); @@ -258,9 +255,6 @@ int rtapi_app_main(void) { return -1; } - // Initialize HAL pin - *(port_data->input_inv[pin + (header - 8)*PINS_PER_HEADER]) = 0; - int gpio_num = bbpin->port_num; // configure gpio port if necessary @@ -315,7 +309,7 @@ int rtapi_app_main(void) { data = NULL; // after the first call, subsequent calls to strtok need to be on NULL // Add HAL pin - retval = hal_pin_bit_newf(HAL_IN, &(port_data->output_pins[pin + (header - 8)*PINS_PER_HEADER]), comp_id, "bb_gpio.p%d.out-%02d", header, pin); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data->output_pins[pin + (header - 8)*PINS_PER_HEADER]), 0, "bb_gpio.p%d.out-%02d", header, pin); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: pin p%d.%02d could not export pin, err: %d\n", modname, header, pin, retval); @@ -324,7 +318,7 @@ int rtapi_app_main(void) { } // Add HAL pin - retval = hal_pin_bit_newf(HAL_IN, &(port_data->output_inv[pin + (header - 8)*PINS_PER_HEADER]), comp_id, "bb_gpio.p%d.out-%02d-invert", header, pin); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data->output_inv[pin + (header - 8)*PINS_PER_HEADER]), 0, "bb_gpio.p%d.out-%02d-invert", header, pin); if(retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: ERROR: pin p%d.%02d could not export pin, err: %d\n", modname, header, pin, retval); @@ -332,9 +326,6 @@ int rtapi_app_main(void) { return -1; } - // Initialize HAL pin - *(port_data->output_inv[pin + (header - 8)*PINS_PER_HEADER]) = 0; - int gpio_num = bbpin->port_num; // configure gpio port if necessary @@ -393,7 +384,7 @@ static void write_port(void *arg, long period) { if(pin.claimed != 'O') continue; // if we somehow get here but the pin isn't claimed as output, short circuit - if((*port->led_pins[i] ^ *(port->led_inv[i])) == 0) + if((hal_get_bool(port->led_pins[i]) ^ hal_get_bool(port->led_inv[i])) == 0) *(pin.port->clrdataout_reg) = (1 << pin.pin_num); else *(pin.port->setdataout_reg) = (1 << pin.pin_num); @@ -412,7 +403,7 @@ static void write_port(void *arg, long period) { if(pin.claimed != 'O') continue; // if we somehow get here but the pin isn't claimed as output, short circuit - if((*port->output_pins[i] ^ *(port->output_inv[i])) == 0) + if((hal_get_bool(port->output_pins[i]) ^ hal_get_bool(port->output_inv[i])) == 0) *(pin.port->clrdataout_reg) = (1 << pin.pin_num); else *(pin.port->setdataout_reg) = (1 << pin.pin_num); @@ -440,7 +431,7 @@ static void read_port(void *arg, long period) { if(!(pin.claimed == 'I' || pin.claimed == 'U' || pin.claimed == 'D')) continue; // if we get here but the pin isn't claimed as input, short circuit - *port->input_pins[i] = ((*(pin.port->datain_reg) & (1 << pin.pin_num)) >> pin.pin_num) ^ *(port->input_inv[i]); + hal_set_bool(port->input_pins[i], ((*(pin.port->datain_reg) & (1 << pin.pin_num)) >> pin.pin_num) ^ hal_get_bool(port->input_inv[i])); } } diff --git a/src/hal/drivers/hal_evoreg.c b/src/hal/drivers/hal_evoreg.c index cf33a78a11f..e84e31b6338 100644 --- a/src/hal/drivers/hal_evoreg.c +++ b/src/hal/drivers/hal_evoreg.c @@ -87,13 +87,13 @@ RTAPI_MP_STRING(cfg, "config string"); */ typedef struct { void *io_base; - hal_float_t *dac_out[3]; /* ptrs for dac output */ - hal_float_t *position[3]; /* ptrs for encoder input */ - hal_bit_t *digital_in[47]; /* ptrs for digital input pins 0 - 45 */ - hal_bit_t *digital_out[25]; /* ptrs for digital output pins 0 - 20 */ + hal_real_t dac_out[3]; /* ptrs for dac output */ + hal_real_t position[3]; /* ptrs for encoder input */ + hal_bool_t digital_in[47]; /* ptrs for digital input pins 0 - 45 */ + hal_bool_t digital_out[25]; /* ptrs for digital output pins 0 - 20 */ __u16 raw_counts_old[3]; __s32 counts[3]; - hal_float_t pos_scale; /*! \todo scale for position command FIXME should be one per axis */ + hal_real_t pos_scale; /*! \todo scale for position command FIXME should be one per axis */ } evoreg_t; /* pointer to array of evoreg_t structs in shared memory, 1 per port */ @@ -172,8 +172,8 @@ int rtapi_app_main(void) /* Export DAC pin's */ for ( num_dac=1; num_dac<=MAX_DAC; num_dac++) { - retval = hal_pin_float_newf(HAL_IN, &(port_data_array->dac_out[num_dac-1]), - comp_id, "evoreg.%d.dac-%02d-out", 1, num_dac); + retval = hal_pin_new_real(comp_id, HAL_IN, &(port_data_array->dac_out[num_dac-1]), + 0.0, "evoreg.%d.dac-%02d-out", 1, num_dac); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "EVOREG: ERROR: port %d var export failed with err=%i\n", n + 1, @@ -185,8 +185,8 @@ int rtapi_app_main(void) /* Export Encoder pin's */ for ( num_enc=1; num_enc<=MAX_ENC; num_enc++) { - retval = hal_pin_float_newf(HAL_OUT, &(port_data_array->position[num_enc - 1]), - comp_id, "evoreg.%d.position-%02d-in", 1, num_enc); + retval = hal_pin_new_real(comp_id, HAL_OUT, &(port_data_array->position[num_enc - 1]), + 0.0, "evoreg.%d.position-%02d-in", 1, num_enc); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "EVOREG: ERROR: port %d var export failed with err=%i\n", n + 1, @@ -200,8 +200,8 @@ int rtapi_app_main(void) /* export write only HAL pin's for the input bit */ for ( i=0; i<=45;i++) { - retval += hal_pin_bit_newf(HAL_OUT, &(port_data_array->digital_in[i]), - comp_id, "evoreg.%d.pin-%02d-in", 1, i); + retval += hal_pin_new_bool(comp_id, HAL_OUT, &(port_data_array->digital_in[i]), + 0, "evoreg.%d.pin-%02d-in", 1, i); /* export another write only HAL pin for the same bit inverted */ /* @@ -218,8 +218,8 @@ int rtapi_app_main(void) /* export read only HAL pin's for the output bit */ for ( i=0; i<=23;i++) { - retval += hal_pin_bit_newf(HAL_IN, &(port_data_array->digital_out[i]), - comp_id, "evoreg.%d.pin-%02d-out", 1, i); + retval += hal_pin_new_bool(comp_id, HAL_IN, &(port_data_array->digital_out[i]), + 0, "evoreg.%d.pin-%02d-out", 1, i); /* export another read only HAL pin for the same bit inverted */ /* @@ -235,8 +235,8 @@ int rtapi_app_main(void) } /* export parameter for scaling */ - retval = hal_param_float_newf(HAL_RW, &(port_data_array->pos_scale), - comp_id, "evoreg.%d.position-scale", 1); + retval = hal_param_new_real(comp_id, HAL_RW, &(port_data_array->pos_scale), + 0.0, "evoreg.%d.position-scale", 1); if (retval != 0) { return retval; } @@ -278,9 +278,9 @@ static void update_port(void *arg, long period) port = arg; /* write DAC's */ - writew((*(port->dac_out[0])/10 * 0x7fff), (char *)port->io_base + 0x60); - writew((*(port->dac_out[1])/10 * 0x7fff), (char *)port->io_base + 0x80); - writew((*(port->dac_out[2])/10 * 0x7fff), (char *)port->io_base + 0xa0); + writew((hal_get_real(port->dac_out[0])/10 * 0x7fff), (char *)port->io_base + 0x60); + writew((hal_get_real(port->dac_out[1])/10 * 0x7fff), (char *)port->io_base + 0x80); + writew((hal_get_real(port->dac_out[2])/10 * 0x7fff), (char *)port->io_base + 0xa0); /* Read Encoders, improve the 16bit hardware counters to 32bit and scale the values */ raw_counts[0] = (__u16) readw(port->io_base); @@ -296,29 +296,30 @@ static void update_port(void *arg, long period) port->counts[2] += (__s16) (raw_counts[2] - port->raw_counts_old[2]); port->raw_counts_old[2] = raw_counts[2]; - *port->position[0] = port->counts[0] * port->pos_scale; - *port->position[1] = port->counts[1] * port->pos_scale; - *port->position[2] = port->counts[2] * port->pos_scale; + rtapi_real pos_scale = hal_get_real(port->pos_scale); + hal_set_real(port->position[0], port->counts[0] * pos_scale); + hal_set_real(port->position[1], port->counts[1] * pos_scale); + hal_set_real(port->position[2], port->counts[2] * pos_scale); /* read digital inputs */ tmp = readw((char *)port->io_base + 0x20); /* digital input 0-15 */ mask = 0x01; for (pin=0 ; pin < 16 ; pin++) { - *port->digital_in[pin] = (tmp & mask) ? 1:0 ; + hal_set_bool(port->digital_in[pin], (tmp & mask) ? 1:0); mask <<= 1; } tmp = readw((char *)port->io_base + 0x40); /* digital input 16-31 */ mask = 0x01; for (pin=16 ; pin < 32 ; pin++) { - *port->digital_in[pin] = (tmp & mask) ? 1:0 ; + hal_set_bool(port->digital_in[pin], (tmp & mask) ? 1:0); mask <<= 1; } tmp = readw((char *)port->io_base + 0x60); /* digital input 32-45 */ mask = 0x01; for (pin=32 ; pin < 46 ; pin++) { - *port->digital_in[pin] = (tmp & mask) ? 1:0 ; + hal_set_bool(port->digital_in[pin], (tmp & mask) ? 1:0); mask <<= 1; } @@ -327,7 +328,7 @@ static void update_port(void *arg, long period) tmp = 0x0; mask = 0x01; for (pin=0; pin < 16; pin++) { - if (port->digital_out[pin]) { + if (hal_get_bool(port->digital_out[pin])) { tmp |= mask; mask <<= 1; } @@ -338,7 +339,7 @@ static void update_port(void *arg, long period) tmp = 0x0; mask = 0x01; for (pin=16; pin < 24; pin++) { - if (port->digital_out[pin]) { + if (hal_get_bool(port->digital_out[pin])) { tmp |= mask; mask <<= 1; } diff --git a/src/hal/drivers/hal_gm.c b/src/hal/drivers/hal_gm.c index ab4bf7cf024..09beeefe905 100644 --- a/src/hal/drivers/hal_gm.c +++ b/src/hal/drivers/hal_gm.c @@ -14,297 +14,307 @@ MODULE_LICENSE("GPL"); typedef struct { //encoder_t // Pins - hal_bit_t *reset; - hal_s32_t *counts; - hal_float_t *position; - hal_float_t *velocity; - hal_s32_t *rawcounts; - hal_bit_t *index_enable; + hal_bool_t reset; + hal_sint_t counts; + hal_real_t position; + hal_real_t velocity; + hal_sint_t rawcounts; + hal_bool_t index_enable; // Parameters - hal_bit_t counter_mode; - hal_bit_t index_mode; - hal_bit_t index_invert; - hal_u32_t counts_per_rev; - hal_float_t position_scale; - hal_float_t min_speed_estimate; + hal_bool_t counter_mode; + hal_bool_t index_mode; + hal_bool_t index_invert; + hal_uint_t counts_per_rev; + hal_real_t position_scale; + hal_real_t min_speed_estimate; // Private data - hal_s32_t raw_offset; - hal_s32_t index_offset; - hal_s32_t last_index_latch; - hal_bit_t first_index; - hal_bit_t module_exist; + rtapi_s32 raw_offset; + rtapi_s32 index_offset; + rtapi_s32 last_index_latch; + rtapi_bool first_index; + rtapi_bool module_exist; } encoder_t; typedef struct { //switches_t // Pins. - hal_bit_t *home; - hal_bit_t *homeNot; + hal_bool_t home; + hal_bool_t homeNot; - hal_bit_t *posLimSwIn; - hal_bit_t *posLimSwInNot; - hal_bit_t *negLimSwIn; - hal_bit_t *negLimSwInNot; + hal_bool_t posLimSwIn; + hal_bool_t posLimSwInNot; + hal_bool_t negLimSwIn; + hal_bool_t negLimSwInNot; } switches_t; typedef struct { //estop_t // Pins. - hal_bit_t *in; - hal_bit_t *inNot; + hal_bool_t in; + hal_bool_t inNot; } estop_t; typedef struct { //gpio_t // Pins. - hal_bit_t *in; - hal_bit_t *inNot; - hal_bit_t *out; - hal_bit_t isOut; - hal_bit_t invertOut; + hal_bool_t in; + hal_bool_t inNot; + hal_bool_t out; + // Parameters + hal_bool_t isOut; + hal_bool_t invertOut; } gpio_t; typedef struct { //RS485_8output_t // Pins. - hal_bit_t *out_0; - hal_bit_t *out_1; - hal_bit_t *out_2; - hal_bit_t *out_3; - hal_bit_t *out_4; - hal_bit_t *out_5; - hal_bit_t *out_6; - hal_bit_t *out_7; + hal_bool_t out_0; + hal_bool_t out_1; + hal_bool_t out_2; + hal_bool_t out_3; + hal_bool_t out_4; + hal_bool_t out_5; + hal_bool_t out_6; + hal_bool_t out_7; // Parameters - hal_bit_t invertOut_0; - hal_bit_t invertOut_1; - hal_bit_t invertOut_2; - hal_bit_t invertOut_3; - hal_bit_t invertOut_4; - hal_bit_t invertOut_5; - hal_bit_t invertOut_6; - hal_bit_t invertOut_7; + hal_bool_t invertOut_0; + hal_bool_t invertOut_1; + hal_bool_t invertOut_2; + hal_bool_t invertOut_3; + hal_bool_t invertOut_4; + hal_bool_t invertOut_5; + hal_bool_t invertOut_6; + hal_bool_t invertOut_7; } RS485_8output_t; typedef struct { //RS485_8input_t // Pins. - hal_bit_t *in_0; - hal_bit_t *inNot_0; - hal_bit_t *in_1; - hal_bit_t *inNot_1; - hal_bit_t *in_2; - hal_bit_t *inNot_2; - hal_bit_t *in_3; - hal_bit_t *inNot_3; - hal_bit_t *in_4; - hal_bit_t *inNot_4; - hal_bit_t *in_5; - hal_bit_t *inNot_5; - hal_bit_t *in_6; - hal_bit_t *inNot_6; - hal_bit_t *in_7; - hal_bit_t *inNot_7; + hal_bool_t in_0; + hal_bool_t inNot_0; + hal_bool_t in_1; + hal_bool_t inNot_1; + hal_bool_t in_2; + hal_bool_t inNot_2; + hal_bool_t in_3; + hal_bool_t inNot_3; + hal_bool_t in_4; + hal_bool_t inNot_4; + hal_bool_t in_5; + hal_bool_t inNot_5; + hal_bool_t in_6; + hal_bool_t inNot_6; + hal_bool_t in_7; + hal_bool_t inNot_7; } RS485_8input_t; typedef struct { //RS485_DacAdc_t // Pins. - hal_float_t *DAC_0; - hal_float_t *DAC_1; - hal_float_t *DAC_2; - hal_float_t *DAC_3; - - hal_bit_t *dac_0_enable; - hal_bit_t *dac_1_enable; - hal_bit_t *dac_2_enable; - hal_bit_t *dac_3_enable; - - hal_float_t *ADC_0; - hal_float_t *ADC_1; - hal_float_t *ADC_2; - hal_float_t *ADC_3; - hal_float_t *ADC_4; - hal_float_t *ADC_5; - hal_float_t *ADC_6; - hal_float_t *ADC_7; + hal_real_t DAC_0; + hal_real_t DAC_1; + hal_real_t DAC_2; + hal_real_t DAC_3; + + hal_bool_t dac_0_enable; + hal_bool_t dac_1_enable; + hal_bool_t dac_2_enable; + hal_bool_t dac_3_enable; + + hal_real_t ADC_0; + hal_real_t ADC_1; + hal_real_t ADC_2; + hal_real_t ADC_3; + hal_real_t ADC_4; + hal_real_t ADC_5; + hal_real_t ADC_6; + hal_real_t ADC_7; // Parameters. - hal_float_t DAC_0_offset; - hal_float_t DAC_1_offset; - hal_float_t DAC_2_offset; - hal_float_t DAC_3_offset; + hal_real_t DAC_0_offset; + hal_real_t DAC_1_offset; + hal_real_t DAC_2_offset; + hal_real_t DAC_3_offset; - hal_float_t DAC_0_min; - hal_float_t DAC_1_min; - hal_float_t DAC_2_min; - hal_float_t DAC_3_min; + hal_real_t DAC_0_min; + hal_real_t DAC_1_min; + hal_real_t DAC_2_min; + hal_real_t DAC_3_min; - hal_float_t DAC_0_max; - hal_float_t DAC_1_max; - hal_float_t DAC_2_max; - hal_float_t DAC_3_max; + hal_real_t DAC_0_max; + hal_real_t DAC_1_max; + hal_real_t DAC_2_max; + hal_real_t DAC_3_max; - hal_float_t ADC_0_offset; - hal_float_t ADC_1_offset; - hal_float_t ADC_2_offset; - hal_float_t ADC_3_offset; - hal_float_t ADC_4_offset; - hal_float_t ADC_5_offset; - hal_float_t ADC_6_offset; - hal_float_t ADC_7_offset; + hal_real_t ADC_0_offset; + hal_real_t ADC_1_offset; + hal_real_t ADC_2_offset; + hal_real_t ADC_3_offset; + hal_real_t ADC_4_offset; + hal_real_t ADC_5_offset; + hal_real_t ADC_6_offset; + hal_real_t ADC_7_offset; - hal_float_t ADC_0_scale; - hal_float_t ADC_1_scale; - hal_float_t ADC_2_scale; - hal_float_t ADC_3_scale; - hal_float_t ADC_4_scale; - hal_float_t ADC_5_scale; - hal_float_t ADC_6_scale; - hal_float_t ADC_7_scale; + hal_real_t ADC_0_scale; + hal_real_t ADC_1_scale; + hal_real_t ADC_2_scale; + hal_real_t ADC_3_scale; + hal_real_t ADC_4_scale; + hal_real_t ADC_5_scale; + hal_real_t ADC_6_scale; + hal_real_t ADC_7_scale; } RS485_DacAdc_t; typedef struct { //RS485_TeachPad_t // Pins. //6 ADC channel - hal_float_t *ADC_0; - hal_float_t *ADC_1; - hal_float_t *ADC_2; - hal_float_t *ADC_3; - hal_float_t *ADC_4; - hal_float_t *ADC_5; + hal_real_t ADC_0; + hal_real_t ADC_1; + hal_real_t ADC_2; + hal_real_t ADC_3; + hal_real_t ADC_4; + hal_real_t ADC_5; //8 digital input - hal_bit_t *in_0; - hal_bit_t *inNot_0; - hal_bit_t *in_1; - hal_bit_t *inNot_1; - hal_bit_t *in_2; - hal_bit_t *inNot_2; - hal_bit_t *in_3; - hal_bit_t *inNot_3; - hal_bit_t *in_4; - hal_bit_t *inNot_4; - hal_bit_t *in_5; - hal_bit_t *inNot_5; - hal_bit_t *in_6; - hal_bit_t *inNot_6; - hal_bit_t *in_7; - hal_bit_t *inNot_7; + hal_bool_t in_0; + hal_bool_t inNot_0; + hal_bool_t in_1; + hal_bool_t inNot_1; + hal_bool_t in_2; + hal_bool_t inNot_2; + hal_bool_t in_3; + hal_bool_t inNot_3; + hal_bool_t in_4; + hal_bool_t inNot_4; + hal_bool_t in_5; + hal_bool_t inNot_5; + hal_bool_t in_6; + hal_bool_t inNot_6; + hal_bool_t in_7; + hal_bool_t inNot_7; //encoder - hal_bit_t *enc_reset; - hal_s32_t *enc_counts; - hal_float_t *enc_position; - hal_s32_t *enc_rawcounts; + hal_bool_t enc_reset; + hal_sint_t enc_counts; + hal_real_t enc_position; + hal_sint_t enc_rawcounts; // Parameters //6 ADC channels - hal_float_t ADC_0_offset; - hal_float_t ADC_1_offset; - hal_float_t ADC_2_offset; - hal_float_t ADC_3_offset; - hal_float_t ADC_4_offset; - hal_float_t ADC_5_offset; - hal_float_t ADC_0_scale; - hal_float_t ADC_1_scale; - hal_float_t ADC_2_scale; - hal_float_t ADC_3_scale; - hal_float_t ADC_4_scale; - hal_float_t ADC_5_scale; + hal_real_t ADC_0_offset; + hal_real_t ADC_1_offset; + hal_real_t ADC_2_offset; + hal_real_t ADC_3_offset; + hal_real_t ADC_4_offset; + hal_real_t ADC_5_offset; + hal_real_t ADC_0_scale; + hal_real_t ADC_1_scale; + hal_real_t ADC_2_scale; + hal_real_t ADC_3_scale; + hal_real_t ADC_4_scale; + hal_real_t ADC_5_scale; //encoder - hal_float_t enc_position_scale; + hal_real_t enc_position_scale; // Private data //encoder - hal_s32_t enc_raw_offset; + rtapi_s32 enc_raw_offset; } RS485_TeachPad_t; typedef struct { //RS485_mgr_t - hal_u32_t ID[16]; - hal_u32_t BYTES_TO_WRITE[16]; - hal_u32_t BYTES_TO_READ[16]; + rtapi_u32 ID[16]; + rtapi_u32 BYTES_TO_WRITE[16]; + rtapi_u32 BYTES_TO_READ[16]; } RS485_mgr_t; typedef struct { //axisdac_t // Pins. - hal_float_t *value; - hal_bit_t *enable; + hal_real_t value; + hal_bool_t enable; // Parameters. - hal_float_t min; - hal_float_t max; - hal_float_t offset; + hal_real_t min; + hal_real_t max; + hal_real_t offset; - hal_bit_t invert_serial; + hal_bool_t invert_serial; } axisdac_t; typedef struct { //stepgen_t // Pins. - hal_float_t *position_cmd; - hal_float_t *velocity_cmd; - hal_float_t *position_fb; - hal_s32_t *count_fb; - hal_bit_t *enable; + hal_real_t position_cmd; + hal_real_t velocity_cmd; + hal_real_t position_fb; + hal_sint_t count_fb; + hal_bool_t enable; // Parameters - hal_u32_t step_type; //0: StepDir, 1: UpDown, 2: Quadrature - hal_bit_t control_type; //0: position, 1: velocity - hal_u32_t steplen; - hal_u32_t stepspace; - hal_u32_t dirdelay; - hal_float_t maxaccel; - hal_float_t maxvel; - hal_bit_t polarity_A; - hal_bit_t polarity_B; - hal_float_t position_scale; + hal_uint_t step_type; //0: StepDir, 1: UpDown, 2: Quadrature + hal_bool_t control_type; //0: position, 1: velocity + hal_uint_t steplen; + hal_uint_t stepspace; + hal_uint_t dirdelay; + hal_real_t maxaccel; + hal_real_t maxvel; + hal_bool_t polarity_A; + hal_bool_t polarity_B; + hal_real_t position_scale; //Saved Parameters - hal_u32_t curr_steplen; - hal_u32_t curr_stepspace; - hal_u32_t curr_dirdelay; - hal_float_t curr_maxaccel; - hal_float_t curr_maxvel; - hal_float_t curr_position_scale; + rtapi_u32 curr_steplen; + rtapi_u32 curr_stepspace; + rtapi_u32 curr_dirdelay; + rtapi_real curr_maxaccel; + rtapi_real curr_maxvel; + rtapi_real curr_position_scale; // Private data - hal_u32_t stepgen_fb_offset; - hal_float_t old_pos_cmd; - hal_float_t max_dv; - hal_float_t old_vel; - hal_float_t steprate_scale; + rtapi_u32 stepgen_fb_offset; + union { + rtapi_real old_pos_cmd; + // This is here to guarantee that the pointer hack works. + rtapi_uint __old_pos_cmd_field_size_match_r; + }; + rtapi_real max_dv; + rtapi_real old_vel; + rtapi_real steprate_scale; } stepgen_t; typedef struct { //CardMgr_t // Pins. - hal_bit_t *cardEnable; - hal_bit_t *power_enable; - hal_bit_t *power_fault; - hal_bit_t *watchdog_expired; + hal_bool_t cardEnable; + hal_bool_t power_enable; + hal_bool_t power_fault; + hal_bool_t watchdog_expired; // Parameters - hal_bit_t watchdog_enable; - hal_u32_t watchdog_timeout_ns; + hal_bool_t watchdog_enable; + hal_uint_t watchdog_timeout_ns; // Private data - hal_u32_t card_control_reg; - hal_bit_t disable; - hal_u32_t dbg_PCI_counter_last; - hal_u32_t cntr; + rtapi_u32 card_control_reg; + union { + rtapi_bool disable; + // These are here to guarantee that the pointer hack works. + rtapi_uint __disable_field_size_match_u; + rtapi_real __disable_field_size_match_r; + }; + rtapi_u32 dbg_PCI_counter_last; + rtapi_u32 cntr; } cardMgr_t; typedef struct { //CAN_GM_t //Pins - hal_bit_t *enable; - hal_float_t *position_cmd; - hal_float_t *position_fb; + hal_bool_t enable; + hal_real_t position_cmd; + hal_real_t position_fb; //Parameters - hal_float_t position_scale; + hal_real_t position_scale; } CAN_GM_t; typedef struct { //CANmsg_t - hal_bit_t Ext; //0: Standrad ID, 1: Extended ID - hal_u32_t ID; - hal_u32_t data[8]; - hal_u32_t DLC; - hal_bit_t RTR; + rtapi_bool Ext; //0: Standrad ID, 1: Extended ID + rtapi_u32 ID; + rtapi_u32 data[8]; + rtapi_u32 DLC; + rtapi_bool RTR; }CANmsg_t; typedef struct { //gm_device_t @@ -327,15 +337,15 @@ typedef struct { //gm_device_t CAN_GM_t CAN_GM[6]; stepgen_t stepgen[6]; - hal_u32_t stepgen_status; + rtapi_u32 stepgen_status; axisdac_t axisdac[6]; encoder_t encoder[6]; cardMgr_t cardMgr; - hal_u32_t period_ns; - hal_float_t period_s; - hal_float_t rec_period_s; + rtapi_u32 period_ns; + rtapi_real period_s; + rtapi_real rec_period_s; } gm_device_t; typedef struct { //gm_driver_t @@ -396,10 +406,10 @@ rtapi_pci_device_id gm_pci_tbl[] = { static void stepgenControl(void *arg, long period, unsigned int i); static void stepgenCheckParameters(void *arg, long period, unsigned int channel); //RS485 - static unsigned int RS485_CheckChecksum(hal_u32_t* data, hal_u32_t length); - static unsigned int RS485_CalcChecksum(hal_u32_t* data, hal_u32_t length); - static void RS485_OrderDataRead(hal_u32_t* dataIn32, hal_u32_t* dataOut8, hal_u32_t length); - static void RS485_OrderDataWrite(hal_u32_t* dataIn8, hal_u32_t* dataOut32, hal_u32_t length); + static unsigned int RS485_CheckChecksum(rtapi_u32* data, rtapi_u32 length); + static unsigned int RS485_CalcChecksum(rtapi_u32* data, rtapi_u32 length); + static void RS485_OrderDataRead(rtapi_u32* dataIn32, rtapi_u32* dataOut8, rtapi_u32 length); + static void RS485_OrderDataWrite(rtapi_u32* dataIn8, rtapi_u32* dataOut32, rtapi_u32 length); //Encoders static void encoder(void *arg, long period); //CAN @@ -408,9 +418,9 @@ rtapi_pci_device_id gm_pci_tbl[] = { static void CAN_ReceiveDataFrame(void *arg, CANmsg_t *Msg); #ifdef CANOPEN static void CAN_Reset(void *arg); - static void CAN_SetBaud(void *arg, hal_u32_t Baud); + static void CAN_SetBaud(void *arg, rtapi_u32 Baud); #endif - static int CAN_ReadStatus(void *arg, hal_u32_t *RxCnt, hal_u32_t *TxCnt); + static int CAN_ReadStatus(void *arg, rtapi_u32 *RxCnt, rtapi_u32 *TxCnt); //Card management static void card_mgr(void *arg, long period); @@ -508,7 +518,7 @@ gm_pci_remove(struct rtapi_pci_dev *dev) if((pDevice = driver.device[i]) != NULL) { // turn off all - pDevice->pCard->card_control_reg = (hal_s32_t) 0; + pDevice->pCard->card_control_reg = 0; // Unmap card rtapi_iounmap((void *)(pDevice->pCard)); @@ -621,20 +631,20 @@ ExportEncoder(void *arg, int comp_id, int version) for(i=0;i<6;i++) { //Export Pins - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->encoder[i].reset), comp_id, "gm.%1d.encoder.%1d.reset", boardId, i); - if(error == 0) error = hal_pin_s32_newf(HAL_OUT, &(device->encoder[i].counts), comp_id, "gm.%1d.encoder.%1d.counts", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->encoder[i].position), comp_id, "gm.%1d.encoder.%1d.position", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->encoder[i].velocity), comp_id, "gm.%1d.encoder.%1d.velocity", boardId, i); - if(error == 0) error = hal_pin_s32_newf(HAL_OUT, &(device->encoder[i].rawcounts), comp_id, "gm.%1d.encoder.%1d.rawcounts", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IO, &(device->encoder[i].index_enable), comp_id, "gm.%1d.encoder.%1d.index-enable", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->encoder[i].reset), 0, "gm.%1d.encoder.%1d.reset", boardId, i); + if(error == 0) error = hal_pin_new_si32(comp_id, HAL_OUT, &(device->encoder[i].counts), 0, "gm.%1d.encoder.%1d.counts", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->encoder[i].position), 0.0, "gm.%1d.encoder.%1d.position", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->encoder[i].velocity), 0.0, "gm.%1d.encoder.%1d.velocity", boardId, i); + if(error == 0) error = hal_pin_new_si32(comp_id, HAL_OUT, &(device->encoder[i].rawcounts), 0, "gm.%1d.encoder.%1d.rawcounts", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IO, &(device->encoder[i].index_enable), 0, "gm.%1d.encoder.%1d.index-enable", boardId, i); //Export Parameters - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->encoder[i].counter_mode), comp_id, "gm.%1d.encoder.%1d.counter-mode", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->encoder[i].index_mode), comp_id, "gm.%1d.encoder.%1d.index-mode", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->encoder[i].index_invert), comp_id, "gm.%1d.encoder.%1d.index-invert", boardId, i); - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->encoder[i].counts_per_rev), comp_id, "gm.%1d.encoder.%1d.counts-per-rev", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->encoder[i].position_scale), comp_id, "gm.%1d.encoder.%1d.position-scale", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->encoder[i].min_speed_estimate), comp_id, "gm.%1d.encoder.%1d.min-speed-estimate", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->encoder[i].counter_mode), 0, "gm.%1d.encoder.%1d.counter-mode", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->encoder[i].index_mode), 0, "gm.%1d.encoder.%1d.index-mode", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->encoder[i].index_invert), 0, "gm.%1d.encoder.%1d.index-invert", boardId, i); + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->encoder[i].counts_per_rev), 0, "gm.%1d.encoder.%1d.counts-per-rev", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->encoder[i].position_scale), 0.0, "gm.%1d.encoder.%1d.position-scale", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->encoder[i].min_speed_estimate), 0.0, "gm.%1d.encoder.%1d.min-speed-estimate", boardId, i); //Init parameters device->encoder[i].raw_offset = pCard->ENC_counter[i]; @@ -664,8 +674,10 @@ ExportStepgen(void *arg, int comp_id, int version) case notPresented: for(i=0;i<6;i++) { - device->stepgen[i].enable = &(device->cardMgr.disable); //Set enable pointers to a 0 value variable - device->stepgen[i].position_cmd = &(device->stepgen[i].old_pos_cmd); + // FIXME: This is a hack. We shouldn't reference local variables as if + // they were pins or params. That can only end very badly... + device->stepgen[i].enable = (hal_bool_t)&(device->cardMgr.disable); //Set enable pointers to a 0 value variable + device->stepgen[i].position_cmd = (hal_real_t)&(device->stepgen[i].old_pos_cmd); } rtapi_print_msg(RTAPI_MSG_WARN, "General Mechatronics: No stepgen module available in this version of the Card.\n"); break; @@ -676,23 +688,23 @@ ExportStepgen(void *arg, int comp_id, int version) for(i = 0; i < 6; i++) { //Export Pins - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->stepgen[i].position_cmd), comp_id, "gm.%1d.stepgen.%1d.position-cmd", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->stepgen[i].position_fb), comp_id, "gm.%1d.stepgen.%1d.position-fb", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->stepgen[i].velocity_cmd), comp_id, "gm.%1d.stepgen.%1d.velocity-cmd", boardId, i); - if(error == 0) error = hal_pin_s32_newf(HAL_OUT, &(device->stepgen[i].count_fb), comp_id, "gm.%1d.stepgen.%1d.count-fb", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->stepgen[i].enable), comp_id, "gm.%1d.stepgen.%1d.enable", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->stepgen[i].position_cmd), 0.0, "gm.%1d.stepgen.%1d.position-cmd", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->stepgen[i].position_fb), 0.0, "gm.%1d.stepgen.%1d.position-fb", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->stepgen[i].velocity_cmd), 0.0, "gm.%1d.stepgen.%1d.velocity-cmd", boardId, i); + if(error == 0) error = hal_pin_new_si32(comp_id, HAL_OUT, &(device->stepgen[i].count_fb), 0, "gm.%1d.stepgen.%1d.count-fb", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->stepgen[i].enable), 0, "gm.%1d.stepgen.%1d.enable", boardId, i); //Export Parameters. - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->stepgen[i].control_type), comp_id, "gm.%1d.stepgen.%1d.control-type", boardId, i); //0: StepDir, 1: UpDown, 2: Quadrature - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->stepgen[i].step_type), comp_id, "gm.%1d.stepgen.%1d.step-type", boardId, i); //0: position, 1: velocity - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->stepgen[i].steplen), comp_id, "gm.%1d.stepgen.%1d.steplen", boardId, i); - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->stepgen[i].stepspace), comp_id, "gm.%1d.stepgen.%1d.stepspace", boardId, i); - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->stepgen[i].dirdelay), comp_id, "gm.%1d.stepgen.%1d.dirdelay", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->stepgen[i].maxaccel), comp_id, "gm.%1d.stepgen.%1d.maxaccel", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->stepgen[i].maxvel), comp_id, "gm.%1d.stepgen.%1d.maxvel", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->stepgen[i].polarity_A), comp_id, "gm.%1d.stepgen.%1d.invert-step1", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->stepgen[i].polarity_B), comp_id, "gm.%1d.stepgen.%1d.invert-step2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->stepgen[i].position_scale), comp_id, "gm.%1d.stepgen.%1d.position-scale", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->stepgen[i].control_type), 0, "gm.%1d.stepgen.%1d.control-type", boardId, i); //0: position, 1: velocity + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->stepgen[i].step_type), 0, "gm.%1d.stepgen.%1d.step-type", boardId, i); //0: StepDir, 1: UpDown, 2: Quadrature + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->stepgen[i].steplen), 0, "gm.%1d.stepgen.%1d.steplen", boardId, i); + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->stepgen[i].stepspace), 0, "gm.%1d.stepgen.%1d.stepspace", boardId, i); + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->stepgen[i].dirdelay), 0, "gm.%1d.stepgen.%1d.dirdelay", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->stepgen[i].maxaccel), 0.0, "gm.%1d.stepgen.%1d.maxaccel", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->stepgen[i].maxvel), 0.0, "gm.%1d.stepgen.%1d.maxvel", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->stepgen[i].polarity_A), 0, "gm.%1d.stepgen.%1d.invert-step1", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->stepgen[i].polarity_B), 0, "gm.%1d.stepgen.%1d.invert-step2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->stepgen[i].position_scale), 0.0, "gm.%1d.stepgen.%1d.position-scale", boardId, i); if(error != 0) break; //Init parameters @@ -731,14 +743,14 @@ ExportDAC(void *arg, int comp_id, int version) case notPresented: for(i=0;i<6;i++) { - device->axisdac[i].enable = &(device->cardMgr.disable); //Set enable pointers to a 0 value variable + device->axisdac[i].enable = (hal_bool_t)&(device->cardMgr.disable); //Set enable pointers to a 0 value variable } rtapi_print_msg(RTAPI_MSG_WARN, "General Mechatronics: No DAC module available in this version of the Card.\n"); break; case dacVersion1: for(i=0;i<6;i++) { - device->axisdac[i].enable = &(device->cardMgr.disable); //Set enable pointers to a 0 value variable + device->axisdac[i].enable = (hal_bool_t)&(device->cardMgr.disable); //Set enable pointers to a 0 value variable } rtapi_print_msg(RTAPI_MSG_WARN, "General Mechatronics: This card supports DAC ver.1 only, which is no longer produced. No DAC pins will be exported to HAL. If you need DAC, contact to bence.kovacs@generalmechatronics.com for firmware upgrade.\n"); break; @@ -746,20 +758,14 @@ ExportDAC(void *arg, int comp_id, int version) for(i=0;i<6;i++) { //Export Pins - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->axisdac[i].enable), comp_id, "gm.%1d.dac.%1d.enable", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->axisdac[i].value), comp_id, "gm.%1d.dac.%1d.value", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->axisdac[i].enable), 0, "gm.%1d.dac.%1d.enable", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->axisdac[i].value), 0.0, "gm.%1d.dac.%1d.value", boardId, i); //Export Parameters. - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->axisdac[i].min), comp_id, "gm.%1d.dac.%1d.low-limit", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->axisdac[i].max), comp_id, "gm.%1d.dac.%1d.high-limit", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->axisdac[i].offset), comp_id, "gm.%1d.dac.%1d.offset", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->axisdac[i].invert_serial), comp_id, "gm.%1d.dac.%1d.invert-serial", boardId, i); - - //Init Parameters - device->axisdac[i].max = 10; - device->axisdac[i].min = -10; - device->axisdac[i].offset = 0; - device->axisdac[i].invert_serial = 0; + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->axisdac[i].min), -10.0, "gm.%1d.dac.%1d.low-limit", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->axisdac[i].max), 10.0, "gm.%1d.dac.%1d.high-limit", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->axisdac[i].offset), 0.0, "gm.%1d.dac.%1d.offset", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->axisdac[i].invert_serial), 0, "gm.%1d.dac.%1d.invert-serial", boardId, i); //Init FPGA regs pCard->DAC_0 = 0x1FFF1FFF; @@ -793,7 +799,7 @@ ExportRS485(void *arg, int comp_id, int version) //READ IDs of connected modules for(i=0; i<8; i++) { - temp=(hal_u32_t)pCard->moduleId[i]; + temp = pCard->moduleId[i]; if(((temp & 0xff)^0xaa) == ((temp & 0xff00)>>8)) { @@ -818,181 +824,149 @@ ExportRS485(void *arg, int comp_id, int version) device-> RS485_mgr.BYTES_TO_WRITE[i]=0; device-> RS485_mgr.BYTES_TO_READ[i]=2; //1 data byte + 1 Checksum - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_0), comp_id, "gm.%1d.rs485.%02d.in-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_0), comp_id, "gm.%1d.rs485.%02d.in-not-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_1), comp_id, "gm.%1d.rs485.%02d.in-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_1), comp_id, "gm.%1d.rs485.%02d.in-not-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_2), comp_id, "gm.%1d.rs485.%02d.in-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_2), comp_id, "gm.%1d.rs485.%02d.in-not-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_3), comp_id, "gm.%1d.rs485.%02d.in-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_3), comp_id, "gm.%1d.rs485.%02d.in-not-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_4), comp_id, "gm.%1d.rs485.%02d.in-4", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_4), comp_id, "gm.%1d.rs485.%02d.in-not-4", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_5), comp_id, "gm.%1d.rs485.%02d.in-5", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_5), comp_id, "gm.%1d.rs485.%02d.in-not-5", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_6), comp_id, "gm.%1d.rs485.%02d.in-6", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_6), comp_id, "gm.%1d.rs485.%02d.in-not-6", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].in_7), comp_id, "gm.%1d.rs485.%02d.in-7", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_8input[i].inNot_7), comp_id, "gm.%1d.rs485.%02d.in-not-7", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_0), 0, "gm.%1d.rs485.%02d.in-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_0), 1, "gm.%1d.rs485.%02d.in-not-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_1), 0, "gm.%1d.rs485.%02d.in-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_1), 1, "gm.%1d.rs485.%02d.in-not-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_2), 0, "gm.%1d.rs485.%02d.in-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_2), 1, "gm.%1d.rs485.%02d.in-not-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_3), 0, "gm.%1d.rs485.%02d.in-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_3), 1, "gm.%1d.rs485.%02d.in-not-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_4), 0, "gm.%1d.rs485.%02d.in-4", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_4), 1, "gm.%1d.rs485.%02d.in-not-4", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_5), 0, "gm.%1d.rs485.%02d.in-5", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_5), 1, "gm.%1d.rs485.%02d.in-not-5", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_6), 0, "gm.%1d.rs485.%02d.in-6", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_6), 1, "gm.%1d.rs485.%02d.in-not-6", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].in_7), 0, "gm.%1d.rs485.%02d.in-7", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_8input[i].inNot_7), 1, "gm.%1d.rs485.%02d.in-not-7", boardId, i); break; case RS485MODUL_ID_8OUTPUT: device-> RS485_mgr.BYTES_TO_WRITE[i]=2; // 1 data byte + 1 Checksum device-> RS485_mgr.BYTES_TO_READ[i]=0; - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_0), comp_id, "gm.%1d.rs485.%02d.relay-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_1), comp_id, "gm.%1d.rs485.%02d.relay-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_2), comp_id, "gm.%1d.rs485.%02d.relay-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_3), comp_id, "gm.%1d.rs485.%02d.relay-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_4), comp_id, "gm.%1d.rs485.%02d.relay-4", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_5), comp_id, "gm.%1d.rs485.%02d.relay-5", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_6), comp_id, "gm.%1d.rs485.%02d.relay-6", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_8output[i].out_7), comp_id, "gm.%1d.rs485.%02d.relay-7", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_0), 0, "gm.%1d.rs485.%02d.relay-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_1), 0, "gm.%1d.rs485.%02d.relay-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_2), 0, "gm.%1d.rs485.%02d.relay-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_3), 0, "gm.%1d.rs485.%02d.relay-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_4), 0, "gm.%1d.rs485.%02d.relay-4", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_5), 0, "gm.%1d.rs485.%02d.relay-5", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_6), 0, "gm.%1d.rs485.%02d.relay-6", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_8output[i].out_7), 0, "gm.%1d.rs485.%02d.relay-7", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_0), comp_id, "gm.%1d.rs485.%02d.invert-relay-0", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_1), comp_id, "gm.%1d.rs485.%02d.invert-relay-1", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_2), comp_id, "gm.%1d.rs485.%02d.invert-relay-2", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_3), comp_id, "gm.%1d.rs485.%02d.invert-relay-3", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_4), comp_id, "gm.%1d.rs485.%02d.invert-relay-4", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_5), comp_id, "gm.%1d.rs485.%02d.invert-relay-5", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_6), comp_id, "gm.%1d.rs485.%02d.invert-relay-6", boardId, i); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->RS485_8output[i].invertOut_7), comp_id, "gm.%1d.rs485.%02d.invert-relay-7", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_0), 0, "gm.%1d.rs485.%02d.invert-relay-0", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_1), 0, "gm.%1d.rs485.%02d.invert-relay-1", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_2), 0, "gm.%1d.rs485.%02d.invert-relay-2", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_3), 0, "gm.%1d.rs485.%02d.invert-relay-3", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_4), 0, "gm.%1d.rs485.%02d.invert-relay-4", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_5), 0, "gm.%1d.rs485.%02d.invert-relay-5", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_6), 0, "gm.%1d.rs485.%02d.invert-relay-6", boardId, i); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->RS485_8output[i].invertOut_7), 0, "gm.%1d.rs485.%02d.invert-relay-7", boardId, i); break; case RS485MODUL_ID_DACADC: device-> RS485_mgr.BYTES_TO_WRITE[i]=5; // 8 data byte + 1 Checksum device-> RS485_mgr.BYTES_TO_READ[i]=9; - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->RS485_DacAdc[i].DAC_0), comp_id, "gm.%1d.rs485.%02d.dac-0", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->RS485_DacAdc[i].DAC_1), comp_id, "gm.%1d.rs485.%02d.dac-1", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->RS485_DacAdc[i].DAC_2), comp_id, "gm.%1d.rs485.%02d.dac-2", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->RS485_DacAdc[i].DAC_3), comp_id, "gm.%1d.rs485.%02d.dac-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_DacAdc[i].dac_0_enable), comp_id, "gm.%1d.rs485.%02d.dac-enable-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_DacAdc[i].dac_1_enable), comp_id, "gm.%1d.rs485.%02d.dac-enable-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_DacAdc[i].dac_2_enable), comp_id, "gm.%1d.rs485.%02d.dac-enable-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_DacAdc[i].dac_3_enable), comp_id, "gm.%1d.rs485.%02d.dac-enable-3", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_0), comp_id, "gm.%1d.rs485.%02d.adc-0", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_1), comp_id, "gm.%1d.rs485.%02d.adc-1", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_2), comp_id, "gm.%1d.rs485.%02d.adc-2", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_3), comp_id, "gm.%1d.rs485.%02d.adc-3", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_4), comp_id, "gm.%1d.rs485.%02d.adc-4", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_5), comp_id, "gm.%1d.rs485.%02d.adc-5", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_6), comp_id, "gm.%1d.rs485.%02d.adc-6", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_DacAdc[i].ADC_7), comp_id, "gm.%1d.rs485.%02d.adc-7", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_0_offset), comp_id, "gm.%1d.rs485.%02d.dac-offset-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_1_offset), comp_id, "gm.%1d.rs485.%02d.dac-offset-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_2_offset), comp_id, "gm.%1d.rs485.%02d.dac-offset-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_3_offset), comp_id, "gm.%1d.rs485.%02d.dac-offset-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_0_max), comp_id, "gm.%1d.rs485.%02d.dac-high-limit-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_1_max), comp_id, "gm.%1d.rs485.%02d.dac-high-limit-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_2_max), comp_id, "gm.%1d.rs485.%02d.dac-high-limit-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_3_max), comp_id, "gm.%1d.rs485.%02d.dac-high-limit-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_0_min), comp_id, "gm.%1d.rs485.%02d.dac-low-limit-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_1_min), comp_id, "gm.%1d.rs485.%02d.dac-low-limit-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_2_min), comp_id, "gm.%1d.rs485.%02d.dac-low-limit-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].DAC_3_min), comp_id, "gm.%1d.rs485.%02d.dac-low-limit-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_0_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_1_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_2_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_3_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_4_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-4", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_5_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-5", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_6_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-6", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_7_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-7", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_0_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_1_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_2_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_3_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_4_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-4", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_5_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-5", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_6_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-6", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_DacAdc[i].ADC_7_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-7", boardId, i); - - device->RS485_DacAdc[i].DAC_0_max = 10; - device->RS485_DacAdc[i].DAC_0_min = -10; - device->RS485_DacAdc[i].DAC_1_max = 10; - device->RS485_DacAdc[i].DAC_1_min = -10; - device->RS485_DacAdc[i].DAC_2_max = 10; - device->RS485_DacAdc[i].DAC_2_min = -10; - device->RS485_DacAdc[i].DAC_3_max = 10; - device->RS485_DacAdc[i].DAC_3_min = -10; - device->RS485_DacAdc[i].ADC_0_scale = 1; - device->RS485_DacAdc[i].ADC_1_scale = 1; - device->RS485_DacAdc[i].ADC_2_scale = 1; - device->RS485_DacAdc[i].ADC_3_scale = 1; - device->RS485_DacAdc[i].ADC_4_scale = 1; - device->RS485_DacAdc[i].ADC_5_scale = 1; - device->RS485_DacAdc[i].ADC_6_scale = 1; - device->RS485_DacAdc[i].ADC_7_scale = 1; - break; + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->RS485_DacAdc[i].DAC_0), 0.0, "gm.%1d.rs485.%02d.dac-0", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->RS485_DacAdc[i].DAC_1), 0.0, "gm.%1d.rs485.%02d.dac-1", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->RS485_DacAdc[i].DAC_2), 0.0, "gm.%1d.rs485.%02d.dac-2", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->RS485_DacAdc[i].DAC_3), 0.0, "gm.%1d.rs485.%02d.dac-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_DacAdc[i].dac_0_enable), 0, "gm.%1d.rs485.%02d.dac-enable-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_DacAdc[i].dac_1_enable), 0, "gm.%1d.rs485.%02d.dac-enable-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_DacAdc[i].dac_2_enable), 0, "gm.%1d.rs485.%02d.dac-enable-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_DacAdc[i].dac_3_enable), 0, "gm.%1d.rs485.%02d.dac-enable-3", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_0), 0.0, "gm.%1d.rs485.%02d.adc-0", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_1), 0.0, "gm.%1d.rs485.%02d.adc-1", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_2), 0.0, "gm.%1d.rs485.%02d.adc-2", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_3), 0.0, "gm.%1d.rs485.%02d.adc-3", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_4), 0.0, "gm.%1d.rs485.%02d.adc-4", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_5), 0.0, "gm.%1d.rs485.%02d.adc-5", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_6), 0.0, "gm.%1d.rs485.%02d.adc-6", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_DacAdc[i].ADC_7), 0.0, "gm.%1d.rs485.%02d.adc-7", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_0_offset), 0.0, "gm.%1d.rs485.%02d.dac-offset-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_1_offset), 0.0, "gm.%1d.rs485.%02d.dac-offset-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_2_offset), 0.0, "gm.%1d.rs485.%02d.dac-offset-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_3_offset), 0.0, "gm.%1d.rs485.%02d.dac-offset-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_0_max), 10.0, "gm.%1d.rs485.%02d.dac-high-limit-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_1_max), 10.0, "gm.%1d.rs485.%02d.dac-high-limit-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_2_max), 10.0, "gm.%1d.rs485.%02d.dac-high-limit-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_3_max), 10.0, "gm.%1d.rs485.%02d.dac-high-limit-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_0_min), -10.0, "gm.%1d.rs485.%02d.dac-low-limit-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_1_min), -10.0, "gm.%1d.rs485.%02d.dac-low-limit-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_2_min), -10.0, "gm.%1d.rs485.%02d.dac-low-limit-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].DAC_3_min), -10.0, "gm.%1d.rs485.%02d.dac-low-limit-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_0_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_1_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_2_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_3_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_4_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-4", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_5_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-5", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_6_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-6", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_7_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-7", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_0_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_1_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_2_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_3_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_4_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-4", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_5_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-5", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_6_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-6", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_DacAdc[i].ADC_7_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-7", boardId, i); + break; case RS485MODUL_ID_TEACHPAD: device-> RS485_mgr.BYTES_TO_WRITE[i]=0; - device-> RS485_mgr.BYTES_TO_READ[i]=12; //1 for 8 digit input, 6 for adc, 4 for encoder + 1 Checksum - - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_0), comp_id, "gm.%1d.rs485.%02d.in-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_0), comp_id, "gm.%1d.rs485.%02d.in-not-0", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_1), comp_id, "gm.%1d.rs485.%02d.in-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_1), comp_id, "gm.%1d.rs485.%02d.in-not-1", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_2), comp_id, "gm.%1d.rs485.%02d.in-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_2), comp_id, "gm.%1d.rs485.%02d.in-not-2", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_3), comp_id, "gm.%1d.rs485.%02d.in-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_3), comp_id, "gm.%1d.rs485.%02d.in-not-3", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_4), comp_id, "gm.%1d.rs485.%02d.in-4", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_4), comp_id, "gm.%1d.rs485.%02d.in-not-4", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_5), comp_id, "gm.%1d.rs485.%02d.in-5", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_5), comp_id, "gm.%1d.rs485.%02d.in-not-5", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_6), comp_id, "gm.%1d.rs485.%02d.in-6", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_6), comp_id, "gm.%1d.rs485.%02d.in-not-6", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].in_7), comp_id, "gm.%1d.rs485.%02d.in-7", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->RS485_TeachPad[i].inNot_7), comp_id, "gm.%1d.rs485.%02d.in-not-7", boardId, i); - - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_0), comp_id, "gm.%1d.rs485.%02d.adc-0", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_1), comp_id, "gm.%1d.rs485.%02d.adc-1", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_2), comp_id, "gm.%1d.rs485.%02d.adc-2", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_3), comp_id, "gm.%1d.rs485.%02d.adc-3", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_4), comp_id, "gm.%1d.rs485.%02d.adc-4", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].ADC_5), comp_id, "gm.%1d.rs485.%02d.adc-5", boardId, i); - - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_0_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_1_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_2_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_3_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_4_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-4", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_5_offset), comp_id, "gm.%1d.rs485.%02d.adc-offset-5", boardId, i); - - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_0_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-0", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_1_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-1", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_2_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-2", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_3_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-3", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_4_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-4", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].ADC_5_scale), comp_id, "gm.%1d.rs485.%02d.adc-scale-5", boardId, i); - - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->RS485_TeachPad[i].enc_reset), comp_id, "gm.%1d.rs485.%02d.enc-reset", boardId, i); - if(error == 0) error = hal_pin_s32_newf(HAL_OUT, &(device->RS485_TeachPad[i].enc_counts), comp_id, "gm.%1d.rs485.%02d.enc-counts", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->RS485_TeachPad[i].enc_position), comp_id, "gm.%1d.rs485.%02d.enc-position", boardId, i); - if(error == 0) error = hal_pin_s32_newf(HAL_OUT, &(device->RS485_TeachPad[i].enc_rawcounts), comp_id, "gm.%1d.rs485.%02d.enc-rawcounts", boardId, i); - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->RS485_TeachPad[i].enc_position_scale), comp_id, "gm.%1d.rs485.%02d.enc-position-scale", boardId, i); - - device->RS485_TeachPad[i].ADC_0_scale = 1; - device->RS485_TeachPad[i].ADC_1_scale = 1; - device->RS485_TeachPad[i].ADC_2_scale = 1; - device->RS485_TeachPad[i].ADC_3_scale = 1; - device->RS485_TeachPad[i].ADC_4_scale = 1; - device->RS485_TeachPad[i].ADC_5_scale = 1; - - device->RS485_TeachPad[i].ADC_0_offset = 0; - device->RS485_TeachPad[i].ADC_1_offset = 0; - device->RS485_TeachPad[i].ADC_2_offset = 0; - device->RS485_TeachPad[i].ADC_3_offset = 0; - device->RS485_TeachPad[i].ADC_4_offset = 0; - device->RS485_TeachPad[i].ADC_5_offset = 0; - + device-> RS485_mgr.BYTES_TO_READ[i]=12; //1 for 8 digit input, 6 for adc, 4 for encoder + 1 Checksum + + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_0), 0, "gm.%1d.rs485.%02d.in-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_0), 1, "gm.%1d.rs485.%02d.in-not-0", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_1), 0, "gm.%1d.rs485.%02d.in-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_1), 1, "gm.%1d.rs485.%02d.in-not-1", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_2), 0, "gm.%1d.rs485.%02d.in-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_2), 1, "gm.%1d.rs485.%02d.in-not-2", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_3), 0, "gm.%1d.rs485.%02d.in-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_3), 1, "gm.%1d.rs485.%02d.in-not-3", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_4), 0, "gm.%1d.rs485.%02d.in-4", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_4), 1, "gm.%1d.rs485.%02d.in-not-4", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_5), 0, "gm.%1d.rs485.%02d.in-5", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_5), 1, "gm.%1d.rs485.%02d.in-not-5", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_6), 0, "gm.%1d.rs485.%02d.in-6", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_6), 1, "gm.%1d.rs485.%02d.in-not-6", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].in_7), 0, "gm.%1d.rs485.%02d.in-7", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].inNot_7), 1, "gm.%1d.rs485.%02d.in-not-7", boardId, i); + + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_0), 0.0, "gm.%1d.rs485.%02d.adc-0", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_1), 0.0, "gm.%1d.rs485.%02d.adc-1", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_2), 0.0, "gm.%1d.rs485.%02d.adc-2", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_3), 0.0, "gm.%1d.rs485.%02d.adc-3", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_4), 0.0, "gm.%1d.rs485.%02d.adc-4", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].ADC_5), 0.0, "gm.%1d.rs485.%02d.adc-5", boardId, i); + + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_0_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_1_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_2_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_3_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_4_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-4", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_5_offset), 0.0, "gm.%1d.rs485.%02d.adc-offset-5", boardId, i); + + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_0_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-0", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_1_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-1", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_2_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-2", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_3_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-3", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_4_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-4", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].ADC_5_scale), 1.0, "gm.%1d.rs485.%02d.adc-scale-5", boardId, i); + + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->RS485_TeachPad[i].enc_reset), 0, "gm.%1d.rs485.%02d.enc-reset", boardId, i); + if(error == 0) error = hal_pin_new_si32(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].enc_counts), 0, "gm.%1d.rs485.%02d.enc-counts", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].enc_position), 0.0, "gm.%1d.rs485.%02d.enc-position", boardId, i); + if(error == 0) error = hal_pin_new_si32(comp_id, HAL_OUT, &(device->RS485_TeachPad[i].enc_rawcounts), 0, "gm.%1d.rs485.%02d.enc-rawcounts", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->RS485_TeachPad[i].enc_position_scale), 1.0, "gm.%1d.rs485.%02d.enc-position-scale", boardId, i); + device->RS485_TeachPad[i].enc_raw_offset = 0; - device->RS485_TeachPad[i].enc_position_scale=1; break; default: rtapi_print_msg(RTAPI_MSG_ERR, "General Mechatronics: ERROR, unknown rs485 module type.\nPlease, download the latest driver.\n"); } - } + } break; default: rtapi_print_msg(RTAPI_MSG_ERR, "General Mechatronics: ERROR, unknown rs485 version.\nPlease, download the latest driver.\n"); @@ -1013,7 +987,7 @@ ExportCAN(void *arg, int comp_id, int version) case notPresented: for(i=0;i<6;i++) { - device->CAN_GM[i].enable = &(device->cardMgr.disable); //Set enable pointers to a 0 value variable + device->CAN_GM[i].enable = (hal_bool_t)&(device->cardMgr.disable); //Set enable pointers to a 0 value variable } rtapi_print_msg(RTAPI_MSG_WARN, "General Mechatronics: No CAN module available in this version of the Card.\n"); break; @@ -1023,12 +997,12 @@ ExportCAN(void *arg, int comp_id, int version) for(i=0;i<6;i++) { //Export Pins - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->CAN_GM[i].enable), comp_id, "gm.%1d.can-gm.%1d.enable", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_IN, &(device->CAN_GM[i].position_cmd), comp_id, "gm.%1d.can-gm.%1d.position-cmd", boardId, i); - if(error == 0) error = hal_pin_float_newf(HAL_OUT, &(device->CAN_GM[i].position_fb), comp_id, "gm.%1d.can-gm.%1d.position-fb", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->CAN_GM[i].enable), 0, "gm.%1d.can-gm.%1d.enable", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_IN, &(device->CAN_GM[i].position_cmd), 0.0, "gm.%1d.can-gm.%1d.position-cmd", boardId, i); + if(error == 0) error = hal_pin_new_real(comp_id, HAL_OUT, &(device->CAN_GM[i].position_fb), 0.0, "gm.%1d.can-gm.%1d.position-fb", boardId, i); //Export Parameters - if(error == 0) error = hal_param_float_newf(HAL_RW, &(device->CAN_GM[i].position_scale), comp_id, "gm.%1d.can-gm.%1d.position-scale", boardId, i); + if(error == 0) error = hal_param_new_real(comp_id, HAL_RW, &(device->CAN_GM[i].position_scale), 0.0, "gm.%1d.can-gm.%1d.position-scale", boardId, i); } //Export Pins and Parameters for CANopen Servo Controllers @@ -1052,41 +1026,41 @@ ExportMixed(void *arg, int comp_id) for(i = 0; i < 6; i++) { // Pins - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].home), comp_id, "gm.%1d.axis.%1d.home-sw-in", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].homeNot), comp_id, "gm.%1d.axis.%1d.home-sw-in-not", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].posLimSwIn), comp_id, "gm.%1d.axis.%1d.pos-lim-sw-in", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].posLimSwInNot), comp_id, "gm.%1d.axis.%1d.pos-lim-sw-in-not", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].negLimSwIn), comp_id, "gm.%1d.axis.%1d.neg-lim-sw-in", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->switches[i].negLimSwInNot), comp_id, "gm.%1d.axis.%1d.neg-lim-sw-in-not", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].home), 0, "gm.%1d.axis.%1d.home-sw-in", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].homeNot), 0, "gm.%1d.axis.%1d.home-sw-in-not", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].posLimSwIn), 0, "gm.%1d.axis.%1d.pos-lim-sw-in", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].posLimSwInNot), 0, "gm.%1d.axis.%1d.pos-lim-sw-in-not", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].negLimSwIn), 0, "gm.%1d.axis.%1d.neg-lim-sw-in", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->switches[i].negLimSwInNot), 0, "gm.%1d.axis.%1d.neg-lim-sw-in-not", boardId, i); } //Power bridge Fault and Error pins - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->cardMgr.power_enable), comp_id, "gm.%1d.power-enable", boardId); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->cardMgr.power_fault), comp_id, "gm.%1d.power-fault", boardId); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->cardMgr.power_enable), 0, "gm.%1d.power-enable", boardId); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->cardMgr.power_fault), 0, "gm.%1d.power-fault", boardId); //Watchdog pins and parameters - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->cardMgr.watchdog_enable), comp_id, "gm.%1d.watchdog-enable", boardId); - if(error == 0) error = hal_param_u32_newf(HAL_RW, &(device->cardMgr.watchdog_timeout_ns), comp_id, "gm.%1d.watchdog-timeout-ns", boardId); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->cardMgr.watchdog_expired), comp_id, "gm.%1d.watchdog-expired", boardId); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->cardMgr.watchdog_enable), 0, "gm.%1d.watchdog-enable", boardId); + if(error == 0) error = hal_param_new_ui32(comp_id, HAL_RW, &(device->cardMgr.watchdog_timeout_ns), 0, "gm.%1d.watchdog-timeout-ns", boardId); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->cardMgr.watchdog_expired), 0, "gm.%1d.watchdog-expired", boardId); //Export pins and parameters for parallel IOs for(i=0;i<4;i++) { for(j=0;j<8;j++) { - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->gpio[i*8+j].in), comp_id, "gm.%1d.gpio.%1d.in-%1d", boardId, i, j); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->gpio[i*8+j].inNot), comp_id, "gm.%1d.gpio.%1d.in-not-%1d", boardId, i, j); - if(error == 0) error = hal_pin_bit_newf(HAL_IN, &(device->gpio[i*8+j].out), comp_id, "gm.%1d.gpio.%1d.out-%1d", boardId, i, j); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->gpio[i*8+j].isOut), comp_id, "gm.%1d.gpio.%1d.is-out-%1d", boardId, i, j); - if(error == 0) error = hal_param_bit_newf(HAL_RW, &(device->gpio[i*8+j].invertOut), comp_id, "gm.%1d.gpio.%1d.invert-out-%1d", boardId, i, j); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->gpio[i*8+j].in), 0, "gm.%1d.gpio.%1d.in-%1d", boardId, i, j); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->gpio[i*8+j].inNot), 1, "gm.%1d.gpio.%1d.in-not-%1d", boardId, i, j); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_IN, &(device->gpio[i*8+j].out), 0, "gm.%1d.gpio.%1d.out-%1d", boardId, i, j); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->gpio[i*8+j].isOut), 0, "gm.%1d.gpio.%1d.is-out-%1d", boardId, i, j); + if(error == 0) error = hal_param_new_bool(comp_id, HAL_RW, &(device->gpio[i*8+j].invertOut), 0, "gm.%1d.gpio.%1d.invert-out-%1d", boardId, i, j); } } //Export pins and parameters for estops for(i=0;i<2;i++) { - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->estop[i].in), comp_id, "gm.%1d.estop.%1d.in", boardId, i); - if(error == 0) error = hal_pin_bit_newf(HAL_OUT, &(device->estop[i].inNot), comp_id, "gm.%1d.estop.%1d.in-not", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->estop[i].in), 0, "gm.%1d.estop.%1d.in", boardId, i); + if(error == 0) error = hal_pin_new_bool(comp_id, HAL_OUT, &(device->estop[i].inNot), 1, "gm.%1d.estop.%1d.in-not", boardId, i); } device->cardMgr.cntr = 0; //Counter of executing card_mgr() function @@ -1124,7 +1098,7 @@ read(void *arg, long period) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; unsigned int i; - hal_u32_t temp; + rtapi_u32 temp; //basic card functionality: watchdog, switches, estop card_mgr(arg, period); @@ -1133,8 +1107,8 @@ read(void *arg, long period) temp=pCard->gpio; for(i = 0; i < 32; i++) { - *(device->gpio[i].in) = (hal_bit_t)((temp & ((unsigned int) 1 << i)) == 0 ? 0 : 1); - *(device->gpio[i].inNot) = (hal_bit_t)((temp & ((unsigned int) 1 << i)) == 0 ? 1 : 0); + hal_set_bool(device->gpio[i].in, (temp & ((unsigned int) 1 << i)) == 0 ? 0 : 1); + hal_set_bool(device->gpio[i].inNot, (temp & ((unsigned int) 1 << i)) == 0 ? 1 : 0); } //Read Encoders @@ -1148,25 +1122,25 @@ write(void *arg, long period) card *pCard = device->pCard; int i, temp1=0, temp2=0; - hal_float_t DAC[6]; - hal_u32_t DAC_INTEGER[6]; + rtapi_real DAC[6]; + rtapi_u32 DAC_INTEGER[6]; //Refresh DAC values for(i=0;i<6;i++) { - if(*(device->axisdac[i].enable)) + if(hal_get_bool(device->axisdac[i].enable)) { - if( (*(device->axisdac[i].value) + device->axisdac[i].offset) > device->axisdac[i].max) + if( (hal_get_real(device->axisdac[i].value) + hal_get_real(device->axisdac[i].offset)) > hal_get_real(device->axisdac[i].max)) { - DAC[i] = device->axisdac[i].max; + DAC[i] = hal_get_real(device->axisdac[i].max); } - else if ( (*(device->axisdac[i].value) + device->axisdac[i].offset) < device->axisdac[i].min) + else if ( (hal_get_real(device->axisdac[i].value) + hal_get_real(device->axisdac[i].offset)) < hal_get_real(device->axisdac[i].min)) { - DAC[i] = device->axisdac[i].min; + DAC[i] = hal_get_real(device->axisdac[i].min); } else { - DAC[i] = (*(device->axisdac[i].value) + device->axisdac[i].offset); + DAC[i] = (hal_get_real(device->axisdac[i].value) + hal_get_real(device->axisdac[i].offset)); } } else @@ -1178,9 +1152,9 @@ write(void *arg, long period) if(DAC[i] < 0) DAC[i] = 0; else if (DAC[i] > 16383) DAC[i] = 16383; - DAC_INTEGER[i] = (hal_u32_t)(DAC[i]); + DAC_INTEGER[i] = (rtapi_u32)(DAC[i]); - if(device->axisdac[i].invert_serial) DAC_INTEGER[i] |= 0x8000; + if(hal_get_bool(device->axisdac[i].invert_serial)) DAC_INTEGER[i] |= 0x8000; } pCard->DAC_0 = ((DAC_INTEGER[1] & 0xFFFF) << 16) | (DAC_INTEGER[0] & 0xFFFF); pCard->DAC_1 = ((DAC_INTEGER[3] & 0xFFFF) << 16) | (DAC_INTEGER[2] & 0xFFFF); @@ -1196,8 +1170,8 @@ write(void *arg, long period) temp1 = 0; for(i = 0; i < 32; i++) { - if(device->gpio[i].isOut) temp1 |= 0x0001 << i; //write gpio mask: 1=output, 0=input - if((*(device->gpio[i].out)) ^ (device->gpio[i].invertOut)) temp2 |= 0x0001 << i; //write outputs + if(hal_get_bool(device->gpio[i].isOut)) temp1 |= 0x0001 << i; //write gpio mask: 1=output, 0=input + if((hal_get_bool(device->gpio[i].out)) ^ hal_get_bool(device->gpio[i].invertOut)) temp2 |= 0x0001 << i; //write outputs } pCard->gpioDir=temp1; pCard->gpio=temp2; @@ -1214,9 +1188,9 @@ GM_CAN_SERVO(void *arg) { gm_device_t *device = (gm_device_t *)arg; - hal_u32_t Rx_buf_cntr, Tx_buf_cntr; - hal_u32_t i, temp=0; - hal_s32_t posFb; + rtapi_u32 Rx_buf_cntr, Tx_buf_cntr; + rtapi_u32 i, temp=0; + rtapi_s32 posFb; CANmsg_t CAN_msg; //Position references: ID 0x10 - 0x15 @@ -1224,7 +1198,7 @@ GM_CAN_SERVO(void *arg) //Do not run, if none of the GM CAN channels are enabled for(i=0;i<6;i++){ - if(*(device->CAN_GM[i].enable) == 1) temp++; + if(hal_get_bool(device->CAN_GM[i].enable)) temp++; } if(temp == 0) return; @@ -1238,30 +1212,30 @@ GM_CAN_SERVO(void *arg) if((CAN_msg.ID >= 0x20) && (CAN_msg.ID <= 0x25)) { - if((device->CAN_GM[CAN_msg.ID - 0x20].position_scale<10e-6) && (device->CAN_GM[CAN_msg.ID - 0x20].position_scale>-10e-6)) + if((hal_get_real(device->CAN_GM[CAN_msg.ID - 0x20].position_scale)<10e-6) && (hal_get_real(device->CAN_GM[CAN_msg.ID - 0x20].position_scale)>-10e-6)) { - device->CAN_GM[CAN_msg.ID - 0x20].position_scale = 1; + hal_set_real(device->CAN_GM[CAN_msg.ID - 0x20].position_scale, 1); } posFb = (CAN_msg.data[3] << 24) | (CAN_msg.data[2] << 16) | (CAN_msg.data[1] << 8) | CAN_msg.data[0]; - *(device->CAN_GM[CAN_msg.ID - 0x20].position_fb) = (hal_float_t)posFb / device->CAN_GM[CAN_msg.ID - 0x20].position_scale; + hal_set_real(device->CAN_GM[CAN_msg.ID - 0x20].position_fb, (rtapi_real)posFb / hal_get_real(device->CAN_GM[CAN_msg.ID - 0x20].position_scale)); } } //Send reference for(i=0;i<6;i++) { - if(*(device->CAN_GM[i].enable) == 1) + if(hal_get_bool(device->CAN_GM[i].enable)) { CAN_msg.RTR = 0; //Not a request frame CAN_msg.Ext = 0; //Standard ID CAN_msg.DLC = 4; //4 byte data CAN_msg.ID = 0x10 + i; - if((device->CAN_GM[i].position_scale<10e-6) && (device->CAN_GM[i].position_scale>-10e-6)) + if((hal_get_real(device->CAN_GM[i].position_scale)<10e-6) && (hal_get_real(device->CAN_GM[i].position_scale)>-10e-6)) { - device->CAN_GM[i].position_scale = 1; + hal_set_real(device->CAN_GM[i].position_scale, 1); } - temp = (hal_u32_t)(*(device->CAN_GM[i].position_cmd) * device->CAN_GM[i].position_scale); + temp = (rtapi_u32)(hal_get_real(device->CAN_GM[i].position_cmd) * hal_get_real(device->CAN_GM[i].position_scale)); CAN_msg.data[0] = temp & 0xFF; CAN_msg.data[1] = (temp >> 8) & 0xFF; CAN_msg.data[2] = (temp >> 16) & 0xFF; @@ -1276,12 +1250,12 @@ GM_CAN_SERVO(void *arg) } } static int -CAN_ReadStatus(void *arg, hal_u32_t *RxCnt, hal_u32_t *TxCnt) +CAN_ReadStatus(void *arg, rtapi_u32 *RxCnt, rtapi_u32 *TxCnt) { gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_u32_t temp; + rtapi_u32 temp; temp = pCard->CAN_status_reg; *TxCnt = temp & 0x3FF; @@ -1296,7 +1270,7 @@ CAN_ReceiveDataFrame(void *arg, CANmsg_t *Msg) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_u32_t temp; + rtapi_u32 temp; temp = pCard->CAN_RX_buffer[0]; if(temp & 0x80000000) @@ -1334,7 +1308,7 @@ CAN_SendDataFrame(void *arg, CANmsg_t *Msg) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_u32_t ID; + rtapi_u32 ID; ID = Msg->ID;//MsgID; if(Msg->Ext) ID |= 0x80000000; @@ -1359,7 +1333,7 @@ CAN_Reset(void *arg) } static void -CAN_SetBaud(void *arg, hal_u32_t Baud) +CAN_SetBaud(void *arg, rtapi_u32 Baud) { gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; @@ -1401,42 +1375,42 @@ card_mgr(void *arg, long period) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_u32_t temp=0, i, j; + rtapi_u32 temp=0, i, j; //Read card status reg and process data temp = pCard->card_status_reg; //This resets watch dog timer - *(device->cardMgr.watchdog_expired) = (hal_bit_t)((temp & (0x0001 << 0)) == 0 ? 0 : 1); - *(device->cardMgr.power_fault) = (hal_bit_t)((temp & (0x0001 << 2)) == 0 ? 0 : 1); - *(device->estop[0].in) = (hal_bit_t)((temp & (0x0001 << 3)) == 0 ? 0 : 1); - *(device->estop[0].inNot) = (hal_bit_t)((temp & (0x0001 << 3)) == 0 ? 1 : 0); - *(device->estop[1].in) = (hal_bit_t)((temp & (0x0001 << 4)) == 0 ? 0 : 1); - *(device->estop[1].inNot) = (hal_bit_t)((temp & (0x0001 << 4)) == 0 ? 1 : 0); + hal_set_bool(device->cardMgr.watchdog_expired, (temp & (0x0001 << 0)) == 0 ? 0 : 1); + hal_set_bool(device->cardMgr.power_fault, (temp & (0x0001 << 2)) == 0 ? 0 : 1); + hal_set_bool(device->estop[0].in, (temp & (0x0001 << 3)) == 0 ? 0 : 1); + hal_set_bool(device->estop[0].inNot, (temp & (0x0001 << 3)) == 0 ? 1 : 0); + hal_set_bool(device->estop[1].in, (temp & (0x0001 << 4)) == 0 ? 0 : 1); + hal_set_bool(device->estop[1].inNot, (temp & (0x0001 << 4)) == 0 ? 1 : 0); for(i=5, j=0; i<11; i++,j++) { - *(device->switches[j].home) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 0 : 1); - *(device->switches[j].homeNot) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 1 : 0); + hal_set_bool(device->switches[j].home, (temp & (0x0001 << i)) == 0 ? 0 : 1); + hal_set_bool(device->switches[j].homeNot, (temp & (0x0001 << i)) == 0 ? 1 : 0); } for(j=0;i<17;i++,j++){ - *(device->switches[j].posLimSwIn) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 0 : 1); - *(device->switches[j].posLimSwInNot) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 1 : 0); + hal_set_bool(device->switches[j].posLimSwIn, (temp & (0x0001 << i)) == 0 ? 0 : 1); + hal_set_bool(device->switches[j].posLimSwInNot, (temp & (0x0001 << i)) == 0 ? 1 : 0); } for(j=0;i<23;i++,j++){ - *(device->switches[j].negLimSwIn) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 0 : 1); - *(device->switches[j].negLimSwInNot) = (hal_bit_t)((temp & (0x0001 << i)) == 0 ? 1 : 0); + hal_set_bool(device->switches[j].negLimSwIn, (temp & (0x0001 << i)) == 0 ? 0 : 1); + hal_set_bool(device->switches[j].negLimSwInNot, (temp & (0x0001 << i)) == 0 ? 1 : 0); } //Check if change happened in control reg and write control reg if well // ... Estop_1 | Estop_0 | Pwr_fault | Bus_err | Wdt_err //Card status read resets wdt temp = 1; //EMC run - if(*(device->cardMgr.power_enable)) temp |= (0x0001 << 1); //power enable + if(hal_get_bool(device->cardMgr.power_enable)) temp |= (0x0001 << 1); //power enable - if(device->cardMgr.watchdog_enable) //watchdog timeout in ns*256 unit. 0 if watchdog is disabled + if(hal_get_bool(device->cardMgr.watchdog_enable)) //watchdog timeout in ns*256 unit. 0 if watchdog is disabled { - if(device->cardMgr.watchdog_timeout_ns < 256) temp |= 0x100; - else temp |= (device->cardMgr.watchdog_timeout_ns & 0xFFFFFF00); + if(hal_get_ui32(device->cardMgr.watchdog_timeout_ns) < 256) temp |= 0x100; + else temp |= (hal_get_ui32(device->cardMgr.watchdog_timeout_ns) & 0xFFFFFF00); } if(temp != device->cardMgr.card_control_reg) @@ -1454,7 +1428,7 @@ card_mgr(void *arg, long period) temp = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_ALL); rtapi_print_msg(RTAPI_MSG_INFO, "General Mechatronics: PCI clk frequency is %d khz.\n", - (int)((hal_float_t)(pCard->PCI_clk_counter - device->cardMgr.dbg_PCI_counter_last)/period*62500)); //Calculate frequency + (int)((rtapi_real)(pCard->PCI_clk_counter - device->cardMgr.dbg_PCI_counter_last)/period*62500)); //Calculate frequency rtapi_set_msg_level(temp); } device->cardMgr.cntr++; @@ -1472,14 +1446,14 @@ encoder(void *arg, long period) card *pCard = device->pCard; int i; - hal_s32_t temp1 = 0, temp2; - hal_float_t vel; + rtapi_s32 temp1 = 0, temp2; + rtapi_real vel; //Update parameters for(i=0; i<6; i++) { - if(device->encoder[i].index_invert == 1) temp1 |= (0x1 << i); - if(device->encoder[i].counter_mode == 1) temp1 |= (0x1 << (i+6)); + if(hal_get_bool(device->encoder[i].index_invert)) temp1 |= (0x1 << i); + if(hal_get_bool(device->encoder[i].counter_mode)) temp1 |= (0x1 << (i+6)); } pCard->ENC_control_reg = temp1; @@ -1491,18 +1465,18 @@ encoder(void *arg, long period) temp1 = pCard->ENC_counter[i]; temp2 = pCard->ENC_index_latch[i]; - if(*(device->encoder[i].reset) == 1) //If encoder in reset state + if(hal_get_bool(device->encoder[i].reset)) //If encoder in reset state { device->encoder[i].index_offset = temp1; } - else if(*(device->encoder[i].index_enable) == 1) //If not in reset and index is enabled + else if(hal_get_bool(device->encoder[i].index_enable) == 1) //If not in reset and index is enabled { if (temp2 != device->encoder[i].last_index_latch) //If index pulse come { - if(device->encoder[i].index_mode == 0) //reset counter at index + if(!hal_get_bool(device->encoder[i].index_mode)) //reset counter at index { device->encoder[i].index_offset = temp2; - *(device->encoder[i].index_enable) = 0; //disable index + hal_set_bool(device->encoder[i].index_enable, 0); //disable index } else //round counter at index { @@ -1512,13 +1486,13 @@ encoder(void *arg, long period) } else { - if(temp2 > (device->encoder[i].last_index_latch + (hal_s32_t)(device->encoder[i].counts_per_rev/4))) + if(temp2 > (device->encoder[i].last_index_latch + (rtapi_sint)(hal_get_ui32(device->encoder[i].counts_per_rev)/4))) { - device->encoder[i].index_offset -= device->encoder[i].last_index_latch + device->encoder[i].counts_per_rev - temp2; + device->encoder[i].index_offset -= device->encoder[i].last_index_latch + hal_get_ui32(device->encoder[i].counts_per_rev) - temp2; } - else if(temp2 < (device->encoder[i].last_index_latch - (hal_s32_t)(device->encoder[i].counts_per_rev/4))) + else if(temp2 < (device->encoder[i].last_index_latch - (rtapi_sint)(hal_get_ui32(device->encoder[i].counts_per_rev)/4))) { - device->encoder[i].index_offset -= device->encoder[i].last_index_latch - device->encoder[i].counts_per_rev - temp2; + device->encoder[i].index_offset -= device->encoder[i].last_index_latch - hal_get_ui32(device->encoder[i].counts_per_rev) - temp2; } else { @@ -1530,23 +1504,23 @@ encoder(void *arg, long period) } device->encoder[i].last_index_latch = temp2; - *(device->encoder[i].rawcounts) = temp1 - device->encoder[i].raw_offset; - *(device->encoder[i].counts) = *(device->encoder[i].rawcounts) - device->encoder[i].index_offset; + hal_set_si32(device->encoder[i].rawcounts, temp1 - device->encoder[i].raw_offset); + hal_set_si32(device->encoder[i].counts, hal_get_si32(device->encoder[i].rawcounts) - device->encoder[i].index_offset); - if((device->encoder[i].position_scale < 0.000001) && (device->encoder[i].position_scale > -0.000001)) device->encoder[i].position_scale = 1; //Don't like to divide by 0 - *(device->encoder[i].position) = (hal_float_t) *(device->encoder[i].counts) / device->encoder[i].position_scale; + if((hal_get_real(device->encoder[i].position_scale) < 0.000001) && (hal_get_real(device->encoder[i].position_scale) > -0.000001)) hal_set_real(device->encoder[i].position_scale, 1); //Don't like to divide by 0 + hal_set_real(device->encoder[i].position, (rtapi_real) hal_get_si32(device->encoder[i].counts) / hal_get_real(device->encoder[i].position_scale)); - vel = (hal_float_t) pCard->ENC_period[i]; + vel = (rtapi_real) pCard->ENC_period[i]; if(vel == 0) vel = 1; - vel = 33333333 / ( vel * device->encoder[i].position_scale); //velocity in position units / s + vel = 33333333 / ( vel * hal_get_real(device->encoder[i].position_scale)); //velocity in position units / s - if(fabs(vel) > device->encoder[i].min_speed_estimate) + if(fabs(vel) > hal_get_real(device->encoder[i].min_speed_estimate)) { - *(device->encoder[i].velocity) = vel; + hal_set_real(device->encoder[i].velocity, vel); } else { - *(device->encoder[i].velocity) = 0; + hal_set_real(device->encoder[i].velocity, 0); } } } @@ -1565,7 +1539,7 @@ stepgen(void *arg, long period) //Update stepgen status with enable bits for(i=0;i<6;i++) { - if(*(device->stepgen[i].enable) == 1) device->stepgen_status |= (0x1 << i); //six stepgens share one status reg, 5 bits for each. + if(hal_get_bool(device->stepgen[i].enable)) device->stepgen_status |= (0x1 << i); //six stepgens share one status reg, 5 bits for each. else { device->stepgen_status &= ~(0x1 << i); //LS bits of 5 bits are the enable bits @@ -1576,7 +1550,7 @@ stepgen(void *arg, long period) //Check parameter changes, if enabled for(i=0;i<6;i++) { - if(*(device->stepgen[i].enable) == 1) + if(hal_get_bool(device->stepgen[i].enable)) { stepgenCheckParameters(arg, period, i); } @@ -1588,7 +1562,7 @@ stepgen(void *arg, long period) //Run steppers, if enabled for(i=0;i<6;i++) { - if(*(device->stepgen[i].enable) == 1) + if(hal_get_bool(device->stepgen[i].enable)) { stepgenControl(arg, period, i); } @@ -1597,7 +1571,7 @@ stepgen(void *arg, long period) //update old pos_cmd for(i=0;i<6;i++) { - device->stepgen[i].old_pos_cmd = *(device->stepgen[i].position_cmd); + device->stepgen[i].old_pos_cmd = hal_get_real(device->stepgen[i].position_cmd); } } @@ -1607,8 +1581,8 @@ stepgenCheckParameters(void *arg, long period, unsigned int channel) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_u32_t temp1, temp2; - hal_float_t min_period, max_vel; + rtapi_u32 temp1, temp2; + rtapi_real min_period, max_vel; //If period changed : recalc period related parameters if(device->period_ns != period) @@ -1618,41 +1592,41 @@ stepgenCheckParameters(void *arg, long period, unsigned int channel) } //If position scale changed : update steprate_scale - if(device->stepgen[channel].curr_position_scale != device->stepgen[channel].position_scale) + if(device->stepgen[channel].curr_position_scale != hal_get_real(device->stepgen[channel].position_scale)) { //30 ns is circley time of CLK, 1/10e9 is ns -sec conversion, 42.. is 2^32 because steprate is 32 bit - device->stepgen[channel].steprate_scale = device->stepgen[channel].position_scale * 30.0 / 1000000000.0 * 4294967296.0; + device->stepgen[channel].steprate_scale = hal_get_real(device->stepgen[channel].position_scale) * 30.0 / 1000000000.0 * 4294967296.0; } //If steplen, stepspace, position_scale or max_vel changed : update max_vel - if((device->stepgen[channel].steplen != device->stepgen[channel].curr_steplen) || (device->stepgen[channel].stepspace != device->stepgen[channel].curr_stepspace) || - (device->stepgen[channel].maxvel != device->stepgen[channel].curr_maxvel) || (device->stepgen[channel].curr_position_scale != device->stepgen[channel].position_scale)) + if((hal_get_ui32(device->stepgen[channel].steplen) != device->stepgen[channel].curr_steplen) || (hal_get_ui32(device->stepgen[channel].stepspace) != device->stepgen[channel].curr_stepspace) || + (hal_get_real(device->stepgen[channel].maxvel) != device->stepgen[channel].curr_maxvel) || (device->stepgen[channel].curr_position_scale != hal_get_real(device->stepgen[channel].position_scale))) { - min_period = (device->stepgen[channel].steplen + device->stepgen[channel].stepspace) * 0.000000001; - max_vel = 1/((hal_float_t)min_period * fabs(device->stepgen[channel].position_scale)); + min_period = (hal_get_ui32(device->stepgen[channel].steplen) + hal_get_ui32(device->stepgen[channel].stepspace)) * 0.000000001; + max_vel = 1.0/((rtapi_real)min_period * fabs(hal_get_real(device->stepgen[channel].position_scale))); - if(device->stepgen[channel].maxvel <= 0) + if(hal_get_real(device->stepgen[channel].maxvel) <= 0) { - device->stepgen[channel].maxvel = max_vel; + hal_set_real(device->stepgen[channel].maxvel, max_vel); } else { - if(max_vel < device->stepgen[channel].maxvel) //if stepgen given velocity is higher, then what is possible with step timing parameters + if(max_vel < hal_get_real(device->stepgen[channel].maxvel)) //if stepgen given velocity is higher, then what is possible with step timing parameters { - device->stepgen[channel].maxvel = max_vel; + hal_set_real(device->stepgen[channel].maxvel, max_vel); rtapi_print_msg(RTAPI_MSG_ERR, "GM: stepgen.%d.maxvel can not be reached with given 'steplen' and 'stepspace' parameters.\n", channel); } } } //If steplen or dirdelay changed : update FPGA time parameter regs - if((device->stepgen[channel].steplen != device->stepgen[channel].curr_steplen) || (device->stepgen[channel].dirdelay != device->stepgen[channel].curr_dirdelay)) + if((hal_get_ui32(device->stepgen[channel].steplen) != device->stepgen[channel].curr_steplen) || (hal_get_ui32(device->stepgen[channel].dirdelay) != device->stepgen[channel].curr_dirdelay)) { //Init time constants, send them to PCI - temp1= (device->stepgen[channel].steplen <= 1900000) ? (device->stepgen[channel].steplen/30) : 63333; - temp2= (device->stepgen[channel].dirdelay <= 1900000) ? (device->stepgen[channel].dirdelay/30) : 63333; + temp1= (hal_get_ui32(device->stepgen[channel].steplen) <= 1900000) ? (hal_get_ui32(device->stepgen[channel].steplen)/30) : 63333; + temp2= (hal_get_ui32(device->stepgen[channel].dirdelay) <= 1900000) ? (hal_get_ui32(device->stepgen[channel].dirdelay)/30) : 63333; - if((device->stepgen[channel].steplen > 1900000) || (device->stepgen[channel].dirdelay > 1900000)) + if((hal_get_ui32(device->stepgen[channel].steplen) > 1900000) || (hal_get_ui32(device->stepgen[channel].dirdelay) > 1900000)) { rtapi_print_msg(RTAPI_MSG_ERR, "GM: stepgen: 'steplen' and 'dirdelay' must be lower than 1 900 000 ns.\n"); } @@ -1660,30 +1634,30 @@ stepgenCheckParameters(void *arg, long period, unsigned int channel) } //If enable, step_type or polarity bits changed : update fpga status reg - if (*(device->stepgen[channel].enable) == 1) device->stepgen_status |= (0x1 << channel); //Bit 0-5 is the enable bit + if (hal_get_bool(device->stepgen[channel].enable)) device->stepgen_status |= (0x1 << channel); //Bit 0-5 is the enable bit else device->stepgen_status &= ~(0x1 << channel); - if (device->stepgen[channel].step_type == 1) device->stepgen_status |= (0x1 << (channel + 6)); //Bits 6-17 are the step_mode bits + if (hal_get_ui32(device->stepgen[channel].step_type) == 1) device->stepgen_status |= (0x1 << (channel + 6)); //Bits 6-17 are the step_mode bits else device->stepgen_status &= ~(0x1 << (channel + 6)); - if (device->stepgen[channel].step_type == 2) device->stepgen_status |= (0x1 << (channel + 12)); + if (hal_get_ui32(device->stepgen[channel].step_type) == 2) device->stepgen_status |= (0x1 << (channel + 12)); else device->stepgen_status &= ~(0x1 << (channel + 12)); - if (device->stepgen[channel].polarity_A == 1) device->stepgen_status |= (0x1 << (channel + 18)); //18-23. bit is polarity of channel A + if (hal_get_bool(device->stepgen[channel].polarity_A)) device->stepgen_status |= (0x1 << (channel + 18)); //18-23. bit is polarity of channel A else device->stepgen_status &= ~(0x1 << (channel + 18)); - if (device->stepgen[channel].polarity_B == 1) device->stepgen_status |= (0x1 << (channel + 24)); //24-29. bit is polarity of channel B + if (hal_get_bool(device->stepgen[channel].polarity_B)) device->stepgen_status |= (0x1 << (channel + 24)); //24-29. bit is polarity of channel B else device->stepgen_status &= ~(0x1 << (channel + 24)); pCard->StepGen_status = device->stepgen_status; //If max_vel, max_accel or period changed : calc max_dv - if((device->stepgen[channel].maxvel != device->stepgen[channel].curr_maxvel) || (device->stepgen[channel].maxaccel != device->stepgen[channel].curr_maxaccel) || (device->period_ns != period)) + if((hal_get_real(device->stepgen[channel].maxvel) != device->stepgen[channel].curr_maxvel) || (hal_get_real(device->stepgen[channel].maxaccel) != device->stepgen[channel].curr_maxaccel) || (device->period_ns != period)) { - if(device->stepgen[channel].maxaccel <= 1e-20) + if(hal_get_real(device->stepgen[channel].maxaccel) <= 1e-20) { - device->stepgen[channel].maxaccel = device->stepgen[channel].maxvel * device->rec_period_s; - device->stepgen[channel].max_dv = device->stepgen[channel].maxvel; + hal_set_real(device->stepgen[channel].maxaccel, hal_get_real(device->stepgen[channel].maxvel) * device->rec_period_s); + device->stepgen[channel].max_dv = hal_get_real(device->stepgen[channel].maxvel); } else { - device->stepgen[channel].max_dv = device->stepgen[channel].maxaccel * device->period_s; //max velocity change in position_unit/period^2 + device->stepgen[channel].max_dv = hal_get_real(device->stepgen[channel].maxaccel) * device->period_s; //max velocity change in position_unit/period^2 } //vel = freq/pos_scale //pos=counts/pos_scale @@ -1691,12 +1665,12 @@ stepgenCheckParameters(void *arg, long period, unsigned int channel) //Update current values device->period_ns = period; - device->stepgen[channel].curr_position_scale = device->stepgen[channel].position_scale; - device->stepgen[channel].curr_stepspace = device->stepgen[channel].stepspace; - device->stepgen[channel].curr_maxvel = device->stepgen[channel].maxvel; - device->stepgen[channel].curr_maxaccel = device->stepgen[channel].maxaccel; - device->stepgen[channel].curr_steplen = device->stepgen[channel].steplen; - device->stepgen[channel].curr_dirdelay= device->stepgen[channel].dirdelay; + device->stepgen[channel].curr_position_scale = hal_get_real(device->stepgen[channel].position_scale); + device->stepgen[channel].curr_stepspace = hal_get_ui32(device->stepgen[channel].stepspace); + device->stepgen[channel].curr_maxvel = hal_get_real(device->stepgen[channel].maxvel); + device->stepgen[channel].curr_maxaccel = hal_get_real(device->stepgen[channel].maxaccel); + device->stepgen[channel].curr_steplen = hal_get_ui32(device->stepgen[channel].steplen); + device->stepgen[channel].curr_dirdelay= hal_get_ui32(device->stepgen[channel].dirdelay); } @@ -1707,63 +1681,63 @@ stepgenControl(void *arg, long period, unsigned int channel) gm_device_t *device = (gm_device_t *)arg; card *pCard = device->pCard; - hal_s32_t stepgen_fb, stepgen_fb_int, last_count_fb_LS16_bits, last_count_fb_MS16_bits, last_count_fb; - hal_float_t ref_vel = 0, match_acc, match_time, avg_v, est_out, est_cmd, est_err, dp; + rtapi_s32 stepgen_fb, stepgen_fb_int, last_count_fb_LS16_bits, last_count_fb_MS16_bits, last_count_fb; + rtapi_real ref_vel = 0, match_acc, match_time, avg_v, est_out, est_cmd, est_err, dp; //read and count feedbacks stepgen_fb = pCard->StepGen_fb[channel]; //pCard->StepGen_Fb[channel] is 16.16 bit fixed point feedback in [step] unit stepgen_fb -= device->stepgen[channel].stepgen_fb_offset; stepgen_fb_int= stepgen_fb >> 16; //get integer part of step feedback - last_count_fb = *(device->stepgen[channel].count_fb); + last_count_fb = hal_get_si32(device->stepgen[channel].count_fb); last_count_fb_LS16_bits = last_count_fb & 0xFFFF; last_count_fb_MS16_bits = last_count_fb & 0xFFFF0000; //Check for 16 bit overflow of stepgen_fb if(stepgen_fb_int > last_count_fb_LS16_bits + 32768) //16 bit step counter down overflow { - *(device->stepgen[channel].count_fb) = (last_count_fb_MS16_bits + stepgen_fb_int - 65536); + hal_set_si32(device->stepgen[channel].count_fb, (last_count_fb_MS16_bits + stepgen_fb_int - 65536)); } else if (stepgen_fb_int + 32768 < last_count_fb_LS16_bits) //16 bit step counter up overflow { - *(device->stepgen[channel].count_fb) = (last_count_fb_MS16_bits + stepgen_fb_int + 65536); + hal_set_si32(device->stepgen[channel].count_fb, (last_count_fb_MS16_bits + stepgen_fb_int + 65536)); } else //no overflow { - *(device->stepgen[channel].count_fb) = (last_count_fb_MS16_bits + stepgen_fb_int); + hal_set_si32(device->stepgen[channel].count_fb, (last_count_fb_MS16_bits + stepgen_fb_int)); } //save old position and get new one - *(device->stepgen[channel].position_fb) = (*(device->stepgen[channel].count_fb) + ((hal_float_t)(stepgen_fb & 0xFFFF))/65536)/device->stepgen[channel].position_scale; //[pos_unit] + hal_set_real(device->stepgen[channel].position_fb, (hal_get_si32(device->stepgen[channel].count_fb) + ((rtapi_real)(stepgen_fb & 0xFFFF))/65536)/hal_get_real(device->stepgen[channel].position_scale)); //[pos_unit] //velocity control is easy - if(device->stepgen[channel].control_type == 1) + if(hal_get_bool(device->stepgen[channel].control_type)) { - ref_vel = *(device->stepgen[channel].velocity_cmd); + ref_vel = hal_get_real(device->stepgen[channel].velocity_cmd); } //Position control is more difficult /*Position control based on John Kasunich's stepgen hal component.*/ - else if(device->stepgen[channel].control_type == 0) + else if(hal_get_bool(device->stepgen[channel].control_type) == 0) { //Reference velocity: - ref_vel = (*(device->stepgen[channel].position_cmd) - device->stepgen[channel].old_pos_cmd) * device->rec_period_s; + ref_vel = (hal_get_real(device->stepgen[channel].position_cmd) - device->stepgen[channel].old_pos_cmd) * device->rec_period_s; if(ref_vel > device->stepgen[channel].old_vel) { - match_acc = device->stepgen[channel].maxaccel; + match_acc = hal_get_real(device->stepgen[channel].maxaccel); } else { - match_acc = -device->stepgen[channel].maxaccel; + match_acc = -hal_get_real(device->stepgen[channel].maxaccel); } match_time = (ref_vel - device->stepgen[channel].old_vel) / match_acc; avg_v = (ref_vel + device->stepgen[channel].old_vel) * 0.5; - est_out = *(device->stepgen[channel].position_fb) + avg_v * match_time;; - est_cmd = *(device->stepgen[channel].position_cmd) + ref_vel * (match_time - 1.5 * device->period_s); + est_out = hal_get_real(device->stepgen[channel].position_fb) + avg_v * match_time;; + est_cmd = hal_get_real(device->stepgen[channel].position_cmd) + ref_vel * (match_time - 1.5 * device->period_s); est_err = est_out - est_cmd; @@ -1794,8 +1768,8 @@ stepgenControl(void *arg, long period, unsigned int channel) //Check max velocity, max acceleration and output baudrate //Check max velocity - if(ref_vel > device->stepgen[channel].maxvel) ref_vel = device->stepgen[channel].maxvel; - else if(ref_vel < -device->stepgen[channel].maxvel) ref_vel = -device->stepgen[channel].maxvel; + if(ref_vel > hal_get_real(device->stepgen[channel].maxvel)) ref_vel = hal_get_real(device->stepgen[channel].maxvel); + else if(ref_vel < -hal_get_real(device->stepgen[channel].maxvel)) ref_vel = -hal_get_real(device->stepgen[channel].maxvel); //Check max acceleration if((device->stepgen[channel].old_vel-ref_vel) > device->stepgen[channel].max_dv) @@ -1809,7 +1783,7 @@ stepgenControl(void *arg, long period, unsigned int channel) //Save old velocity device->stepgen[channel].old_vel=ref_vel; //Set steprate - pCard->StepGen_steprate[channel] = (hal_s32_t)(ref_vel * device->stepgen[channel].steprate_scale); + pCard->StepGen_steprate[channel] = (rtapi_s32)(ref_vel * device->stepgen[channel].steprate_scale); } @@ -1824,21 +1798,21 @@ RS485(void *arg, long period) card *pCard = device->pCard; unsigned int i, j; - hal_float_t temp; - hal_u32_t temp_u32; + rtapi_real temp; + rtapi_u32 temp_u32; bool data_wr = 0; - static hal_bit_t failed=0; + static rtapi_bool failed=0; //for write function - hal_u32_t RS485DataIn8[32], RS485DataOut32[8]; + rtapi_u32 RS485DataIn8[32], RS485DataOut32[8]; //for read function - hal_u32_t RS485DataIn32[8], RS485DataOut8[32]; + rtapi_u32 RS485DataIn32[8], RS485DataOut8[32]; //Check modules if any of it failed: //READ IDs of correctly connected modules and compare it with saved ID-s. for(i=0; i<8; i++) { - temp_u32=(hal_u32_t)pCard->moduleId[i]; + temp_u32 = pCard->moduleId[i]; if(((temp_u32 & 0xff)^0xaa) == ((temp_u32 & 0xff00)>>8)) { @@ -1850,7 +1824,7 @@ RS485(void *arg, long period) failed=1; rtapi_print_msg(RTAPI_MSG_ERR, "GM: ERROR: RS485 module ID:%2d failed.\n", 2*i); } - *(device->cardMgr.power_fault) = 1; + hal_set_bool(device->cardMgr.power_fault, 1); } } @@ -1864,7 +1838,7 @@ RS485(void *arg, long period) failed=1; rtapi_print_msg(RTAPI_MSG_ERR, "GM: ERROR: RS485 module ID:%2d failed.\n", 2*i+1); } - *(device->cardMgr.power_fault) = 1; + hal_set_bool(device->cardMgr.power_fault, 1); } } } @@ -1876,7 +1850,7 @@ RS485(void *arg, long period) if(i != 0) *(&(pCard->serialModulesDataIn[i-1][7])); else *(&(pCard->serialModulesDataOut[15][7])); //Read bytes to RS485DataIn32 array - for(j=0; j<8; j++) RS485DataIn32[j]= (hal_u32_t)pCard->serialModulesDataIn[i][j]; + for(j=0; j<8; j++) RS485DataIn32[j]= (rtapi_u32)pCard->serialModulesDataIn[i][j]; //Order data to RS485DataOut8 buffer RS485_OrderDataRead(RS485DataIn32, RS485DataOut8, device-> RS485_mgr.BYTES_TO_READ[i]); @@ -1886,72 +1860,71 @@ RS485(void *arg, long period) switch (device-> RS485_mgr.ID[i]) { case RS485MODUL_ID_8INPUT: - *(device->RS485_8input[i].in_0) = ((hal_bit_t)(RS485DataOut8[0] & 0x1) ? 1 : 0); - *(device->RS485_8input[i].inNot_0) = (hal_bit_t)(RS485DataOut8[0] & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_1) = (hal_bit_t)((RS485DataOut8[0] >> 1) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_1) = (hal_bit_t)((RS485DataOut8[0] >> 1) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_2) = (hal_bit_t)((RS485DataOut8[0] >> 2) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_2) = (hal_bit_t)((RS485DataOut8[0] >> 2) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_3) = (hal_bit_t)((RS485DataOut8[0] >> 3) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_3) = (hal_bit_t)((RS485DataOut8[0] >> 3) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_4) = (hal_bit_t)((RS485DataOut8[0] >> 4) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_4) = (hal_bit_t)((RS485DataOut8[0] >> 4) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_5) = (hal_bit_t)((RS485DataOut8[0] >> 5) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_5) = (hal_bit_t)((RS485DataOut8[0] >> 5) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_6) = (hal_bit_t)((RS485DataOut8[0] >> 6) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_6) = (hal_bit_t)((RS485DataOut8[0] >> 6) & 0x1) ? 0 : 1; - *(device->RS485_8input[i].in_7) = (hal_bit_t)((RS485DataOut8[0] >> 7) & 0x1) ? 1 : 0; - *(device->RS485_8input[i].inNot_7) = (hal_bit_t)((RS485DataOut8[0] >> 7) & 0x1) ? 0 : 1; + hal_set_bool(device->RS485_8input[i].in_0, (RS485DataOut8[0] & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_0, (RS485DataOut8[0] & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_1, ((RS485DataOut8[0] >> 1) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_1, ((RS485DataOut8[0] >> 1) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_2, ((RS485DataOut8[0] >> 2) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_2, ((RS485DataOut8[0] >> 2) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_3, ((RS485DataOut8[0] >> 3) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_3, ((RS485DataOut8[0] >> 3) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_4, ((RS485DataOut8[0] >> 4) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_4, ((RS485DataOut8[0] >> 4) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_5, ((RS485DataOut8[0] >> 5) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_5, ((RS485DataOut8[0] >> 5) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_6, ((RS485DataOut8[0] >> 6) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_6, ((RS485DataOut8[0] >> 6) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_8input[i].in_7, ((RS485DataOut8[0] >> 7) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_8input[i].inNot_7, ((RS485DataOut8[0] >> 7) & 0x1) ? 0 : 1); break; case RS485MODUL_ID_DACADC: - *(device->RS485_DacAdc[i].ADC_0) = (((hal_float_t)RS485DataOut8[0])/25.5-5) * device->RS485_DacAdc[i].ADC_0_scale - device->RS485_DacAdc[i].ADC_0_offset; - *(device->RS485_DacAdc[i].ADC_1) = (((hal_float_t)RS485DataOut8[1])/25.5-5) * device->RS485_DacAdc[i].ADC_1_scale - device->RS485_DacAdc[i].ADC_1_offset; - *(device->RS485_DacAdc[i].ADC_2) = (((hal_float_t)RS485DataOut8[2])/25.5-5) * device->RS485_DacAdc[i].ADC_2_scale - device->RS485_DacAdc[i].ADC_2_offset; - *(device->RS485_DacAdc[i].ADC_3) = (((hal_float_t)RS485DataOut8[3])/25.5-5) * device->RS485_DacAdc[i].ADC_3_scale - device->RS485_DacAdc[i].ADC_3_offset; - *(device->RS485_DacAdc[i].ADC_4) = (((hal_float_t)RS485DataOut8[4])/25.5-5) * device->RS485_DacAdc[i].ADC_4_scale - device->RS485_DacAdc[i].ADC_4_offset; - *(device->RS485_DacAdc[i].ADC_5) = (((hal_float_t)RS485DataOut8[5])/25.5-5) * device->RS485_DacAdc[i].ADC_5_scale - device->RS485_DacAdc[i].ADC_5_offset; - *(device->RS485_DacAdc[i].ADC_6) = (((hal_float_t)RS485DataOut8[6])/25.5-5) * device->RS485_DacAdc[i].ADC_6_scale - device->RS485_DacAdc[i].ADC_6_offset; - *(device->RS485_DacAdc[i].ADC_7) = (((hal_float_t)RS485DataOut8[7])/25.5-5) * device->RS485_DacAdc[i].ADC_7_scale - device->RS485_DacAdc[i].ADC_7_offset; - + hal_set_real(device->RS485_DacAdc[i].ADC_0, (((rtapi_real)RS485DataOut8[0])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_0_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_0_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_1, (((rtapi_real)RS485DataOut8[1])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_1_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_1_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_2, (((rtapi_real)RS485DataOut8[2])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_2_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_2_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_3, (((rtapi_real)RS485DataOut8[3])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_3_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_3_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_4, (((rtapi_real)RS485DataOut8[4])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_4_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_4_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_5, (((rtapi_real)RS485DataOut8[5])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_5_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_5_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_6, (((rtapi_real)RS485DataOut8[6])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_6_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_6_offset)); + hal_set_real(device->RS485_DacAdc[i].ADC_7, (((rtapi_real)RS485DataOut8[7])/25.5-5) * hal_get_real(device->RS485_DacAdc[i].ADC_7_scale) - hal_get_real(device->RS485_DacAdc[i].ADC_7_offset)); break; case RS485MODUL_ID_TEACHPAD: - *(device->RS485_TeachPad[i].in_0) = ((hal_bit_t)(RS485DataOut8[0] & 0x1) ? 1 : 0); - *(device->RS485_TeachPad[i].inNot_0) = (hal_bit_t)(RS485DataOut8[0] & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_1) = (hal_bit_t)((RS485DataOut8[0] >> 1) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_1) = (hal_bit_t)((RS485DataOut8[0] >> 1) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_2) = (hal_bit_t)((RS485DataOut8[0] >> 2) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_2) = (hal_bit_t)((RS485DataOut8[0] >> 2) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_3) = (hal_bit_t)((RS485DataOut8[0] >> 3) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_3) = (hal_bit_t)((RS485DataOut8[0] >> 3) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_4) = (hal_bit_t)((RS485DataOut8[0] >> 4) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_4) = (hal_bit_t)((RS485DataOut8[0] >> 4) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_5) = (hal_bit_t)((RS485DataOut8[0] >> 5) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_5) = (hal_bit_t)((RS485DataOut8[0] >> 5) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_6) = (hal_bit_t)((RS485DataOut8[0] >> 6) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_6) = (hal_bit_t)((RS485DataOut8[0] >> 6) & 0x1) ? 0 : 1; - *(device->RS485_TeachPad[i].in_7) = (hal_bit_t)((RS485DataOut8[0] >> 7) & 0x1) ? 1 : 0; - *(device->RS485_TeachPad[i].inNot_7) = (hal_bit_t)((RS485DataOut8[0] >> 7) & 0x1) ? 0 : 1; - - *(device->RS485_TeachPad[i].ADC_0) = (hal_float_t)RS485DataOut8[1]/51.2 * device->RS485_TeachPad[i].ADC_0_scale - device->RS485_TeachPad[i].ADC_0_offset; - *(device->RS485_TeachPad[i].ADC_1) = (hal_float_t)RS485DataOut8[2]/51.2 * device->RS485_TeachPad[i].ADC_1_scale - device->RS485_TeachPad[i].ADC_1_offset; - *(device->RS485_TeachPad[i].ADC_2) = (hal_float_t)RS485DataOut8[3]/51.2 * device->RS485_TeachPad[i].ADC_2_scale - device->RS485_TeachPad[i].ADC_2_offset; - *(device->RS485_TeachPad[i].ADC_3) = (hal_float_t)RS485DataOut8[4]/51.2 * device->RS485_TeachPad[i].ADC_3_scale - device->RS485_TeachPad[i].ADC_3_offset; - *(device->RS485_TeachPad[i].ADC_4) = (hal_float_t)RS485DataOut8[5]/51.2 * device->RS485_TeachPad[i].ADC_4_scale - device->RS485_TeachPad[i].ADC_4_offset; - *(device->RS485_TeachPad[i].ADC_5) = (hal_float_t)RS485DataOut8[6]/51.2 * device->RS485_TeachPad[i].ADC_5_scale - device->RS485_TeachPad[i].ADC_5_offset; - - *(device->RS485_TeachPad[i].enc_rawcounts)= (RS485DataOut8[7] & 0xff) | ((RS485DataOut8[8] & 0xff) << 8) | ((RS485DataOut8[9] & 0xff) << 16) | (RS485DataOut8[10] << 24); - if(*(device->RS485_TeachPad[i].enc_reset)) + hal_set_bool(device->RS485_TeachPad[i].in_0, (RS485DataOut8[0] & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_0, (RS485DataOut8[0] & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_1, ((RS485DataOut8[0] >> 1) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_1, ((RS485DataOut8[0] >> 1) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_2, ((RS485DataOut8[0] >> 2) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_2, ((RS485DataOut8[0] >> 2) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_3, ((RS485DataOut8[0] >> 3) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_3, ((RS485DataOut8[0] >> 3) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_4, ((RS485DataOut8[0] >> 4) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_4, ((RS485DataOut8[0] >> 4) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_5, ((RS485DataOut8[0] >> 5) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_5, ((RS485DataOut8[0] >> 5) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_6, ((RS485DataOut8[0] >> 6) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_6, ((RS485DataOut8[0] >> 6) & 0x1) ? 0 : 1); + hal_set_bool(device->RS485_TeachPad[i].in_7, ((RS485DataOut8[0] >> 7) & 0x1) ? 1 : 0); + hal_set_bool(device->RS485_TeachPad[i].inNot_7, ((RS485DataOut8[0] >> 7) & 0x1) ? 0 : 1); + + hal_set_real(device->RS485_TeachPad[i].ADC_0, (rtapi_real)RS485DataOut8[1]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_0_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_0_offset)); + hal_set_real(device->RS485_TeachPad[i].ADC_1, (rtapi_real)RS485DataOut8[2]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_1_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_1_offset)); + hal_set_real(device->RS485_TeachPad[i].ADC_2, (rtapi_real)RS485DataOut8[3]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_2_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_2_offset)); + hal_set_real(device->RS485_TeachPad[i].ADC_3, (rtapi_real)RS485DataOut8[4]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_3_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_3_offset)); + hal_set_real(device->RS485_TeachPad[i].ADC_4, (rtapi_real)RS485DataOut8[5]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_4_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_4_offset)); + hal_set_real(device->RS485_TeachPad[i].ADC_5, (rtapi_real)RS485DataOut8[6]/51.2 * hal_get_real(device->RS485_TeachPad[i].ADC_5_scale) - hal_get_real(device->RS485_TeachPad[i].ADC_5_offset)); + + hal_set_si32(device->RS485_TeachPad[i].enc_rawcounts, (RS485DataOut8[7] & 0xff) | ((RS485DataOut8[8] & 0xff) << 8) | ((RS485DataOut8[9] & 0xff) << 16) | (RS485DataOut8[10] << 24)); + if(hal_get_bool(device->RS485_TeachPad[i].enc_reset)) { - device->RS485_TeachPad[i].enc_raw_offset = *(device->RS485_TeachPad[i].enc_rawcounts); + device->RS485_TeachPad[i].enc_raw_offset = hal_get_si32(device->RS485_TeachPad[i].enc_rawcounts); } - *(device->RS485_TeachPad[i].enc_counts) = *(device->RS485_TeachPad[i].enc_rawcounts) - device->RS485_TeachPad[i].enc_raw_offset; + hal_set_si32(device->RS485_TeachPad[i].enc_counts, hal_get_si32(device->RS485_TeachPad[i].enc_rawcounts) - device->RS485_TeachPad[i].enc_raw_offset); - if((device->RS485_TeachPad[i].enc_position_scale < 0.000001) && (device->RS485_TeachPad[i].enc_position_scale > -0.000001)) device->RS485_TeachPad[i].enc_position_scale=1; //don't divide by 0 + if((hal_get_real(device->RS485_TeachPad[i].enc_position_scale) < 0.000001) && (hal_get_real(device->RS485_TeachPad[i].enc_position_scale) > -0.000001)) hal_set_real(device->RS485_TeachPad[i].enc_position_scale, 1); //don't divide by 0 - *(device->RS485_TeachPad[i].enc_position) = *(device->RS485_TeachPad[i].enc_counts) / device->RS485_TeachPad[i].enc_position_scale; + hal_set_real(device->RS485_TeachPad[i].enc_position, hal_get_si32(device->RS485_TeachPad[i].enc_counts) / hal_get_real(device->RS485_TeachPad[i].enc_position_scale)); default: break; @@ -1967,24 +1940,24 @@ RS485(void *arg, long period) switch (device-> RS485_mgr.ID[i]) { case RS485MODUL_ID_8OUTPUT: - RS485DataIn8[0]=((*(device->RS485_8output[i].out_7) ^ (device->RS485_8output[i].invertOut_7)) << 7) | - ((*(device->RS485_8output[i].out_6) ^ (device->RS485_8output[i].invertOut_6)) << 6) | - ((*(device->RS485_8output[i].out_5) ^ (device->RS485_8output[i].invertOut_5)) << 5) | - ((*(device->RS485_8output[i].out_4) ^ (device->RS485_8output[i].invertOut_4)) << 4) | - ((*(device->RS485_8output[i].out_3) ^ (device->RS485_8output[i].invertOut_3)) << 3) | - ((*(device->RS485_8output[i].out_2) ^ (device->RS485_8output[i].invertOut_2)) << 2) | - ((*(device->RS485_8output[i].out_1) ^ (device->RS485_8output[i].invertOut_1)) << 1) | - ((*(device->RS485_8output[i].out_0) ^ (device->RS485_8output[i].invertOut_0)) << 0); + RS485DataIn8[0]=((hal_get_bool(device->RS485_8output[i].out_7) ^ hal_get_bool(device->RS485_8output[i].invertOut_7)) << 7) | + ((hal_get_bool(device->RS485_8output[i].out_6) ^ hal_get_bool(device->RS485_8output[i].invertOut_6)) << 6) | + ((hal_get_bool(device->RS485_8output[i].out_5) ^ hal_get_bool(device->RS485_8output[i].invertOut_5)) << 5) | + ((hal_get_bool(device->RS485_8output[i].out_4) ^ hal_get_bool(device->RS485_8output[i].invertOut_4)) << 4) | + ((hal_get_bool(device->RS485_8output[i].out_3) ^ hal_get_bool(device->RS485_8output[i].invertOut_3)) << 3) | + ((hal_get_bool(device->RS485_8output[i].out_2) ^ hal_get_bool(device->RS485_8output[i].invertOut_2)) << 2) | + ((hal_get_bool(device->RS485_8output[i].out_1) ^ hal_get_bool(device->RS485_8output[i].invertOut_1)) << 1) | + ((hal_get_bool(device->RS485_8output[i].out_0) ^ hal_get_bool(device->RS485_8output[i].invertOut_0)) << 0); break; case RS485MODUL_ID_DACADC: //DAC 0 - if(*(device->RS485_DacAdc[i].dac_0_enable)) + if(hal_get_bool(device->RS485_DacAdc[i].dac_0_enable)) { - temp = *(device->RS485_DacAdc[i].DAC_0)+ device->RS485_DacAdc[i].DAC_0_offset; + temp = hal_get_real(device->RS485_DacAdc[i].DAC_0)+ hal_get_real(device->RS485_DacAdc[i].DAC_0_offset); - if(temp > device->RS485_DacAdc[i].DAC_0_max) { temp = device->RS485_DacAdc[i].DAC_0_max; } - else if(temp < device->RS485_DacAdc[i].DAC_0_min) { temp = device->RS485_DacAdc[i].DAC_0_min; } + if(temp > hal_get_real(device->RS485_DacAdc[i].DAC_0_max)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_0_max); } + else if(temp < hal_get_real(device->RS485_DacAdc[i].DAC_0_min)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_0_min); } temp = (temp + 10)*12.8 + 0.5; } @@ -1992,14 +1965,14 @@ RS485(void *arg, long period) if(temp>255) temp=255; else if(temp <0) temp=0; - RS485DataIn8[0]= (hal_u32_t)temp; + RS485DataIn8[0]= (rtapi_u32)temp; //DAC 1 - if(*(device->RS485_DacAdc[i].dac_1_enable)) + if(hal_get_bool(device->RS485_DacAdc[i].dac_1_enable)) { - temp = *(device->RS485_DacAdc[i].DAC_1)+ device->RS485_DacAdc[i].DAC_1_offset; + temp = hal_get_real(device->RS485_DacAdc[i].DAC_1)+ hal_get_real(device->RS485_DacAdc[i].DAC_1_offset); - if(temp > device->RS485_DacAdc[i].DAC_1_max) { temp = device->RS485_DacAdc[i].DAC_1_max; } - else if(temp < device->RS485_DacAdc[i].DAC_1_min) { temp = device->RS485_DacAdc[i].DAC_1_min; } + if(temp > hal_get_real(device->RS485_DacAdc[i].DAC_1_max)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_1_max); } + else if(temp < hal_get_real(device->RS485_DacAdc[i].DAC_1_min)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_1_min); } temp = (temp + 10)*12.8 + 0.5; } @@ -2007,15 +1980,15 @@ RS485(void *arg, long period) if(temp>255) temp=255; else if(temp <0) temp=0; - RS485DataIn8[1]= (hal_u32_t)temp; + RS485DataIn8[1]= (rtapi_u32)temp; //DAC 2 - if(*(device->RS485_DacAdc[i].dac_2_enable)) + if(hal_get_bool(device->RS485_DacAdc[i].dac_2_enable)) { - temp = *(device->RS485_DacAdc[i].DAC_2)+ device->RS485_DacAdc[i].DAC_2_offset; + temp = hal_get_real(device->RS485_DacAdc[i].DAC_2)+ hal_get_real(device->RS485_DacAdc[i].DAC_2_offset); - if(temp > device->RS485_DacAdc[i].DAC_2_max) { temp = device->RS485_DacAdc[i].DAC_2_max; } - else if(temp < device->RS485_DacAdc[i].DAC_2_min) { temp = device->RS485_DacAdc[i].DAC_2_min; } + if(temp > hal_get_real(device->RS485_DacAdc[i].DAC_2_max)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_2_max); } + else if(temp < hal_get_real(device->RS485_DacAdc[i].DAC_2_min)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_2_min); } temp = (temp + 10)*12.8 + 0.5; } @@ -2023,15 +1996,15 @@ RS485(void *arg, long period) if(temp>255) temp=255; else if(temp <0) temp=0; - RS485DataIn8[2]= (hal_u32_t)temp; + RS485DataIn8[2]= (rtapi_u32)temp; //DAC 3 - if(*(device->RS485_DacAdc[i].dac_3_enable)) + if(hal_get_bool(device->RS485_DacAdc[i].dac_3_enable)) { - temp = *(device->RS485_DacAdc[i].DAC_3)+ device->RS485_DacAdc[i].DAC_3_offset; + temp = hal_get_real(device->RS485_DacAdc[i].DAC_3)+ hal_get_real(device->RS485_DacAdc[i].DAC_3_offset); - if(temp > device->RS485_DacAdc[i].DAC_3_max) { temp = device->RS485_DacAdc[i].DAC_3_max; } - else if(temp < device->RS485_DacAdc[i].DAC_3_min) { temp = device->RS485_DacAdc[i].DAC_3_min; } + if(temp > hal_get_real(device->RS485_DacAdc[i].DAC_3_max)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_3_max); } + else if(temp < hal_get_real(device->RS485_DacAdc[i].DAC_3_min)) { temp = hal_get_real(device->RS485_DacAdc[i].DAC_3_min); } temp = (temp + 10)*12.8 + 0.5; } @@ -2039,7 +2012,7 @@ RS485(void *arg, long period) if(temp>255) temp=255; else if(temp <0) temp=0; - RS485DataIn8[3]= (hal_u32_t)temp; + RS485DataIn8[3]= (rtapi_u32)temp; break; @@ -2064,7 +2037,7 @@ RS485(void *arg, long period) static void -RS485_OrderDataRead(hal_u32_t* dataIn32, hal_u32_t* dataOut8, hal_u32_t length) +RS485_OrderDataRead(rtapi_u32* dataIn32, rtapi_u32* dataOut8, rtapi_u32 length) { int i, j; //Order data (received to dataIn in reverse order and shifted) to dataOut[0]-dataOut[length-1] @@ -2077,7 +2050,7 @@ RS485_OrderDataRead(hal_u32_t* dataIn32, hal_u32_t* dataOut8, hal_u32_t length) } static void -RS485_OrderDataWrite(hal_u32_t* dataIn8, hal_u32_t* dataOut32, hal_u32_t length) +RS485_OrderDataWrite(rtapi_u32* dataIn8, rtapi_u32* dataOut32, rtapi_u32 length) { unsigned i, j; /* Byte order: @@ -2100,7 +2073,7 @@ RS485_OrderDataWrite(hal_u32_t* dataIn8, hal_u32_t* dataOut32, hal_u32_t length) } static unsigned int -RS485_CheckChecksum(hal_u32_t* data, hal_u32_t length) +RS485_CheckChecksum(rtapi_u32* data, rtapi_u32 length) { unsigned int i=0, tempChecksum=0; @@ -2116,7 +2089,7 @@ RS485_CheckChecksum(hal_u32_t* data, hal_u32_t length) } static unsigned int -RS485_CalcChecksum(hal_u32_t* data, hal_u32_t length) +RS485_CalcChecksum(rtapi_u32* data, rtapi_u32 length) { unsigned int i, tempChecksum=0; diff --git a/src/hal/drivers/hal_gpio.c b/src/hal/drivers/hal_gpio.c index cf01c836284..bcac7c27c02 100644 --- a/src/hal/drivers/hal_gpio.c +++ b/src/hal/drivers/hal_gpio.c @@ -81,8 +81,8 @@ RTAPI_MP_ARRAY_STRING(pullup, MAX_CHAN, "set BIAS_PULL_UP flag"); */ typedef struct{ - hal_bit_t *value; - hal_bit_t *value_not; + hal_bool_t value; + hal_bool_t value_not; } hal_gpio_hal_t; /* flags are defined such: @@ -115,7 +115,7 @@ typedef struct { typedef struct { // Bulk line access has to all be to the same "chip" so we have an // array of chips with their bulk line collections. - hal_u32_t *reset_ns; + hal_uint_t *reset_ns; int num_in_chips; int num_out_chips; hal_gpio_bulk_t *in_chips; @@ -400,8 +400,8 @@ rtapi_print_msg(RTAPI_MSG_INFO, "Libgpiod is %i\n", LIBGPIOD_VER); gpio->in_chips[c].hal = hal_malloc(gpio->in_chips[c].num_lines * sizeof(hal_gpio_hal_t)); for (i = 0; i < gpio->in_chips[c].num_lines; i++){ line_name = get_line_name(&gpio->in_chips[c], i); - retval += hal_pin_bit_newf(HAL_OUT, &(gpio->in_chips[c].hal[i].value), comp_id, "hal_gpio.%s-in", line_name); - retval += hal_pin_bit_newf(HAL_OUT, &(gpio->in_chips[c].hal[i].value_not), comp_id, "hal_gpio.%s-in-not", line_name); + retval += hal_pin_new_bool(comp_id, HAL_OUT, &(gpio->in_chips[c].hal[i].value), 0, "hal_gpio.%s-in", line_name); + retval += hal_pin_new_bool(comp_id, HAL_OUT, &(gpio->in_chips[c].hal[i].value_not), 1, "hal_gpio.%s-in-not", line_name); } if (retval < 0){ rtapi_print_msg(RTAPI_MSG_ERR, "hal_gpio: Failed to allocate GPIO input HAL pins\n"); @@ -437,7 +437,7 @@ rtapi_print_msg(RTAPI_MSG_INFO, "Libgpiod is %i\n", LIBGPIOD_VER); gpio->out_chips[c].hal = hal_malloc(gpio->out_chips[c].num_lines * sizeof(hal_gpio_hal_t)); for (i = 0; i < gpio->out_chips[c].num_lines; i++){ line_name = get_line_name(&gpio->out_chips[c], i); - retval += hal_pin_bit_newf(HAL_IN, &(gpio->out_chips[c].hal[i].value), comp_id, "hal_gpio.%s-out", line_name); + retval += hal_pin_new_bool(comp_id, HAL_IN, &(gpio->out_chips[c].hal[i].value), 0, "hal_gpio.%s-out", line_name); } if (retval < 0){ rtapi_print_msg(RTAPI_MSG_ERR, "hal_gpio: Failed to allocate GPIO output HAL pins\n"); @@ -451,9 +451,9 @@ rtapi_print_msg(RTAPI_MSG_INFO, "Libgpiod is %i\n", LIBGPIOD_VER); retval += hal_export_funct(hal_name, hal_gpio_write, gpio, 0, 0, comp_id); if (reset_active){ - gpio->reset_ns = hal_malloc(sizeof(hal_u32_t)); + gpio->reset_ns = hal_malloc(sizeof(*gpio->reset_ns)); rtapi_snprintf(hal_name, HAL_NAME_LEN, "hal_gpio.reset"); - retval += hal_param_u32_newf(HAL_RW, gpio->reset_ns, comp_id, "hal_gpio.reset_ns"); + retval += hal_param_new_ui32(comp_id, HAL_RW, gpio->reset_ns, 0, "hal_gpio.reset_ns"); retval += hal_export_funct(hal_name, hal_gpio_reset, gpio, 0, 0, comp_id); } if (retval < 0){ @@ -484,8 +484,8 @@ static void hal_gpio_read(void *arg, __attribute__((unused)) long period) gpiod_line_get_value_bulk(gpio->in_chips[c].lines, gpio->in_chips[c].vals); #endif for (i = 0; i < gpio->in_chips[c].num_lines; i++){ - *(gpio->in_chips[c].hal[i].value) = gpio->in_chips[c].vals[i]; - *(gpio->in_chips[c].hal[i].value_not) = ! gpio->in_chips[c].vals[i]; + hal_set_bool(gpio->in_chips[c].hal[i].value, gpio->in_chips[c].vals[i]); + hal_set_bool(gpio->in_chips[c].hal[i].value_not, ! gpio->in_chips[c].vals[i]); } } } @@ -497,9 +497,9 @@ static void hal_gpio_write(void *arg, __attribute__((unused)) long period) for (c = 0; c < gpio->num_out_chips; c++){ for (i = 0; i < gpio->out_chips[c].num_lines; i++){ if (gpio->out_chips[c].flags[i] & 0x20){ - gpio->out_chips[c].vals[i] = ! *(gpio->out_chips[c].hal[i].value); + gpio->out_chips[c].vals[i] = ! hal_get_bool(gpio->out_chips[c].hal[i].value); } else { - gpio->out_chips[c].vals[i] = *(gpio->out_chips[c].hal[i].value); + gpio->out_chips[c].vals[i] = hal_get_bool(gpio->out_chips[c].hal[i].value); } } #if LIBGPIOD_VER >200 @@ -525,8 +525,8 @@ static void hal_gpio_reset(void *arg, long period) gpio->out_chips[c].vals[i] = 0; } } - if (*gpio->reset_ns > period/4) *gpio->reset_ns = period/4; - deadline = last_reset + *gpio->reset_ns; + if (hal_get_ui32(*gpio->reset_ns) > period/4) hal_set_ui32(*gpio->reset_ns, period/4); + deadline = last_reset + hal_get_ui32(*gpio->reset_ns); while(rtapi_get_time() < deadline) {} // busy-wait! #if LIBGPIOD_VER > 200 gpiod_line_request_set_values(gpio->out_chips[c].lines, gpio->out_chips[c].vals); diff --git a/src/hal/drivers/hal_motenc.c b/src/hal/drivers/hal_motenc.c index b8e4a97d9c6..01471f7c679 100644 --- a/src/hal/drivers/hal_motenc.c +++ b/src/hal/drivers/hal_motenc.c @@ -146,17 +146,17 @@ MODULE_LICENSE("GPL"); typedef struct { // Pins. - hal_s32_t *pCount; // Captured binary count value. - hal_float_t *pPosition; // Scaled position (floating point). - hal_bit_t *pIndex; // Current state of index. - hal_bit_t *pIndexEnable; // Setting this pin causes the count + hal_sint_t pCount; // Captured binary count value. + hal_real_t pPosition; // Scaled position (floating point). + hal_bool_t pIndex; // Current state of index. + hal_bool_t pIndexEnable; // Setting this pin causes the count // to be cleared on the next index pulse. // Use this feature at your own risk as the PID loop // may get upset. This pin is self clearing. - hal_bit_t *pReset; // Setting this pin causes Count to be reset. + hal_bool_t pReset; // Setting this pin causes Count to be reset. // Parameters. - hal_float_t scale; // Scaling factor for position. + hal_real_t scale; // Scaling factor for position. // Private data. double oldScale; // Stored scale value. @@ -165,44 +165,44 @@ typedef struct { typedef struct { // Pins. - hal_float_t *pValue; // Desired value. + hal_real_t pValue; // Desired value. // Parameters. - hal_float_t offset; - hal_float_t gain; + hal_real_t offset; + hal_real_t gain; } DacPinsParams; typedef struct { // Pins. - hal_float_t *pValue; // Converted value. + hal_real_t pValue; // Converted value. // Parameters. - hal_float_t offset; - hal_float_t gain; + hal_real_t offset; + hal_real_t gain; } AdcPinsParams; typedef struct { // Pins. - hal_bit_t *pValue; - hal_bit_t *pValueNot; + hal_bool_t pValue; + hal_bool_t pValueNot; } DigitalInPinsParams; typedef struct { // Pins. - hal_bit_t *pValue; + hal_bool_t pValue; // Parameters. - hal_bit_t invert; + hal_bool_t invert; } DigitalOutPinsParams; typedef struct { // Pins. - hal_bit_t *pEstopIn; - hal_bit_t *pEstopInNot; - hal_bit_t *pWatchdogReset;// This pin is self clearing. + hal_bool_t pEstopIn; + hal_bool_t pEstopInNot; + hal_bool_t pWatchdogReset;// This pin is self clearing. // Parameters. - hal_u32_t watchdogControl; + hal_uint_t watchdogControl; } MiscPinsParams; typedef struct { @@ -213,7 +213,7 @@ typedef struct { int boardID; int numFpga; int adcState; - hal_u32_t watchdogControl;// Shadow HW register. + rtapi_u32 watchdogControl;// Shadow HW register. // Exported to HAL. EncoderPinsParams encoder[MOTENC_NUM_ENCODER_CHANNELS]; @@ -490,40 +490,34 @@ Device_ExportEncoderPinsParametersFunctions(Device *this, int componentId, int b halError = 0; for(channel = 0; channel < this->numFpga * MOTENC_FPGA_NUM_ENCODER_CHANNELS; channel++){ // Pins. - if((halError = hal_pin_s32_newf(HAL_OUT, &(this->encoder[channel].pCount), - componentId, "motenc.%d.enc-%02d-count", boardId, channel)) != 0) + if((halError = hal_pin_new_si32(componentId, HAL_OUT, &(this->encoder[channel].pCount), + 0, "motenc.%d.enc-%02d-count", boardId, channel)) != 0) break; - if((halError = hal_pin_float_newf(HAL_OUT, &(this->encoder[channel].pPosition), - componentId, "motenc.%d.enc-%02d-position", boardId, channel)) != 0) + if((halError = hal_pin_new_real(componentId, HAL_OUT, &(this->encoder[channel].pPosition), + 0.0, "motenc.%d.enc-%02d-position", boardId, channel)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_OUT, &(this->encoder[channel].pIndex), - componentId, "motenc.%d.enc-%02d-index", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_OUT, &(this->encoder[channel].pIndex), + 0, "motenc.%d.enc-%02d-index", boardId, channel)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_IO, &(this->encoder[channel].pIndexEnable), - componentId, "motenc.%d.enc-%02d-index-enable", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_IO, &(this->encoder[channel].pIndexEnable), + 0, "motenc.%d.enc-%02d-index-enable", boardId, channel)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_IN, &(this->encoder[channel].pReset), - componentId, "motenc.%d.enc-%02d-reset", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_IN, &(this->encoder[channel].pReset), + 0, "motenc.%d.enc-%02d-reset", boardId, channel)) != 0) break; // Parameters. - if((halError = hal_param_float_newf(HAL_RW, &(this->encoder[channel].scale), - componentId, "motenc.%d.enc-%02d-scale", boardId, channel)) != 0) + if((halError = hal_param_new_real(componentId, HAL_RW, &(this->encoder[channel].scale), + 1.0, "motenc.%d.enc-%02d-scale", boardId, channel)) != 0) break; // Init encoder. - *(this->encoder[channel].pCount) = 0; - *(this->encoder[channel].pPosition) = 0.0; - *(this->encoder[channel].pIndex) = 0; - *(this->encoder[channel].pIndexEnable) = 0; - *(this->encoder[channel].pReset) = 0; - this->encoder[channel].scale = 1.0; this->encoder[channel].oldScale = 1.0; - this->encoder[channel].scaleRecip = 1.0 / this->encoder[channel].scale; + this->encoder[channel].scaleRecip = 1.0 / hal_get_real(this->encoder[channel].scale); } // Export functions. @@ -549,23 +543,18 @@ Device_ExportDacPinsParametersFunctions(Device *this, int componentId, int board halError = 0; for(channel = 0; channel < MOTENC_NUM_DAC_CHANNELS; channel++){ // Pins. - if((halError = hal_pin_float_newf(HAL_IN, &(this->dac[channel].pValue), - componentId, "motenc.%d.dac-%02d-value", boardId, channel)) != 0) + if((halError = hal_pin_new_real(componentId, HAL_IN, &(this->dac[channel].pValue), + 0.0, "motenc.%d.dac-%02d-value", boardId, channel)) != 0) break; // Parameters. - if((halError = hal_param_float_newf(HAL_RW, &(this->dac[channel].offset), - componentId, "motenc.%d.dac-%02d-offset", boardId, channel)) != 0) + if((halError = hal_param_new_real(componentId, HAL_RW, &(this->dac[channel].offset), + 0.0, "motenc.%d.dac-%02d-offset", boardId, channel)) != 0) break; - if((halError = hal_param_float_newf(HAL_RW, &(this->dac[channel].gain), - componentId, "motenc.%d.dac-%02d-gain", boardId, channel)) != 0) + if((halError = hal_param_new_real(componentId, HAL_RW, &(this->dac[channel].gain), + 1.0, "motenc.%d.dac-%02d-gain", boardId, channel)) != 0) break; - - // Init DAC. - *(this->dac[channel].pValue) = 0.0; - this->dac[channel].offset = 0.0; - this->dac[channel].gain = 1.0; } // Export functions. @@ -591,23 +580,18 @@ Device_ExportAdcPinsParametersFunctions(Device *this, int componentId, int board halError = 0; for(channel = 0; channel < MOTENC_NUM_ADC_CHANNELS; channel++){ // Pins. - if((halError = hal_pin_float_newf(HAL_OUT, &(this->adc[channel].pValue), - componentId, "motenc.%d.adc-%02d-value", boardId, channel)) != 0) + if((halError = hal_pin_new_real(componentId, HAL_OUT, &(this->adc[channel].pValue), + 0.0, "motenc.%d.adc-%02d-value", boardId, channel)) != 0) break; // Parameters. - if((halError = hal_param_float_newf(HAL_RW, &(this->adc[channel].offset), - componentId, "motenc.%d.adc-%02d-offset", boardId, channel)) != 0) + if((halError = hal_param_new_real(componentId, HAL_RW, &(this->adc[channel].offset), + 0.0, "motenc.%d.adc-%02d-offset", boardId, channel)) != 0) break; - if((halError = hal_param_float_newf(HAL_RW, &(this->adc[channel].gain), - componentId, "motenc.%d.adc-%02d-gain", boardId, channel)) != 0) + if((halError = hal_param_new_real(componentId, HAL_RW, &(this->adc[channel].gain), + 1.0, "motenc.%d.adc-%02d-gain", boardId, channel)) != 0) break; - - // Init ADC. - *(this->adc[channel].pValue) = 0.0; - this->adc[channel].offset = 0.0; - this->adc[channel].gain = 1.0; } // Export functions. @@ -633,17 +617,13 @@ Device_ExportDigitalInPinsParametersFunctions(Device *this, int componentId, int halError = 0; for(channel = 0; channel < (this->numFpga * MOTENC_FPGA_NUM_DIGITAL_INPUTS - 4); channel++){ // Pins. - if((halError = hal_pin_bit_newf(HAL_OUT, &(this->in[channel].pValue), - componentId, "motenc.%d.in-%02d", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_OUT, &(this->in[channel].pValue), + 0, "motenc.%d.in-%02d", boardId, channel)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_OUT, &(this->in[channel].pValueNot), - componentId, "motenc.%d.in-%02d-not", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_OUT, &(this->in[channel].pValueNot), + 1, "motenc.%d.in-%02d-not", boardId, channel)) != 0) break; - - // Init pin. - *(this->in[channel].pValue) = 0; - *(this->in[channel].pValueNot) = 1; } // Export functions. @@ -669,18 +649,14 @@ Device_ExportDigitalOutPinsParametersFunctions(Device *this, int componentId, in halError = 0; for(channel = 0; channel < this->numFpga * MOTENC_FPGA_NUM_DIGITAL_OUTPUTS; channel++){ // Pins. - if((halError = hal_pin_bit_newf(HAL_IN, &(this->out[channel].pValue), - componentId, "motenc.%d.out-%02d", boardId, channel)) != 0) + if((halError = hal_pin_new_bool(componentId, HAL_IN, &(this->out[channel].pValue), + 0, "motenc.%d.out-%02d", boardId, channel)) != 0) break; // Parameters. - if((halError = hal_param_bit_newf(HAL_RW, &(this->out[channel].invert), - componentId, "motenc.%d.out-%02d-invert", boardId, channel)) != 0) + if((halError = hal_param_new_bool(componentId, HAL_RW, &(this->out[channel].invert), + 0, "motenc.%d.out-%02d-invert", boardId, channel)) != 0) break; - - // Init pin. - *(this->out[channel].pValue) = 0; - this->out[channel].invert = 0; } // Export functions. @@ -703,33 +679,25 @@ Device_ExportMiscPinsParametersFunctions(Device *this, int componentId, int boar int halError; // Export Pins. - halError = hal_pin_bit_newf(HAL_OUT, &(this->misc.pEstopIn), componentId, + halError = hal_pin_new_bool(componentId, HAL_OUT, &(this->misc.pEstopIn), 0, "motenc.%d.estop-in", boardId); if(!halError){ - halError = hal_pin_bit_newf(HAL_OUT, &(this->misc.pEstopInNot), componentId, + halError = hal_pin_new_bool(componentId, HAL_OUT, &(this->misc.pEstopInNot), 1, "motenc.%d.estop-in-not", boardId); } if(!halError){ - halError = hal_pin_bit_newf(HAL_IO, &(this->misc.pWatchdogReset), componentId, + halError = hal_pin_new_bool(componentId, HAL_IO, &(this->misc.pWatchdogReset), 0, "motenc.%d.watchdog-reset", boardId); } // Export Parameters. if(!halError){ - halError = hal_param_u32_newf(HAL_RW, &(this->misc.watchdogControl), componentId, + halError = hal_param_new_ui32(componentId, HAL_RW, &(this->misc.watchdogControl), this->watchdogControl, "motenc.%d.watchdog-control", boardId); } - // Init pins. - if(!halError){ - *(this->misc.pEstopIn) = 0; - *(this->misc.pEstopInNot) = 1; - *(this->misc.pWatchdogReset) = 0; - this->misc.watchdogControl = this->watchdogControl; - } - // Export functions. if(!halError){ halError = hal_export_functf(Device_MiscUpdate, this, 0, 0, componentId, "motenc.%d.misc-update", boardId); @@ -755,7 +723,7 @@ Device_EncoderRead(void *arg, long period) MotencRegMap *pCard = this->pCard; EncoderPinsParams *pEncoder; int i, j; - hal_u32_t status; + rtapi_u32 status; pEncoder = &this->encoder[0]; @@ -769,22 +737,22 @@ Device_EncoderRead(void *arg, long period) for(j = 0; j < MOTENC_FPGA_NUM_ENCODER_CHANNELS; j++, pEncoder++){ // Check reset pin. - if(*(pEncoder->pReset)){ + if(hal_get_bool(pEncoder->pReset)){ // Reset encoder. pCard->fpga[i].statusControl = 1 << (MOTENC_CONTROL_ENCODER_RESET_SHFT + j); } // check state of hardware index pin - *(pEncoder->pIndex) = (status >> (MOTENC_STATUS_INDEX_SHFT + j)) & 1; + hal_set_bool(pEncoder->pIndex, (status >> (MOTENC_STATUS_INDEX_SHFT + j)) & 1); // check for index pulse detected if((status >> (MOTENC_STATUS_INDEX_LATCH_SHFT + j)) & 1){ // cancel index-enable - *(pEncoder->pIndexEnable) = 0; + hal_set_bool(pEncoder->pIndexEnable, 0); } // Check for index enable request from HAL - if(*(pEncoder->pIndexEnable)){ + if(hal_get_bool(pEncoder->pIndexEnable)){ // tell hardware to latch on index pCard->fpga[i].encoderCount[j] = 1; } else { @@ -793,25 +761,25 @@ Device_EncoderRead(void *arg, long period) } // Read encoder counts. - *(pEncoder->pCount) = pCard->fpga[i].encoderCount[j]; + hal_set_si32(pEncoder->pCount, pCard->fpga[i].encoderCount[j]); // Check for change in scale value. - if ( pEncoder->scale != pEncoder->oldScale ) { + if ( hal_get_real(pEncoder->scale) != pEncoder->oldScale ) { // Get ready to detect future scale changes. - pEncoder->oldScale = pEncoder->scale; + pEncoder->oldScale = hal_get_real(pEncoder->scale); // Validate the new scale value. - if ((pEncoder->scale < 1e-20) && (pEncoder->scale > -1e-20)) { + if ((hal_get_real(pEncoder->scale) < 1e-20) && (hal_get_real(pEncoder->scale) > -1e-20)) { // Value too small, divide by zero is a bad thing. - pEncoder->scale = 1.0; + hal_set_real(pEncoder->scale, 1.0); } // We will need the reciprocal. - pEncoder->scaleRecip = 1.0 / pEncoder->scale; + pEncoder->scaleRecip = 1.0 / hal_get_real(pEncoder->scale); } // Scale count to make floating point position. - *(pEncoder->pPosition) = *(pEncoder->pCount) * pEncoder->scaleRecip; + hal_set_real(pEncoder->pPosition, hal_get_si32(pEncoder->pCount) * pEncoder->scaleRecip); } } } @@ -824,8 +792,8 @@ Device_DacWrite(void *arg, long period) MotencRegMap *pCard = this->pCard; DacPinsParams *pDac; int i; - hal_float_t volts; - hal_u32_t dacCount; + rtapi_real volts; + rtapi_u32 dacCount; pDac = &this->dac[0]; @@ -833,7 +801,7 @@ Device_DacWrite(void *arg, long period) for(i = 0; i < MOTENC_NUM_DAC_CHANNELS; i++, pDac++){ // Calculate hardware register value. - volts = (*(pDac->pValue) - pDac->offset) * pDac->gain; + volts = (hal_get_real(pDac->pValue) - hal_get_real(pDac->offset)) * hal_get_real(pDac->gain); // Truncate volts to DAC limits. if(volts > MOTENC_DAC_VOLTS_MAX){ @@ -843,7 +811,7 @@ Device_DacWrite(void *arg, long period) } // Transform volts to counts. - dacCount = (hal_u32_t)(volts * MOTENC_DAC_SCALE_MULTIPLY / + dacCount = (rtapi_u32)(volts * MOTENC_DAC_SCALE_MULTIPLY / MOTENC_DAC_SCALE_DIVIDE + MOTENC_DAC_COUNT_ZERO); // Write DAC. @@ -900,8 +868,8 @@ Device_AdcRead4(Device *this, int startChannel) MotencRegMap *pCard = this->pCard; AdcPinsParams *pAdc; int i; - hal_s32_t adcCount; - hal_float_t volts; + rtapi_s32 adcCount; + rtapi_real volts; if(pCard->fpga[0].statusControl & MOTENC_STATUS_ADC_DONE) return(0); @@ -921,10 +889,10 @@ Device_AdcRead4(Device *this, int startChannel) volts = adcCount * MOTENC_ADC_SCALE_MULTIPLY / MOTENC_ADC_SCALE_DIVIDE; // Scale and offset volts. - volts = volts * pAdc->gain - pAdc->offset; + volts = volts * hal_get_real(pAdc->gain) - hal_get_real(pAdc->offset); // Update pin. - *(pAdc->pValue) = volts; + hal_set_real(pAdc->pValue, volts); } return(1); @@ -938,7 +906,7 @@ Device_DigitalInRead(void *arg, long period) MotencRegMap *pCard = this->pCard; DigitalInPinsParams *pDigitalIn; int i, j, n; - hal_u32_t pins; + rtapi_u32 pins; pDigitalIn = &this->in[0]; @@ -952,8 +920,8 @@ Device_DigitalInRead(void *arg, long period) for(j = 0; j < 16; j++, pDigitalIn++){ // Update pins. - *(pDigitalIn->pValue) = pins & 1; - *(pDigitalIn->pValueNot) = !*(pDigitalIn->pValue); + rtapi_bool b = hal_set_bool(pDigitalIn->pValue, pins & 1); + hal_set_bool(pDigitalIn->pValueNot, !b); pins >>= 1; } @@ -969,8 +937,8 @@ Device_DigitalInRead(void *arg, long period) for(j = 0; j < n; j++, pDigitalIn++){ // Update pins. - *(pDigitalIn->pValue) = pins & 1; - *(pDigitalIn->pValueNot) = !*(pDigitalIn->pValue); + rtapi_bool b = hal_set_bool(pDigitalIn->pValue, pins & 1); + hal_set_bool(pDigitalIn->pValueNot, !b); pins >>= 1; } @@ -985,7 +953,7 @@ Device_DigitalOutWrite(void *arg, long period) MotencRegMap *pCard = this->pCard; DigitalOutPinsParams *pDigitalOut; int i, j; - hal_u32_t pins, mask; + rtapi_u32 pins, mask; pDigitalOut = &this->out[0]; @@ -999,7 +967,7 @@ Device_DigitalOutWrite(void *arg, long period) for(j = 0; j < MOTENC_FPGA_NUM_DIGITAL_OUTPUTS; j++, pDigitalOut++){ // Build hardware register value. - if(*(pDigitalOut->pValue) != pDigitalOut->invert){ + if(hal_get_bool(pDigitalOut->pValue) != hal_get_bool(pDigitalOut->invert)){ pins |= mask; } @@ -1020,24 +988,24 @@ Device_MiscUpdate(void *arg, long period) MotencRegMap *pCard = this->pCard; // Check watchdog control parameter. - if(this->watchdogControl != this->misc.watchdogControl){ + if(this->watchdogControl != hal_get_ui32(this->misc.watchdogControl)){ // Update shadow register. - this->watchdogControl = this->misc.watchdogControl; + this->watchdogControl = hal_get_ui32(this->misc.watchdogControl); // Write hardware. pCard->watchdogControl = this->watchdogControl; } // Check watchdog reset pin. - if(*(this->misc.pWatchdogReset)){ + if(hal_get_bool(this->misc.pWatchdogReset)){ // Clear pin. - *(this->misc.pWatchdogReset) = 0; + hal_set_bool(this->misc.pWatchdogReset, 0); // Reset the watchdog timer. pCard->watchdogReset = MOTENC_WATCHDOG_RESET_VALUE; } // Update E-STOP pin. - *(this->misc.pEstopIn) = (pCard->fpga[0].statusControl & MOTENC_STATUS_ESTOP)? 1: 0; - *(this->misc.pEstopInNot) = !*(this->misc.pEstopIn); + rtapi_bool b = hal_set_bool(this->misc.pEstopIn, (pCard->fpga[0].statusControl & MOTENC_STATUS_ESTOP)? 1: 0); + hal_set_bool(this->misc.pEstopInNot, !b); } diff --git a/src/hal/drivers/hal_parport.c b/src/hal/drivers/hal_parport.c index 9eb0f722db7..22d89317226 100644 --- a/src/hal/drivers/hal_parport.c +++ b/src/hal/drivers/hal_parport.c @@ -124,17 +124,17 @@ typedef struct { unsigned short base_addr; /* base I/O address (0x378, etc.) */ unsigned char data_dir; /* non-zero if pins 2-9 are input */ unsigned char use_control_in; /* non-zero if pins 1, 4, 16, 17 are input */ - hal_bit_t *status_in[10]; /* ptrs for in pins 15, 13, 12, 10, 11 */ - hal_bit_t *data_in[16]; /* ptrs for input pins 2 - 9 */ - hal_bit_t *data_out[8]; /* ptrs for output pins 2 - 9 */ - hal_bit_t data_inv[8]; /* polarity params for output pins 2 - 9 */ - hal_bit_t data_reset[8]; /* reset flag for output pins 2 - 9 */ - hal_bit_t *control_in[8]; /* ptrs for in pins 1, 14, 16, 17 */ - hal_bit_t *control_out[4]; /* ptrs for out pins 1, 14, 16, 17 */ - hal_bit_t control_inv[4]; /* pol. params for output pins 1, 14, 16, 17 */ - hal_bit_t control_reset[4]; /* reset flag for output pins 1, 14, 16, 17 */ - hal_u32_t reset_time; /* min ns between write and reset */ - hal_u32_t debug1, debug2; + hal_bool_t status_in[10]; /* (pin) ptrs for in pins 15, 13, 12, 10, 11 */ + hal_bool_t data_in[16]; /* (pin) ptrs for input pins 2 - 9 */ + hal_bool_t data_out[8]; /* (pin) ptrs for output pins 2 - 9 */ + hal_bool_t data_inv[8]; /* (param) polarity params for output pins 2 - 9 */ + hal_bool_t data_reset[8]; /* (param) reset flag for output pins 2 - 9 */ + hal_bool_t control_in[8]; /* ptrs for in pins 1, 14, 16, 17 */ + hal_bool_t control_out[4]; /* ptrs for out pins 1, 14, 16, 17 */ + hal_bool_t control_inv[4]; /* (param) pol. params for output pins 1, 14, 16, 17 */ + hal_bool_t control_reset[4];/* (param) reset flag for output pins 1, 14, 16, 17 */ + hal_uint_t reset_time; /* (param) min ns between write and reset */ + hal_uint_t debug1, debug2; /* (param) */ long long write_time; unsigned short outdata; unsigned char reset_mask; /* reset flag for pin 2..9 */ @@ -178,9 +178,9 @@ static int pins_and_params(char *argv[]); static unsigned short parse_port_addr(char *cp); static int export_port(int portnum, parport_t * addr); -static int export_input_pin(int portnum, int pin, hal_bit_t ** base, int n); -static int export_output_pin(int portnum, int pin, hal_bit_t ** dbase, - hal_bit_t * pbase, hal_bit_t * rbase, int n); +static int export_input_pin(int portnum, int pin, hal_bool_t * base, int n); +static int export_output_pin(int portnum, int pin, hal_bool_t * dbase, + hal_bool_t * pbase, hal_bool_t * rbase, int n); /*********************************************************************** * INIT AND EXIT CODE * @@ -316,8 +316,8 @@ static void read_port(void *arg, long period) /* split the bits into 10 variables (5 regular, 5 inverted) */ mask = 0x08; for (b = 0; b < 10; b += 2) { - *(port->status_in[b]) = indata & mask; - *(port->status_in[b + 1]) = !(indata & mask); + hal_set_bool(port->status_in[b], indata & mask); + hal_set_bool(port->status_in[b + 1], !(indata & mask)); mask <<= 1; } /* are we using the data port for input? */ @@ -327,8 +327,8 @@ static void read_port(void *arg, long period) /* split the bits into 16 variables (8 regular, 8 inverted) */ mask = 0x01; for (b = 0; b < 16; b += 2) { - *(port->data_in[b]) = indata & mask; - *(port->data_in[b + 1]) = !(indata & mask); + hal_set_bool(port->data_in[b], indata & mask); + hal_set_bool(port->data_in[b + 1], !(indata & mask)); mask <<= 1; } } @@ -338,8 +338,8 @@ static void read_port(void *arg, long period) /* correct for hardware inverters on pins 1, 14, & 17 */ indata = rtapi_inb(port->base_addr + 2) ^ 0x0B; for (b = 0; b < 8; b += 2) { - *(port->control_in[b]) = indata & mask; - *(port->control_in[b + 1]) = !(indata & mask); + hal_set_bool(port->control_in[b], indata & mask); + hal_set_bool(port->control_in[b + 1], !(indata & mask)); mask <<= 1; } } @@ -350,10 +350,10 @@ static void reset_port(void *arg, long period) { long long deadline; unsigned char outdata = (unsigned char)((port->outdata&~port->reset_mask) ^ port->reset_val); - if(port->reset_time > period/4) port->reset_time = period/4; + if(hal_get_ui32(port->reset_time) > period/4) hal_set_ui32(port->reset_time, period/4); if(outdata != port->outdata) { - deadline = port->write_time + port->reset_time; + deadline = port->write_time + hal_get_ui32(port->reset_time); while(rtapi_get_time() < deadline) {} rtapi_outb(outdata, port->base_addr); port->outdata = outdata; @@ -362,7 +362,7 @@ static void reset_port(void *arg, long period) { outdata = (unsigned char)((port->outdata_ctrl&~port->reset_mask_ctrl)^port->reset_val_ctrl); if(outdata != port->outdata_ctrl) { - deadline = port->write_time_ctrl + port->reset_time; + deadline = port->write_time_ctrl + hal_get_ui32(port->reset_time); while(rtapi_get_time() < deadline) {} /* correct for hardware inverters on pins 1, 14, & 17 */ rtapi_outb(outdata ^ 0x0B, port->base_addr + 2); @@ -387,15 +387,15 @@ static void write_port(void *arg, long period) /* assemble output byte for data port from 8 source variables */ for (b = 0; b < 8; b++) { /* get the data, add to output byte */ - if ((*(port->data_out[b])) && (!port->data_inv[b])) { + if ((hal_get_bool(port->data_out[b])) && (!hal_get_bool(port->data_inv[b]))) { outdata |= mask; } - if ((!*(port->data_out[b])) && (port->data_inv[b])) { + if ((!hal_get_bool(port->data_out[b])) && (hal_get_bool(port->data_inv[b]))) { outdata |= mask; } - if (port->data_reset[b]) { + if (hal_get_bool(port->data_reset[b])) { reset_mask |= mask; - if(port->data_inv[b]) reset_val |= mask; + if(hal_get_bool(port->data_inv[b])) reset_val |= mask; } mask <<= 1; } @@ -424,15 +424,15 @@ static void write_port(void *arg, long period) mask = 0x01; for (b = 0; b < 4; b++) { /* get the data, add to output byte */ - if ((*(port->control_out[b])) && (!port->control_inv[b])) { + if ((hal_get_bool(port->control_out[b])) && (!hal_get_bool(port->control_inv[b]))) { outdata |= mask; } - if ((!*(port->control_out[b])) && (port->control_inv[b])) { + if ((!hal_get_bool(port->control_out[b])) && (hal_get_bool(port->control_inv[b]))) { outdata |= mask; } - if (port->control_reset[b]) { + if (hal_get_bool(port->control_reset[b])) { reset_mask |= mask; - if(port->control_inv[b]) reset_val |= mask; + if(hal_get_bool(port->control_inv[b])) reset_val |= mask; } mask <<= 1; } @@ -545,7 +545,7 @@ static int pins_and_params(char *argv[]) return -1; } /* allocate shared memory for parport data */ - port_data_array = hal_malloc(num_ports * sizeof(parport_t)); + port_data_array = hal_malloc(num_ports * sizeof(*port_data_array)); if (port_data_array == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "PARPORT: ERROR: hal_malloc() failed\n"); @@ -684,11 +684,11 @@ static int export_port(int portnum, parport_t * port) port->data_out, port->data_inv, port->data_reset, 6); retval += export_output_pin(portnum, 9, port->data_out, port->data_inv, port->data_reset, 7); - retval += hal_param_u32_newf(HAL_RW, &port->reset_time, comp_id, + retval += hal_param_new_ui32(comp_id, HAL_RW, &port->reset_time, 0.0, "parport.%d.reset-time", portnum); - retval += hal_param_u32_newf(HAL_RW, &port->debug1, comp_id, + retval += hal_param_new_ui32(comp_id, HAL_RW, &port->debug1, 0.0, "parport.%d.debug1", portnum); - retval += hal_param_u32_newf(HAL_RW, &port->debug2, comp_id, + retval += hal_param_new_ui32(comp_id, HAL_RW, &port->debug2, 0.0, "parport.%d.debug2", portnum); port->write_time = 0; } @@ -715,42 +715,42 @@ static int export_port(int portnum, parport_t * port) return retval; } -static int export_input_pin(int portnum, int pin, hal_bit_t ** base, int n) +static int export_input_pin(int portnum, int pin, hal_bool_t * base, int n) { int retval; /* export write only HAL pin for the input bit */ - retval = hal_pin_bit_newf(HAL_OUT, base + (2 * n), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, base + (2 * n), 0, "parport.%d.pin-%02d-in", portnum, pin); if (retval != 0) { return retval; } /* export another write only HAL pin for the same bit inverted */ - retval = hal_pin_bit_newf(HAL_OUT, base + (2 * n) + 1, comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, base + (2 * n) + 1, 0, "parport.%d.pin-%02d-in-not", portnum, pin); return retval; } -static int export_output_pin(int portnum, int pin, hal_bit_t ** dbase, - hal_bit_t * pbase, hal_bit_t * rbase, int n) +static int export_output_pin(int portnum, int pin, hal_bool_t * dbase, + hal_bool_t * pbase, hal_bool_t * rbase, int n) { int retval; /* export read only HAL pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, dbase + n, comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, dbase + n, 0, "parport.%d.pin-%02d-out", portnum, pin); if (retval != 0) { return retval; } /* export parameter for polarity */ - retval = hal_param_bit_newf(HAL_RW, pbase + n, comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, pbase + n, 0, "parport.%d.pin-%02d-out-invert", portnum, pin); if (retval != 0) { return retval; } /* export parameter for reset */ if (rbase) - retval = hal_param_bit_newf(HAL_RW, rbase + n, comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, rbase + n, 0, "parport.%d.pin-%02d-out-reset", portnum, pin); return retval; } diff --git a/src/hal/drivers/hal_pi_gpio.c b/src/hal/drivers/hal_pi_gpio.c index cb8caafbe40..3c4abeb3c53 100644 --- a/src/hal/drivers/hal_pi_gpio.c +++ b/src/hal/drivers/hal_pi_gpio.c @@ -78,7 +78,7 @@ static unsigned exclude_map; static int comp_id; /* component ID */ static unsigned char *pins, *gpios; -hal_bit_t **port_data; +hal_bool_t *port_data; static void write_port(void *arg, long period); static void read_port(void *arg, long period); @@ -262,8 +262,8 @@ int rtapi_app_main(void) } break; } - port_data = hal_malloc(npins * sizeof(void *)); - if (port_data == 0) { + port_data = hal_malloc(npins * sizeof(*port_data)); + if (NULL == port_data) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL_PI_GPIO: ERROR: hal_malloc() failed\n"); hal_exit(comp_id); @@ -312,13 +312,13 @@ int rtapi_app_main(void) pinno = pins[n]; if (dir_map & RTAPI_BIT(n)) { bcm2835_gpio_fsel(gpios[n], BCM2835_GPIO_FSEL_OUTP); - if ((retval = hal_pin_bit_newf(HAL_IN, &port_data[n], - comp_id, "hal_pi_gpio.pin-%02d-out", pinno)) < 0) + if ((retval = hal_pin_new_bool(comp_id, HAL_IN, &port_data[n], + 0, "hal_pi_gpio.pin-%02d-out", pinno)) < 0) break; } else { bcm2835_gpio_fsel(gpios[n], BCM2835_GPIO_FSEL_INPT); - if ((retval = hal_pin_bit_newf(HAL_OUT, &port_data[n], - comp_id, "hal_pi_gpio.pin-%02d-in", pinno)) < 0) + if ((retval = hal_pin_new_bool(comp_id, HAL_OUT, &port_data[n], + 0, "hal_pi_gpio.pin-%02d-in", pinno)) < 0) break; } } @@ -372,7 +372,7 @@ static void write_port(void *arg, long period) if (exclude_map & RTAPI_BIT(n)) continue; if (dir_map & RTAPI_BIT(n)) { - if (*(port_data[n])) { + if (hal_get_bool(port_data[n])) { bcm2835_gpio_set(gpios[n]); } else { bcm2835_gpio_clr(gpios[n]); @@ -389,6 +389,6 @@ static void read_port(void *arg, long period) for (n = 0; n < npins; n++) { if ((~dir_map & RTAPI_BIT(n)) && (~exclude_map & RTAPI_BIT(n))) - *port_data[n] = bcm2835_gpio_lev(gpios[n]); + hal_set_bool(port_data[n], bcm2835_gpio_lev(gpios[n])); } } diff --git a/src/hal/drivers/hal_ppmc.c b/src/hal/drivers/hal_ppmc.c index 6f357b78aef..88198071662 100644 --- a/src/hal/drivers/hal_ppmc.c +++ b/src/hal/drivers/hal_ppmc.c @@ -219,31 +219,31 @@ an unsafe condition, then the board will immediately return to the ESTOP state. /* this structure contains the runtime data for a digital output */ typedef struct { - hal_bit_t *data; /* output pin value */ - hal_bit_t invert; /* parameter to invert output pin */ + hal_bool_t data; /* output pin value */ + hal_bool_t invert; /* parameter: to invert output pin */ } dout_t; /* this structure contains the runtime data for a digital input */ typedef struct { - hal_bit_t *data; /* input pin value */ - hal_bit_t *data_not; /* inverted input pin value */ + hal_bool_t data; /* input pin value */ + hal_bool_t data_not; /* inverted input pin value */ } din_t; /* this structure contains the runtime data for a step pulse generator */ typedef struct { - hal_bit_t *enable; /* enable pin for step generator */ - hal_float_t *vel; /* velocity command pin*/ - hal_float_t scale; /* parameter: scaling for vel to Hz */ - hal_float_t max_vel; /* velocity limit */ - hal_float_t freq; /* parameter: velocity cmd scaled to Hz */ + hal_bool_t enable; /* enable pin for step generator */ + hal_real_t vel; /* velocity command pin*/ + hal_real_t scale; /* parameter: scaling for vel to Hz */ + hal_real_t max_vel; /* parameter: velocity limit */ + hal_real_t freq; /* parameter: velocity cmd scaled to Hz */ } stepgen_t; /* runtime data for a set of 4 step pulse generators */ typedef struct { stepgen_t sg[4]; /* per generator data */ - hal_u32_t setup_time_ns; /* setup time in nanoseconds */ - hal_u32_t pulse_width_ns; /* pulse width in nanoseconds */ - hal_u32_t pulse_space_ns; /* min pulse space in nanoseconds */ + hal_uint_t setup_time_ns; /* parameter: setup time in nanoseconds */ + hal_uint_t pulse_width_ns; /* parameter: pulse width in nanoseconds */ + hal_uint_t pulse_space_ns; /* parameter: min pulse space in nanoseconds */ } stepgens_t; #define BOOT_NORMAL 0 @@ -252,13 +252,13 @@ typedef struct { /* this structure contains the runtime data for a PWM generator */ typedef struct { - hal_bit_t *enable; /* enable pin for PWM generator */ - hal_float_t *value; /* value command pin */ - hal_float_t scale; /* parameter: scaling */ - hal_float_t max_dc; /* maximum duty cycle 0.0-1.0 */ - hal_float_t min_dc; /* minimum duty cycle 0.0-1.0 */ - hal_float_t duty_cycle; /* actual duty cycle output */ - hal_bit_t bootstrap; /* enable bootstrap mode (pulses at startup) */ + hal_bool_t enable; /* enable pin for PWM generator */ + hal_real_t value; /* value command pin */ + hal_real_t scale; /* parameter: scaling */ + hal_real_t max_dc; /* parameter: maximum duty cycle 0.0-1.0 */ + hal_real_t min_dc; /* parameter: minimum duty cycle 0.0-1.0 */ + hal_real_t duty_cycle; /* parameter: actual duty cycle output */ + hal_bool_t bootstrap; /* parameter: enable bootstrap mode (pulses at startup) */ unsigned char boot_state; /* state for bootstrap state machine */ unsigned char old_enable; /* used to detect rising edge, for boot */ } pwmgen_t; @@ -266,16 +266,16 @@ typedef struct { /* runtime data for a set of 4 PWM generators */ typedef struct { pwmgen_t pg[4]; /* per generator data */ - hal_float_t freq; /* PWM frequency */ - hal_float_t old_freq; /* previous value, to detect changes */ + hal_real_t freq; /* parameter: PWM frequency */ + rtapi_real old_freq; /* previous value, to detect changes */ unsigned short period; /* period in clock ticks */ double period_recip; /* reciprocal of period */ } pwmgens_t; /* this structure contains the runtime data for a 16-bit DAC */ typedef struct { - hal_float_t *value; /* value command pin */ - hal_float_t scale; /* parameter: scaling */ + hal_real_t value; /* value command pin */ + hal_real_t scale; /* parameter: scaling */ } DAC_t; /* runtime data for a 4-channel 16-bit DAC */ @@ -291,19 +291,19 @@ typedef union { /* runtime data for a single encoder */ typedef struct { - hal_float_t *position; /* output: scaled position pointer */ - hal_s32_t *count; /* output: unscaled encoder counts */ - hal_s32_t *delta; /* output: delta counts since last read */ - hal_s32_t prevdir; /* local: previous direction */ - hal_float_t scale; /* parameter: scale factor */ - hal_bit_t *index; /* output: index flag */ - hal_bit_t *index_enable; /* enable index pulse to reset encoder count */ - hal_s32_t oldreading; /* used to detect overflow / underflow of the counter JE001 */ - unsigned int indres; /* copy of reset-on-index register bits (only valid on 1st encoder of board)*/ - unsigned int indrescnt; /* counts servo cycles since index reset was turned on */ - hal_float_t *vel; /* output: scaled velocity */ - hal_float_t min_speed; /* parameter: min speed for velocity estimation */ - hal_u32_t counts_since_timeout; /* for velocity estimation */ + hal_real_t position; /* output: scaled position pointer */ + hal_sint_t count; /* output: unscaled encoder counts */ + hal_sint_t delta; /* output: delta counts since last read */ + rtapi_s32 prevdir; /* local: previous direction */ + hal_real_t scale; /* parameter: scale factor */ + hal_bool_t index; /* output: index flag */ + hal_bool_t index_enable; /* enable index pulse to reset encoder count */ + rtapi_s32 oldreading; /* used to detect overflow / underflow of the counter JE001 */ + unsigned int indres; /* copy of reset-on-index register bits (only valid on 1st encoder of board)*/ + unsigned int indrescnt; /* counts servo cycles since index reset was turned on */ + hal_real_t vel; /* output: scaled velocity */ + hal_real_t min_speed; /* parameter: min speed for velocity estimation */ + rtapi_u32 counts_since_timeout; /* for velocity estimation */ unsigned short old_timestamp; unsigned short timestamp; } encoder_t; @@ -957,8 +957,8 @@ static void read_digins(slot_data_t *slot) b = 0; mask = 0x01; while ( b < 8 ) { - *(slot->digin[b].data) = indata & mask; - *(slot->digin[b].data_not) = !(indata & mask); + hal_set_bool(slot->digin[b].data, indata & mask); + hal_set_bool(slot->digin[b].data_not, !(indata & mask)); mask <<= 1; b++; } @@ -967,8 +967,8 @@ static void read_digins(slot_data_t *slot) /* and split them too */ mask = 0x01; while ( b < 16 ) { - *(slot->digin[b].data) = indata & mask; - *(slot->digin[b].data_not) = !(indata & mask); + hal_set_bool(slot->digin[b].data, indata & mask); + hal_set_bool(slot->digin[b].data_not, !(indata & mask)); mask <<= 1; b++; } @@ -984,10 +984,10 @@ static void write_digouts(slot_data_t *slot) /* assemble output byte from 8 source variables */ for (b = 0; b < 8; b++) { /* get the data, add to output byte */ - if ((*(slot->digout[b].data)) && (!slot->digout[b].invert)) { + if ((hal_get_bool(slot->digout[b].data)) && !hal_get_bool(slot->digout[b].invert)) { outdata |= mask; } - if ((!*(slot->digout[b].data)) && (slot->digout[b].invert)) { + if ((!hal_get_bool(slot->digout[b].data)) && hal_get_bool(slot->digout[b].invert)) { outdata |= mask; } mask <<= 1; @@ -1008,8 +1008,8 @@ static void read_PPMC_digins(slot_data_t *slot) b = 0; mask = 0x01; while ( b < 8 ) { - *(slot->digin[b].data) = indata & mask; - *(slot->digin[b].data_not) = !(indata & mask); + hal_set_bool(slot->digin[b].data, indata & mask); + hal_set_bool(slot->digin[b].data_not, !(indata & mask)); mask <<= 1; b++; } @@ -1018,8 +1018,8 @@ static void read_PPMC_digins(slot_data_t *slot) /* and split them too */ mask = 0x01; while ( b < 16 ) { - *(slot->digin[b].data) = indata & mask; - *(slot->digin[b].data_not) = !(indata & mask); + hal_set_bool(slot->digin[b].data, indata & mask); + hal_set_bool(slot->digin[b].data_not, !(indata & mask)); mask <<= 1; b++; } @@ -1029,8 +1029,8 @@ static void read_PPMC_digins(slot_data_t *slot) /* and split them too */ mask = 0x01; while ( b < 18 ) { - *(slot->digin[b].data) = indata & mask; - *(slot->digin[b].data_not) = !(indata & mask); + hal_set_bool(slot->digin[b].data, indata & mask); + hal_set_bool(slot->digin[b].data_not, !(indata & mask)); mask <<= 1; b++; } @@ -1048,10 +1048,10 @@ static void write_PPMC_digouts(slot_data_t *slot) /* assemble output byte from 8 source variables */ for (b = 0; b < 8; b++) { /* get the data, add to output byte */ - if ((*(slot->digout[b].data)) && (!slot->digout[b].invert)) { + if ((hal_get_bool(slot->digout[b].data)) && !hal_get_bool(slot->digout[b].invert)) { outdata |= mask; } - if ((!*(slot->digout[b].data)) && (slot->digout[b].invert)) { + if ((!hal_get_bool(slot->digout[b].data)) && hal_get_bool(slot->digout[b].invert)) { outdata |= mask; } mask <<= 1; @@ -1060,10 +1060,10 @@ static void write_PPMC_digouts(slot_data_t *slot) slot->wr_buf[DIO_DOUTA] = outdata; if (slot->digout[8].data != NULL) { // no estop funct on slave boards - hal pin doesn't exist outdata = 0; // now process estop bit - if ((*(slot->digout[8].data)) && (!slot->digout[8].invert)) { + if ((hal_get_bool(slot->digout[8].data)) && !hal_get_bool(slot->digout[8].invert)) { outdata =1; } - if ((!*(slot->digout[8].data)) && (slot->digout[8].invert)) { + if ((!hal_get_bool(slot->digout[8].data)) && hal_get_bool(slot->digout[8].invert)) { outdata |= 1; } slot->wr_buf[DIO_ESTOP_OUT] = outdata; @@ -1076,7 +1076,7 @@ static void read_encoders(slot_data_t *slot) int i, byteindex, byteindx2; double vel; // local temporary velocity union pos_tag { - hal_s32_t l; // JE001 + rtapi_s32 l; // JE001 struct byte_tag { signed char b0; signed char b1; @@ -1092,8 +1092,6 @@ static void read_encoders(slot_data_t *slot) } byte; } timebase, timestamp; unsigned short delta_time; - // hal_u32_t timestamp; - // hal_u32_t timebase; // sample timebase only on boards so equipped if (slot->use_timestamp) { @@ -1116,22 +1114,22 @@ static void read_encoders(slot_data_t *slot) else if ((oldpos.byte.b2 == 0) && (pos.byte.b2 & 0xc0) == 0xc0) pos.byte.b3--; - *(slot->encoder[i].delta) = pos.l - slot->encoder[i].oldreading; + hal_set_si32(slot->encoder[i].delta, pos.l - slot->encoder[i].oldreading); vel = (pos.l - slot->encoder[i].oldreading) / - (read_period * 1e-9 * slot->encoder[i].scale); + (read_period * 1e-9 * hal_get_real(slot->encoder[i].scale)); /* index processing */ if ( (slot->rd_buf[ENCISR] & ( 1 << i )) != 0 ) { // rtapi_print_msg(RTAPI_MSG_INFO, "index seen for axis %d",i); // rtapi_print_msg(RTAPI_MSG_INFO, "indrescnt %d\n",slot->encoder[i].indrescnt); /* index edge occurred since last time this code ran */ - *(slot->encoder[i].index) = 1; + hal_set_bool(slot->encoder[i].index, 1); /* index-enable only works on version 2 and up */ if (slot->ver >= 2) { /* were we looking for an index edge? */ if ( ((slot->encoder[0].indres & ( 1 << i )) != 0) && (slot->encoder[i].indrescnt > 3)) { /* yes, clear index-enable to announce that we found it */ - *(slot->encoder[i].index_enable) = 0; + hal_set_bool(slot->encoder[i].index_enable, 0); /* need to properly set the 24->32 bit extension byte */ if ( pos.byte.b2 < 0 ) { /* going backwards */ @@ -1144,18 +1142,18 @@ static void read_encoders(slot_data_t *slot) } } else { /* no index edge since last check */ - *(slot->encoder[i].index) = 0; + hal_set_bool(slot->encoder[i].index, 0); } slot->encoder[i].oldreading = pos.l; - *(slot->encoder[i].count) = pos.l; - if (slot->encoder[i].scale < 0.0) { - if (slot->encoder[i].scale > -EPSILON) - slot->encoder[i].scale = -1.0; + hal_set_si32(slot->encoder[i].count, pos.l); + if (hal_get_real(slot->encoder[i].scale) < 0.0) { + if (hal_get_real(slot->encoder[i].scale) > -EPSILON) + hal_set_real(slot->encoder[i].scale, -1.0); } else { - if (slot->encoder[i].scale < EPSILON) - slot->encoder[i].scale = 1.0; + if (hal_get_real(slot->encoder[i].scale) < EPSILON) + hal_set_real(slot->encoder[i].scale, 1.0); } - *(slot->encoder[i].position) = pos.l / slot->encoder[i].scale; + hal_set_real(slot->encoder[i].position, pos.l / hal_get_real(slot->encoder[i].scale)); // perform velocity estimate when hardware provides timestamps if (slot->use_timestamp) { slot->encoder[i].old_timestamp = slot->encoder[i].timestamp; @@ -1163,20 +1161,20 @@ static void read_encoders(slot_data_t *slot) timestamp.byte.b1 = slot->rd_buf[byteindx2++]; slot->encoder[i].timestamp = timestamp.s; // one or more counts this sample - if (*(slot->encoder[i].delta) != 0.0) { + if (hal_get_si32(slot->encoder[i].delta) != 0.0) { delta_time = timestamp.s - slot->encoder[i].old_timestamp; delta_time = delta_time & 0xffff; if (slot->encoder[i].counts_since_timeout < 2) { // just keep simple vel calc from above slot->encoder[i].counts_since_timeout++; - *(slot->encoder[i].vel) = vel; // cannot make estimate + hal_set_real(slot->encoder[i].vel, vel); // cannot make estimate } else { - vel = *(slot->encoder[i].delta) / (delta_time * 1e-6 * slot->encoder[i].scale); - *(slot->encoder[i].vel) = vel; + vel = hal_get_si32(slot->encoder[i].delta) / (delta_time * 1e-6 * hal_get_real(slot->encoder[i].scale)); + hal_set_real(slot->encoder[i].vel, vel); } - if (((slot->encoder[i].prevdir > 0) && (*(slot->encoder[i].delta) < 0)) || - ((slot->encoder[i].prevdir < 0) && (*(slot->encoder[i].delta) > 0))) { - *(slot->encoder[i].vel) = 0.0; /* suppress velocity of dithering encoder at reversal */ + if (((slot->encoder[i].prevdir > 0) && (hal_get_si32(slot->encoder[i].delta) < 0)) || + ((slot->encoder[i].prevdir < 0) && (hal_get_si32(slot->encoder[i].delta) > 0))) { + hal_set_real(slot->encoder[i].vel, 0.0); /* suppress velocity of dithering encoder at reversal */ } } else { // no counts this sample @@ -1186,27 +1184,27 @@ static void read_encoders(slot_data_t *slot) // if (delta_time < slot->encoder[i].scale * slot->encoder[i].min_speed) { if (delta_time < 65500) { // 1e-6 is timebase period - vel = 1.0 / (slot->encoder[i].scale * delta_time * 1e-6); + vel = 1.0 / (hal_get_real(slot->encoder[i].scale) * delta_time * 1e-6); if (vel < 0.0) vel = -vel; - if (vel < *(slot->encoder[i].vel)) { - *(slot->encoder[i].vel) = vel; + if (vel < hal_get_real(slot->encoder[i].vel)) { + hal_set_real(slot->encoder[i].vel, vel); } - if (-vel > *(slot->encoder[i].vel)) { - *(slot->encoder[i].vel) = -vel; + if (-vel > hal_get_real(slot->encoder[i].vel)) { + hal_set_real(slot->encoder[i].vel, -vel); } } else { slot->encoder[i].counts_since_timeout = 0; - *(slot->encoder[i].vel) = 0; + hal_set_real(slot->encoder[i].vel, 0); } } else { - *(slot->encoder[i].vel) = 0; + hal_set_real(slot->encoder[i].vel, 0); } } } else { - *(slot->encoder[i].vel) = vel; // encoder without timestamp + hal_set_real(slot->encoder[i].vel, vel); // encoder without timestamp } - if (*(slot->encoder[i].delta) > 0) slot->encoder[i].prevdir = 1; // mark last direction moved - if (*(slot->encoder[i].delta) < 0) slot->encoder[i].prevdir = -1; + if (hal_get_si32(slot->encoder[i].delta) > 0) slot->encoder[i].prevdir = 1; // mark last direction moved + if (hal_get_si32(slot->encoder[i].delta) < 0) slot->encoder[i].prevdir = -1; } } @@ -1224,7 +1222,7 @@ static void write_encoders(slot_data_t *slot) return; } for (i = 0; i < 4; i++) { - if ( *(slot->encoder[i].index_enable) ) { + if ( hal_get_bool(slot->encoder[i].index_enable) ) { /* all 4 control bits are packed into the same register */ if ((slot->encoder[0].indres & (1 << i)) == 0) { slot->encoder[i].indrescnt = 0; /* clear counter first time only */ @@ -1244,16 +1242,16 @@ static void write_encoders(slot_data_t *slot) /* fetch a time parameter (in nS), make sure it is a multiple of 100nS, and is between min_ns and 25.4uS, and return the value in 10MHz clock pulses. */ -static unsigned int ns2cp( hal_u32_t *pns, unsigned int min_ns ) +static unsigned int ns2cp( hal_uint_t pns, unsigned int min_ns ) { unsigned ns, cp; - ns = *pns; + ns = hal_get_ui32(pns); if ( ns < min_ns ) ns = min_ns; if ( ns > 25400 ) ns = 25400; cp = ns / 100; ns = cp * 100; - *pns = ns; + hal_set_ui32(pns, ns); return cp; } @@ -1267,13 +1265,13 @@ static void write_stepgens(slot_data_t *slot) unsigned char control_byte; /* pulse width cannot be less than 200nS (HW limit) */ - pulse_width = ns2cp(&(slot->stepgen->pulse_width_ns), 200); + pulse_width = ns2cp(slot->stepgen->pulse_width_ns, 200); /* write pulse width to the cache, inverted */ slot->wr_buf[RATE_WIDTH_0] = 256 - pulse_width; /* pulse space cannot be less than 300nS (HW limitation) */ - pulse_space = ns2cp(&(slot->stepgen->pulse_space_ns), 300); + pulse_space = ns2cp(slot->stepgen->pulse_space_ns, 300); /* setup time cannot be less than 2 (HW limit) */ - setup_time = ns2cp(&(slot->stepgen->setup_time_ns), 200); + setup_time = ns2cp(slot->stepgen->setup_time_ns, 200); /* write it to the cache, inverted */ slot->wr_buf[RATE_SETUP_0] = 256 - setup_time; /* calculate the max frequency, varies with pulse width and @@ -1285,37 +1283,37 @@ static void write_stepgens(slot_data_t *slot) /* point to the specific stepgen */ sg = &(slot->stepgen->sg[n]); /* validate the scale value */ - if ( sg->scale < 0.0 ) { - if ( sg->scale > -EPSILON ) { + if ( hal_get_real(sg->scale) < 0.0 ) { + if ( hal_get_real(sg->scale) > -EPSILON ) { /* too small, divide by zero is bad */ - sg->scale = -1.0; + hal_set_real(sg->scale, -1.0); } - abs_scale = -sg->scale; + abs_scale = -hal_get_real(sg->scale); } else { - if ( sg->scale < EPSILON ) { - sg->scale = 1.0; + if ( hal_get_real(sg->scale) < EPSILON ) { + hal_set_real(sg->scale, 1.0); } - abs_scale = sg->scale; + abs_scale = hal_get_real(sg->scale); } ch_max_freq = bd_max_freq; /* check for user specified max velocity */ - if (sg->max_vel <= 0.0) { + if (hal_get_real(sg->max_vel) <= 0.0) { /* set to zero if negative, and ignore if zero */ - sg->max_vel = 0.0; + hal_set_real(sg->max_vel, 0.0); } else { /* parameter is non-zero and positive, compare to max_freq */ - if ( (sg->max_vel * abs_scale) > ch_max_freq) { + if ( (hal_get_real(sg->max_vel) * abs_scale) > ch_max_freq) { /* parameter is too high, lower it */ - sg->max_vel = ch_max_freq / abs_scale; + hal_set_real(sg->max_vel, ch_max_freq / abs_scale); } else { /* lower max_freq to match parameter */ - ch_max_freq = sg->max_vel * abs_scale; + ch_max_freq = hal_get_real(sg->max_vel) * abs_scale; } } /* calculate desired frequency */ - freq = *(sg->vel) * sg->scale; + freq = hal_get_real(sg->vel) * hal_get_real(sg->scale); /* should we be running? */ - if ( *(sg->enable) != 0 ) { + if ( hal_get_bool(sg->enable) != 0 ) { run = 1; } else { run = 0; @@ -1350,9 +1348,9 @@ static void write_stepgens(slot_data_t *slot) } /* set dir bit in the control byte, and save the frequency */ if ( reverse ) { - sg->freq = -freq; + hal_set_real(sg->freq, -freq); } else { - sg->freq = freq; + hal_set_real(sg->freq, freq); control_byte |= 0x40; } /* correct for an offset of 4 in the hardware */ @@ -1378,17 +1376,17 @@ static void write_pwmgens(slot_data_t *slot) unsigned char control_byte; /* zero frequency is a special case, turn off everything */ - if ( slot->pwmgen->freq == 0.0 ) { - slot->pwmgen->old_freq = slot->pwmgen->freq; + if ( hal_get_real(slot->pwmgen->freq) == 0.0 ) { + slot->pwmgen->old_freq = hal_get_real(slot->pwmgen->freq); /* write control byte to cache */ slot->wr_buf[PWM_CTRL_0] = 0; /* done */ return; } /* check for new frequency setting */ - if ( slot->pwmgen->freq != slot->pwmgen->old_freq ) { + if ( hal_get_real(slot->pwmgen->freq) != slot->pwmgen->old_freq ) { /* process new frequency value */ - freq = slot->pwmgen->freq; + freq = hal_get_real(slot->pwmgen->freq); /* frequency must be between 153Hz and 500KHz */ if ( freq < 153.0 ) { freq = 153.0; @@ -1404,7 +1402,7 @@ static void write_pwmgens(slot_data_t *slot) /* calculate actual frequency (after rounding, etc) */ freq = 10000000.0 / period; /* save values */ - slot->pwmgen->freq = freq; + hal_set_real(slot->pwmgen->freq, freq); slot->pwmgen->old_freq = freq; slot->pwmgen->period = period; slot->pwmgen->period_recip = 1.0 / period; @@ -1420,31 +1418,31 @@ static void write_pwmgens(slot_data_t *slot) /* point to the specific pwm generator */ pg = &(slot->pwmgen->pg[n]); /* validate the scale value */ - if ( pg->scale < 0.0 ) { - if ( pg->scale > -EPSILON ) { + if ( hal_get_real(pg->scale) < 0.0 ) { + if ( hal_get_real(pg->scale) > -EPSILON ) { /* too small, divide by zero is bad */ - pg->scale = -1.0; + hal_set_real(pg->scale, -1.0); } } else { - if ( pg->scale < EPSILON ) { - pg->scale = 1.0; + if ( hal_get_real(pg->scale) < EPSILON ) { + hal_set_real(pg->scale, 1.0); } } /* calculate desired duty cycle */ - dc = *(pg->value) / pg->scale; + dc = hal_get_real(pg->value) / hal_get_real(pg->scale); /* Special code to deal with the requirements of the Pico PWM amps. They need at least one PWM pulse in each direction every time you enable the amps. So we override the commanded duty cycle with +5%, then -5%, for one thread execution time each, when we see a rising edge on enable. */ - if ( pg->bootstrap != 0 ) { + if ( hal_get_bool(pg->bootstrap) != 0 ) { /* check for rising edge on enable */ - if (( *(pg->enable) != 0 ) && ( pg->old_enable == 0 )) { + if (( hal_get_bool(pg->enable) != 0 ) && ( pg->old_enable == 0 )) { /* kick off state machine */ pg->boot_state = BOOT_FWD; } - pg->old_enable = *(pg->enable); + pg->old_enable = hal_get_bool(pg->enable); /* now execute a state machine */ switch(pg->boot_state) { case BOOT_NORMAL: @@ -1471,21 +1469,21 @@ static void write_pwmgens(slot_data_t *slot) abs_dc = dc; } /* reset any illegal duty cycle limits */ - if (( pg->min_dc > 1.0 ) || ( pg->min_dc < 0.0 )) { - pg->min_dc = 0.0; + if (( hal_get_real(pg->min_dc) > 1.0 ) || ( hal_get_real(pg->min_dc) < 0.0 )) { + hal_set_real(pg->min_dc, 0.0); } - if (( pg->max_dc > 1.0 ) || ( pg->max_dc < 0.0 )) { - pg->max_dc = 1.0; + if (( hal_get_real(pg->max_dc) > 1.0 ) || ( hal_get_real(pg->max_dc) < 0.0 )) { + hal_set_real(pg->max_dc, 1.0); } - if ( pg->min_dc >= pg->max_dc ) { - pg->min_dc = 0.0; - pg->max_dc = 1.0; + if ( hal_get_real(pg->min_dc) >= hal_get_real(pg->max_dc) ) { + hal_set_real(pg->min_dc, 0.0); + hal_set_real(pg->max_dc, 1.0); } /* apply limits */ - if ( abs_dc > pg->max_dc ) { - abs_dc = pg->max_dc; - } else if ( abs_dc < pg->min_dc ) { - abs_dc = pg->min_dc; + if ( abs_dc > hal_get_real(pg->max_dc) ) { + abs_dc = hal_get_real(pg->max_dc); + } else if ( abs_dc < hal_get_real(pg->min_dc) ) { + abs_dc = hal_get_real(pg->min_dc); } /* calculate length of PWM pulse in clocks */ len = ( abs_dc * slot->pwmgen->period ) + 0.5; @@ -1493,14 +1491,14 @@ static void write_pwmgens(slot_data_t *slot) abs_dc = len * slot->pwmgen->period_recip; /* set run bit in the control byte */ control_byte >>= 2; - if ( *(pg->enable) != 0 ) { + if ( hal_get_bool(pg->enable) != 0 ) { control_byte |= 0x80; } /* set dir bit in the control byte, and save the duty cycle */ if ( reverse ) { - pg->duty_cycle = -abs_dc; + hal_set_real(pg->duty_cycle, -abs_dc); } else { - pg->duty_cycle = abs_dc; + hal_set_real(pg->duty_cycle, abs_dc); control_byte |= 0x40; } /* calculate count at which to turn off output */ @@ -1527,18 +1525,18 @@ static void write_DACs(slot_data_t *slot) /* point to the specific DAC */ pg = &(slot->DAC->pg[n]); /* validate the scale value */ - if ( pg->scale < 0.0 ) { - if ( pg->scale > -EPSILON ) { + if ( hal_get_real(pg->scale) < 0.0 ) { + if ( hal_get_real(pg->scale) > -EPSILON ) { /* too small, divide by zero is bad */ - pg->scale = -1.0; + hal_set_real(pg->scale, -1.0); } } else { - if ( pg->scale < EPSILON ) { - pg->scale = 1.0; + if ( hal_get_real(pg->scale) < EPSILON ) { + hal_set_real(pg->scale, 1.0); } } /* calculate desired output voltage */ - volts = *(pg->value) / pg->scale; + volts = hal_get_real(pg->value) / hal_get_real(pg->scale); /* output to DAC word works like: 0xFFFF -> +10 V 0x8000 -> 0 V @@ -1568,14 +1566,14 @@ static void write_extraDAC(slot_data_t *slot) /* point to the DAC */ pg = &(slot->extra->dac); /* validate the scale value */ - if ( pg->scale < 0.0 ) { - if ( pg->scale > -EPSILON ) { + if ( hal_get_real(pg->scale) < 0.0 ) { + if ( hal_get_real(pg->scale) > -EPSILON ) { /* too small, divide by zero is bad */ - pg->scale = -1.0; + hal_set_real(pg->scale, -1.0); } } else { - if ( pg->scale < EPSILON ) { - pg->scale = 1.0; + if ( hal_get_real(pg->scale) < EPSILON ) { + hal_set_real(pg->scale, 1.0); } } /* calculate desired output voltage */ @@ -1589,7 +1587,7 @@ static void write_extraDAC(slot_data_t *slot) UPC and USC boards sold with the spindle DAC option have SSR1 set up for + output, and SSR2 for - output. */ - volts = *(pg->value) / pg->scale; + volts = hal_get_real(pg->value) / hal_get_real(pg->scale); if (volts < 0.0 ) volts = -volts; // no fabs function available!! /* output to DAC word works like: 0xFF -> +10 V @@ -1620,10 +1618,10 @@ static void write_extra_dout(slot_data_t *slot) for (b = 0; b < 8; b++) { pg = &(slot->extra->douts[b]); /* get the data, add to output byte */ - if ((*(pg->data)) && (!pg->invert)) { + if ((hal_get_bool(pg->data)) && !hal_get_bool(pg->invert)) { outdata |= mask; } - if ((!*(pg->data)) && (pg->invert)) { + if ((!hal_get_bool(pg->data)) && hal_get_bool(pg->invert)) { outdata |= mask; } mask <<= 1; @@ -1704,12 +1702,12 @@ static int export_UxC_digin(slot_data_t *slot, bus_data_t *bus) } for ( n = 0 ; n < 16 ; n++ ) { /* export pins for input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[n].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[n].data), 0, "ppmc.%d.din.%02d.in", bus->busnum, bus->last_digin); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[n].data_not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[n].data_not), 0, "ppmc.%d.din.%02d.in-not", bus->busnum, bus->last_digin); if (retval != 0) { return retval; @@ -1744,18 +1742,17 @@ static int export_UxC_digout(slot_data_t *slot, bus_data_t *bus) } for ( n = 0 ; n < 8 ; n++ ) { /* export pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(slot->digout[n].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(slot->digout[n].data), 0, "ppmc.%d.dout.%02d.out", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } /* export parameter for inversion */ - retval = hal_param_bit_newf(HAL_RW, &(slot->digout[n].invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(slot->digout[n].invert), 0, "ppmc.%d.dout.%02d-invert", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } - slot->digout[n].invert = 0; /* increment number to prepare for next output */ bus->last_digout++; } @@ -1780,12 +1777,12 @@ static int export_PPMC_digin(slot_data_t *slot, bus_data_t *bus) } for ( n = 0 ; n < 16 ; n++ ) { /* export pins for input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[n].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[n].data), 0, "ppmc.%d.din.%02d.in", bus->busnum, bus->last_digin); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[n].data_not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[n].data_not), 0, "ppmc.%d.din.%02d.in-not", bus->busnum, bus->last_digin); if (retval != 0) { return retval; @@ -1794,22 +1791,22 @@ static int export_PPMC_digin(slot_data_t *slot, bus_data_t *bus) bus->last_digin++; } if (bus->last_digin < 31) { - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[16].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[16].data), 0, "ppmc.%d.din.estop.in", bus->busnum); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[16].data_not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[16].data_not), 0, "ppmc.%d.din.estop.in-not", bus->busnum); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[17].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[17].data), 0, "ppmc.%d.din.fault.in", bus->busnum); if (retval != 0) { return retval; } - retval = hal_pin_bit_newf(HAL_OUT, &(slot->digin[17].data_not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->digin[17].data_not), 0, "ppmc.%d.din.fault.in-not", bus->busnum); if (retval != 0) { return retval; @@ -1848,36 +1845,34 @@ static int export_PPMC_digout(slot_data_t *slot, bus_data_t *bus) } for ( n = 0 ; n < 8 ; n++ ) { /* export pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(slot->digout[n].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(slot->digout[n].data), 0, "ppmc.%d.dout.%02d.out", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } /* export parameter for inversion */ - retval = hal_param_bit_newf(HAL_RW, &(slot->digout[n].invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(slot->digout[n].invert), 0, "ppmc.%d.dout.%02d.invert", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } - slot->digout[n].invert = 0; /* increment number to prepare for next output */ bus->last_digout++; } /* export pin for E-Stop control */ if (bus->last_digout < 15) { // only on first DIO board rtapi_print_msg(RTAPI_MSG_INFO, "PPMC: master DIO at # %d\n",bus->last_digout); - retval = hal_pin_bit_newf(HAL_IN, &(slot->digout[8].data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(slot->digout[8].data), 0, "ppmc.%d.dout.Estop.out", bus->busnum); if (retval != 0) { return retval; } /* export parameter for inversion */ - retval = hal_param_bit_newf(HAL_RW, &(slot->digout[8].invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(slot->digout[8].invert), 0, "ppmc.%d.dout.Estop.invert", bus->busnum); if (retval != 0) { return retval; } - slot->digout[8].invert = 0; add_wr_funct(write_PPMC_digouts, slot, block(DIO_DOUTA, DIO_ESTOP_OUT)); rtapi_print_msg(RTAPI_MSG_INFO, "PPMC: exporting as MASTER D Out\n"); } @@ -1907,59 +1902,54 @@ static int export_USC_stepgen(slot_data_t *slot, bus_data_t *bus) return -1; } /* export params that apply to all four stepgens */ - retval = hal_param_u32_newf(HAL_RW, &(slot->stepgen->setup_time_ns), comp_id, + /* 10uS default setup time */ + retval = hal_param_new_ui32(comp_id, HAL_RW, &(slot->stepgen->setup_time_ns), 10000, "ppmc.%d.stepgen.%02d-%02d.setup-time-ns", bus->busnum, bus->last_stepgen, bus->last_stepgen+3); if (retval != 0) { return retval; } - /* 10uS default setup time */ - slot->stepgen->setup_time_ns = 10000; - retval = hal_param_u32_newf(HAL_RW, &(slot->stepgen->pulse_width_ns), comp_id, + /* 4uS default pulse width */ + retval = hal_param_new_ui32(comp_id, HAL_RW, &(slot->stepgen->pulse_width_ns), 4000, "ppmc.%d.stepgen.%02d-%02d.pulse-width-ns", bus->busnum, bus->last_stepgen, bus->last_stepgen+3); if (retval != 0) { return retval; } - /* 4uS default pulse width */ - slot->stepgen->pulse_width_ns = 4000; - retval = hal_param_u32_newf(HAL_RW, &(slot->stepgen->pulse_space_ns), comp_id, + /* 4uS default pulse spacing */ + retval = hal_param_new_ui32(comp_id, HAL_RW, &(slot->stepgen->pulse_space_ns), 4000, "ppmc.%d.stepgen.%02d-%02d.pulse-space-min-ns", bus->busnum, bus->last_stepgen, bus->last_stepgen+3); if (retval != 0) { return retval; } - /* 4uS default pulse spacing */ - slot->stepgen->pulse_space_ns = 4000; /* export per-stepgen pins and params */ for ( n = 0 ; n < 4 ; n++ ) { /* pointer to the stepgen struct */ sg = &(slot->stepgen->sg[n]); /* enable pin */ - retval = hal_pin_bit_newf(HAL_IN, &(sg->enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(sg->enable), 0, "ppmc.%d.stepgen.%02d.enable", bus->busnum, bus->last_stepgen); if (retval != 0) { return retval; } /* velocity command pin */ - retval = hal_pin_float_newf(HAL_IN, &(sg->vel), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(sg->vel), 0.0, "ppmc.%d.stepgen.%02d.velocity", bus->busnum, bus->last_stepgen); if (retval != 0) { return retval; } /* velocity scaling parameter */ - retval = hal_param_float_newf(HAL_RW, &(sg->scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(sg->scale), 1.0, "ppmc.%d.stepgen.%02d.scale", bus->busnum, bus->last_stepgen); if (retval != 0) { return retval; } - sg->scale = 1.0; /* maximum velocity parameter */ - retval = hal_param_float_newf(HAL_RW, &(sg->max_vel), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(sg->max_vel), 0.0, "ppmc.%d.stepgen.%02d.max-vel", bus->busnum, bus->last_stepgen); if (retval != 0) { return retval; } - sg->max_vel = 0.0; /* actual frequency parameter */ - retval = hal_param_float_newf(HAL_RO, &(sg->freq), comp_id, + retval = hal_param_new_real(comp_id, HAL_RO, &(sg->freq), 0.0, "ppmc.%d.stepgen.%02d.freq", bus->busnum, bus->last_stepgen); if (retval != 0) { return retval; @@ -1989,63 +1979,57 @@ static int export_UPC_pwmgen(slot_data_t *slot, bus_data_t *bus) return -1; } /* export params that apply to all four pwmgens */ - retval = hal_param_float_newf(HAL_RW, &(slot->pwmgen->freq), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(slot->pwmgen->freq), 0.0, "ppmc.%d.pwm.%02d-%02d.freq", bus->busnum, bus->last_pwmgen, bus->last_pwmgen+3); if (retval != 0) { return retval; } - /* set initial value for param */ - slot->pwmgen->freq = 0.0; /* export per-pwmgen pins and params, and set initial values */ for ( n = 0 ; n < 4 ; n++ ) { /* pointer to the pwmgen struct */ pg = &(slot->pwmgen->pg[n]); /* enable pin */ - retval = hal_pin_bit_newf(HAL_IN, &(pg->enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(pg->enable), 0, "ppmc.%d.pwm.%02d.enable", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } /* value command pin */ - retval = hal_pin_float_newf(HAL_IN, &(pg->value), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(pg->value), 0.0, "ppmc.%d.pwm.%02d.value", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } /* output scaling parameter */ - retval = hal_param_float_newf(HAL_RW, &(pg->scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(pg->scale), 1.0, "ppmc.%d.pwm.%02d.scale", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } - pg->scale = 1.0; /* maximum duty cycle parameter */ - retval = hal_param_float_newf(HAL_RW, &(pg->max_dc), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(pg->max_dc), 1.0, "ppmc.%d.pwm.%02d.max-dc", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } - pg->max_dc = 1.0; /* minimum duty cycle parameter */ - retval = hal_param_float_newf(HAL_RW, &(pg->min_dc), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(pg->min_dc), 0.0, "ppmc.%d.pwm.%02d.min-dc", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } - pg->min_dc = 0.0; /* actual duty cycle parameter */ - retval = hal_param_float_newf(HAL_RO, &(pg->duty_cycle), comp_id, + retval = hal_param_new_real(comp_id, HAL_RO, &(pg->duty_cycle), 0.0, "ppmc.%d.pwm.%02d.duty-cycle", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } /* bootstrap mode parameter */ - retval = hal_param_bit_newf(HAL_RW, &(pg->bootstrap), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(pg->bootstrap), 0, "ppmc.%d.pwm.%02d.bootstrap", bus->busnum, bus->last_pwmgen); if (retval != 0) { return retval; } - pg->bootstrap = 0; pg->boot_state = 0; pg->old_enable = 0; /* increment number to prepare for next output */ @@ -2076,18 +2060,17 @@ static int export_PPMC_DAC(slot_data_t *slot, bus_data_t *bus) /* pointer to the DAC struct */ pg = &(slot->DAC->pg[n]); /* value command pin */ - retval = hal_pin_float_newf(HAL_IN, &(pg->value), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(pg->value), 0.0, "ppmc.%d.DAC.%02d.value", bus->busnum, bus->last_DAC); if (retval != 0) { return retval; } /* output scaling parameter */ - retval = hal_param_float_newf(HAL_RW, &(pg->scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(pg->scale), 1.0, "ppmc.%d.DAC.%02d.scale", bus->busnum, bus->last_DAC); if (retval != 0) { return retval; } - pg->scale = 1.0; /* increment number to prepare for next output */ bus->last_DAC++; } @@ -2184,36 +2167,36 @@ static int export_encoders(slot_data_t *slot, bus_data_t *bus) } for ( n = 0 ; n < 4 ; n++ ) { /* scale input parameter */ - retval = hal_param_float_newf(HAL_RW, &(slot->encoder[n].scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(slot->encoder[n].scale), 1.0, "ppmc.%d.encoder.%02d.scale", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; } /* scaled encoder position */ - retval = hal_pin_float_newf(HAL_OUT, &(slot->encoder[n].position), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(slot->encoder[n].position), 0.0, "ppmc.%d.encoder.%02d.position", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; } /* raw encoder position */ - retval = hal_pin_s32_newf(HAL_OUT, &(slot->encoder[n].count), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(slot->encoder[n].count), 0, "ppmc.%d.encoder.%02d.count", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; } /* raw encoder delta */ - retval = hal_pin_s32_newf(HAL_OUT, &(slot->encoder[n].delta), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(slot->encoder[n].delta), 0, "ppmc.%d.encoder.%02d.delta", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; } /* encoder index bit */ - retval = hal_pin_bit_newf(HAL_OUT, &(slot->encoder[n].index), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(slot->encoder[n].index), 0, "ppmc.%d.encoder.%02d.index", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; } - retval = hal_pin_float_newf(HAL_OUT, &(slot->encoder[n].vel), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(slot->encoder[n].vel), 0.0, "ppmc.%d.encoder.%02d.velocity",bus->busnum,bus->last_encoder); if (retval != 0) { return retval; @@ -2222,7 +2205,7 @@ static int export_encoders(slot_data_t *slot, bus_data_t *bus) /* encoder index enable bit */ /* if the ver of the board firmware is >= 2 then the board supports this function, so export the pin */ - retval = hal_pin_bit_newf(HAL_IO, &(slot->encoder[n].index_enable), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IO, &(slot->encoder[n].index_enable), 0, "ppmc.%d.encoder.%02d.index-enable", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; @@ -2230,7 +2213,7 @@ static int export_encoders(slot_data_t *slot, bus_data_t *bus) if (slot->use_timestamp) { /* encoder time stamp function / velocity estimation */ /* only implemented on latest UPC right now */ - retval = hal_param_float_newf(HAL_RW, &(slot->encoder[n].min_speed), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(slot->encoder[n].min_speed), 0.0, "ppmc.%d.encoder.%02d.min-speed-estimate", bus->busnum, bus->last_encoder); if (retval != 0) { return retval; @@ -2276,18 +2259,17 @@ static int export_extra_dac(slot_data_t *slot, bus_data_t *bus) /* pointer to the DAC struct */ pg = &(slot->extra->dac); /* value command pin */ - retval = hal_pin_float_newf(HAL_IN, &(pg->value), comp_id, + retval = hal_pin_new_real(comp_id, HAL_IN, &(pg->value), 0.0, "ppmc.%d.DAC8.%02d.value", bus->busnum, bus->last_extraDAC); if (retval != 0) { return retval; } /* output scaling parameter */ - retval = hal_param_float_newf(HAL_RW, &(pg->scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(pg->scale), 1.0, "ppmc.%d.DAC8.%02d.scale", bus->busnum, bus->last_extraDAC); if (retval != 0) { return retval; } - pg->scale = 1.0; /* increment number to prepare for next output */ bus->last_extraDAC++; add_wr_funct(write_extraDAC, slot, block(UxC_EXTRA, UxC_EXTRA)); @@ -2340,18 +2322,17 @@ static int export_extra_dout(slot_data_t *slot, bus_data_t *bus) for ( n = 0 ; n < 8 ; n++ ) { pg = &(slot->extra->douts[n]); /* export pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(pg->data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_IN, &(pg->data), 0, "ppmc.%d.dout.%02d.out", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } /* export parameter for inversion */ - retval = hal_param_bit_newf(HAL_RW, &(pg->invert), comp_id, + retval = hal_param_new_bool(comp_id, HAL_RW, &(pg->invert), 0, "ppmc.%d.dout.%02d.invert", bus->busnum, bus->last_digout); if (retval != 0) { return retval; } - pg->invert = 0; /* increment number to prepare for next output */ bus->last_digout++; } diff --git a/src/hal/drivers/hal_skeleton.c b/src/hal/drivers/hal_skeleton.c index 17774929e11..2496f066152 100644 --- a/src/hal/drivers/hal_skeleton.c +++ b/src/hal/drivers/hal_skeleton.c @@ -109,7 +109,7 @@ RTAPI_MP_STRING(cfg, "config string"); */ */ typedef struct { - hal_u32_t *data_out; /* ptrs for output */ + hal_uint_t data_out; /* ptrs for output */ } skeleton_t; /* pointer to array of skeleton_t structs in shared memory, 1 per port */ @@ -161,8 +161,8 @@ int rtapi_app_main(void) } /* STEP 3: export the pin(s) */ - retval = hal_pin_u32_newf(HAL_IN, &(port_data_array->data_out), - comp_id, "skeleton.%d.pin-%02d-out", n, 1); + retval = hal_pin_new_ui32(comp_id, HAL_IN, &(port_data_array->data_out), + 0, "skeleton.%d.pin-%02d-out", n, 1); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "SKELETON: ERROR: port %d var export failed with err=%i\n", n, @@ -202,7 +202,7 @@ static void write_port(void *arg, long period) unsigned char outdata; port = arg; - outdata = *(port->data_out) & 0xFF; + outdata = hal_get_ui32(port->data_out) & 0xFF; /* write it to the hardware */ rtapi_outb(outdata, 0x378); } diff --git a/src/hal/drivers/hal_speaker.c b/src/hal/drivers/hal_speaker.c index bf3fa84e97d..c4e30db1abd 100644 --- a/src/hal/drivers/hal_speaker.c +++ b/src/hal/drivers/hal_speaker.c @@ -98,7 +98,7 @@ RTAPI_MP_STRING(cfg, "config string"); */ */ typedef struct { - hal_bit_t *signals[8]; + hal_bool_t signals[8]; uint8_t last; } speaker_t; @@ -125,7 +125,7 @@ static void write_port(void *arg, long period) port = arg; for(i=0; i<8; i++) { - if(*(port->signals[i])) v = v | (1<signals[i])) v = v | (1<signals[i]), - comp_id, "speaker.%d.pin-%02d-out", n, i); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(port_data_array->signals[i]), + 0, "speaker.%d.pin-%02d-out", n, i); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "SPEAKER: ERROR: port %d var export failed with err=%i\n", n, diff --git a/src/hal/drivers/hal_stg.c b/src/hal/drivers/hal_stg.c index ec0357883de..95d2c5c1766 100644 --- a/src/hal/drivers/hal_stg.c +++ b/src/hal/drivers/hal_stg.c @@ -161,33 +161,33 @@ RTAPI_MP_STRING(dio, "dio config string - expects something like IIOO"); ************************************************************************/ typedef struct { - hal_bit_t *data; /* basic pin for input or output */ + hal_bool_t data; /* basic pin for input or output */ union { - hal_bit_t *not; /* pin for inverted data (input only) */ - hal_bit_t invert; /* param for inversion (output only) */ + hal_bool_t not; /* pin for inverted data (input only) */ + hal_bool_t invert; /* param for inversion (output only) */ } io; } io_pin; typedef struct { /* counter data */ - hal_s32_t *count[MAX_CHANS]; /* captured binary count value */ - hal_s32_t offset[MAX_CHANS]; /* offset to hold latched position from index pulse */ - hal_float_t *pos[MAX_CHANS]; /* scaled position (floating point) */ - hal_float_t pos_scale[MAX_CHANS]; /* parameter: scaling factor for pos */ - hal_bit_t *index_enable[MAX_CHANS]; /* pins for index homing */ - hal_bit_t *index_latch[MAX_CHANS]; /* value of the index latch for the axis */ + hal_sint_t count[MAX_CHANS]; /* captured binary count value */ + rtapi_s32 offset[MAX_CHANS]; /* offset to hold latched position from index pulse */ + hal_real_t pos[MAX_CHANS]; /* scaled position (floating point) */ + hal_real_t pos_scale[MAX_CHANS]; /* parameter: scaling factor for pos */ + hal_bool_t index_enable[MAX_CHANS]; /* pins for index homing */ + hal_bool_t index_latch[MAX_CHANS]; /* value of the index latch for the axis */ // hal_s32_t check_index[MAX_CHANS]; /* internal marker for two stage index pulse check */ - hal_bit_t *index_polarity[MAX_CHANS]; /* Polarity of index pulse */ + hal_bool_t index_polarity[MAX_CHANS]; /* Polarity of index pulse */ /* dac data */ - hal_float_t *dac_value[MAX_CHANS]; /* value to be written to dac */ - hal_float_t dac_offset[MAX_CHANS]; /* offset value for DAC */ - hal_float_t dac_gain[MAX_CHANS]; /* gain to be applied */ + hal_real_t dac_value[MAX_CHANS]; /* value to be written to dac */ + hal_real_t dac_offset[MAX_CHANS]; /* offset value for DAC */ + hal_real_t dac_gain[MAX_CHANS]; /* gain to be applied */ /* adc data */ - hal_float_t *adc_value[MAX_CHANS]; /* value to be read from adc */ - hal_float_t adc_offset[MAX_CHANS]; /* offset value for ADC */ - hal_float_t adc_gain[MAX_CHANS]; /* gain to be applied */ + hal_real_t adc_value[MAX_CHANS]; /* value to be read from adc */ + hal_real_t adc_offset[MAX_CHANS]; /* offset value for ADC */ + hal_real_t adc_gain[MAX_CHANS]; /* gain to be applied */ int adc_current_chan; /* holds the currently converting channel */ /* dio data */ @@ -357,23 +357,23 @@ int rtapi_app_main(void) return -1; } /* init counter */ - *(stg_driver->count[n]) = 0; + hal_set_si32(stg_driver->count[n], 0); stg_driver->offset[n] = 0; - *(stg_driver->pos[n]) = 0.0; + hal_set_real(stg_driver->pos[n], 0.0); /* By default the index pulse is not processed/used */ - *(stg_driver->index_enable[n]) = 0; + hal_set_bool(stg_driver->index_enable[n], 0); /* Default polarity for the index pulse is active high */ if( stg_driver->model == 1 ) { - *(stg_driver->index_polarity[n]) = 1; + hal_set_bool(stg_driver->index_polarity[n], 1); } /* Default value for the index latch output is false */ - *(stg_driver->index_latch[n]) = 0; + hal_set_bool(stg_driver->index_latch[n], 0); - stg_driver->pos_scale[n] = 1.0; + hal_set_real(stg_driver->pos_scale[n], 1.0); /* init counter chip */ stg_counter_init(n); @@ -386,9 +386,9 @@ int rtapi_app_main(void) return -1; } /* init counter */ - *(stg_driver->dac_value[n]) = 0; - stg_driver->dac_offset[n] = 0.0; - stg_driver->dac_gain[n] = 1.0; + hal_set_real(stg_driver->dac_value[n], 0); + hal_set_real(stg_driver->dac_offset[n], 0.0); + hal_set_real(stg_driver->dac_gain[n], 1.0); /* init dac chip */ stg_dac_init(n); @@ -401,9 +401,9 @@ int rtapi_app_main(void) return -1; } /* init counter */ - *(stg_driver->adc_value[n]) = 0; - stg_driver->adc_offset[n] = 0.0; - stg_driver->adc_gain[n] = 1.0; + hal_set_real(stg_driver->adc_value[n], 0); + hal_set_real(stg_driver->adc_offset[n], 0.0); + hal_set_real(stg_driver->adc_gain[n], 1.0); stg_driver->adc_current_chan = -1; /* notify that no conversion has been started yet */ @@ -521,15 +521,15 @@ static void stg_counter_capture(void *arg, long period) if (stg1_get_index_pulse_latch(arg, n)) { - *(stg->index_latch[n]) = 1; + hal_set_bool(stg->index_latch[n], 1); - if ( *(stg->index_enable[n]) == 1 ) + if (hal_get_bool(stg->index_enable[n])) { // read the value without latching, latching was done on index // remember this as an offset, it will be substracted from nominal stg->offset[n] = stg_counter_read(n); /* set index-enable false, so outside knows we found the index, and reset the position */ - *(stg->index_enable[n]) = 0; + hal_set_bool(stg->index_enable[n], 0); /* msg = rtapi_get_msg_level(); @@ -542,7 +542,7 @@ static void stg_counter_capture(void *arg, long period) * pair is selected */ } } else { - *(stg->index_latch[n]) = 0; + hal_set_bool(stg->index_latch[n], 0); } } @@ -555,7 +555,7 @@ static void stg_counter_capture(void *arg, long period) // Set IDLEN for( mask = 0, n = 0; n < num_chan; n++ ) { - if( *(stg->index_enable[n]) == 1 ) + if(hal_get_bool(stg->index_enable[n])) { mask |= ( 1<index_latch[n]) = 1; + hal_set_bool(stg->index_latch[n], 1); - if ( *(stg->index_enable[n]) == 1 ) + if (hal_get_bool(stg->index_enable[n])) { // read the value without latching, latching was done on index // remember this as an offset, it will be substracted from nominal stg->offset[n] = stg_counter_read(n); /* set index-enable false, so outside knows we found the index, and reset the position */ - *(stg->index_enable[n]) = 0; + hal_set_bool(stg->index_enable[n], 0); /* msg = rtapi_get_msg_level(); @@ -591,7 +591,7 @@ static void stg_counter_capture(void *arg, long period) /* NOP, no action needed, since all index latches will be clearer for the next iteration anyway */ } } else { - *(stg->index_latch[n]) = 0; + hal_set_bool(stg->index_latch[n], 0); } } // Reset all latches @@ -606,17 +606,17 @@ static void stg_counter_capture(void *arg, long period) /* capture raw counts to latches */ stg_counter_latch(n); /* read raw count, and substract the offset (determined by indexed homing) */ - *(stg->count[n]) = stg_counter_read(n) - stg->offset[n]; + hal_set_si32(stg->count[n], stg_counter_read(n) - stg->offset[n]); /* make sure scale isn't zero or tiny to avoid divide error */ - if (stg->pos_scale[n] < 0.0) { - if (stg->pos_scale[n] > -EPSILON) - stg->pos_scale[n] = -1.0; + if (hal_get_real(stg->pos_scale[n]) < 0.0) { + if (hal_get_real(stg->pos_scale[n]) > -EPSILON) + hal_set_real(stg->pos_scale[n], -1.0); } else { - if (stg->pos_scale[n] < EPSILON) - stg->pos_scale[n] = 1.0; + if (hal_get_real(stg->pos_scale[n]) < EPSILON) + hal_set_real(stg->pos_scale[n], 1.0); } /* scale count to make floating point position */ - *(stg->pos[n]) = *(stg->count[n]) / stg->pos_scale[n]; + hal_set_real(stg->pos[n], hal_get_si32(stg->count[n]) / hal_get_real(stg->pos_scale[n])); } /* done */ return; @@ -682,7 +682,7 @@ static void stg_dacs_write(void *arg, long period) stg=arg; for (i=0;i < num_chan; i++) { /* scale the voltage to be written based on offset and gain */ - volts = (*(stg->dac_value[i]) - stg->dac_offset[i]) * stg->dac_gain[i]; + volts = (hal_get_real(stg->dac_value[i]) - hal_get_real(stg->dac_offset[i])) * hal_get_real(stg->dac_gain[i]); /* clamp the scaled voltage value to the -10V to 10V output range of the STG */ if (volts < -10.0) volts = -10.0; @@ -731,7 +731,7 @@ static void stg_adcs_read(void *arg, long period) /* we should have the conversion done for adc_num_chan */ ncounts = stg_adc_read(stg,i); volts = ncounts * 10.0 / 4096; - *(stg->adc_value[i]) = volts * stg->adc_gain[i] - stg->adc_offset[i]; + hal_set_real(stg->adc_value[i], volts * hal_get_real(stg->adc_gain[i]) - hal_get_real(stg->adc_offset[i])); } /* if adc_num_chan < 0, it's the first time this routine runs thus we don't have any ready data, we simply start the next conversion */ @@ -757,12 +757,12 @@ static void split_input(unsigned char data, io_pin *dest, int num) for (b = 0 ; b < num ; b++ ) { if ( data & mask ) { /* input high, which means FALSE (active low) */ - *(dest->data) = 0; - *(dest->io.not) = 1; + hal_set_bool(dest->data, 0); + hal_set_bool(dest->io.not, 1); } else { /* input low, which means TRUE */ - *(dest->data) = 1; - *(dest->io.not) = 0; + hal_set_bool(dest->data, 1); + hal_set_bool(dest->io.not, 0); } mask <<= 1; dest++; @@ -782,12 +782,12 @@ unsigned char build_output(io_pin *src, int num) /* assemble output byte for data port from 'num' source variables */ for (b = 0; b < num; b++) { /* get the data, add to output byte */ - if ( *(src->data) ) { - if ( !(src->io.invert) ) { + if ( hal_get_bool(src->data) ) { + if ( !hal_get_bool(src->io.invert) ) { data |= mask; } } else { - if ( (src->io.invert) ) { + if ( hal_get_bool(src->io.invert) ) { data |= mask; } } @@ -1054,7 +1054,7 @@ static void stg1_select_index_axis(void *arg, unsigned int channel) /* * Set polarity to low active if that is requested */ - if( *(stg->index_polarity[channel]) == 0 ) + if( hal_get_bool(stg->index_polarity[channel]) == 0 ) { byPol = 0; } @@ -1436,34 +1436,34 @@ static int export_counter(int num, stg_struct *addr) rtapi_set_msg_level( STG_MSG_LEVEL ); /* export pin for counts captured by update() */ - retval = hal_pin_s32_newf(HAL_OUT, &addr->count[num], - comp_id, "stg.%d.counts", num); + retval = hal_pin_new_si32(comp_id, HAL_OUT, &addr->count[num], + 0, "stg.%d.counts", num); if (retval != 0) { return retval; } /* export pin for scaled position captured by update() */ - retval = hal_pin_float_newf(HAL_OUT, &addr->pos[num], - comp_id, "stg.%d.position", num); + retval = hal_pin_new_real(comp_id, HAL_OUT, &addr->pos[num], + 0.0, "stg.%d.position", num); if (retval != 0) { return retval; } /* export parameter for scaling */ - retval = hal_param_float_newf(HAL_RW, &addr->pos_scale[num], - comp_id, "stg.%d.position-scale", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->pos_scale[num], + 1.0, "stg.%d.position-scale", num); if (retval != 0) { return retval; } /* export pin for index homing */ - retval = hal_pin_bit_newf(HAL_IO, &addr->index_enable[num], - comp_id, "stg.%d.index-enable", num); + retval = hal_pin_new_bool(comp_id, HAL_IO, &addr->index_enable[num], + 0, "stg.%d.index-enable", num); if (retval != 0) { return retval; } /* export pin for reading the index latch */ - retval = hal_pin_bit_newf(HAL_OUT, &addr->index_latch[num], - comp_id, "stg.%d.index-latch", num); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &addr->index_latch[num], + 0, "stg.%d.index-latch", num); if (retval != 0) { return retval; } @@ -1476,8 +1476,8 @@ static int export_counter(int num, stg_struct *addr) if( addr->model == 1 ) { /* export read only HAL pin for index pulse polarity */ - retval = hal_pin_bit_newf(HAL_IN, &addr->index_polarity[num], - comp_id, "stg.%d.index-polarity", num); + retval = hal_pin_new_bool(comp_id, HAL_IN, &addr->index_polarity[num], + 0, "stg.%d.index-polarity", num); if (retval != 0) { return retval; @@ -1502,20 +1502,20 @@ static int export_dac(int num, stg_struct *addr) rtapi_set_msg_level( STG_MSG_LEVEL ); /* export pin for voltage received by the board() */ - retval = hal_pin_float_newf(HAL_IN, &addr->dac_value[num], - comp_id, "stg.%d.dac-value", num); + retval = hal_pin_new_real(comp_id, HAL_IN, &addr->dac_value[num], + 0.0, "stg.%d.dac-value", num); if (retval != 0) { return retval; } /* export parameter for offset */ - retval = hal_param_float_newf(HAL_RW, &addr->dac_offset[num], - comp_id, "stg.%d.dac-offset", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->dac_offset[num], + 0.0, "stg.%d.dac-offset", num); if (retval != 0) { return retval; } /* export parameter for gain */ - retval = hal_param_float_newf(HAL_RW, &addr->dac_gain[num], - comp_id, "stg.%d.dac-gain", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->dac_gain[num], + 1.0, "stg.%d.dac-gain", num); if (retval != 0) { return retval; } @@ -1537,20 +1537,20 @@ static int export_adc(int num, stg_struct *addr) rtapi_set_msg_level( STG_MSG_LEVEL ); /* export pin for voltage received by the board() */ - retval = hal_pin_float_newf(HAL_OUT, &addr->adc_value[num], - comp_id, "stg.%d.adc-value", num); + retval = hal_pin_new_real(comp_id, HAL_OUT, &addr->adc_value[num], + 0.0, "stg.%d.adc-value", num); if (retval != 0) { return retval; } /* export parameter for offset */ - retval = hal_param_float_newf(HAL_RW, &addr->adc_offset[num], - comp_id, "stg.%d.adc-offset", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->adc_offset[num], + 0.0, "stg.%d.adc-offset", num); if (retval != 0) { return retval; } /* export parameter for gain */ - retval = hal_param_float_newf(HAL_RW, &addr->adc_gain[num], - comp_id, "stg.%d.adc-gain", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->adc_gain[num], + 1.0, "stg.%d.adc-gain", num); if (retval != 0) { return retval; } @@ -1599,17 +1599,14 @@ static int export_input_pin(int pinnum, io_pin * pin) rtapi_set_msg_level( STG_MSG_LEVEL ); /* export read only HAL pin for input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->data), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->data), 0, "stg.in-%02d", pinnum); if (retval != 0) { return retval; } /* export additional pin for inverted input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->io.not), comp_id, + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->io.not), 1, "stg.in-%02d-not", pinnum); - /* initialize HAL pins */ - *(pin->data) = 0; - *(pin->io.not) = 1; /* restore saved message level */ rtapi_set_msg_level(msg); @@ -1632,18 +1629,14 @@ static int export_output_pin(int pinnum, io_pin * pin) rtapi_set_msg_level( STG_MSG_LEVEL ); /* export read only HAL pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(pin->data), - comp_id, "stg.out-%02d", pinnum); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(pin->data), + 0, "stg.out-%02d", pinnum); if (retval != 0) { return retval; } /* export parameter for polarity */ - retval = hal_param_bit_newf(HAL_RW, &(pin->io.invert), - comp_id, "stg.out-%02d-invert", pinnum); - /* initialize HAL pin and param */ - *(pin->data) = 0; - pin->io.invert = 0; - + retval = hal_param_new_bool(comp_id, HAL_RW, &(pin->io.invert), + 0, "stg.out-%02d-invert", pinnum); /* restore saved message level */ rtapi_set_msg_level(msg); diff --git a/src/hal/drivers/hal_tiro.c b/src/hal/drivers/hal_tiro.c index e79dedde708..eba33782d3a 100644 --- a/src/hal/drivers/hal_tiro.c +++ b/src/hal/drivers/hal_tiro.c @@ -85,9 +85,9 @@ RTAPI_MP_INT(num_chan, "number of channels"); /* this structure contains the runtime data for a single counter */ typedef struct { - hal_s32_t *count; /* captured binary count value */ - hal_float_t *pos; /* scaled position (floating point) */ - hal_float_t pos_scale; /* parameter: scaling factor for pos */ + hal_sint_t count; /* captured binary count value */ + hal_real_t pos; /* scaled position (floating point) */ + hal_real_t pos_scale; /* parameter: scaling factor for pos */ } counter_t; /* pointer to array of counter_t structs in shmem, 1 per counter */ @@ -149,9 +149,9 @@ int rtapi_app_main(void) return -1; } /* init counter */ - *(counter_array[n].count) = 0; - *(counter_array[n].pos) = 0.0; - counter_array[n].pos_scale = 1.0; + hal_set_si32(counter_array[n].count, 0); + hal_set_real(counter_array[n].pos, 0.0); + hal_set_real(counter_array[n].pos_scale, 1.0); /* init counter chip */ LS7166Init(n); @@ -189,9 +189,9 @@ static void capture(void *arg, long period) for (n = 0; n < num_chan; n++) { /* capture raw counts to latches */ - *(cntr->count) = LS7166Read(n); + hal_set_si32(cntr->count, LS7166Read(n)); /* scale count to make floating point position */ - *(cntr->pos) = *(cntr->count) * cntr->pos_scale; + hal_set_real(cntr->pos, hal_get_si32(cntr->count) * hal_get_real(cntr->pos_scale)); /* move on to next channel */ cntr++; } @@ -254,19 +254,19 @@ static int export_counter(int num, counter_t * addr) rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pin for counts captured by update() */ - retval = hal_pin_s32_newf(HAL_OUT, &(addr->count), comp_id, + retval = hal_pin_new_si32(comp_id, HAL_OUT, &(addr->count), 0, "tiro.%d.counts", num); if (retval != 0) { return retval; } /* export pin for scaled position captured by update() */ - retval = hal_pin_float_newf(HAL_OUT, &(addr->pos), comp_id, + retval = hal_pin_new_real(comp_id, HAL_OUT, &(addr->pos), 0.0, "tiro.%d.position", num); if (retval != 0) { return retval; } /* export parameter for scaling */ - retval = hal_param_float_newf(HAL_RW, &(addr->pos_scale), comp_id, + retval = hal_param_new_real(comp_id, HAL_RW, &(addr->pos_scale), 1.0, "tiro.%d.position-scale", num); if (retval != 0) { return retval; diff --git a/src/hal/drivers/hal_vti.c b/src/hal/drivers/hal_vti.c index 9252335b2a4..7f5cb7c7ce8 100644 --- a/src/hal/drivers/hal_vti.c +++ b/src/hal/drivers/hal_vti.c @@ -174,28 +174,29 @@ RTAPI_MP_STRING(dio, "dio config string - expects something like IOiooi"); ************************************************************************/ typedef struct { - hal_bit_t *data; /* basic pin for input or output */ + hal_bool_t data; /* basic pin for input or output */ union { - hal_bit_t *not; /* pin for inverted data (input only) */ - hal_bit_t invert; /* param for inversion (output only) */ + hal_bool_t not; /* pin for inverted data (input only) */ + hal_bool_t invert; /* param for inversion (output only) */ } io; } io_pin; typedef struct { /* counter data */ - hal_s32_t *count[MAX_CHANS]; /* captured binary count value */ - hal_float_t *pos[MAX_CHANS]; /* scaled position (floating point) */ - hal_float_t pos_scale[MAX_CHANS]; /* parameter: scaling factor for pos */ + hal_sint_t count[MAX_CHANS]; /* captured binary count value */ + hal_real_t pos[MAX_CHANS]; /* scaled position (floating point) */ + hal_real_t pos_scale[MAX_CHANS]; /* parameter: scaling factor for pos */ /* dac data */ - hal_float_t *dac_value[MAX_CHANS]; /* value to be written to dac */ - hal_float_t dac_offset[MAX_CHANS]; /* offset value for DAC */ - hal_float_t dac_gain[MAX_CHANS]; /* gain to be applied */ + hal_real_t dac_value[MAX_CHANS]; /* value to be written to dac */ + hal_real_t dac_offset[MAX_CHANS]; /* offset value for DAC */ + hal_real_t dac_gain[MAX_CHANS]; /* gain to be applied */ /* adc data */ - hal_float_t *adc_value[MAX_CHANS]; /* value to be read from adc */ - hal_float_t adc_offset[MAX_CHANS]; /* offset value for ADC */ - hal_float_t adc_gain[MAX_CHANS]; /* gain to be applied */ + // These adc thingies are apparently unused... + hal_real_t adc_value[MAX_CHANS]; /* value to be read from adc */ + hal_real_t adc_offset[MAX_CHANS]; /* offset value for ADC */ + hal_real_t adc_gain[MAX_CHANS]; /* gain to be applied */ int adc_current_chan; /* holds the currently converting channel */ /* dio data */ @@ -219,7 +220,7 @@ volatile struct ip *ip = NULL; static int comp_id; /* component ID */ static int outpinnum = 0, inputpinnum = 0; static int diocount = 0; -static hal_s32_t enc_counts[MAX_CHANS]; +static rtapi_s32 enc_counts[MAX_CHANS]; /*********************************************************************** * LOCAL FUNCTION DECLARATIONS * @@ -456,15 +457,15 @@ static void vti_counter_capture(void *arg, long period) vti = arg; for (i = 0; i < num_chan; i++) { /* capture raw counts to latches */ - *(vti->count[i]) = vti_counter_read(i); + hal_set_si32(vti->count[i], vti_counter_read(i)); /* scale count to make floating point position */ - if (vti->pos_scale[i] < 0.0) { - if (vti->pos_scale[i] > -EPSILON) - vti->pos_scale[i] = -1.0;} + if (hal_get_real(vti->pos_scale[i]) < 0.0) { + if (hal_get_real(vti->pos_scale[i]) > -EPSILON) + hal_set_real(vti->pos_scale[i], -1.0);} else { - if (vti->pos_scale[i] < EPSILON) - vti->pos_scale[i] = 1.0; } - *(vti->pos[i]) = *(vti->count[i]) / vti->pos_scale[i]; + if (hal_get_real(vti->pos_scale[i]) < EPSILON) + hal_set_real(vti->pos_scale[i], 1.0); } + hal_set_real(vti->pos[i], hal_get_si32(vti->count[i]) / hal_get_real(vti->pos_scale[i])); } /* done */ } @@ -481,7 +482,7 @@ static void vti_dacs_write(void *arg, long period) for (i = 0; i < num_chan; i++) { /* scale the voltage to be written based on offset and gain */ volts = - (*(vti->dac_value[i]) - vti->dac_offset[i]) * vti->dac_gain[i]; + (hal_get_real(vti->dac_value[i]) - hal_get_real(vti->dac_offset[i])) * hal_get_real(vti->dac_gain[i]); /* compute the value for the DAC, the extra - in there is vti specific */ ncounts = ((volts / 10) * 0x7fff) + 0x8000; @@ -510,12 +511,12 @@ static void split_input(unsigned char data, io_pin * dest, int num) for (b = 0; b < num; b++) { if (data & mask) { /* input high, which means FALSE (active low) */ - *(dest->data) = 0; - *(dest->io.not) = 1; + hal_set_bool(dest->data, 0); + hal_set_bool(dest->io.not, 1); } else { /* input low, which means TRUE */ - *(dest->data) = 1; - *(dest->io.not) = 0; + hal_set_bool(dest->data, 1); + hal_set_bool(dest->io.not, 0); } mask <<= 1; dest++; @@ -534,12 +535,12 @@ unsigned char build_output(io_pin * src, int num) /* assemble output byte for data port from 'num' source variables */ for (b = 0; b < num; b++) { /* get the data, add to output byte */ - if (*(src->data)) { - if (!(src->io.invert)) { + if (hal_get_bool(src->data)) { + if (!hal_get_bool(src->io.invert)) { data |= mask; } } else { - if ((src->io.invert)) { + if (hal_get_bool(src->io.invert)) { data |= mask; } } @@ -622,9 +623,9 @@ static int vti_counter_init(int counters) return -1; } /* init counter */ - *(vti_driver->count[i]) = 0; - *(vti_driver->pos[i]) = 0.0; - vti_driver->pos_scale[i] = 1.0; + hal_set_si32(vti_driver->count[i], 0); + hal_set_real(vti_driver->pos[i], 0.0); + hal_set_real(vti_driver->pos_scale[i], 1.0); } return 0; } @@ -648,9 +649,9 @@ static int vti_dac_init(int channels) return -1; } /* init counter */ - *(vti_driver->dac_value[i]) = 0; - vti_driver->dac_offset[i] = 0.0; - vti_driver->dac_gain[i] = 1.0; + hal_set_real(vti_driver->dac_value[i], 0); + hal_set_real(vti_driver->dac_offset[i], 0.0); + hal_set_real(vti_driver->dac_gain[i], 1.0); vti_dac_write(i, DAC_ZERO_VOLTS); } return 0; @@ -848,20 +849,20 @@ static int export_counter(int num, vti_struct * addr) msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pin for counts captured by update() */ - retval = hal_pin_s32_newf(HAL_OUT, &addr->count[num], - comp_id, "vti.%d.counts", num); + retval = hal_pin_new_si32(comp_id, HAL_OUT, &addr->count[num], + 0, "vti.%d.counts", num); if (retval != 0) { return retval; } /* export pin for scaled position captured by update() */ - retval = hal_pin_float_newf(HAL_OUT, &addr->pos[num], - comp_id, "vti.%d.position", num); + retval = hal_pin_new_real(comp_id, HAL_OUT, &addr->pos[num], + 0.0, "vti.%d.position", num); if (retval != 0) { return retval; } /* export parameter for scaling */ - retval = hal_param_float_newf(HAL_RW, &addr->pos_scale[num], - comp_id, "vti.%d.position-scale", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->pos_scale[num], + 1.0, "vti.%d.position-scale", num); if (retval != 0) { return retval; } @@ -880,20 +881,20 @@ static int export_dac(int num, vti_struct * addr) msg = rtapi_get_msg_level(); rtapi_set_msg_level(RTAPI_MSG_WARN); /* export pin for voltage received by the board() */ - retval = hal_pin_float_newf(HAL_IN, &addr->dac_value[num], - comp_id, "vti.%d.dac-value", num); + retval = hal_pin_new_real(comp_id, HAL_IN, &addr->dac_value[num], + 0.0, "vti.%d.dac-value", num); if (retval != 0) { return retval; } /* export parameter for offset */ - retval = hal_param_float_newf(HAL_RW, &addr->dac_offset[num], - comp_id, "vti.%d.dac-offset", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->dac_offset[num], + 0.0, "vti.%d.dac-offset", num); if (retval != 0) { return retval; } /* export parameter for gain */ - retval = hal_param_float_newf(HAL_RW, &addr->dac_gain[num], - comp_id, "vti.%d.dac-gain", num); + retval = hal_param_new_real(comp_id, HAL_RW, &addr->dac_gain[num], + 1.0, "vti.%d.dac-gain", num); if (retval != 0) { return retval; } @@ -943,31 +944,25 @@ static int export_input_pin(int pinnum, io_pin * pin) { int retval; /* export read only HAL pin for input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->data), - comp_id, "vti.in-%02d", pinnum); + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->data), + 0, "vti.in-%02d", pinnum); if (retval != 0) return retval; /* export additional pin for inverted input data */ - retval = hal_pin_bit_newf(HAL_OUT, &(pin->io.not), - comp_id, "vti.in-%02d-not", pinnum); - /* initialize HAL pins */ - *(pin->data) = 0; - *(pin->io.not) = 1; + retval = hal_pin_new_bool(comp_id, HAL_OUT, &(pin->io.not), + 1, "vti.in-%02d-not", pinnum); return retval; } static int export_output_pin(int pinnum, io_pin * pin) { int retval; /* export read only HAL pin for output data */ - retval = hal_pin_bit_newf(HAL_IN, &(pin->data), - comp_id, "vti.out-%02d", pinnum); + retval = hal_pin_new_bool(comp_id, HAL_IN, &(pin->data), + 0, "vti.out-%02d", pinnum); if (retval != 0) return retval; /* export parameter for polarity */ - retval = hal_param_bit_newf(HAL_RW, &(pin->io.invert), - comp_id, "vti.out-%02d-invert", pinnum); - /* initialize HAL pin and param */ - *(pin->data) = 0; - pin->io.invert = 0; + retval = hal_param_new_bool(comp_id, HAL_RW, &(pin->io.invert), + 0, "vti.out-%02d-invert", pinnum); return retval; } diff --git a/src/hal/drivers/mesa-hostmot2/abs_encoder.c b/src/hal/drivers/mesa-hostmot2/abs_encoder.c index 8a8c96bf910..b4a5707aac1 100644 --- a/src/hal/drivers/mesa-hostmot2/abs_encoder.c +++ b/src/hal/drivers/mesa-hostmot2/abs_encoder.c @@ -141,7 +141,7 @@ int hm2_absenc_setup_ssi(hostmot2_t *hm2, hm2_sserial_remote_t *chan, if ( hm2_sserial_create_pins(hm2, chan)) return -EINVAL; - chan->params = hal_malloc(sizeof(hm2_sserial_params_t)); + chan->params = hal_malloc(sizeof(*chan->params)); hm2->absenc.clock_frequency = md->clock_freq; hm2->absenc.ssi_version = md->version; @@ -159,8 +159,8 @@ int hm2_absenc_setup_ssi(hostmot2_t *hm2, hm2_sserial_remote_t *chan, chan->data_written[0] = 0; - chan->params->float_param = 500; - chan->params->timer_num = 0; + hal_set_real(chan->params->param.r, 500); + hal_set_ui32(chan->params->timer_num, 0); return 0; } @@ -169,7 +169,7 @@ int hm2_absenc_setup_biss(hostmot2_t *hm2, hm2_sserial_remote_t *chan, if ( hm2_sserial_create_pins(hm2, chan)) return -EINVAL; - chan->params = hal_malloc(sizeof(hm2_sserial_params_t)); + chan->params = hal_malloc(sizeof(*chan->params)); hm2->absenc.clock_frequency = md->clock_freq; hm2->absenc.biss_version = md->version; @@ -186,8 +186,8 @@ int hm2_absenc_setup_biss(hostmot2_t *hm2, hm2_sserial_remote_t *chan, + (3 * md->register_stride); chan->data_written[0] = 0; - chan->params->float_param = 500; - chan->params->timer_num = 0; + hal_set_real(chan->params->param.r, 500); + hal_set_ui32(chan->params->timer_num, 0); return 0; } @@ -196,7 +196,7 @@ int hm2_absenc_setup_fabs(hostmot2_t *hm2, hm2_sserial_remote_t *chan, if ( hm2_sserial_create_pins(hm2, chan)) return -EINVAL; - chan->params = hal_malloc(sizeof(hm2_sserial_params_t)); + chan->params = hal_malloc(sizeof(*chan->params)); hm2->absenc.clock_frequency = md->clock_freq; hm2->absenc.fanuc_version = md->version; @@ -219,15 +219,13 @@ int hm2_absenc_setup_fabs(hostmot2_t *hm2, hm2_sserial_remote_t *chan, + (5 * md->register_stride); chan->data_written[0] = 0; - if (hal_param_u32_newf(HAL_RW, &(chan->params->u32_param), - hm2->llio->comp_id,"%s.filter", - chan->name)){ + if (hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(chan->params->param.u), + 0, "%s.filter", chan->name)){ HM2_ERR("error adding param fanuc param 2, aborting\n"); return -EINVAL; } - chan->params->float_param = 1024.0; - chan->params->u32_param = 0xF; - chan->params->timer_num = 0; + hal_set_ui32(chan->params->param.u, 0xF); + hal_set_ui32(chan->params->timer_num, 0); return 0; } @@ -355,7 +353,7 @@ int hm2_absenc_parse_format(hm2_sserial_remote_t *chan, hm2_absenc_format_t *de int hm2_absenc_parse_md(hostmot2_t *hm2, int md_index) { hm2_module_descriptor_t *md = &hm2->md[md_index]; - hm2_absenc_format_t *def = 0; + hm2_absenc_format_t *def = NULL; struct rtapi_list_head *ptr; int index; @@ -444,24 +442,21 @@ int hm2_absenc_parse_md(hostmot2_t *hm2, int md_index) { } // Set up the common pins - if (hal_pin_bit_newf(HAL_OUT, &(chan->params->error), - hm2->llio->comp_id,"%s.data-invalid", - chan->name)){ + if (hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(chan->params->error), + 0, "%s.data-invalid", chan->name)){ HM2_ERR("error adding %s over-run pin, aborting\n", chan->name); return -EINVAL; } // And Params - if (hal_param_float_newf(HAL_RW, &(chan->params->float_param), - hm2->llio->comp_id,"%s.frequency-khz", - chan->name)){ + if (hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(chan->params->param.r), + 0.0, "%s.frequency-khz", chan->name)){ HM2_ERR("error adding frequency param for %s, aborting\n", chan->name); return -EINVAL; } - if (hal_param_u32_newf(HAL_RW, &(chan->params->timer_num), - hm2->llio->comp_id,"%s.timer-number", - chan->name)){ + if (hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(chan->params->timer_num), + 0, "%s.timer-number", chan->name)){ HM2_ERR("error adding %s timer number param, aborting\n", chan->name); return -EINVAL; @@ -528,7 +523,7 @@ void hm2_absenc_process_tram_read(hostmot2_t *hm2, long period) { HM2_ERR("Data transmission not complete on channel %s read." " You may need to change the timing of %s. This " "warning will not repeat\n", chan->name, - (chan->params->timer_num == 0) ? + (hal_get_ui32(chan->params->timer_num) == 0) ? "the trigger function" : "the hm2dpll timer"); err_tag[i] = 1; } @@ -540,14 +535,14 @@ void hm2_absenc_process_tram_read(hostmot2_t *hm2, long period) { if (err_count[i] < 5001) { ++err_count[i]; } else { - *chan->params->error = 1; + hal_set_bool(chan->params->error, 1); } } else { if (err_count[i] > 4950){ --err_count[i]; } else { - *chan->params->error = 0; + hal_set_bool(chan->params->error, 0); } } } @@ -562,14 +557,15 @@ void hm2_absenc_write(hostmot2_t *hm2){ for (i = 0; i < hm2->absenc.num_chans; i ++) { hm2_sserial_remote_t *chan = &hm2->absenc.chans[i]; + rtapi_u32 timer_num = hal_get_ui32(chan->params->timer_num); switch (chan->myinst){ case HM2_GTAG_SSI: - if (chan->params->timer_num > 4) chan->params->timer_num = 4; - buff = ((rtapi_u32)(0x10000 * (chan->params->float_param * 1000 + if (timer_num > 4) timer_num = hal_set_ui32(chan->params->timer_num, 4); + buff = ((rtapi_u32)(0x10000 * (hal_get_real(chan->params->param.r) * 1000 / hm2->absenc.clock_frequency))) << 16 - | chan->params->timer_num << 12 - | (chan->params->timer_num == 0) << 8 - | (chan->params->timer_num != 0) << 9 + | timer_num << 12 + | (timer_num == 0) << 8 + | (timer_num != 0) << 9 | chan->num_read_bits; if (buff != chan->data_written[0]){ hm2->llio->write(hm2->llio, @@ -581,8 +577,8 @@ void hm2_absenc_write(hostmot2_t *hm2){ break; case HM2_GTAG_BISS: - if (chan->params->timer_num > 4) chan->params->timer_num = 4; - dds = ((rtapi_u32)(0x10000 * (chan->params->float_param * 1000 + if (timer_num > 4) timer_num = hal_set_ui32(chan->params->timer_num, 4); + dds = ((rtapi_u32)(0x10000 * (hal_get_real(chan->params->param.r) * 1000 / hm2->absenc.clock_frequency))); filt = 0x8000/dds; // RX data filter set to 1/2 a clock period if (filt > 63) { filt = 63; } // bound so we dont splatter into adjacent fields @@ -598,9 +594,9 @@ void hm2_absenc_write(hostmot2_t *hm2){ sizeof(rtapi_u32)); chan->data_written[0] = buff; } - buff2 = chan->params->timer_num << 12 - | (chan->params->timer_num == 0) << 8 - | (chan->params->timer_num != 0) << 9; + buff2 = timer_num << 12 + | (timer_num == 0) << 8 + | (timer_num != 0) << 9; if (buff2 != chan->data_written[1]){ hm2->llio->write(hm2->llio, chan->rw_addr[2], @@ -611,16 +607,15 @@ void hm2_absenc_write(hostmot2_t *hm2){ break; case HM2_GTAG_FABS: - if (chan->params->timer_num > 4) chan->params->timer_num = 4; - if (chan->params->u32_param > 15) chan->params->u32_param = 15; - buff3 = chan->num_read_bits << 24 + if (timer_num > 4) timer_num = hal_set_ui32(chan->params->timer_num, 4); + if (hal_get_ui32(chan->params->param.u) > 15) hal_set_ui32(chan->params->param.u, 15); + buff3 = (chan->num_read_bits << 24) | (rtapi_u32)(8.0e-6 * hm2->absenc.clock_frequency) << 14; - buff2 = chan->params->u32_param << 28 - | ((rtapi_u32)(0x100000 * (chan->params->float_param * 1000 - / hm2->absenc.clock_frequency))); - buff = chan->params->timer_num << 12 - | (chan->params->timer_num == 0) << 8 - | (chan->params->timer_num != 0) << 9 + buff2 = (hal_get_ui32(chan->params->param.u) << 28) + | ((rtapi_u32)(0x100000ull * 1024000ull / hm2->absenc.clock_frequency)); + buff = (timer_num << 12) + | (timer_num == 0) << 8 + | (timer_num != 0) << 9 | (buff3 != chan->data_written[2] || buff2 != chan->data_written[1]) << 7; if (buff != chan->data_written[0]){ // if necessary this will set the write flag, then next time through diff --git a/src/hal/drivers/mesa-hostmot2/bspi.c b/src/hal/drivers/mesa-hostmot2/bspi.c index e1c504ce691..64d3fbae2f7 100644 --- a/src/hal/drivers/mesa-hostmot2/bspi.c +++ b/src/hal/drivers/mesa-hostmot2/bspi.c @@ -75,8 +75,7 @@ int hm2_bspi_parse_md(hostmot2_t *hm2, int md_index) hm2->bspi.num_instances = hm2->config.num_bspis; } - hm2->bspi.instance = (hm2_bspi_instance_t *)hal_malloc(hm2->bspi.num_instances - * sizeof(hm2_bspi_instance_t)); + hm2->bspi.instance = hal_malloc(hm2->bspi.num_instances * sizeof(*hm2->bspi.instance)); if (hm2->bspi.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; diff --git a/src/hal/drivers/mesa-hostmot2/dpll.c b/src/hal/drivers/mesa-hostmot2/dpll.c index a8149bc8380..6b1377e0be7 100644 --- a/src/hal/drivers/mesa-hostmot2/dpll.c +++ b/src/hal/drivers/mesa-hostmot2/dpll.c @@ -70,46 +70,39 @@ int hm2_dpll_parse_md(hostmot2_t *hm2, int md_index) { hm2->dpll.hm2_dpll_sync_addr = md->base_address + 6 * md->register_stride; // export to HAL - hm2->dpll.pins = hal_malloc(sizeof(hm2_dpll_pins_t)); - - r = hal_pin_float_newf(HAL_IN, &(hm2->dpll.pins->time1_us), - hm2->llio->comp_id, "%s.dpll.01.timer-us", hm2->llio->name); - r += hal_pin_float_newf(HAL_IN, &(hm2->dpll.pins->time2_us), - hm2->llio->comp_id, "%s.dpll.02.timer-us", hm2->llio->name); - r += hal_pin_float_newf(HAL_IN, &(hm2->dpll.pins->time3_us), - hm2->llio->comp_id, "%s.dpll.03.timer-us", hm2->llio->name); - r += hal_pin_float_newf(HAL_IN, &(hm2->dpll.pins->time4_us), - hm2->llio->comp_id, "%s.dpll.04.timer-us", hm2->llio->name); - r += hal_pin_float_newf(HAL_IN, &(hm2->dpll.pins->base_freq), - hm2->llio->comp_id, "%s.dpll.base-freq-khz", hm2->llio->name); - r += hal_pin_float_newf(HAL_OUT, &(hm2->dpll.pins->phase_error), - hm2->llio->comp_id, "%s.dpll.phase-error-us", hm2->llio->name); - r += hal_pin_u32_newf(HAL_IN, &(hm2->dpll.pins->time_const), - hm2->llio->comp_id, "%s.dpll.time-const", hm2->llio->name); - r += hal_pin_u32_newf(HAL_IN, &(hm2->dpll.pins->plimit), - hm2->llio->comp_id, "%s.dpll.plimit", hm2->llio->name); - r += hal_pin_u32_newf(HAL_OUT, &(hm2->dpll.pins->ddssize), - hm2->llio->comp_id, "%s.dpll.ddsize", hm2->llio->name); - r += hal_pin_u32_newf(HAL_OUT, &(hm2->dpll.pins->prescale), - hm2->llio->comp_id, "%s.dpll.prescale", hm2->llio->name); - if (r < 0) { - HM2_ERR("error adding hm2_dpll timer pins, Aborting\n"); - goto fail0; - } - *hm2->dpll.pins->time1_us = 100.0; - *hm2->dpll.pins->time2_us = 100.0; - *hm2->dpll.pins->time3_us = 100.0; - *hm2->dpll.pins->time4_us = 100.0; - *hm2->dpll.pins->prescale = 1; - *hm2->dpll.pins->base_freq = -1; // An indication it needs init - /* This value is an empirical compromise between insensitivity to + hm2->dpll.pins = hal_malloc(sizeof(*hm2->dpll.pins)); + + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->time1_us), + 100.0, "%s.dpll.01.timer-us", hm2->llio->name); + r += hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->time2_us), + 100.0, "%s.dpll.02.timer-us", hm2->llio->name); + r += hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->time3_us), + 100.0, "%s.dpll.03.timer-us", hm2->llio->name); + r += hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->time4_us), + 100.0, "%s.dpll.04.timer-us", hm2->llio->name); + // init=-1 is an indication it needs init + r += hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->base_freq), + -1.0, "%s.dpll.base-freq-khz", hm2->llio->name); + r += hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->dpll.pins->phase_error), + 0.0, "%s.dpll.phase-error-us", hm2->llio->name); + /* The init value is an empirical compromise between insensitivity to * single-cycle variations (larger values) and being resilient to changes to * the Linux CLOCK_MONOTONIC timescale, which can instantly change by up to * +-500ppm from its nominal value, usually by timekeeping software like ntp * and ntpdate. */ - *hm2->dpll.pins->time_const = 2000; - *hm2->dpll.pins->plimit = 0x400000; + r += hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->time_const), + 2000, "%s.dpll.time-const", hm2->llio->name); + r += hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->dpll.pins->plimit), + 0x400000, "%s.dpll.plimit", hm2->llio->name); + r += hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(hm2->dpll.pins->ddssize), + 0, "%s.dpll.ddsize", hm2->llio->name); + r += hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(hm2->dpll.pins->prescale), + 1, "%s.dpll.prescale", hm2->llio->name); + if (r < 0) { + HM2_ERR("error adding hm2_dpll timer pins, Aborting\n"); + goto fail0; + } r = hm2_register_tram_read_region(hm2, hm2->dpll.hm2_dpll_sync_addr, sizeof(rtapi_u32), &hm2->dpll.hm2_dpll_sync_reg); @@ -138,9 +131,9 @@ void hm2_dpll_process_tram_read(hostmot2_t *hm2, long period){ pins = hm2->dpll.pins; - *pins->phase_error = (rtapi_s32)*hm2->dpll.hm2_dpll_sync_reg - * (period / 4294967296000.00) ; - *pins->ddssize = *hm2->dpll.control_reg1_read & 0xFF; + hal_set_real(pins->phase_error, (rtapi_s32)*hm2->dpll.hm2_dpll_sync_reg + * (period / 4294967296000.00)); + hal_set_ui32(pins->ddssize, *hm2->dpll.control_reg1_read & 0xFF); } void hm2_dpll_write(hostmot2_t *hm2, long period) { @@ -163,18 +156,21 @@ void hm2_dpll_write(hostmot2_t *hm2, long period) { pins = hm2->dpll.pins; - if (*pins->base_freq < 0 ) { - *pins->base_freq = 1000.0/period_us; + rtapi_real base_freq = hal_get_real(pins->base_freq); + if (base_freq < 0 ) { + base_freq = hal_set_real(pins->base_freq, 1000.0/period_us); } - *pins->prescale = (0x40000000LL * hm2->dpll.clock_frequency) - / ((1LL << *pins->ddssize) * *pins->base_freq * 1000.0); + rtapi_u32 ddssize = hal_get_ui32(pins->ddssize); + rtapi_u32 prescale = (0x40000000LL * hm2->dpll.clock_frequency) + / ((1LL << ddssize) * base_freq * 1000.0); - if (*pins->prescale < 1) *pins->prescale = 1; + if (prescale < 1) prescale = 1; + hal_set_ui32(pins->prescale, prescale); - buff = (rtapi_u32)((*pins->base_freq * 1000.0 - * (1LL << *pins->ddssize) - * *pins->prescale) + buff = (rtapi_u32)((base_freq * 1000.0 + * (1LL << ddssize) + * prescale) / hm2->dpll.clock_frequency); if (buff != hm2->dpll.base_rate_written){ @@ -184,8 +180,8 @@ void hm2_dpll_write(hostmot2_t *hm2, long period) { sizeof(rtapi_u32)); hm2->dpll.base_rate_written= buff; } - buff = (rtapi_u32)(*pins->prescale << 24 - | *pins->plimit); + buff = (rtapi_u32)(prescale << 24 + | hal_get_ui32(pins->plimit)); if (buff != hm2->dpll.control_reg0_written){ hm2->llio->write(hm2->llio, hm2->dpll.control_reg0_addr, @@ -193,7 +189,7 @@ void hm2_dpll_write(hostmot2_t *hm2, long period) { sizeof(rtapi_u32)); hm2->dpll.control_reg0_written= buff; } - buff = (rtapi_u32)(*pins->time_const << 16); + buff = (rtapi_u32)(hal_get_ui32(pins->time_const) << 16); if (buff != hm2->dpll.control_reg1_written){ hm2->llio->write(hm2->llio, hm2->dpll.control_reg1_addr, @@ -201,8 +197,8 @@ void hm2_dpll_write(hostmot2_t *hm2, long period) { sizeof(rtapi_u32)); hm2->dpll.control_reg1_written= buff; } - buff = (rtapi_u32)((-*hm2->dpll.pins->time2_us / period_us) * 0x10000) << 16 - | ((rtapi_u32)((-*hm2->dpll.pins->time1_us / period_us) * 0x10000) & 0xFFFF); + buff = (rtapi_u32)((-hal_get_real(hm2->dpll.pins->time2_us) / period_us) * 0x10000) << 16 + | ((rtapi_u32)((-hal_get_real(hm2->dpll.pins->time1_us) / period_us) * 0x10000) & 0xFFFF); if (buff != hm2->dpll.timer_12_written){ hm2->llio->write(hm2->llio, hm2->dpll.timer_12_addr, @@ -210,8 +206,8 @@ void hm2_dpll_write(hostmot2_t *hm2, long period) { sizeof(rtapi_u32)); hm2->dpll.timer_12_written = buff; } - buff = (rtapi_u32)((-*hm2->dpll.pins->time4_us / period_us) * 0x10000) << 16 - | ((rtapi_u32)((-*hm2->dpll.pins->time3_us / period_us) * 0x10000) & 0xFFFF); + buff = (rtapi_u32)((-hal_get_real(hm2->dpll.pins->time4_us) / period_us) * 0x10000) << 16 + | ((rtapi_u32)((-hal_get_real(hm2->dpll.pins->time3_us) / period_us) * 0x10000) & 0xFFFF); if (buff != hm2->dpll.timer_34_written){ hm2->llio->write(hm2->llio, hm2->dpll.timer_34_addr, diff --git a/src/hal/drivers/mesa-hostmot2/encoder.c b/src/hal/drivers/mesa-hostmot2/encoder.c index 31badad5e82..4ed8ad05e22 100644 --- a/src/hal/drivers/mesa-hostmot2/encoder.c +++ b/src/hal/drivers/mesa-hostmot2/encoder.c @@ -53,10 +53,10 @@ static void hm2_encoder_update_control_register(hostmot2_t *hm2) { int latch_polarity; for (i = 0; i < hm2->encoder.num_instances; i ++) { hm2_encoder_instance_t *e = &hm2->encoder.instance[i]; - int index_enable = *e->hal.pin.index_enable; + int index_enable = hal_get_bool(e->hal.pin.index_enable); if (hm2->encoder.firmware_supports_probe) { - latch_enable = *e->hal.pin.latch_enable; - latch_polarity = *e->hal.pin.latch_polarity; + latch_enable = hal_get_bool(e->hal.pin.latch_enable); + latch_polarity = hal_get_bool(e->hal.pin.latch_polarity); } else { latch_enable = 0; @@ -90,31 +90,31 @@ static void hm2_encoder_update_control_register(hostmot2_t *hm2) { do_flag( &hm2->encoder.control_reg[i], - e->hal.param.index_invert, + hal_get_bool(e->hal.param.index_invert), HM2_ENCODER_INDEX_POLARITY ); do_flag( &hm2->encoder.control_reg[i], - e->hal.param.index_mask, + hal_get_bool(e->hal.param.index_mask), HM2_ENCODER_INDEX_MASK ); do_flag( &hm2->encoder.control_reg[i], - e->hal.param.index_mask_invert, + hal_get_bool(e->hal.param.index_mask_invert), HM2_ENCODER_INDEX_MASK_POLARITY ); do_flag( &hm2->encoder.control_reg[i], - e->hal.param.counter_mode, + hal_get_bool(e->hal.param.counter_mode), HM2_ENCODER_COUNTER_MODE ); do_flag( &hm2->encoder.control_reg[i], - e->hal.param.filter, + hal_get_bool(e->hal.param.filter), HM2_ENCODER_FILTER ); do_flag( @@ -132,55 +132,55 @@ static void hm2_encoder_read_control_register(hostmot2_t *hm2) { for (i = 0; i < hm2->encoder.num_instances; i ++) { hm2_encoder_instance_t *e = &hm2->encoder.instance[i]; - if (*e->hal.pin.quadrature_error_enable) { + if (hal_get_bool(e->hal.pin.quadrature_error_enable)) { e->reset_quadrature_error=0; if(!e->prev_quadrature_error_enable){ // detect rising edge of pin quadrature_error_enable e->reset_quadrature_error = 1; hm2_encoder_force_write(hm2); } int state = ((hm2->encoder.read_control_reg[i] & HM2_ENCODER_CONTROL_MASK) & HM2_ENCODER_QUADRATURE_ERROR) && e->prev_quadrature_error_enable; - if ((*e->hal.pin.quadrature_error == 0) && state) { + if ((hal_get_bool(e->hal.pin.quadrature_error) == 0) && state) { HM2_ERR("Encoder %d: quadrature count error\n", i); } - *e->hal.pin.quadrature_error = (hal_bit_t) state; + hal_set_bool(e->hal.pin.quadrature_error, state); } else{ // quadrature error disabled, set reported error to 0 - *e->hal.pin.quadrature_error = 0; + hal_set_bool(e->hal.pin.quadrature_error, 0); } - e->prev_quadrature_error_enable = *e->hal.pin.quadrature_error_enable; + e->prev_quadrature_error_enable = hal_get_bool(e->hal.pin.quadrature_error_enable); - *e->hal.pin.input_a = hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_A; - *e->hal.pin.input_b = hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_B; - *e->hal.pin.input_idx = hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_INDEX; + hal_set_bool(e->hal.pin.input_a, hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_A); + hal_set_bool(e->hal.pin.input_b, hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_B); + hal_set_bool(e->hal.pin.input_idx, hm2->encoder.read_control_reg[i] & HM2_ENCODER_INPUT_INDEX); } } static void hm2_encoder_set_filter_rate_and_skew(hostmot2_t *hm2) { - rtapi_u32 filter_rate = hm2->encoder.clock_frequency/(*hm2->encoder.hal->pin.sample_frequency); + rtapi_u32 filter_rate = hm2->encoder.clock_frequency/hal_get_ui32(hm2->encoder.hal->pin.sample_frequency); if (filter_rate == 1) { filter_rate = 0xFFF; } else { filter_rate -= 2; } - *hm2->encoder.hal->pin.sample_frequency = hm2->encoder.clock_frequency/(filter_rate + 2); + hal_set_ui32(hm2->encoder.hal->pin.sample_frequency, hm2->encoder.clock_frequency/(filter_rate + 2)); HM2_DBG("Setting encoder QFilterRate to %d\n", filter_rate); if (hm2->encoder.has_skew) { rtapi_u32 divisor = (1e9/hm2->encoder.clock_frequency); // Unsigned division rounding for integers. This is only valid for unsigned division - rtapi_u32 skew = (*hm2->encoder.hal->pin.skew + (divisor/2))/divisor; + rtapi_u32 skew = (hal_get_ui32(hm2->encoder.hal->pin.skew) + (divisor/2))/divisor; if (skew > 15) { skew = 15; } HM2_DBG("Setting mux encoder skew to %d\n", skew); filter_rate |= (skew & 0xF) << 28; - *hm2->encoder.hal->pin.skew = skew*(1e9/hm2->encoder.clock_frequency); - hm2->encoder.written_skew = *hm2->encoder.hal->pin.skew; + hal_set_ui32(hm2->encoder.hal->pin.skew, skew*(1e9/hm2->encoder.clock_frequency)); + hm2->encoder.written_skew = hal_get_ui32(hm2->encoder.hal->pin.skew); } hm2->llio->write(hm2->llio, hm2->encoder.filter_rate_addr, &filter_rate, sizeof(rtapi_u32)); - hm2->encoder.written_sample_frequency = *hm2->encoder.hal->pin.sample_frequency; + hm2->encoder.written_sample_frequency = hal_get_ui32(hm2->encoder.hal->pin.sample_frequency); } static void hm2_encoder_set_dpll_timer_if_present(hostmot2_t *hm2) { @@ -209,16 +209,16 @@ void hm2_encoder_write(hostmot2_t *hm2) { } } - if (*hm2->encoder.hal->pin.sample_frequency != hm2->encoder.written_sample_frequency) { + if (hal_get_ui32(hm2->encoder.hal->pin.sample_frequency) != hm2->encoder.written_sample_frequency) { goto force_write; } if (hm2->encoder.has_skew) { - if (*hm2->encoder.hal->pin.skew != hm2->encoder.written_skew) { + if (hal_get_ui32(hm2->encoder.hal->pin.skew) != hm2->encoder.written_skew) { goto force_write; } } - if (*hm2->encoder.hal->pin.hires_timestamp != hm2->encoder.written_hires_timestamp) { // + if (hal_get_bool(hm2->encoder.hal->pin.hires_timestamp) != hm2->encoder.written_hires_timestamp) { // // Set the Timestamp Divisor Register // // We want the timestamp to count as quickly as possible, so we get the @@ -255,7 +255,7 @@ void hm2_encoder_write(hostmot2_t *hm2) { // seconds_per_clock = 1 / rate = (TSDiv+2) / ClockLow // - if (*hm2->encoder.hal->pin.hires_timestamp == 0) { + if (hal_get_bool(hm2->encoder.hal->pin.hires_timestamp) == 0) { hm2->encoder.timestamp_div_reg = (hm2->encoder.clock_frequency / 2e6) - 2; } else { hm2->encoder.timestamp_div_reg = (hm2->encoder.clock_frequency / 1e7) - 2; @@ -263,12 +263,12 @@ void hm2_encoder_write(hostmot2_t *hm2) { hm2->encoder.seconds_per_tsdiv_clock = (double)(hm2->encoder.timestamp_div_reg + 2) / (double)hm2->encoder.clock_frequency; - hm2->encoder.written_hires_timestamp = *hm2->encoder.hal->pin.hires_timestamp; + hm2->encoder.written_hires_timestamp = hal_get_bool(hm2->encoder.hal->pin.hires_timestamp); goto force_write; } if(hm2->encoder.dpll_timer_num_addr) { - int32_t dpll_timer_num = *hm2->encoder.hal->pin.dpll_timer_num; + int32_t dpll_timer_num = hal_get_si32(hm2->encoder.hal->pin.dpll_timer_num); if(dpll_timer_num < -1 || dpll_timer_num > 4) dpll_timer_num = -1; if(dpll_timer_num == -1) hm2->encoder.desired_dpll_timer_reg = 0; @@ -397,14 +397,14 @@ int hm2_encoder_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->encoder.hal = (hm2_encoder_module_global_t *)hal_malloc(sizeof(hm2_encoder_module_global_t)); + hm2->encoder.hal = hal_malloc(sizeof(*hm2->encoder.hal)); if (hm2->encoder.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - hm2->encoder.instance = (hm2_encoder_instance_t *)hal_malloc(hm2->encoder.num_instances * sizeof(hm2_encoder_instance_t)); + hm2->encoder.instance = hal_malloc(hm2->encoder.num_instances * sizeof(*hm2->encoder.instance)); if (hm2->encoder.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -459,269 +459,248 @@ int hm2_encoder_parse_md(hostmot2_t *hm2, int md_index) { // export the encoders to HAL - // FIXME: r hides the r in enclosing function, and it returns the wrong thing { - int i; - int r; - char name[HAL_NAME_LEN + 1]; - // these hal parameters affect all encoder instances + const char *sfpinname; if (md->gtag == HM2_GTAG_MUXED_ENCODER) { - rtapi_snprintf(name, sizeof(name), "%s.encoder.muxed-sample-frequency", hm2->llio->name); + sfpinname = "encoder.muxed-sample-frequency"; } else { - rtapi_snprintf(name, sizeof(name), "%s.encoder.sample-frequency", hm2->llio->name); + sfpinname = "encoder.sample-frequency"; } - r = hal_pin_u32_new(name, HAL_IN, &(hm2->encoder.hal->pin.sample_frequency), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.hal->pin.sample_frequency), + 0, "%s.%s", hm2->llio->name, sfpinname); if (r < 0) { - HM2_ERR("error adding pin %s, aborting\n", name); + HM2_ERR("error %d adding pin %s.%s, aborting\n", r, hm2->llio->name, sfpinname); goto fail1; } if ((md->gtag == HM2_GTAG_MUXED_ENCODER) && (md->version > 3 )) { // >3 to include modules with probe enable - rtapi_snprintf(name, sizeof(name), "%s.encoder.muxed-skew", hm2->llio->name); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->encoder.hal->pin.skew), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.hal->pin.skew), + 0, "%s.encoder.muxed-skew", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin %s, aborting\n", name); + HM2_ERR("error %d adding pin %s.encoder.muxed-skew, aborting\n", r, hm2->llio->name); goto fail1; } hm2->encoder.has_skew = 1; } if(hm2->encoder.dpll_timer_num_addr) { - r = hal_pin_s32_newf(HAL_IN, &(hm2->encoder.hal->pin.dpll_timer_num), hm2->llio->comp_id, "%s.encoder.timer-number", hm2->llio->name); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.hal->pin.dpll_timer_num), + -1, "%s.encoder.timer-number", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin %s, aborting\n", name); + HM2_ERR("error %d adding pin %s.encoder.timer-number, aborting\n", r, hm2->llio->name); goto fail1; } - *(hm2->encoder.hal->pin.dpll_timer_num) = -1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.hires-timestamp", hm2->llio->name); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.hal->pin.hires_timestamp), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.hal->pin.hires_timestamp), + 0, "%s.encoder.hires-timestamp", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin %s, aborting\n", name); + HM2_ERR("error %d adding pin %s.encoder.hires-timestamp, aborting\n", r, hm2->llio->name); goto fail1; } - for (i = 0; i < hm2->encoder.num_instances; i ++) { + for (int i = 0; i < hm2->encoder.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.rawcounts", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.rawcounts), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.rawcounts), + 0, "%s.encoder.%02d.rawcounts", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.rawcounts', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.rawlatch", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.rawlatch), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.rawlatch), + 0, "%s.encoder.%02d.rawlatch", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.rawlatch', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.count), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.count), + 0, "%s.encoder.%02d.count", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.count', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.count-latched", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.count_latch), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.count_latch), + 0, "%s.encoder.%02d.count-latched", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.count-latched', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.position", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position), + 0.0, "%s.encoder.%02d.position", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.position', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.position-interpolated", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position_interpolated), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position_interpolated), + 0.0, "%s.encoder.%02d.position-interpolated", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.position-interpolated', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.position-latched", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position_latch), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.position_latch), + 0.0, "%s.encoder.%02d.position-latched", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.position-latched', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.velocity", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.velocity), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.velocity), + 0.0, "%s.encoder.%02d.velocity", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.velocity', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.velocity-rpm", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.velocity_rpm), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.velocity_rpm), + 0.0, "%s.encoder.%02d.velocity-rpm", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.velocity-rpm', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.instance[i].hal.pin.reset), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.instance[i].hal.pin.reset), + 0, "%s.encoder.%02d.reset", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.reset', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.index-enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IO, &(hm2->encoder.instance[i].hal.pin.index_enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->encoder.instance[i].hal.pin.index_enable), + 0, "%s.encoder.%02d.index-enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.index-enable', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.no_clear_on_index", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.instance[i].hal.pin.no_clear_on_index), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.instance[i].hal.pin.no_clear_on_index), + 0, "%s.encoder.%02d.no_clear_on_index", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.no_clear_on_index', aborting\n", r, hm2->llio->name, i); goto fail1; } - + if (hm2->encoder.firmware_supports_probe) { - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.probe-enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.instance[i].hal.pin.latch_enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.instance[i].hal.pin.latch_enable), + 0, "%s.encoder.%02d.probe-enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.probe-enable', aborting\n", r, hm2->llio->name, i); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.probe-invert", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.instance[i].hal.pin.latch_polarity), hm2->llio->comp_id); + + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.instance[i].hal.pin.latch_polarity), + 0, "%s.encoder.%02d.probe-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.probe-invert', aborting\n", r, hm2->llio->name, i); goto fail1; } } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.quad-error", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.quadrature_error), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.quadrature_error), + 0, "%s.encoder.%02d.quad-error", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.quad-error', aborting\n", r, hm2->llio->name, i); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.quad-error-enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->encoder.instance[i].hal.pin.quadrature_error_enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->encoder.instance[i].hal.pin.quadrature_error_enable), + 0, "%s.encoder.%02d.quad-error-enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.quad-error-enable', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.input-a", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_a), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_a), + 0, "%s.encoder.%02d.input-a", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.input-a', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.input-b", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_b), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_b), + 0, "%s.encoder.%02d.input-b", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.input-b', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.input-index", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_idx), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->encoder.instance[i].hal.pin.input_idx), + 0, "%s.encoder.%02d.input-index", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.encoder.%02d.input-index', aborting\n", r, hm2->llio->name, i); goto fail1; } // parameters - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.scale", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.scale), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.scale), + 1.0, "%s.encoder.%02d.scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.scale', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.index-invert", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_invert), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_invert), + 0, "%s.encoder.%02d.index-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.index-invert', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.index-mask", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_mask), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_mask), + 0, "%s.encoder.%02d.index-mask", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.index-mask', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.index-mask-invert", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_mask_invert), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.index_mask_invert), + 0, "%s.encoder.%02d.index-mask-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.index-mask-invert', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.counter-mode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.counter_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.counter_mode), + 0, "%s.encoder.%02d.counter-mode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.counter-mode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.filter", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.filter), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.filter), + 1, "%s.encoder.%02d.filter", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.filter', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.encoder.%02d.vel-timeout", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->encoder.instance[i].hal.param.vel_timeout), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->encoder.instance[i].hal.param.vel_timeout), + 0.5, "%s.encoder.%02d.vel-timeout", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.encoder.%02d.vel-timeout', aborting\n", r, hm2->llio->name, i); goto fail1; } - // - // init the hal objects that need it // the things not initialized here will be set by hm2_encoder_tram_init() // - - *hm2->encoder.instance[i].hal.pin.reset = 0; - *hm2->encoder.instance[i].hal.pin.index_enable = 0; - *hm2->encoder.instance[i].hal.pin.no_clear_on_index = 0; - - hm2->encoder.instance[i].hal.param.scale = 1.0; - hm2->encoder.instance[i].hal.param.index_invert = 0; - hm2->encoder.instance[i].hal.param.index_mask = 0; - hm2->encoder.instance[i].hal.param.index_mask_invert = 0; - hm2->encoder.instance[i].hal.param.counter_mode = 0; - hm2->encoder.instance[i].hal.param.filter = 1; - hm2->encoder.instance[i].hal.param.vel_timeout = 0.5; - hm2->encoder.instance[i].state = HM2_ENCODER_STOPPED; - } } - // initialize with hires off and force update + // initialize with hires off and force update // (with somewhat shady trick to force update if set true in halfile) - *hm2->encoder.hal->pin.hires_timestamp = 0; - hm2->encoder.written_hires_timestamp = 666; + hm2->encoder.written_hires_timestamp = 666; if (md->gtag == HM2_GTAG_ENCODER) { - *hm2->encoder.hal->pin.sample_frequency = 25000000; + hal_set_ui32(hm2->encoder.hal->pin.sample_frequency, 25000000); } else { - *hm2->encoder.hal->pin.sample_frequency = 8000000; + hal_set_ui32(hm2->encoder.hal->pin.sample_frequency, 8000000); } return hm2->encoder.num_instances; @@ -749,20 +728,20 @@ void hm2_encoder_tram_init(hostmot2_t *hm2) { count = hm2_encoder_get_reg_count(hm2, i); - *hm2->encoder.instance[i].hal.pin.rawcounts = count; - *hm2->encoder.instance[i].hal.pin.rawlatch = count; + hal_set_si32(hm2->encoder.instance[i].hal.pin.rawcounts, count); + hal_set_si32(hm2->encoder.instance[i].hal.pin.rawlatch, count); hm2->encoder.instance[i].rawcounts_64 = count; hm2->encoder.instance[i].rawlatch_64 = count; - *hm2->encoder.instance[i].hal.pin.count = 0; - *hm2->encoder.instance[i].hal.pin.count_latch = 0; + hal_set_si32(hm2->encoder.instance[i].hal.pin.count, 0); + hal_set_si32(hm2->encoder.instance[i].hal.pin.count_latch, 0); hm2->encoder.instance[i].count_64 = 0; hm2->encoder.instance[i].count_latch_64 = 0; - *hm2->encoder.instance[i].hal.pin.position = 0.0; - *hm2->encoder.instance[i].hal.pin.position_latch = 0.0; - *hm2->encoder.instance[i].hal.pin.velocity = 0.0; - *hm2->encoder.instance[i].hal.pin.velocity_rpm = 0.0; - *hm2->encoder.instance[i].hal.pin.quadrature_error = 0; + hal_set_real(hm2->encoder.instance[i].hal.pin.position, 0.0); + hal_set_real(hm2->encoder.instance[i].hal.pin.position_latch, 0.0); + hal_set_real(hm2->encoder.instance[i].hal.pin.velocity, 0.0); + hal_set_real(hm2->encoder.instance[i].hal.pin.velocity_rpm, 0.0); + hal_set_bool(hm2->encoder.instance[i].hal.pin.quadrature_error, 0); hm2->encoder.instance[i].zero_offset = count; @@ -818,7 +797,7 @@ static void hm2_encoder_instance_update_rawcounts_and_handle_index(hostmot2_t *h reg_count = hm2_encoder_get_reg_count(hm2, instance); e->rawcounts_64 = hal_extend_counter(e->rawcounts_64, reg_count, 16); - *e->hal.pin.rawcounts = (rtapi_s32)e->rawcounts_64; + hal_set_si32(e->hal.pin.rawcounts, (rtapi_s32)e->rawcounts_64); // @@ -840,13 +819,13 @@ static void hm2_encoder_instance_update_rawcounts_and_handle_index(hostmot2_t *h latched_count = (latch_ctrl >> 16) & 0xffff; latched_64 = hal_extend_counter(prev_rawcounts_64, latched_count, 16); - if (!*(e->hal.pin.no_clear_on_index)) { + if (!hal_get_bool(e->hal.pin.no_clear_on_index)) { e->zero_offset_64 = latched_64; e->zero_offset = (rtapi_s32)latched_64; } e->rawlatch_64 = latched_64; - *(e->hal.pin.rawlatch) = (rtapi_s32)latched_64; - *e->hal.pin.index_enable = 0; + hal_set_si32(e->hal.pin.rawlatch, (rtapi_s32)latched_64); + hal_set_bool(e->hal.pin.index_enable, 0); // may need to update interpolated position after index event because // this _may_ happen without a count but its pretty ugly... // *e->hal.pin.count = *e->hal.pin.rawcounts - e->zero_offset; @@ -867,8 +846,8 @@ static void hm2_encoder_instance_update_rawcounts_and_handle_index(hostmot2_t *h latched_64 = hal_extend_counter(prev_rawcounts_64, latched_count, 16); e->rawlatch_64 = latched_64; - *(e->hal.pin.rawlatch) = (rtapi_s32)latched_64; - *e->hal.pin.latch_enable = 0; + hal_set_si32(e->hal.pin.rawlatch, (rtapi_s32)latched_64); + hal_set_bool(e->hal.pin.latch_enable, 0); } } } @@ -913,12 +892,12 @@ static void hm2_encoder_instance_update_position(hostmot2_t *hm2, int instance) // reset count if the user wants us to (by just setting the zero offset to the current rawcounts) // - if (*e->hal.pin.reset) { - e->zero_offset = *e->hal.pin.rawcounts; + if (hal_get_bool(e->hal.pin.reset)) { + e->zero_offset = hal_get_si32(e->hal.pin.rawcounts); e->zero_offset_64 = e->rawcounts_64; - *e->hal.pin.rawlatch = e->zero_offset; + hal_set_si32(e->hal.pin.rawlatch, e->zero_offset); e->rawlatch_64 = e->zero_offset_64; - *e->hal.pin.position_interpolated = *e->hal.pin.position; + hal_set_real(e->hal.pin.position_interpolated, hal_get_real(e->hal.pin.position)); } @@ -930,9 +909,9 @@ static void hm2_encoder_instance_update_position(hostmot2_t *hm2, int instance) // From that we easily compute count and scaled position. // - *e->hal.pin.count = *e->hal.pin.rawcounts - e->zero_offset; + hal_set_si32(e->hal.pin.count, hal_get_si32(e->hal.pin.rawcounts) - e->zero_offset); e->count_64 = e->rawcounts_64 - e->zero_offset_64; - *e->hal.pin.count_latch = *e->hal.pin.rawlatch - e->zero_offset; + hal_set_si32(e->hal.pin.count_latch, hal_get_si32(e->hal.pin.rawlatch) - e->zero_offset); e->count_latch_64 = e->rawlatch_64 - e->zero_offset_64; @@ -942,8 +921,8 @@ static void hm2_encoder_instance_update_position(hostmot2_t *hm2, int instance) // to avoid wrap on high-resolution encoders. // - *e->hal.pin.position = e->count_64 / e->hal.param.scale; - *e->hal.pin.position_latch = e->count_latch_64 / e->hal.param.scale; + hal_set_real(e->hal.pin.position, e->count_64 / hal_get_real(e->hal.param.scale)); + hal_set_real(e->hal.pin.position_latch, e->count_latch_64 / hal_get_real(e->hal.param.scale)); } @@ -960,9 +939,9 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance e = &hm2->encoder.instance[instance]; // sanity check - if (e->hal.param.scale == 0.0) { + if (hal_get_real(e->hal.param.scale) == 0.0) { HM2_ERR("encoder.%02d.scale == 0.0, bogus, setting to 1.0\n", instance); - e->hal.param.scale = 1.0; + hal_set_real(e->hal.param.scale, 1.0); } @@ -985,7 +964,7 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance hm2_encoder_instance_update_rawcounts_and_handle_index(hm2, instance); hm2_encoder_instance_update_position(hm2, instance); - e->prev_event_rawcounts = *e->hal.pin.rawcounts; + e->prev_event_rawcounts = hal_get_si32(e->hal.pin.rawcounts); e->prev_event_reg_timestamp = hm2_encoder_get_reg_timestamp(hm2, instance); e->prev_dS_counts = 0; @@ -1031,31 +1010,31 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance dT_clocks = (time_of_interest - e->prev_event_reg_timestamp) + (e->tsc_num_rollovers << 16); dT_s = (double)dT_clocks * hm2->encoder.seconds_per_tsdiv_clock; - if (dT_s >= e->hal.param.vel_timeout) { - *e->hal.pin.velocity = 0.0; - *e->hal.pin.velocity_rpm = 0.0; - *e->hal.pin.position_interpolated = *e->hal.pin.position; + if (dT_s >= hal_get_real(e->hal.param.vel_timeout)) { + hal_set_real(e->hal.pin.velocity, 0.0); + hal_set_real(e->hal.pin.velocity_rpm, 0.0); + hal_set_real(e->hal.pin.position_interpolated, hal_get_real(e->hal.pin.position)); e->state = HM2_ENCODER_STOPPED; break; } - if ((*e->hal.pin.velocity * e->hal.param.scale) > 0.0) { + if ((hal_get_real(e->hal.pin.velocity) * hal_get_real(e->hal.param.scale)) > 0.0) { dS_counts = 1; } else { dS_counts = -1; } // if no counts, calculate interpolated position - *e->hal.pin.position_interpolated = *e->hal.pin.position + (dT_s * *e->hal.pin.velocity); + hal_set_real(e->hal.pin.position_interpolated, hal_get_real(e->hal.pin.position) + (dT_s * hal_get_real(e->hal.pin.velocity))); - dS_pos_units = dS_counts / e->hal.param.scale; + dS_pos_units = dS_counts / hal_get_real(e->hal.param.scale); // we can calculate velocity only if timestamp changed along with counts if (dT_clocks > 0) { // we know the encoder velocity is not faster than this vel = dS_pos_units / dT_s; - if (fabs(vel) < fabs(*e->hal.pin.velocity)) { - *e->hal.pin.velocity = vel; - *e->hal.pin.velocity_rpm = vel * 60.0; + if (fabs(vel) < fabs(hal_get_real(e->hal.pin.velocity))) { + hal_set_real(e->hal.pin.velocity, vel); + hal_set_real(e->hal.pin.velocity_rpm, vel * 60.0); } } @@ -1076,14 +1055,14 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance hm2_encoder_instance_update_rawcounts_and_handle_index(hm2, instance); hm2_encoder_instance_update_position(hm2, instance); - *e->hal.pin.position_interpolated = *e->hal.pin.position; + hal_set_real(e->hal.pin.position_interpolated, hal_get_real(e->hal.pin.position)); time_of_interest = hm2_encoder_get_reg_timestamp(hm2, instance); if (time_of_interest < e->prev_time_of_interest) { // tsc rollover! e->tsc_num_rollovers ++; } - dS_counts = *e->hal.pin.rawcounts - e->prev_event_rawcounts; + dS_counts = hal_get_si32(e->hal.pin.rawcounts) - e->prev_event_rawcounts; // If we reversed direction and moved exactly one edge, // we can't reliably estimate velocity. The encoder might @@ -1091,24 +1070,24 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance // small dT between adjacent edges, leading to misleadingly // large velocity estimates. So we just call it 0. if ( - (((*e->hal.pin.rawcounts - e->prev_event_rawcounts) == 1) && (e->prev_dS_counts < 0)) - || (((*e->hal.pin.rawcounts - e->prev_event_rawcounts) == -1) && (e->prev_dS_counts > 0)) + (((hal_get_si32(e->hal.pin.rawcounts) - e->prev_event_rawcounts) == 1) && (e->prev_dS_counts < 0)) + || (((hal_get_si32(e->hal.pin.rawcounts) - e->prev_event_rawcounts) == -1) && (e->prev_dS_counts > 0)) ) { - *e->hal.pin.velocity = 0.0; - *e->hal.pin.velocity_rpm = 0.0; - *e->hal.pin.position_interpolated = *e->hal.pin.position; + hal_set_real(e->hal.pin.velocity, 0.0); + hal_set_real(e->hal.pin.velocity_rpm, 0.0); + hal_set_real(e->hal.pin.position_interpolated, hal_get_real(e->hal.pin.position)); } else { dT_clocks = (time_of_interest - e->prev_event_reg_timestamp) + (e->tsc_num_rollovers << 16); dT_s = (double)dT_clocks * hm2->encoder.seconds_per_tsdiv_clock; - dS_pos_units = dS_counts / e->hal.param.scale; + dS_pos_units = dS_counts / hal_get_real(e->hal.param.scale); // we can calculate velocity only if timestamp changed along with counts if (dT_clocks > 0) { // finally time to do Relative-Time Velocity Estimation - *e->hal.pin.velocity = dS_pos_units / dT_s; - *e->hal.pin.velocity_rpm = *e->hal.pin.velocity * 60.0; + hal_set_real(e->hal.pin.velocity, dS_pos_units / dT_s); + hal_set_real(e->hal.pin.velocity_rpm, hal_get_real(e->hal.pin.velocity) * 60.0); } } @@ -1116,7 +1095,7 @@ static void hm2_encoder_instance_process_tram_read(hostmot2_t *hm2, int instance e->prev_dS_counts = dS_counts; - e->prev_event_rawcounts = *e->hal.pin.rawcounts; + e->prev_event_rawcounts = hal_get_si32(e->hal.pin.rawcounts); e->prev_event_reg_timestamp = time_of_interest; e->prev_time_of_interest = time_of_interest; diff --git a/src/hal/drivers/mesa-hostmot2/hm2_7i43.c b/src/hal/drivers/mesa-hostmot2/hm2_7i43.c index 92acf8c39a4..ac5e23fd508 100644 --- a/src/hal/drivers/mesa-hostmot2/hm2_7i43.c +++ b/src/hal/drivers/mesa-hostmot2/hm2_7i43.c @@ -215,7 +215,7 @@ int hm2_7i43_read(hm2_lowlevel_io_t *this, rtapi_u32 addr, void *buffer, int siz if (hm2_7i43_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of read(addr=0x%04x, size=%d)\n", addr, size); - (*this->io_error) = 1; + hal_set_bool(*this->io_error, 1); this->needs_reset = 1; hm2_7i43_epp_clear_timeout(board); return 0; // fail @@ -246,7 +246,7 @@ int hm2_7i43_write(hm2_lowlevel_io_t *this, rtapi_u32 addr, const void *buffer, if (hm2_7i43_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of write(addr=0x%04x, size=%d)\n", addr, size); - (*this->io_error) = 1; + hal_set_bool(*this->io_error, 1); this->needs_reset = 1; hm2_7i43_epp_clear_timeout(board); return 0; diff --git a/src/hal/drivers/mesa-hostmot2/hm2_7i90.c b/src/hal/drivers/mesa-hostmot2/hm2_7i90.c index 7d6bd0638a6..1275c02015c 100644 --- a/src/hal/drivers/mesa-hostmot2/hm2_7i90.c +++ b/src/hal/drivers/mesa-hostmot2/hm2_7i90.c @@ -211,7 +211,7 @@ int hm2_7i90_read(hm2_lowlevel_io_t *this, rtapi_u32 addr, void *buffer, int siz if (hm2_7i90_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of read(addr=0x%04x, size=%d)\n", addr, size); - (*this->io_error) = 1; + hal_set_bool(*this->io_error, 1); this->needs_reset = 1; hm2_7i90_epp_clear_timeout(board); return 0; // fail @@ -242,7 +242,7 @@ int hm2_7i90_write(hm2_lowlevel_io_t *this, rtapi_u32 addr, const void *buffer, if (hm2_7i90_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of write(addr=0x%04x, size=%d)\n", addr, size); - (*this->io_error) = 1; + hal_set_bool(*this->io_error, 1); this->needs_reset = 1; hm2_7i90_epp_clear_timeout(board); return 0; diff --git a/src/hal/drivers/mesa-hostmot2/hm2_eth.c b/src/hal/drivers/mesa-hostmot2/hm2_eth.c index 5d89756a97a..7fba307f17b 100644 --- a/src/hal/drivers/mesa-hostmot2/hm2_eth.c +++ b/src/hal/drivers/mesa-hostmot2/hm2_eth.c @@ -95,7 +95,7 @@ RTAPI_MP_ARRAY_STRING(config, MAX_ETH_BOARDS, "config string for the AnyIO board int debug = 0; RTAPI_MP_INT(debug, "Developer/debug use only! Enable debug logging."); -static char *firewall = 0; +static char *firewall = NULL; RTAPI_MP_STRING(firewall, "Firewall backend for traffic isolation: auto (default), iptables, nft, or none."); static int boards_count = 0; @@ -1032,29 +1032,29 @@ static int hm2_eth_send_queued_reads(hm2_lowlevel_io_t *this) { static bool record_soft_error(hm2_eth_t *board) { if(!board->hal) return 1; // still early in hm2_eth_probe board->llio.needs_soft_reset = 1; - *board->hal->packet_error = 1; - *board->hal->packet_error_total += 1; - int32_t increment = board->hal->packet_error_increment; + hal_set_bool(board->hal->packet_error, 1); + hal_set_ui32(board->hal->packet_error_total, hal_get_ui32(board->hal->packet_error_total) + 1); + int32_t increment = hal_get_si32(board->hal->packet_error_increment); if(increment < 1) increment = 1; board->comm_error_counter += increment; - if(board->comm_error_counter < 0 || board->comm_error_counter > board->hal->packet_error_limit) - board->comm_error_counter = board->hal->packet_error_limit; - *board->hal->packet_error_level = board->comm_error_counter; - bool result = board->comm_error_counter < board->hal->packet_error_limit; - if(!result) *board->llio.io_error = true; - *board->hal->packet_error_exceeded = !result; + if(board->comm_error_counter < 0 || board->comm_error_counter > hal_get_si32(board->hal->packet_error_limit)) + board->comm_error_counter = hal_get_si32(board->hal->packet_error_limit); + hal_set_si32(board->hal->packet_error_level, board->comm_error_counter); + bool result = board->comm_error_counter < hal_get_si32(board->hal->packet_error_limit); + if(!result) hal_set_bool(*board->llio.io_error, true); + hal_set_bool(board->hal->packet_error_exceeded, !result); return result; } static void decrement_soft_error(hm2_eth_t *board) { if(!board->hal) return; // still early in hm2_eth_probe - int32_t decrement = board->hal->packet_error_decrement; + int32_t decrement = hal_get_si32(board->hal->packet_error_decrement); if(decrement < 1) decrement = 1; board->comm_error_counter -= decrement; if(board->comm_error_counter < 0) board->comm_error_counter = 0; - *board->hal->packet_error_level = board->comm_error_counter; - *board->hal->packet_error = 0; - *board->hal->packet_error_exceeded = 0; + hal_set_si32(board->hal->packet_error_level, board->comm_error_counter); + hal_set_bool(board->hal->packet_error, 0); + hal_set_bool(board->hal->packet_error_exceeded, 0); } static int hm2_eth_receive_queued_reads(hm2_lowlevel_io_t *this) { @@ -1068,11 +1068,11 @@ static int hm2_eth_receive_queued_reads(hm2_lowlevel_io_t *this) { // pin (or they did something else like fiddle with the error limit // during a run, in which case we don't care if we reset the counter // or not) - if(board->hal && board->comm_error_counter == board->hal->packet_error_limit && !*board->llio.io_error) { + if(board->hal && board->comm_error_counter == hal_get_si32(board->hal->packet_error_limit) && !hal_get_bool(*board->llio.io_error)) { board->comm_error_counter = 0; } - long read_timeout = board->hal ? board->hal->read_timeout : 1600000; + long read_timeout = board->hal ? hal_get_si32(board->hal->read_timeout) : 1600000; if(read_timeout <= 0)//less than or equal to 0, use 80% of the thread period. read_timeout = 80; if(read_timeout < 100)//less than 100 is interpreted as a percentage of the thread period. @@ -1661,69 +1661,37 @@ static int hm2_eth_items(hm2_eth_t *board) { board->hal = hal_malloc(sizeof(*board->hal)); if(!board->hal) return -ENOMEM; - if((r = hal_param_s32_newf(HAL_RW, - &board->hal->read_timeout, - board->llio.comp_id, - "%s.packet-read-timeout", - board->llio.name)) < 0) + if((r = hal_param_new_si32(board->llio.comp_id, HAL_RW, &board->hal->read_timeout, + 80, "%s.packet-read-timeout", board->llio.name)) < 0) return r; - board->hal->read_timeout = 80; - if((r = hal_param_s32_newf(HAL_RW, - &board->hal->packet_error_limit, - board->llio.comp_id, - "%s.packet-error-limit", - board->llio.name)) < 0) + if((r = hal_param_new_si32(board->llio.comp_id, HAL_RW, &board->hal->packet_error_limit, + 10, "%s.packet-error-limit", board->llio.name)) < 0) return r; - board->hal->packet_error_limit = 10; - if((r = hal_param_s32_newf(HAL_RW, - &board->hal->packet_error_increment, - board->llio.comp_id, - "%s.packet-error-increment", - board->llio.name)) < 0) + if((r = hal_param_new_si32(board->llio.comp_id, HAL_RW, &board->hal->packet_error_increment, + 2, "%s.packet-error-increment", board->llio.name)) < 0) return r; - board->hal->packet_error_increment = 2; - if((r = hal_param_s32_newf(HAL_RO, - &board->hal->packet_error_decrement, - board->llio.comp_id, - "%s.packet-error-decrement", - board->llio.name)) < 0) + if((r = hal_param_new_si32(board->llio.comp_id, HAL_RO, &board->hal->packet_error_decrement, + 1, "%s.packet-error-decrement", board->llio.name)) < 0) return r; - board->hal->packet_error_decrement = 1; - if((r = hal_pin_bit_newf(HAL_OUT, - &board->hal->packet_error, - board->llio.comp_id, - "%s.packet-error", - board->llio.name)) < 0) + if((r = hal_pin_new_bool(board->llio.comp_id, HAL_OUT, &board->hal->packet_error, + 0, "%s.packet-error", board->llio.name)) < 0) return r; - *board->hal->packet_error = 0; - if((r = hal_pin_u32_newf(HAL_IO, - &board->hal->packet_error_total, - board->llio.comp_id, - "%s.packet-error-total", - board->llio.name)) < 0) + if((r = hal_pin_new_ui32(board->llio.comp_id, HAL_IO, &board->hal->packet_error_total, + 0, "%s.packet-error-total", board->llio.name)) < 0) return r; - *board->hal->packet_error_total = 0; - if((r = hal_pin_s32_newf(HAL_OUT, - &board->hal->packet_error_level, - board->llio.comp_id, - "%s.packet-error-level", - board->llio.name)) < 0) + if((r = hal_pin_new_si32(board->llio.comp_id, HAL_OUT, &board->hal->packet_error_level, + 0, "%s.packet-error-level", board->llio.name)) < 0) return r; - *board->hal->packet_error_level = 0; - if((r = hal_pin_bit_newf(HAL_OUT, - &board->hal->packet_error_exceeded, - board->llio.comp_id, - "%s.packet-error-exceeded", - board->llio.name)) < 0) + if((r = hal_pin_new_bool(board->llio.comp_id, HAL_OUT, &board->hal->packet_error_exceeded, + 0, "%s.packet-error-exceeded", board->llio.name)) < 0) return r; - *board->hal->packet_error_exceeded = 0; return 0; } @@ -1745,7 +1713,7 @@ int rtapi_app_main(void) { for(i = 0, ret = 0; ret == 0 && imaxicharbits = 0; } - inst->hal->icdelay = inst->maxicharbits; + hal_set_ui32(inst->hal->icdelay, inst->maxicharbits); } // @@ -440,12 +440,12 @@ static int send_comms_change(hm2_modbus_inst_t *inst) inst->cfg_tx.drivedelay = cc->cmd.idrvdelay ? cc->cmd.idrvdelay : 1; // Expose to HAL - inst->hal->baudrate = baudrate; - inst->hal->parity = parity; - inst->hal->stopbits = stopbits; - inst->hal->rxdelay = inst->cfg_rx.ifdelay; - inst->hal->txdelay = inst->cfg_tx.ifdelay; - inst->hal->drvdelay = inst->cfg_tx.drivedelay; + hal_set_ui32(inst->hal->baudrate, baudrate); + hal_set_ui32(inst->hal->parity, parity); + hal_set_ui32(inst->hal->stopbits, stopbits); + hal_set_ui32(inst->hal->rxdelay, inst->cfg_rx.ifdelay); + hal_set_ui32(inst->hal->txdelay, inst->cfg_tx.ifdelay); + hal_set_ui32(inst->hal->drvdelay, inst->cfg_tx.drivedelay); // Redo the inter-character delay settings setup_icdelay(inst, baudrate, parity, stopbits, cc->cmd.iicdelay); @@ -460,18 +460,18 @@ static void set_error(hm2_modbus_inst_t *inst, int errcode) { if(handling_inits(inst)) { // No individual pins for init commands, use global - *(inst->hal->fault) = 1; - *(inst->hal->faultcmd) = inst->cmdidx; - *(inst->hal->lasterror) = errcode; + hal_set_bool(inst->hal->fault, 1); + hal_set_ui32(inst->hal->faultcmd, inst->cmdidx); + hal_set_ui32(inst->hal->lasterror, errcode); return; } hm2_modbus_cmd_t *cc = current_cmd(inst); if(++cc->errors >= MAX_ERRORS || cc->disabled) { cc->disabled = 1; - *(inst->hal->cmds[inst->cmdidx].disabled) = 1; - *(inst->hal->cmds[inst->cmdidx].errorcode) = errcode; + hal_set_bool(inst->hal->cmds[inst->cmdidx].disabled, 1); + hal_set_ui32(inst->hal->cmds[inst->cmdidx].errorcode, errcode); } - *(inst->hal->cmds[inst->cmdidx].error) = cc->errors; + hal_set_ui32(inst->hal->cmds[inst->cmdidx].error, cc->errors); } // @@ -612,15 +612,15 @@ static inline int next_command(hm2_modbus_inst_t *inst) // Reset the individual commands on request. // Using modulo index ensures we also reset index zero when we wrap. unsigned i = inst->cmdidx % inst->ncmds; - bool b = !!*(inst->hal->cmds[i].reset); + bool b = hal_get_bool(inst->hal->cmds[i].reset); if(inst->cmds[i].prevreset != b) { inst->cmds[i].prevreset = !inst->cmds[i].prevreset; if(inst->cmds[i].prevreset) { inst->cmds[i].disabled = 0; inst->cmds[i].errors = 0; - *(inst->hal->cmds[i].disabled) = 0; - *(inst->hal->cmds[i].error) = 0; - *(inst->hal->cmds[i].errorcode) = 0; + hal_set_bool(inst->hal->cmds[i].disabled, 0); + hal_set_ui32(inst->hal->cmds[i].error, 0); + hal_set_ui32(inst->hal->cmds[i].errorcode, 0); // Honor the writeflush flag when coming out of disable. write_flush_cmd(inst, i); } @@ -628,15 +628,15 @@ static inline int next_command(hm2_modbus_inst_t *inst) // The run-time disabling of a command takes precedens over reset. // Set it on the rising edge of the 'disable' pin - b = !!*(inst->hal->cmds[i].disable); + b = hal_get_bool(inst->hal->cmds[i].disable); if(inst->cmds[i].prevdisable != b) { inst->cmds[i].prevdisable = !inst->cmds[i].prevdisable; if(inst->cmds[i].prevdisable) { inst->cmds[i].disabled = 1; inst->cmds[i].errors = 0; - *(inst->hal->cmds[i].disabled) = 1; - *(inst->hal->cmds[i].error) = 0; - *(inst->hal->cmds[i].errorcode) = EAGAIN; + hal_set_bool(inst->hal->cmds[i].disabled, 1); + hal_set_ui32(inst->hal->cmds[i].error, 0); + hal_set_ui32(inst->hal->cmds[i].errorcode, EAGAIN); } } } while(inst->cmdidx < inst->ncmds && inst->cmds[inst->cmdidx].disabled); @@ -689,7 +689,7 @@ static inline void set_state(hm2_modbus_inst_t *inst, int newstate) inst->timeout = 25000000; // 25 milliseconds break; case STATE_START: - if(*(inst->hal->suspend)) { + if(hal_get_bool(inst->hal->suspend)) { inst->suspended = 1; } inst->ignoredata = 0; // Re-enable data handling @@ -721,9 +721,9 @@ static void do_timeout(hm2_modbus_inst_t *inst) MSG_DBG("Timeout reset cmd=%u %s(%d)\n", inst->cmdidx, state_names[inst->state], inst->state); force_resend(inst); queue_reset(inst); - *(inst->hal->lasterror) = ETIMEDOUT; - *(inst->hal->fault) = 1; - *(inst->hal->faultcmd) = inst->cmdidx; + hal_set_ui32(inst->hal->lasterror, ETIMEDOUT); + hal_set_bool(inst->hal->fault, 1); + hal_set_ui32(inst->hal->faultcmd, inst->cmdidx); set_error(inst, ETIMEDOUT); set_state(inst, STATE_START); } @@ -749,7 +749,7 @@ static void process(void *arg, long period) hm2_modbus_inst_t *inst = (hm2_modbus_inst_t *)arg; if(inst->suspended) { - if(!*(inst->hal->suspend)) { + if(!hal_get_bool(inst->hal->suspend)) { inst->suspended = 0; // When coming out of suspend, see if we want to suppress writes // because our local data will most likely not match the pin data. @@ -772,18 +772,18 @@ static void process(void *arg, long period) } // Re-enable all commands on rising edge of global reset pin - bool b = !!*(inst->hal->reset); // Make sure its value is bool-worthy + bool b = hal_get_bool(inst->hal->reset); if(inst->prevreset != b) { inst->prevreset = !inst->prevreset; if(inst->prevreset) { for(unsigned i = 0; i < inst->ncmds; i++) { if(inst->cmds[i].disabled) { inst->cmds[i].disabled = 0; - *(inst->hal->cmds[i].disabled) = 0; + hal_set_bool(inst->hal->cmds[i].disabled, 0); write_flush_cmd(inst, i); } - *(inst->hal->cmds[i].errorcode) = 0; - *(inst->hal->cmds[i].error) = 0; + hal_set_ui32(inst->hal->cmds[i].errorcode, 0); + hal_set_ui32(inst->hal->cmds[i].error, 0); inst->cmds[i].errors = 0; } } @@ -864,9 +864,9 @@ static void process(void *arg, long period) // If the next command is again the first, then we have no // messages we can send. if(next_command(inst)) { - *(inst->hal->lasterror) = ENODATA; - *(inst->hal->fault) = 1; - *(inst->hal->faultcmd) = 0; + hal_set_ui32(inst->hal->lasterror, ENODATA); + hal_set_bool(inst->hal->fault, 1); + hal_set_ui32(inst->hal->faultcmd, 0); break; } } @@ -962,7 +962,7 @@ static void process(void *arg, long period) if(inst->timeout < 0) { // Timeout of delay, proceed to next command set_state(inst, STATE_START); - *(inst->hal->fault) = 0; + hal_set_bool(inst->hal->fault, 0); } break; @@ -1086,7 +1086,7 @@ static void process(void *arg, long period) // more (new) data is pending, then that will also be out-of-band. // We can go to the start state and sort it out there. set_state(inst, STATE_START); - *(inst->hal->fault) = 0; + hal_set_bool(inst->hal->fault, 0); } break; @@ -1097,9 +1097,9 @@ static void process(void *arg, long period) default: MSG_ERR("%s: error: Unknown state (%d) in process(), setting START state\n", inst->name, inst->state); - *(inst->hal->fault) = 1; - *(inst->hal->lasterror) = EINVAL; - *(inst->hal->faultcmd) = inst->cmdidx; + hal_set_bool(inst->hal->fault, 1); + hal_set_ui32(inst->hal->lasterror, EINVAL); + hal_set_ui32(inst->hal->faultcmd, inst->cmdidx); set_state(inst, STATE_START); break; } @@ -1450,38 +1450,38 @@ static int build_data_frame(hm2_modbus_inst_t *inst) break; case MBCMD_W_COIL: // Write single coil CHK_RV(ch_append16(cc, cc->cmd.caddr)); - CHK_RV(ch_append16(cc, hal->pins[p].pin->b ? 0xFF00 : 0x0000)); + CHK_RV(ch_append16(cc, hal_get_bool(hal->pins[p].pin.b) ? 0xFF00 : 0x0000)); break; case MBCMD_W_REGISTER: // Write single register // The target mtype can only be MBT_AB or MBT_BA (single reg write) CHK_RV(ch_append16(cc, cc->cmd.caddr)); switch(cc->typeptr[0].htype) { case HAL_BIT: - CHK_RV(map_u(cc, hal->pins[p].pin->b ? 1 : 0, 0)); + CHK_RV(map_u(cc, hal_get_bool(hal->pins[p].pin.b) ? 1 : 0, 0)); break; case HAL_U32: switch(mtypetype(cc->typeptr[0].mtype)) { - case MBT_U: CHK_RV(map_u(cc, hal->pins[p].pin->u, 0)); break; - case MBT_S: CHK_RV(map_s(cc, map_us(hal->pins[p].pin->u), 0)); break; - case MBT_F: CHK_RV(map_f(cc, map_uf(hal->pins[p].pin->u), 0)); break; + case MBT_U: CHK_RV(map_u(cc, hal_get_ui32(hal->pins[p].pin.u), 0)); break; + case MBT_S: CHK_RV(map_s(cc, map_us(hal_get_ui32(hal->pins[p].pin.u)), 0)); break; + case MBT_F: CHK_RV(map_f(cc, map_uf(hal_get_ui32(hal->pins[p].pin.u)), 0)); break; } break; case HAL_U64: switch(mtypetype(cc->typeptr[0].mtype)) { - case MBT_U: CHK_RV(map_u(cc, hal->pins[p].pin->lu, 0)); break; - case MBT_S: CHK_RV(map_s(cc, map_us(hal->pins[p].pin->lu), 0)); break; - case MBT_F: CHK_RV(map_f(cc, map_uf(hal->pins[p].pin->lu), 0)); break; + case MBT_U: CHK_RV(map_u(cc, hal_get_uint(hal->pins[p].pin.u), 0)); break; + case MBT_S: CHK_RV(map_s(cc, map_us(hal_get_uint(hal->pins[p].pin.u)), 0)); break; + case MBT_F: CHK_RV(map_f(cc, map_uf(hal_get_uint(hal->pins[p].pin.u)), 0)); break; } break; case HAL_S32: if(!haspinscale(&cc->typeptr[0])) { switch(mtypetype(cc->typeptr[0].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_su(hal->pins[p].pin->s), 0)); break; - case MBT_S: CHK_RV(map_s(cc, hal->pins[p].pin->s, 0)); break; - case MBT_F: CHK_RV(map_f(cc, map_sf(hal->pins[p].pin->s), 0)); break; + case MBT_U: CHK_RV(map_u(cc, map_su(hal_get_si32(hal->pins[p].pin.s)), 0)); break; + case MBT_S: CHK_RV(map_s(cc, hal_get_si32(hal->pins[p].pin.s), 0)); break; + case MBT_F: CHK_RV(map_f(cc, map_sf(hal_get_si32(hal->pins[p].pin.s)), 0)); break; } } else { - val64.f = (real_t)((rtapi_s64)hal->pins[p].pin->s - hal->pins[p].offset->s) * *(hal->pins[p].scale); + val64.f = (rtapi_real)((rtapi_s64)hal_get_si32(hal->pins[p].pin.s) - hal_get_si32(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[0].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), 0)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), 0)); break; @@ -1492,12 +1492,12 @@ static int build_data_frame(hm2_modbus_inst_t *inst) case HAL_S64: if(!haspinscale(&cc->typeptr[0])) { switch(mtypetype(cc->typeptr[0].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_su(hal->pins[p].pin->ls), 0)); break; - case MBT_S: CHK_RV(map_s(cc, hal->pins[p].pin->ls, 0)); break; - case MBT_F: CHK_RV(map_f(cc, map_sf(hal->pins[p].pin->ls), 0)); break; + case MBT_U: CHK_RV(map_u(cc, map_su(hal_get_sint(hal->pins[p].pin.s)), 0)); break; + case MBT_S: CHK_RV(map_s(cc, hal_get_sint(hal->pins[p].pin.s), 0)); break; + case MBT_F: CHK_RV(map_f(cc, map_sf(hal_get_sint(hal->pins[p].pin.s)), 0)); break; } } else { - val64.f = (real_t)(hal->pins[p].pin->ls - hal->pins[p].offset->ls) * *(hal->pins[p].scale); + val64.f = (rtapi_real)(hal_get_sint(hal->pins[p].pin.s) - hal_get_sint(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[0].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), 0)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), 0)); break; @@ -1508,12 +1508,12 @@ static int build_data_frame(hm2_modbus_inst_t *inst) case HAL_FLOAT: if(!haspinscale(&cc->typeptr[0])) { switch(mtypetype(cc->typeptr[0].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_fu(hal->pins[p].pin->f), 0)); break; - case MBT_S: CHK_RV(map_s(cc, map_fs(hal->pins[p].pin->f), 0)); break; - case MBT_F: CHK_RV(map_f(cc, hal->pins[p].pin->f, 0)); break; + case MBT_U: CHK_RV(map_u(cc, map_fu(hal_get_real(hal->pins[p].pin.r)), 0)); break; + case MBT_S: CHK_RV(map_s(cc, map_fs(hal_get_real(hal->pins[p].pin.r)), 0)); break; + case MBT_F: CHK_RV(map_f(cc, hal_get_real(hal->pins[p].pin.r), 0)); break; } } else { - val64.f = (hal->pins[p].pin->f - hal->pins[p].offset->f) * *(hal->pins[p].scale); + val64.f = (hal_get_real(hal->pins[p].pin.r) - hal_get_real(hal->pins[p].offset.r)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[0].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), 0)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), 0)); break; @@ -1531,7 +1531,7 @@ static int build_data_frame(hm2_modbus_inst_t *inst) CHK_RV(ch_append16(cc, cc->cmd.cpincnt)); CHK_RV(ch_append8(cc, (cc->cmd.cpincnt + 7) / 8)); for(unsigned i = 0; i < cc->cmd.cpincnt; i++) { - if(hal->pins[p++].pin->b) + if(hal_get_bool(hal->pins[p++].pin.b)) acc |= 1u << (i % 8); if((i % 8) == 7 || i == cc->cmd.cpincnt - 1u) { // time for the next byte CHK_RV(ch_append8(cc, acc)); @@ -1553,31 +1553,31 @@ static int build_data_frame(hm2_modbus_inst_t *inst) } switch(cc->typeptr[i].htype) { case HAL_BIT: - CHK_RV(map_u(cc, hal->pins[p].pin->b ? 1 : 0, i)); + CHK_RV(map_u(cc, hal_get_bool(hal->pins[p].pin.b) ? 1 : 0, i)); break; case HAL_U32: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: CHK_RV(map_u(cc, hal->pins[p].pin->u, i)); break; - case MBT_S: CHK_RV(map_s(cc, map_us(hal->pins[p].pin->u), i)); break; - case MBT_F: CHK_RV(map_f(cc, map_uf(hal->pins[p].pin->u), i)); break; + case MBT_U: CHK_RV(map_u(cc, hal_get_ui32(hal->pins[p].pin.u), i)); break; + case MBT_S: CHK_RV(map_s(cc, map_us(hal_get_ui32(hal->pins[p].pin.u)), i)); break; + case MBT_F: CHK_RV(map_f(cc, map_uf(hal_get_ui32(hal->pins[p].pin.u)), i)); break; } break; case HAL_U64: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: CHK_RV(map_u(cc, hal->pins[p].pin->lu, i)); break; - case MBT_S: CHK_RV(map_s(cc, map_us(hal->pins[p].pin->lu), i)); break; - case MBT_F: CHK_RV(map_f(cc, map_uf(hal->pins[p].pin->lu), i)); break; + case MBT_U: CHK_RV(map_u(cc, hal_get_uint(hal->pins[p].pin.u), i)); break; + case MBT_S: CHK_RV(map_s(cc, map_us(hal_get_uint(hal->pins[p].pin.u)), i)); break; + case MBT_F: CHK_RV(map_f(cc, map_uf(hal_get_uint(hal->pins[p].pin.u)), i)); break; } break; case HAL_S32: if(!haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_su(hal->pins[p].pin->s), i)); break; - case MBT_S: CHK_RV(map_s(cc, hal->pins[p].pin->s, i)); break; - case MBT_F: CHK_RV(map_f(cc, map_sf(hal->pins[p].pin->s), i)); break; + case MBT_U: CHK_RV(map_u(cc, map_su(hal_get_si32(hal->pins[p].pin.s)), i)); break; + case MBT_S: CHK_RV(map_s(cc, hal_get_si32(hal->pins[p].pin.s), i)); break; + case MBT_F: CHK_RV(map_f(cc, map_sf(hal_get_si32(hal->pins[p].pin.s)), i)); break; } } else { - val64.f = (real_t)((rtapi_s64)hal->pins[p].pin->s - hal->pins[p].offset->s) * *(hal->pins[p].scale); + val64.f = (rtapi_real)((rtapi_s64)hal_get_si32(hal->pins[p].pin.s) - hal_get_si32(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[i].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), i)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), i)); break; @@ -1588,12 +1588,12 @@ static int build_data_frame(hm2_modbus_inst_t *inst) case HAL_S64: if(!haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_su(hal->pins[p].pin->ls), i)); break; - case MBT_S: CHK_RV(map_s(cc, hal->pins[p].pin->ls, i)); break; - case MBT_F: CHK_RV(map_f(cc, map_sf(hal->pins[p].pin->ls), i)); break; + case MBT_U: CHK_RV(map_u(cc, map_su(hal_get_sint(hal->pins[p].pin.s)), i)); break; + case MBT_S: CHK_RV(map_s(cc, hal_get_sint(hal->pins[p].pin.s), i)); break; + case MBT_F: CHK_RV(map_f(cc, map_sf(hal_get_sint(hal->pins[p].pin.s)), i)); break; } } else { - val64.f = (real_t)(hal->pins[p].pin->ls - hal->pins[p].offset->ls) * *(hal->pins[p].scale); + val64.f = (rtapi_real)(hal_get_sint(hal->pins[p].pin.s) - hal_get_sint(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[i].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), i)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), i)); break; @@ -1604,12 +1604,12 @@ static int build_data_frame(hm2_modbus_inst_t *inst) case HAL_FLOAT: if(!haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: CHK_RV(map_u(cc, map_fu(hal->pins[p].pin->f), i)); break; - case MBT_S: CHK_RV(map_s(cc, map_fs(hal->pins[p].pin->f), i)); break; - case MBT_F: CHK_RV(map_f(cc, hal->pins[p].pin->f, i)); break; + case MBT_U: CHK_RV(map_u(cc, map_fu(hal_get_real(hal->pins[p].pin.r)), i)); break; + case MBT_S: CHK_RV(map_s(cc, map_fs(hal_get_real(hal->pins[p].pin.r)), i)); break; + case MBT_F: CHK_RV(map_f(cc, hal_get_real(hal->pins[p].pin.r), i)); break; } } else { - val64.f = (hal->pins[p].pin->f - hal->pins[p].offset->f) * *(hal->pins[p].scale); + val64.f = (hal_get_real(hal->pins[p].pin.r) - hal_get_real(hal->pins[p].offset.r)) * hal_get_real(hal->pins[p].scale); switch(mtypetype(cc->typeptr[i].mtype)) { case MBT_U: CHK_RV(map_u(cc, map_fu(val64.f), i)); break; case MBT_S: CHK_RV(map_s(cc, map_fs(val64.f), i)); break; @@ -1861,7 +1861,7 @@ static int parse_data_frame(hm2_modbus_inst_t *inst) w = 3; // First data return byte {mbid, func, bytecount, ...} b = 0; for(unsigned i = 0; i < cc->cmd.cpincnt; i++) { - hal->pins[p++].pin->b = !!(bytes[w] & (1u << b)); + hal_set_bool(hal->pins[p++].pin.b, !!(bytes[w] & (1u << b))); if(++b >= 8) { b = 0; w++; } } break; @@ -1971,61 +1971,61 @@ static int parse_data_frame(hm2_modbus_inst_t *inst) switch(cc->typeptr[i].htype) { case HAL_BIT: - hal->pins[p].pin->b = 0 != val64.u; // Zero maps to false, anything else to true + hal_set_bool(hal->pins[p].pin.b, 0 != val64.u); // Zero maps to false, anything else to true break; case HAL_U32: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: hal->pins[p].pin->u = unmap32_uu(cc, val64.u, i); break; - case MBT_S: hal->pins[p].pin->u = unmap32_us(cc, val64.s, i); break; - case MBT_F: hal->pins[p].pin->u = unmap32_uf(cc, val64.f, i); break; + case MBT_U: hal_set_ui32(hal->pins[p].pin.u, unmap32_uu(cc, val64.u, i)); break; + case MBT_S: hal_set_ui32(hal->pins[p].pin.u, unmap32_us(cc, val64.s, i)); break; + case MBT_F: hal_set_ui32(hal->pins[p].pin.u, unmap32_uf(cc, val64.f, i)); break; } break; case HAL_S32: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: hal->pins[p].pin->s = unmap32_su(cc, val64.u, i); break; - case MBT_S: hal->pins[p].pin->s = unmap32_ss(cc, val64.s, i); break; - case MBT_F: hal->pins[p].pin->s = unmap32_sf(cc, val64.f, i); break; + case MBT_U: hal_set_si32(hal->pins[p].pin.s, unmap32_su(cc, val64.u, i)); break; + case MBT_S: hal_set_si32(hal->pins[p].pin.s, unmap32_ss(cc, val64.s, i)); break; + case MBT_F: hal_set_si32(hal->pins[p].pin.s, unmap32_sf(cc, val64.f, i)); break; } if(haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: *(hal->pins[p].scaled) = (real_t)(rtapi_s64)(val64.u - hal->pins[p].offset->lu) * *(hal->pins[p].scale); break; - case MBT_S: *(hal->pins[p].scaled) = (real_t)(val64.s - hal->pins[p].offset->ls) * *(hal->pins[p].scale); break; - case MBT_F: *(hal->pins[p].scaled) = (val64.f - hal->pins[p].offset->f) * *(hal->pins[p].scale); break; + case MBT_U: hal_set_real(hal->pins[p].scaled, (rtapi_real)(rtapi_s64)(val64.u - hal_get_uint(hal->pins[p].offset.u)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_S: hal_set_real(hal->pins[p].scaled, (rtapi_real)(val64.s - hal_get_sint(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_F: hal_set_real(hal->pins[p].scaled, (val64.f - hal_get_real(hal->pins[p].offset.r)) * hal_get_real(hal->pins[p].scale)); break; } } break; case HAL_U64: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: hal->pins[p].pin->lu = val64.u; break; - case MBT_S: hal->pins[p].pin->lu = unmap64_us(cc, val64.s, i); break; - case MBT_F: hal->pins[p].pin->lu = unmap64_uf(cc, val64.f, i); break; + case MBT_U: hal_set_uint(hal->pins[p].pin.u, val64.u); break; + case MBT_S: hal_set_uint(hal->pins[p].pin.u, unmap64_us(cc, val64.s, i)); break; + case MBT_F: hal_set_uint(hal->pins[p].pin.u, unmap64_uf(cc, val64.f, i)); break; } break; case HAL_S64: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: hal->pins[p].pin->ls = unmap64_su(cc, val64.u, i); break; - case MBT_S: hal->pins[p].pin->ls = val64.s; break; - case MBT_F: hal->pins[p].pin->ls = unmap64_sf(cc, val64.f, i); break; + case MBT_U: hal_set_sint(hal->pins[p].pin.s, unmap64_su(cc, val64.u, i)); break; + case MBT_S: hal_set_sint(hal->pins[p].pin.s, val64.s); break; + case MBT_F: hal_set_sint(hal->pins[p].pin.s, unmap64_sf(cc, val64.f, i)); break; } if(haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: *(hal->pins[p].scaled) = (real_t)(rtapi_s64)(val64.u - hal->pins[p].offset->lu) * *(hal->pins[p].scale); break; - case MBT_S: *(hal->pins[p].scaled) = (real_t)(val64.s - hal->pins[p].offset->ls) * *(hal->pins[p].scale); break; - case MBT_F: *(hal->pins[p].scaled) = (val64.f - hal->pins[p].offset->f) * *(hal->pins[p].scale); break; + case MBT_U: hal_set_real(hal->pins[p].scaled, (rtapi_real)(rtapi_s64)(val64.u - hal_get_uint(hal->pins[p].offset.u)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_S: hal_set_real(hal->pins[p].scaled, (rtapi_real)(val64.s - hal_get_sint(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_F: hal_set_real(hal->pins[p].scaled, (val64.f - hal_get_real(hal->pins[p].offset.r)) * hal_get_real(hal->pins[p].scale)); break; } } break; case HAL_FLOAT: switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: hal->pins[p].pin->f = val64.u; break; - case MBT_S: hal->pins[p].pin->f = val64.s; break; - case MBT_F: hal->pins[p].pin->f = val64.f; break; + case MBT_U: hal_set_real(hal->pins[p].pin.r, val64.u); break; + case MBT_S: hal_set_real(hal->pins[p].pin.r, val64.s); break; + case MBT_F: hal_set_real(hal->pins[p].pin.r, val64.f); break; } if(haspinscale(&cc->typeptr[i])) { switch(mtypetype(cc->typeptr[i].mtype)) { - case MBT_U: *(hal->pins[p].scaled) = (real_t)(rtapi_s64)(val64.u - hal->pins[p].offset->lu) * *(hal->pins[p].scale); break; - case MBT_S: *(hal->pins[p].scaled) = (real_t)(val64.s - hal->pins[p].offset->ls) * *(hal->pins[p].scale); break; - case MBT_F: *(hal->pins[p].scaled) = (val64.f - hal->pins[p].offset->f) * *(hal->pins[p].scale); break; + case MBT_U: hal_set_real(hal->pins[p].scaled, (rtapi_real)(rtapi_s64)(val64.u - hal_get_uint(hal->pins[p].offset.u)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_S: hal_set_real(hal->pins[p].scaled, (rtapi_real)(val64.s - hal_get_sint(hal->pins[p].offset.s)) * hal_get_real(hal->pins[p].scale)); break; + case MBT_F: hal_set_real(hal->pins[p].scaled, (val64.f - hal_get_real(hal->pins[p].offset.r)) * hal_get_real(hal->pins[p].scale)); break; } } break; @@ -2820,21 +2820,21 @@ int rtapi_app_main(void) goto errout; \ } \ } while(0) - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->baudrate), comp_id, "%s.baudrate", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->parity), comp_id, "%s.parity", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->stopbits), comp_id, "%s.stopbits", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->icdelay), comp_id, "%s.icdelay", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->txdelay), comp_id, "%s.txdelay", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->rxdelay), comp_id, "%s.rxdelay", inst->name)); - CHECK(hal_param_u32_newf(HAL_RO, &(inst->hal->drvdelay), comp_id, "%s.drivedelay", inst->name)); - - CHECK(hal_pin_bit_newf(HAL_IN, &(inst->hal->suspend), comp_id, "%s.suspend", inst->name)); - CHECK(hal_pin_bit_newf(HAL_IN, &(inst->hal->reset), comp_id, "%s.reset", inst->name)); - CHECK(hal_pin_bit_newf(HAL_OUT, &(inst->hal->fault), comp_id, "%s.fault", inst->name)); - CHECK(hal_pin_u32_newf(HAL_OUT, &(inst->hal->faultcmd), comp_id, "%s.fault-command", inst->name)); - CHECK(hal_pin_u32_newf(HAL_OUT, &(inst->hal->lasterror), comp_id, "%s.last-error-code", inst->name)); - - inst->hal->baudrate = inst->cfg_rx.baudrate = inst->cfg_tx.baudrate = inst->mbccb->baudrate; + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->baudrate), 0, "%s.baudrate", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->parity), 0, "%s.parity", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->stopbits), 0, "%s.stopbits", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->icdelay), 0, "%s.icdelay", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->txdelay), 0, "%s.txdelay", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->rxdelay), 0, "%s.rxdelay", inst->name)); + CHECK(hal_param_new_ui32(comp_id, HAL_RO, &(inst->hal->drvdelay), 0, "%s.drivedelay", inst->name)); + + CHECK(hal_pin_new_bool(comp_id, HAL_IN, &(inst->hal->suspend), 0, "%s.suspend", inst->name)); + CHECK(hal_pin_new_bool(comp_id, HAL_IN, &(inst->hal->reset), 0, "%s.reset", inst->name)); + CHECK(hal_pin_new_bool(comp_id, HAL_OUT, &(inst->hal->fault), 0, "%s.fault", inst->name)); + CHECK(hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal->faultcmd), 0, "%s.fault-command", inst->name)); + CHECK(hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal->lasterror), 0, "%s.last-error-code", inst->name)); + + hal_set_ui32(inst->hal->baudrate, inst->cfg_rx.baudrate = inst->cfg_tx.baudrate = inst->mbccb->baudrate); unsigned parity = 0; if(inst->mbccb->format & MBCCB_FORMAT_PARITYEN) { inst->cfg_rx.flags |= HM2_PKTUART_CONFIG_PARITYEN; @@ -2852,22 +2852,22 @@ int rtapi_app_main(void) inst->cfg_tx.flags |= HM2_PKTUART_CONFIG_STOPBITS2; stopbits = 2; } - inst->hal->parity = parity; - inst->hal->stopbits = stopbits; + hal_set_ui32(inst->hal->parity, parity); + hal_set_ui32(inst->hal->stopbits, stopbits); if(!inst->mbccb->rxdelay) // Auto - inst->hal->rxdelay = inst->cfg_rx.ifdelay = calc_ifdelay(inst, inst->mbccb->baudrate, parity, stopbits) - 1; + inst->cfg_rx.ifdelay = hal_set_ui32(inst->hal->rxdelay, calc_ifdelay(inst, inst->mbccb->baudrate, parity, stopbits) - 1); else // Manual - inst->hal->rxdelay = inst->cfg_rx.ifdelay = inst->mbccb->rxdelay; + inst->cfg_rx.ifdelay = hal_set_ui32(inst->hal->rxdelay, inst->mbccb->rxdelay); if(!inst->mbccb->txdelay) // Auto - inst->hal->txdelay = inst->cfg_tx.ifdelay = calc_ifdelay(inst, inst->mbccb->baudrate, parity, stopbits) + 1; + inst->cfg_tx.ifdelay = hal_set_ui32(inst->hal->txdelay, calc_ifdelay(inst, inst->mbccb->baudrate, parity, stopbits) + 1); else // Manual - inst->hal->txdelay = inst->cfg_tx.ifdelay = inst->mbccb->txdelay; + inst->cfg_tx.ifdelay = hal_set_ui32(inst->hal->txdelay, inst->mbccb->txdelay); if(!inst->mbccb->drvdelay) // Auto - inst->hal->drvdelay = inst->cfg_tx.drivedelay = 1; + inst->cfg_tx.drivedelay = hal_set_ui32(inst->hal->drvdelay, 1); else // Manual - inst->hal->drvdelay = inst->cfg_tx.drivedelay = inst->mbccb->drvdelay; + inst->cfg_tx.drivedelay = hal_set_ui32(inst->hal->drvdelay, inst->mbccb->drvdelay); inst->cfg_rx.filterrate = 0; // Zero means 2 times baudrate inst->cfg_rx.flags |= HM2_PKTUART_CONFIG_RXEN; @@ -2938,10 +2938,7 @@ int rtapi_app_main(void) stopbits > 1 ? '2' : '1', inst->cfg_rx.baudrate); - *(inst->hal->fault) = 0; - *(inst->hal->faultcmd) = 0; - *(inst->hal->lasterror) = 0; - *(inst->hal->suspend) = 0 != (inst->mbccb->format & MBCCB_FORMAT_SUSPEND); + hal_set_bool(inst->hal->suspend, 0 != (inst->mbccb->format & MBCCB_FORMAT_SUSPEND)); // Start with internal suspended bit set. The HAL pin will dictate to // move to the active state in the process() function. This enables to // use the WFLUSH setting each time we come out of suspend and, @@ -2954,24 +2951,24 @@ int rtapi_app_main(void) #define CPTR(x) ((const char *)((x) + 1)) for(unsigned c = 0; c < inst->ncmds; c++) { // First create command status pins - CHECK(hal_pin_bit_newf(HAL_IN, &(inst->hal->cmds[c].disable), - comp_id, "%s.command.%02d.disable", inst->name, c)); - CHECK(hal_pin_bit_newf(HAL_OUT, &(inst->hal->cmds[c].disabled), - comp_id, "%s.command.%02d.disabled", inst->name, c)); - CHECK(hal_pin_u32_newf(HAL_OUT, &(inst->hal->cmds[c].error), - comp_id, "%s.command.%02d.errors", inst->name, c)); - CHECK(hal_pin_u32_newf(HAL_OUT, &(inst->hal->cmds[c].errorcode), - comp_id, "%s.command.%02d.error-code", inst->name, c)); - CHECK(hal_pin_bit_newf(HAL_IN, &(inst->hal->cmds[c].reset), - comp_id, "%s.command.%02d.reset", inst->name, c)); + CHECK(hal_pin_new_bool(comp_id, HAL_IN, &(inst->hal->cmds[c].disable), + 0, "%s.command.%02d.disable", inst->name, c)); + CHECK(hal_pin_new_bool(comp_id, HAL_OUT, &(inst->hal->cmds[c].disabled), + 0, "%s.command.%02d.disabled", inst->name, c)); + CHECK(hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal->cmds[c].error), + 0, "%s.command.%02d.errors", inst->name, c)); + CHECK(hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal->cmds[c].errorcode), + 0, "%s.command.%02d.error-code", inst->name, c)); + CHECK(hal_pin_new_bool(comp_id, HAL_IN, &(inst->hal->cmds[c].reset), + 0, "%s.command.%02d.reset", inst->name, c)); hm2_modbus_cmd_t *cc = &inst->_cmds[c]; // If the command is disabled, set it so if(hasdisabled(cc)) { cc->disabled = 1; - *(inst->hal->cmds[c].disabled) = 1; - *(inst->hal->cmds[c].errorcode) = EAGAIN; + hal_set_bool(inst->hal->cmds[c].disabled, 1); + hal_set_ui32(inst->hal->cmds[c].errorcode, EAGAIN); } // Now create the pins associated with the command @@ -2986,8 +2983,8 @@ int rtapi_app_main(void) /* Fallthrough */ case MBCMD_W_COIL: case MBCMD_W_COILS: - CHECK(hal_pin_bit_newf(dir, (hal_bit_t**)&(inst->hal->pins[p++]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_bool(comp_id, dir, &(inst->hal->pins[p++].pin.b), + 0, "%s.%s", inst->name, CPTR(dptr))); break; case MBCMD_R_INPUTREGS: @@ -2999,111 +2996,107 @@ int rtapi_app_main(void) switch(cc->typeptr[j].htype) { default: case HAL_BIT: - CHECK(hal_pin_bit_newf(dir, (hal_bit_t**)&(inst->hal->pins[p++]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_bool(comp_id, dir, &(inst->hal->pins[p++].pin.b), + 0, "%s.%s", inst->name, CPTR(dptr))); break; case HAL_U32: - CHECK(hal_pin_u32_newf(dir, (hal_u32_t**)&(inst->hal->pins[p++]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_ui32(comp_id, dir, &(inst->hal->pins[p++].pin.u), + 0, "%s.%s", inst->name, CPTR(dptr))); break; case HAL_U64: - CHECK(hal_pin_u64_newf(dir, (hal_u64_t**)&(inst->hal->pins[p++]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_uint(comp_id, dir, &(inst->hal->pins[p++].pin.u), + 0, "%s.%s", inst->name, CPTR(dptr))); break; case HAL_S32: - CHECK(hal_pin_s32_newf(dir, (hal_s32_t**)&(inst->hal->pins[p]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_si32(comp_id, dir, &(inst->hal->pins[p].pin.s), + 0, "%s.%s", inst->name, CPTR(dptr))); if(haspinscale(&cc->typeptr[j])) { - CHECK(hal_pin_float_newf(HAL_IN, &(inst->hal->pins[p].scale), - comp_id, "%s.%s.scale", inst->name, CPTR(dptr))); - *(inst->hal->pins[p].scale) = 1.0; + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].scale), + 1.0, "%s.%s.scale", inst->name, CPTR(dptr))); if(HAL_OUT == dir) { - CHECK(hal_pin_float_newf(HAL_OUT, &(inst->hal->pins[p].scaled), - comp_id, "%s.%s.scaled", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_OUT, &(inst->hal->pins[p].scaled), + 0.0, "%s.%s.scaled", inst->name, CPTR(dptr))); switch(mtypetype(cc->typeptr[j].mtype)) { case MBT_U: - CHECK(hal_pin_u64_newf(HAL_IN, (hal_u64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_uint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.u), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_S: - CHECK(hal_pin_s64_newf(HAL_IN, (hal_s64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_sint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.s), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_F: - CHECK(hal_pin_float_newf(HAL_IN, (hal_float_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].offset.r), + 0.0, "%s.%s.offset", inst->name, CPTR(dptr))); break; } } else { - CHECK(hal_pin_s32_newf(HAL_IN, (hal_s32_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_si32(comp_id, HAL_IN, &(inst->hal->pins[p].offset.s), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); } } p++; break; case HAL_S64: - CHECK(hal_pin_s64_newf(dir, (hal_s64_t**)&(inst->hal->pins[p]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_sint(comp_id, dir, &(inst->hal->pins[p].pin.s), + 0, "%s.%s", inst->name, CPTR(dptr))); if(haspinscale(&cc->typeptr[j])) { - CHECK(hal_pin_float_newf(HAL_IN, &(inst->hal->pins[p].scale), - comp_id, "%s.%s.scale", inst->name, CPTR(dptr))); - *(inst->hal->pins[p].scale) = 1.0; + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].scale), + 1.0, "%s.%s.scale", inst->name, CPTR(dptr))); if(HAL_OUT == dir) { - CHECK(hal_pin_float_newf(HAL_OUT, &(inst->hal->pins[p].scaled), - comp_id, "%s.%s.scaled", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_OUT, &(inst->hal->pins[p].scaled), + 0.0, "%s.%s.scaled", inst->name, CPTR(dptr))); switch(mtypetype(cc->typeptr[j].mtype)) { case MBT_U: - CHECK(hal_pin_u64_newf(HAL_IN, (hal_u64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_uint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.u), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_S: - CHECK(hal_pin_s64_newf(HAL_IN, (hal_s64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_sint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.s), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_F: - CHECK(hal_pin_float_newf(HAL_IN, (hal_float_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].offset.r), + 0.0, "%s.%s.offset", inst->name, CPTR(dptr))); break; } } else { - CHECK(hal_pin_s64_newf(HAL_IN, (hal_s64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_sint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.s), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); } } p++; break; case HAL_FLOAT: - CHECK(hal_pin_float_newf(dir, (hal_float_t**)&(inst->hal->pins[p]), - comp_id, "%s.%s", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, dir, &(inst->hal->pins[p].pin.r), + 0.0, "%s.%s", inst->name, CPTR(dptr))); if(haspinscale(&cc->typeptr[j])) { - CHECK(hal_pin_float_newf(HAL_IN, &(inst->hal->pins[p].scale), - comp_id, "%s.%s.scale", inst->name, CPTR(dptr))); - *(inst->hal->pins[p].scale) = 1.0; + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].scale), + 1.0, "%s.%s.scale", inst->name, CPTR(dptr))); if(HAL_OUT == dir) { - CHECK(hal_pin_float_newf(HAL_OUT, &(inst->hal->pins[p].scaled), - comp_id, "%s.%s.scaled", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_OUT, &(inst->hal->pins[p].scaled), + 0.0, "%s.%s.scaled", inst->name, CPTR(dptr))); switch(mtypetype(cc->typeptr[j].mtype)) { case MBT_U: - CHECK(hal_pin_u64_newf(HAL_IN, (hal_u64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_uint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.u), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_S: - CHECK(hal_pin_s64_newf(HAL_IN, (hal_s64_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_sint(comp_id, HAL_IN, &(inst->hal->pins[p].offset.s), + 0, "%s.%s.offset", inst->name, CPTR(dptr))); break; case MBT_F: - CHECK(hal_pin_float_newf(HAL_IN, (hal_float_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].offset.r), + 0.0, "%s.%s.offset", inst->name, CPTR(dptr))); break; } } else { - CHECK(hal_pin_float_newf(HAL_IN, (hal_float_t**)&(inst->hal->pins[p].offset), - comp_id, "%s.%s.offset", inst->name, CPTR(dptr))); + CHECK(hal_pin_new_real(comp_id, HAL_IN, &(inst->hal->pins[p].offset.r), + 0.0, "%s.%s.offset", inst->name, CPTR(dptr))); } - inst->hal->pins[p].offset->f = 0.0; } p++; break; diff --git a/src/hal/drivers/mesa-hostmot2/hm2_spi.c b/src/hal/drivers/mesa-hostmot2/hm2_spi.c index 3b7af1c87d1..0e2114a87d3 100644 --- a/src/hal/drivers/mesa-hostmot2/hm2_spi.c +++ b/src/hal/drivers/mesa-hostmot2/hm2_spi.c @@ -152,12 +152,12 @@ static int queue_write(hm2_lowlevel_io_t *llio, rtapi_u32 addr, const void *buff if(r < 0) return r; } - PUT(write_command(addr, wsize), 0); + PUT(write_command(addr, wsize), NULL); const uint32_t *wbuffer = buffer; int i=0; for(i=0; illio->period = period; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_tram_read(hm2); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_raw_queue_read(hm2); hm2_tp_pwmgen_queue_read(hm2); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_queue_read(hm2); hm2->llio->read_requested = true; hm2->llio->read_time = rtapi_get_time(); @@ -98,10 +98,10 @@ static void hm2_read(void *void_hm2, long period) { hm2->llio->read_requested = false; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; // if there's a temporary read failure, don't sweat it if(hm2_finish_read(hm2) == -EAGAIN) return; - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_watchdog_process_tram_read(hm2); hm2_ioport_gpio_process_tram_read(hm2); @@ -127,7 +127,7 @@ static void hm2_write(void *void_hm2, long period) { hostmot2_t *hm2 = void_hm2; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; if (!hm2->ddr_initialized) { hm2_ioport_initialize_ddr(hm2); @@ -183,7 +183,7 @@ static void hm2_read_gpio(void *void_hm2, long period) { hostmot2_t *hm2 = void_hm2; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_ioport_gpio_read(hm2); } @@ -193,7 +193,7 @@ static void hm2_write_gpio(void *void_hm2, long period) { hostmot2_t *hm2 = void_hm2; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; hm2_ioport_gpio_write(hm2); hm2_watchdog_write(hm2, period); @@ -957,7 +957,7 @@ static int hm2_parse_module_descriptors(hostmot2_t *hm2) { md_accepted = hm2_ioport_parse_md(hm2, md_index); - if ((*hm2->llio->io_error) != 0) { + if (hal_get_bool(*hm2->llio->io_error)) { HM2_ERR("IO error while parsing Module Descriptor %d\n", md_index); return -EIO; } @@ -1097,7 +1097,7 @@ static int hm2_parse_module_descriptors(hostmot2_t *hm2) { } - if ((*hm2->llio->io_error) != 0) { + if (hal_get_bool(*hm2->llio->io_error)) { HM2_ERR("IO error while parsing Module Descriptor %d\n", md_index); return -EIO; } @@ -1453,17 +1453,14 @@ int hm2_register(hm2_lowlevel_io_t *llio, char *config_string) { int r; char name[HAL_NAME_LEN + 1]; - llio->io_error = (hal_bit_t *)hal_malloc(sizeof(hal_bit_t)); + llio->io_error = hal_malloc(sizeof(*llio->io_error)); if (llio->io_error == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - (*llio->io_error) = 0; - - rtapi_snprintf(name, sizeof(name), "%s.io_error", llio->name); - r = hal_param_bit_new(name, HAL_RW, llio->io_error, llio->comp_id); + r = hal_param_new_bool(llio->comp_id, HAL_RW, llio->io_error, 0, "%s.io_error", llio->name); if (r < 0) { HM2_ERR("error adding param '%s', aborting\n", name); r = -EINVAL; @@ -1676,7 +1673,7 @@ int hm2_register(hm2_lowlevel_io_t *llio, char *config_string) { // final check for comm errors // - if ((*hm2->llio->io_error) != 0) { + if (hal_get_bool(*hm2->llio->io_error)) { HM2_ERR("comm errors while initializing firmware!\n"); goto fail1; } @@ -1776,7 +1773,7 @@ void hm2_unregister(hm2_lowlevel_io_t *llio) { // if there's a watchdog, set it to safe the board right away if (hm2->watchdog.num_instances > 0) { hm2->watchdog.instance[0].enable = 1; - hm2->watchdog.instance[0].hal.param.timeout_ns = 1; + hal_set_ui32(hm2->watchdog.instance[0].hal.param.timeout_ns, 1); hm2_watchdog_force_write(hm2); } diff --git a/src/hal/drivers/mesa-hostmot2/hostmot2.h b/src/hal/drivers/mesa-hostmot2/hostmot2.h index 569ee045c05..69e7de91bbb 100644 --- a/src/hal/drivers/mesa-hostmot2/hostmot2.h +++ b/src/hal/drivers/mesa-hostmot2/hostmot2.h @@ -194,15 +194,15 @@ typedef struct { struct { struct { - hal_bit_t *in; - hal_bit_t *in_not; - hal_bit_t *out; + hal_bool_t in; + hal_bool_t in_not; + hal_bool_t out; } pin; struct { - hal_bit_t is_output; - hal_bit_t is_opendrain; - hal_bit_t invert_output; + hal_bool_t is_output; + hal_bool_t is_opendrain; + hal_bool_t invert_output; } param; } hal; @@ -281,35 +281,35 @@ typedef struct { struct { struct { - hal_s32_t *rawcounts; // raw encoder counts (truncated view of 64-bit internal) - hal_s32_t *rawlatch; // raw encoder of latch (truncated view) - hal_s32_t *count; // (rawcounts - zero_offset), truncated view - hal_s32_t *count_latch; // (rawlatch - zero_offset), truncated view - hal_float_t *position; - hal_float_t *position_latch; - hal_float_t *position_interpolated; - hal_float_t *velocity; - hal_float_t *velocity_rpm; - hal_bit_t *reset; - hal_bit_t *index_enable; - hal_bit_t *latch_enable; - hal_bit_t *latch_polarity; - hal_bit_t *no_clear_on_index; - hal_bit_t *quadrature_error; - hal_bit_t *quadrature_error_enable; - hal_bit_t *input_a; - hal_bit_t *input_b; - hal_bit_t *input_idx; + hal_sint_t rawcounts; // raw encoder counts (truncated view of 64-bit internal) + hal_sint_t rawlatch; // raw encoder of latch (truncated view) + hal_sint_t count; // (rawcounts - zero_offset), truncated view + hal_sint_t count_latch; // (rawlatch - zero_offset), truncated view + hal_real_t position; + hal_real_t position_latch; + hal_real_t position_interpolated; + hal_real_t velocity; + hal_real_t velocity_rpm; + hal_bool_t reset; + hal_bool_t index_enable; + hal_bool_t latch_enable; + hal_bool_t latch_polarity; + hal_bool_t no_clear_on_index; + hal_bool_t quadrature_error; + hal_bool_t quadrature_error_enable; + hal_bool_t input_a; + hal_bool_t input_b; + hal_bool_t input_idx; } pin; struct { - hal_float_t scale; - hal_bit_t index_invert; - hal_bit_t index_mask; - hal_bit_t index_mask_invert; - hal_bit_t counter_mode; - hal_bit_t filter; - hal_float_t vel_timeout; + hal_real_t scale; + hal_bool_t index_invert; + hal_bool_t index_mask; + hal_bool_t index_mask_invert; + hal_bool_t counter_mode; + hal_bool_t filter; + hal_real_t vel_timeout; } param; @@ -331,8 +331,8 @@ typedef struct { rtapi_u32 prev_control; - hal_bit_t prev_quadrature_error_enable; // shadow for detecting rising edge on the quadrature_error_enable - hal_bit_t reset_quadrature_error; // bit to indicate if we want to reset the quadrature error + rtapi_bool prev_quadrature_error_enable; // shadow for detecting rising edge on the quadrature_error_enable + rtapi_bool reset_quadrature_error; // bit to indicate if we want to reset the quadrature error // these two are the datapoint last time we moved (only valid if state == HM2_ENCODER_MOVING) @@ -350,10 +350,10 @@ typedef struct { // these hal pins affect all encoder instances typedef struct { struct { - hal_u32_t *sample_frequency; - hal_u32_t *skew; - hal_s32_t *dpll_timer_num; - hal_bit_t *hires_timestamp; + hal_uint_t sample_frequency; + hal_uint_t skew; + hal_sint_t dpll_timer_num; + hal_bool_t hires_timestamp; } pin; } hm2_encoder_module_global_t; @@ -374,7 +374,7 @@ typedef struct { int has_skew; rtapi_u32 written_skew; rtapi_u32 written_hires_timestamp; - uint32_t desired_dpll_timer_reg, written_dpll_timer_reg; + rtapi_u32 desired_dpll_timer_reg, written_dpll_timer_reg; // hw registers rtapi_u32 counter_addr; @@ -386,7 +386,7 @@ typedef struct { rtapi_u32 timestamp_div_addr; rtapi_u32 timestamp_div_reg; // one register for the whole Function - hal_float_t seconds_per_tsdiv_clock; + rtapi_real seconds_per_tsdiv_clock; rtapi_u32 timestamp_count_addr; rtapi_u32 *timestamp_count_reg; @@ -442,23 +442,23 @@ typedef struct { struct { struct { - hal_s32_t *rawcounts; - hal_s32_t *count; - hal_float_t *angle; - hal_float_t *position; - hal_float_t *velocity; - hal_float_t *velocity_rpm; - hal_bit_t *reset; - hal_bit_t *index_enable; - hal_bit_t *error; - hal_float_t *joint_pos_fb; + hal_sint_t rawcounts; + hal_sint_t count; + hal_real_t angle; + hal_real_t position; + hal_real_t velocity; + hal_real_t velocity_rpm; + hal_bool_t reset; + hal_bool_t index_enable; + hal_bool_t error; + hal_real_t joint_pos_fb; } pin; struct { - hal_float_t scale; - hal_float_t vel_scale; - hal_u32_t index_div; - hal_bit_t use_abs; + hal_real_t scale; + hal_real_t vel_scale; + hal_uint_t index_div; + hal_bool_t use_abs; } param; } hal; @@ -472,7 +472,7 @@ typedef struct { typedef struct { struct { - hal_float_t excitation_khz; + hal_real_t excitation_khz; } param; } hm2_resolver_global_t; @@ -501,8 +501,8 @@ typedef struct { rtapi_u32 velocity_addr; rtapi_s32 *velocity_reg; - hal_float_t written_khz; - hal_float_t kHz; + rtapi_real written_khz; + rtapi_real kHz; } hm2_resolver_t; @@ -521,15 +521,15 @@ typedef struct { struct { struct { - hal_float_t *value; - hal_bit_t *enable; + hal_real_t value; + hal_bool_t enable; } pin; struct { - hal_float_t scale; - hal_bit_t offset_mode; - hal_s32_t output_type; - hal_bit_t dither; + hal_real_t scale; + hal_bool_t offset_mode; + hal_sint_t output_type; + hal_bool_t dither; } param; } hal; @@ -556,8 +556,8 @@ typedef struct { // these hal params affect all pwmgen instances typedef struct { struct { - hal_u32_t pwm_frequency; - hal_u32_t pdm_frequency; + hal_uint_t pwm_frequency; + hal_uint_t pdm_frequency; } param; } hm2_pwmgen_module_global_t; @@ -609,31 +609,31 @@ typedef struct { struct { struct { - hal_float_t *width1; - hal_float_t *width2; - hal_float_t *filter1; - hal_float_t *filter2; - hal_float_t *rate; - hal_u32_t *trigselect1; - hal_u32_t *trigselect2; - hal_bit_t *trigrise1; - hal_bit_t *trigrise2; - hal_bit_t *trigfall1; - hal_bit_t *trigfall2; - hal_bit_t *retrig1; - hal_bit_t *retrig2; - hal_bit_t *enable1; - hal_bit_t *enable2; - hal_bit_t *reset1; - hal_bit_t *reset2; - hal_bit_t *swtrig1; - hal_bit_t *swtrig2; - hal_bit_t *exttrig1; - hal_bit_t *exttrig2; - hal_bit_t *out1; - hal_bit_t *out2; + hal_real_t width1; + hal_real_t width2; + hal_real_t filter1; + hal_real_t filter2; + hal_real_t rate; + hal_uint_t trigselect1; + hal_uint_t trigselect2; + hal_bool_t trigrise1; + hal_bool_t trigrise2; + hal_bool_t trigfall1; + hal_bool_t trigfall2; + hal_bool_t retrig1; + hal_bool_t retrig2; + hal_bool_t enable1; + hal_bool_t enable2; + hal_bool_t reset1; + hal_bool_t reset2; + hal_bool_t swtrig1; + hal_bool_t swtrig2; + hal_bool_t exttrig1; + hal_bool_t exttrig2; + hal_bool_t out1; + hal_bool_t out2; - hal_s32_t *dpll_timer_num; + hal_sint_t dpll_timer_num; } pin; } hal; @@ -682,18 +682,18 @@ typedef struct { struct { struct { - hal_float_t *period; - hal_float_t *width; - hal_float_t *dutycycle; - hal_float_t *frequency; - hal_float_t *filtertc; - hal_float_t *dutyscale; - hal_float_t *dutyoffset; - hal_float_t *minfreq; - hal_u32_t *averages; - hal_bit_t *polarity; - hal_bit_t *valid; - hal_bit_t *input; + hal_real_t period; + hal_real_t width; + hal_real_t dutycycle; + hal_real_t frequency; + hal_real_t filtertc; + hal_real_t dutyscale; + hal_real_t dutyoffset; + hal_real_t minfreq; + hal_uint_t averages; + hal_bool_t polarity; + hal_bool_t valid; + hal_bool_t input; } pin; } hal; @@ -735,9 +735,9 @@ typedef struct { struct { struct { - hal_float_t *width; - hal_float_t *scale; - hal_float_t *offset; + hal_real_t width; + hal_real_t scale; + hal_real_t offset; } pin; } hal; @@ -747,7 +747,7 @@ typedef struct { // this hal pin affects all rcpwmgen instances typedef struct { struct { - hal_float_t *rate; + hal_real_t rate; } pin; } hm2_rcpwmgen_module_global_t; @@ -784,31 +784,30 @@ typedef struct { struct { struct { - hal_bit_t *filt_data[32]; - hal_bit_t *raw_data[32]; - hal_bit_t *filt_data_not[32]; - hal_bit_t *raw_data_not[32]; - hal_bit_t *slow[32] ; - hal_s32_t *enc0_count; - hal_s32_t *enc1_count; - hal_s32_t *enc2_count; - hal_s32_t *enc3_count; - hal_bit_t *enc0_reset; - hal_bit_t *enc1_reset; - hal_bit_t *enc2_reset; - hal_bit_t *enc3_reset; - + hal_bool_t filt_data[32]; + hal_bool_t raw_data[32]; + hal_bool_t filt_data_not[32]; + hal_bool_t raw_data_not[32]; + hal_bool_t slow[32]; + hal_sint_t enc0_count; + hal_sint_t enc1_count; + hal_sint_t enc2_count; + hal_sint_t enc3_count; + hal_bool_t enc0_reset; + hal_bool_t enc1_reset; + hal_bool_t enc2_reset; + hal_bool_t enc3_reset; } pin; struct { - hal_u32_t scan_rate; - hal_u32_t slow_scans; - hal_u32_t fast_scans; - hal_bit_t enc0_mode; - hal_bit_t enc1_mode; - hal_bit_t enc2_mode; - hal_bit_t enc3_mode; - hal_u32_t scan_width; + hal_uint_t scan_rate; + hal_uint_t slow_scans; + hal_uint_t fast_scans; + hal_bool_t enc0_mode; + hal_bool_t enc1_mode; + hal_bool_t enc2_mode; + hal_bool_t enc3_mode; + hal_uint_t scan_width; } param; } hal; @@ -879,30 +878,30 @@ typedef struct { struct { struct { - hal_bit_t *filt_data[32]; - hal_bit_t *raw_data[32]; - hal_bit_t *filt_data_not[32]; - hal_bit_t *raw_data_not[32]; - hal_bit_t *slow[32] ; - hal_s32_t *enc0_count; - hal_s32_t *enc1_count; - hal_s32_t *enc2_count; - hal_s32_t *enc3_count; - hal_bit_t *enc0_reset; - hal_bit_t *enc1_reset; - hal_bit_t *enc2_reset; - hal_bit_t *enc3_reset; + hal_bool_t filt_data[32]; + hal_bool_t raw_data[32]; + hal_bool_t filt_data_not[32]; + hal_bool_t raw_data_not[32]; + hal_bool_t slow[32]; + hal_sint_t enc0_count; + hal_sint_t enc1_count; + hal_sint_t enc2_count; + hal_sint_t enc3_count; + hal_bool_t enc0_reset; + hal_bool_t enc1_reset; + hal_bool_t enc2_reset; + hal_bool_t enc3_reset; } pin; struct { - hal_u32_t scan_rate; - hal_u32_t slow_scans; - hal_u32_t fast_scans; - hal_bit_t enc0_mode; - hal_bit_t enc1_mode; - hal_bit_t enc2_mode; - hal_bit_t enc3_mode; - hal_u32_t scan_width; + hal_uint_t scan_rate; + hal_uint_t slow_scans; + hal_uint_t fast_scans; + hal_bool_t enc0_mode; + hal_bool_t enc1_mode; + hal_bool_t enc2_mode; + hal_bool_t enc3_mode; + hal_uint_t scan_width; } param; } hal; @@ -979,53 +978,53 @@ typedef struct { struct { struct { - hal_float_t *accx_cmd; - hal_float_t *accy_cmd; - hal_float_t *velx_cmd; - hal_float_t *vely_cmd; - hal_float_t *posx_cmd; - hal_float_t *posy_cmd; - hal_float_t *velx_fb; - hal_float_t *vely_fb; - hal_float_t *posx_fb; - hal_float_t *posy_fb; - hal_float_t *posx_scale; - hal_float_t *posy_scale; - hal_bit_t *enable; - hal_u32_t *controlx; - hal_u32_t *controly; - hal_u32_t *commandx; - hal_u32_t *commandy; - hal_bit_t *mode18bitx; - hal_bit_t *mode18bity; - hal_bit_t *commandmodex; - hal_bit_t *commandmodey; - hal_u32_t *status; - hal_bit_t *posx_overflow; - hal_bit_t *posy_overflow; - hal_bit_t *velx_overflow; - hal_bit_t *vely_overflow; + hal_real_t accx_cmd; + hal_real_t accy_cmd; + hal_real_t velx_cmd; + hal_real_t vely_cmd; + hal_real_t posx_cmd; + hal_real_t posy_cmd; + hal_real_t velx_fb; + hal_real_t vely_fb; + hal_real_t posx_fb; + hal_real_t posy_fb; + hal_real_t posx_scale; + hal_real_t posy_scale; + hal_bool_t enable; + hal_uint_t controlx; + hal_uint_t controly; + hal_uint_t commandx; + hal_uint_t commandy; + hal_bool_t mode18bitx; + hal_bool_t mode18bity; + hal_bool_t commandmodex; + hal_bool_t commandmodey; + hal_uint_t status; + hal_bool_t posx_overflow; + hal_bool_t posy_overflow; + hal_bool_t velx_overflow; + hal_bool_t vely_overflow; } pin; } hal; //previous MPG counts for this instance - hal_float_t prev_accx_cmd; - hal_float_t prev_accy_cmd; - hal_float_t prev_velx_cmd; - hal_float_t prev_vely_cmd; - hal_float_t prev_posx_cmd; - hal_float_t prev_posy_cmd; + rtapi_real prev_accx_cmd; + rtapi_real prev_accy_cmd; + rtapi_real prev_velx_cmd; + rtapi_real prev_vely_cmd; + rtapi_real prev_posx_cmd; + rtapi_real prev_posy_cmd; } hm2_xy2mod_instance_t; -// these hal params affect all xy2mod instances +// these hal pins affect all xy2mod instances typedef struct { struct { - hal_s32_t *dpll_rtimer_num; - hal_s32_t *dpll_wtimer_num; + hal_sint_t dpll_rtimer_num; + hal_sint_t dpll_wtimer_num; } pin; } hm2_xy2mod_module_global_t; @@ -1041,8 +1040,8 @@ typedef struct { // module-global HAL objects... hm2_xy2mod_module_global_t *hal; - rtapi_u32 written_dpll_rtimer_num; - rtapi_u32 written_dpll_wtimer_num; + rtapi_s32 written_dpll_rtimer_num; + rtapi_s32 written_dpll_wtimer_num; rtapi_u32 accx_addr; @@ -1092,18 +1091,18 @@ typedef struct { struct { struct { - hal_float_t *Avalue; - hal_float_t *Bvalue; - hal_float_t *Cvalue; - hal_bit_t *fault; - hal_bit_t *enable; + hal_real_t Avalue; + hal_real_t Bvalue; + hal_real_t Cvalue; + hal_bool_t fault; + hal_bool_t enable; } pin; struct { - hal_float_t scale; - hal_float_t deadzone; - hal_bit_t faultpolarity; - hal_float_t sampletime; + hal_real_t scale; + hal_real_t deadzone; + hal_bool_t faultpolarity; + hal_real_t sampletime; } param; } hal; @@ -1112,14 +1111,14 @@ typedef struct { // know if an update-write is needed // enable is a little more complicated and is based on the read-back // of the fault/enable register - double written_deadzone; - int written_faultpolarity; - double written_sampletime; + rtapi_real written_deadzone; + rtapi_bool written_faultpolarity; + rtapi_real written_sampletime; } hm2_tp_pwmgen_instance_t; typedef struct { struct { - hal_u32_t pwm_frequency; // One PWM rate for all instances + hal_uint_t pwm_frequency; // One PWM rate for all instances } param; } hm2_tp_pwmgen_global_hal_t; @@ -1205,49 +1204,55 @@ typedef struct { struct { struct { - hal_float_t *position_cmd; - hal_float_t *velocity_cmd; - hal_s32_t *counts; - hal_float_t *position_fb; - hal_float_t *position_latch; - hal_float_t *velocity_fb; - hal_bit_t *enable; - hal_bit_t *control_type; // 0="position control", 1="velocity control" - hal_bit_t *position_reset; // reset position when true - hal_bit_t *index_enable; - hal_bit_t *index_polarity; - hal_bit_t *latch_enable; - hal_bit_t *latch_polarity; + hal_real_t position_cmd; + hal_real_t velocity_cmd; + hal_sint_t counts; + hal_real_t position_fb; + hal_real_t position_latch; + hal_real_t velocity_fb; + hal_bool_t enable; + hal_bool_t control_type; // 0="position control", 1="velocity control" + hal_bool_t position_reset; // reset position when true + hal_bool_t index_enable; + hal_bool_t index_polarity; + hal_bool_t latch_enable; + hal_bool_t latch_polarity; // debug pins - hal_float_t *dbg_ff_vel; - hal_float_t *dbg_vel_error; - hal_float_t *dbg_s_to_match; - hal_float_t *dbg_err_at_match; - hal_s32_t *dbg_step_rate; - hal_float_t *dbg_pos_minus_prev_cmd; + hal_real_t dbg_ff_vel; + hal_real_t dbg_vel_error; + hal_real_t dbg_s_to_match; + hal_real_t dbg_err_at_match; + hal_sint_t dbg_step_rate; + hal_real_t dbg_pos_minus_prev_cmd; } pin; struct { - hal_float_t position_scale; - hal_float_t maxvel; - hal_float_t maxaccel; - - hal_u32_t steplen; - hal_u32_t stepspace; - hal_u32_t dirsetup; - hal_u32_t dirhold; - - hal_u32_t step_type; - hal_bit_t swap_step_dir; - hal_u32_t table[5]; // the Fifth Element is used as a very crude hash + hal_real_t position_scale; + hal_real_t maxvel; + hal_real_t maxaccel; + + hal_uint_t steplen; + hal_uint_t stepspace; + hal_uint_t dirsetup; + hal_uint_t dirhold; + + hal_uint_t step_type; + hal_bool_t swap_step_dir; + hal_uint_t table[4]; + // the Fifth Element was moved below (used as a very crude hash) } param; } hal; + // This was originally the fifth parameter element in 'table'. It was moved + // here because there was no parameter allocated and is an instance value. + // Parameters work like pins now and cannot be used as local storage. + rtapi_u32 tablehash; + // this variable holds the previous position command, for // computing the feedforward velocity - hal_float_t old_position_cmd; + rtapi_real old_position_cmd; rtapi_u32 prev_accumulator; @@ -1275,7 +1280,7 @@ typedef struct { // these hal params affect all stepgen instances typedef struct { struct { - hal_s32_t *dpll_timer_num; + hal_sint_t dpll_timer_num; } pin; } hm2_stepgen_module_global_t; @@ -1335,7 +1340,9 @@ typedef struct { int conf_flag[16]; rtapi_u16 cd_addr; rtapi_u16 count_addr; - hal_u32_t *count; + // FIXME: count is not used + //hal_u32_t *count; + // FIXME ^^^^^ int num_frames; rtapi_u32 clock_freq; rtapi_u16 base_address; @@ -1426,16 +1433,16 @@ typedef struct { // typedef struct { - hal_float_t *time1_us; - hal_float_t *time2_us; - hal_float_t *time3_us; - hal_float_t *time4_us; - hal_float_t *base_freq; - hal_float_t *phase_error; - hal_u32_t *plimit; - hal_u32_t *ddssize; - hal_u32_t *time_const; - hal_u32_t *prescale; + hal_real_t time1_us; + hal_real_t time2_us; + hal_real_t time3_us; + hal_real_t time4_us; + hal_real_t base_freq; + hal_real_t phase_error; + hal_uint_t plimit; + hal_uint_t ddssize; + hal_uint_t time_const; + hal_uint_t prescale; } hm2_dpll_pins_t ; typedef struct { @@ -1470,11 +1477,11 @@ typedef struct { struct { struct { - hal_bit_t *has_bit; + hal_bool_t has_bit; } pin; struct { - hal_u32_t timeout_ns; + hal_uint_t timeout_ns; } param; } hal; @@ -1508,7 +1515,7 @@ typedef struct { // typedef struct { - hal_bit_t *led; + hal_bool_t led; } hm2_led_instance_t ; typedef struct { @@ -1533,9 +1540,9 @@ typedef struct { struct { struct { - hal_u32_t *rate; - hal_bit_t *out[32]; - hal_bit_t *invert[32]; + hal_uint_t rate; + hal_bool_t out[32]; + hal_bool_t invert[32]; } pin; } hal; @@ -1566,8 +1573,8 @@ typedef struct { struct { struct { - hal_bit_t *out[32]; - hal_bit_t *invert[32]; + hal_bool_t out[32]; + hal_bool_t invert[32]; } pin; } hal; @@ -1596,14 +1603,14 @@ typedef struct { typedef struct { struct { struct { - hal_u32_t *read_address; - hal_u32_t *read_data; + hal_uint_t read_address; + hal_uint_t read_data; - hal_u32_t *write_address; - hal_u32_t *write_data; - hal_bit_t *write_strobe; + hal_uint_t write_address; + hal_uint_t write_data; + hal_bool_t write_strobe; - hal_bit_t *dump_state; + hal_bool_t dump_state; } pin; } hal; } hm2_raw_t; diff --git a/src/hal/drivers/mesa-hostmot2/inm.c b/src/hal/drivers/mesa-hostmot2/inm.c index 22886f80801..e2e0ef8a409 100644 --- a/src/hal/drivers/mesa-hostmot2/inm.c +++ b/src/hal/drivers/mesa-hostmot2/inm.c @@ -96,7 +96,7 @@ int hm2_inm_parse_md(hostmot2_t *hm2, int md_index) { hm2->inm.clock_frequency = md->clock_freq; hm2->inm.version = md->version; - hm2->inm.instance = (hm2_inm_instance_t *)hal_malloc(hm2->inm.num_instances * sizeof(hm2_inm_instance_t)); + hm2->inm.instance = hal_malloc(hm2->inm.num_instances * sizeof(*hm2->inm.instance)); if (hm2->inm.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -153,247 +153,220 @@ int hm2_inm_parse_md(hostmot2_t *hm2, int md_index) { // Export to HAL. // - { - int i; - int j; - int inm_number; - int temp; - char name[HAL_NAME_LEN + 1]; - - for (i = 0; i < hm2->inm.num_instances; i ++) { - hm2->inm.instance[i].enc0_present = false; - hm2->inm.instance[i].enc1_present = false; - hm2->inm.instance[i].enc2_present = false; - hm2->inm.instance[i].enc3_present = false; - temp = 0; - // Determine which MPG encoders have both pins so are useable - for (j = 0; j < hm2->num_pins; j++){ - if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { - inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; - if (inm_number < 8) { - temp = temp | (1 << inm_number); - } + for (int i = 0; i < hm2->inm.num_instances; i ++) { + hm2_inm_instance_t *inst = &hm2->inm.instance[i]; + inst->enc0_present = false; + inst->enc1_present = false; + inst->enc2_present = false; + inst->enc3_present = false; + rtapi_u32 temp = 0; + // Determine which MPG encoders have both pins so are useable + for (int j = 0; j < hm2->num_pins; j++){ + if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { + int inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; + if (inm_number < 8) { + temp = temp | (1 << inm_number); } } - if ((temp & 0x03) == 0x03) { - hm2->inm.instance[i].enc0_present = true; - } - if ((temp & 0x0C) == 0x0C) { - hm2->inm.instance[i].enc1_present = true; - } - if ((temp & 0x30) == 0x30) { - hm2->inm.instance[i].enc2_present = true; - } - if ((temp & 0xC0) == 0xC0) { - hm2->inm.instance[i].enc3_present = true; - } - // Do a low level read to determine the per instance scanwidth - hm2->llio->read(hm2->llio,hm2->inm.control_addr + (i * md->instance_stride),&temp, sizeof(rtapi_u32)); - temp = (temp & 0x0000001f) +1; - hm2->inm.instance[i].scanwidth = temp; - hm2->inm.instance[i].hal.param.scan_width = temp; - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.scan_rate", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.scan_rate), hm2->llio->comp_id); + } + if ((temp & 0x03) == 0x03) { + inst->enc0_present = true; + } + if ((temp & 0x0C) == 0x0C) { + inst->enc1_present = true; + } + if ((temp & 0x30) == 0x30) { + inst->enc2_present = true; + } + if ((temp & 0xC0) == 0xC0) { + inst->enc3_present = true; + } + // Do a low level read to determine the per instance scanwidth + hm2->llio->read(hm2->llio,hm2->inm.control_addr + (i * md->instance_stride),&temp, sizeof(rtapi_u32)); + temp = (temp & 0x0000001f) +1; + inst->scanwidth = temp; + // init 20000: 20 KHz = 50 usec/scan + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.scan_rate), + 20000, "%s.inm.%02d.scan_rate", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.inm.%02d.scan_rate', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + // init 500: 500*50 usec = 25 ms + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.slow_scans), + 500, "%s.inm.%02d.slow_scans", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.inm.%02d.slow_scans', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + // init 5: 5*50 usec = 250 usec + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.fast_scans), + 5, "%s.inm.%02d.fast_scans", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.inm.%02d.fast_scans', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + + if (inst->enc0_present) { + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc0_mode), + 0, "%s.inm.%02d.enc0_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inm.%02d.enc0_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.slow_scans", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.slow_scans), hm2->llio->comp_id); + } + + if (inst->enc1_present) { + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc1_mode), + 0, "%s.inm.%02d.enc1_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inm.%02d.enc1_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.fast_scans", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.fast_scans), hm2->llio->comp_id); + } + } + + if (inst->enc2_present) { + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc2_mode), + 0, "%s.inm.%02d.enc2_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inm.%02d.enc2_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; - } - - if (hm2->inm.instance[i].enc0_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc0_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.enc0_mode), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); - goto fail1; - } - } - - if (hm2->inm.instance[i].enc1_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc1_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.enc1_mode), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); - goto fail1; - } - } - - if (hm2->inm.instance[i].enc2_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc2_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.enc2_mode), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); - goto fail1; - } - } - - if (hm2->inm.instance[i].enc3_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc3_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inm.instance[i].hal.param.enc3_mode), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); - goto fail1; - } } - - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.scan_width", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RO, &(hm2->inm.instance[i].hal.param.scan_width), hm2->llio->comp_id); + } + + if (inst->enc3_present) { + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc3_mode), + 0, "%s.inm.%02d.enc3_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inm.%02d.enc3_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } + } - int j = 0; - int inm_number; - for (j = 0; j < hm2->num_pins; j++){ - if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { - if ((hm2->pin[j].sec_pin & 0x80) != 00) { - HM2_ERR("Pin Descriptor %d has an inm pin that's not an input!\n", j); - r = -EINVAL; - goto fail0; - } - inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; - if (inm_number >= 32) { - HM2_ERR("Pin Descriptor %d has invalid secondary pin number %d for inm module!\n", j, inm_number); - r = -EINVAL; - goto fail0; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.input-%02d", hm2->llio->name, i, inm_number); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.filt_data[inm_number]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.raw-input-%02d", hm2->llio->name, i, inm_number); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.raw_data[inm_number]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.input-%02d-not", hm2->llio->name, i, inm_number); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.filt_data_not[inm_number]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.raw-input-%02d-not", hm2->llio->name, i, inm_number); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.raw_data_not[inm_number]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.input-%02d-slow", hm2->llio->name, i, inm_number); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inm.instance[i].hal.pin.slow[inm_number]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RO, &(inst->hal.param.scan_width), + temp, "%s.inm.%02d.scan_width", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.inm.%02d.scan_width', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + + for (int j = 0; j < hm2->num_pins; j++) { + if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { + if ((hm2->pin[j].sec_pin & 0x80) != 00) { + HM2_ERR("Pin Descriptor %d has an inm pin that's not an input!\n", j); + r = -EINVAL; + goto fail0; } - } - if (hm2->inm.instance[i].enc0_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc0-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.enc0_count), hm2->llio->comp_id); + int inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; + if (inm_number >= 32) { + HM2_ERR("Pin Descriptor %d has invalid secondary pin number %d for inm module!\n", j, inm_number); + r = -EINVAL; + goto fail0; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.filt_data[inm_number]), + 0, "%s.inm.%02d.input-%02d", hm2->llio->name, i, inm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; + HM2_ERR("error %d adding pin '%s.inm.%02d.input-%02d', aborting\n", r, hm2->llio->name, i, inm_number); + goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc0-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inm.instance[i].hal.pin.enc0_reset), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.raw_data[inm_number]), + 0, "%s.inm.%02d.raw-input-%02d", hm2->llio->name, i, inm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inm.%02d.raw-input-%02d', aborting\n", r, hm2->llio->name, i, inm_number); goto fail1; } - } - - if (hm2->inm.instance[i].enc1_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc1-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.enc1_count), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.filt_data_not[inm_number]), + 0, "%s.inm.%02d.input-%02d-not", hm2->llio->name, i, inm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inm.%02d.input-%02d-not', aborting\n", r, hm2->llio->name, i, inm_number); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc1-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inm.instance[i].hal.pin.enc1_reset), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.raw_data_not[inm_number]), + 0, "%s.inm.%02d.raw-input-%02d-not", hm2->llio->name, i, inm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inm.%02d.raw-input-%02d-not', aborting\n", r, hm2->llio->name, i, inm_number); goto fail1; } - - if (hm2->inm.instance[i].enc2_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc2-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.enc2_count), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc2-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inm.instance[i].hal.pin.enc2_reset), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.slow[inm_number]), + 0, "%s.inm.%02d.input-%02d-slow", hm2->llio->name, i, inm_number); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.input-%02d-slow', aborting\n", r, hm2->llio->name, i, inm_number); + goto fail1; } - if (hm2->inm.instance[i].enc3_present) { - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc3-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inm.instance[i].hal.pin.enc3_count), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inm.%02d.enc3-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inm.instance[i].hal.pin.enc3_reset), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - } + } + } + if (inst->enc0_present) { + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc0_count), + 0, "%s.inm.%02d.enc0-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc0-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc0_reset), + 0, "%s.inm.%02d.enc0-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc0-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + } + + if (inst->enc1_present) { + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc1_count), + 0, "%s.inm.%02d.enc1-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc1-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc1_reset), + 0, "%s.inm.%02d.enc1-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc1-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + } + + if (inst->enc2_present) { + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc2_count), + 0, "%s.inm.%02d.enc2-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc2-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc2_reset), + 0, "%s.inm.%02d.enc2-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc2-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + } + if (inst->enc3_present) { + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc3_count), + 0, "%s.inm.%02d.enc3-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc3-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc3_reset), + 0, "%s.inm.%02d.enc3-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inm.%02d.enc3-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; } } } // - // Set inm default scanrate and filter values + // Set inm default scanrate and filter values // and remove initial MPG offset - { - int i; - int rawmpgs; - for (i = 0; i < hm2->inm.num_instances; i ++) { - hm2->inm.instance[i].hal.param.scan_rate = 20000; // 20 KHz = 50 usec/scan - hm2->inm.instance[i].hal.param.slow_scans = 500; // 500*50 usec = 25 ms - hm2->inm.instance[i].hal.param.fast_scans = 5; // 5*50 usec = 250 usec - hm2->llio->read(hm2->llio,hm2->inm.mpg_read_addr + (i * md->instance_stride),&rawmpgs, sizeof(rtapi_u32)); - if (hm2->inm.instance[i].enc0_present) { hm2->inm.instance[i].prev_enc0_count = (rtapi_s32)((rawmpgs >> 0) & 0x000000FF); } - if (hm2->inm.instance[i].enc1_present) { hm2->inm.instance[i].prev_enc1_count = (rtapi_s32)((rawmpgs >> 8) & 0x000000FF); } - if (hm2->inm.instance[i].enc2_present) { hm2->inm.instance[i].prev_enc2_count = (rtapi_s32)((rawmpgs >> 16) & 0x000000FF); } - if (hm2->inm.instance[i].enc3_present) { hm2->inm.instance[i].prev_enc3_count = (rtapi_s32)((rawmpgs >> 24) & 0x000000FF); } - - } - + for (int i = 0; i < hm2->inm.num_instances; i ++) { + hm2_inm_instance_t *inst = &hm2->inm.instance[i]; + rtapi_u32 rawmpgs; + hm2->llio->read(hm2->llio,hm2->inm.mpg_read_addr + (i * md->instance_stride),&rawmpgs, sizeof(rtapi_u32)); + if (inst->enc0_present) { inst->prev_enc0_count = (rtapi_s32)((rawmpgs >> 0) & 0x000000FF); } + if (inst->enc1_present) { inst->prev_enc1_count = (rtapi_s32)((rawmpgs >> 8) & 0x000000FF); } + if (inst->enc2_present) { inst->prev_enc2_count = (rtapi_s32)((rawmpgs >> 16) & 0x000000FF); } + if (inst->enc3_present) { inst->prev_enc3_count = (rtapi_s32)((rawmpgs >> 24) & 0x000000FF); } } return hm2->inm.num_instances; @@ -420,24 +393,24 @@ void hm2_inm_force_write(hostmot2_t *hm2) { // setup control register and mpg_write for (i = 0; i < hm2->inm.num_instances; i ++) { - scanrate = hm2->inm.instance[i].scanwidth * hm2->inm.instance[i].hal.param.scan_rate; + hm2_inm_instance_t *inst = &hm2->inm.instance[i]; + scanrate = inst->scanwidth * hal_get_ui32(inst->hal.param.scan_rate); if (scanrate > 10000000) { scanrate = 10000000; - hm2->inm.instance[i].hal.param.scan_rate = scanrate/hm2->inm.instance[i].scanwidth; + hal_set_ui32(inst->hal.param.scan_rate, scanrate/inst->scanwidth); } divisor = (hm2->inm.clock_frequency / (4 * scanrate)) - 1; - if (hm2->inm.instance[i].hal.param.fast_scans > 63) { - hm2->inm.instance[i].hal.param.fast_scans = 63; + rtapi_u32 fast_scans = hal_get_ui32(inst->hal.param.fast_scans); + if (fast_scans > 63) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 63); } - if (hm2->inm.instance[i].hal.param.slow_scans > 1023) { - hm2->inm.instance[i].hal.param.slow_scans = 1023; + rtapi_u32 slow_scans = hal_get_ui32(inst->hal.param.slow_scans); + if (slow_scans > 1023) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1023); } - hm2->inm.control_reg[i] = (1 << 5) + -// global invert bit(5) fixed to true for now as this matches all existing hardware - (divisor << 6) + - (hm2->inm.instance[i].hal.param.fast_scans << 16) + - (hm2->inm.instance[i].hal.param.slow_scans << 22); + // global invert bit(5) fixed to true for now as this matches all existing hardware + hm2->inm.control_reg[i] = (1 << 5) + (divisor << 6) + (fast_scans << 16) + (slow_scans << 22); } size = hm2->inm.num_instances * sizeof(rtapi_u32); @@ -467,69 +440,69 @@ void hm2_inm_write(hostmot2_t *hm2) { for (i = 0; i < hm2->inm.num_instances; i ++) { - scanrate = hm2->inm.instance[i].scanwidth * hm2->inm.instance[i].hal.param.scan_rate; + hm2_inm_instance_t *inst = &hm2->inm.instance[i]; + scanrate = inst->scanwidth * hal_get_ui32(inst->hal.param.scan_rate); // bound scanrate maximum frequency if (scanrate > 10000000) { scanrate = 10000000; - hm2->inm.instance[i].hal.param.scan_rate = scanrate/hm2->inm.instance[i].scanwidth; - HM2_ERR("inm %d scanrate too high, resetting to %d \n", i,hm2->inm.instance[i].hal.param.scan_rate); + hal_set_ui32(inst->hal.param.scan_rate, scanrate/inst->scanwidth); + HM2_ERR("inm %d scanrate too high, resetting to %d \n", i, hal_get_ui32(inst->hal.param.scan_rate)); } divisor = (hm2->inm.clock_frequency / (4 * scanrate)) - 1; // bound divisor so we dont splatter into other fields if ((divisor > 1023 ) | (scanrate == 0 )) { divisor = 1023; - hm2->inm.instance[i].hal.param.scan_rate = (hm2->inm.clock_frequency/4)/(divisor +1) - /hm2->inm.instance[i].scanwidth; - HM2_ERR("inm %d scanrate too low, resetting to %d \n", i,hm2->inm.instance[i].hal.param.scan_rate); + hal_set_ui32(inst->hal.param.scan_rate, (hm2->inm.clock_frequency/4)/(divisor +1) + /inst->scanwidth); + HM2_ERR("inm %d scanrate too low, resetting to %d \n", i, hal_get_ui32(inst->hal.param.scan_rate)); } - if (hm2->inm.instance[i].hal.param.fast_scans > 63) { - hm2->inm.instance[i].hal.param.fast_scans = 63; + rtapi_u32 fast_scans = hal_get_ui32(inst->hal.param.fast_scans); + if (fast_scans > 63) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 63); HM2_ERR("inm %d fastscans must be less than 63, resetting to %d \n", i,63); } - if (hm2->inm.instance[i].hal.param.slow_scans > 1023) { - hm2->inm.instance[i].hal.param.slow_scans = 1023; + rtapi_u32 slow_scans = hal_get_ui32(inst->hal.param.slow_scans); + if (slow_scans > 1023) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1023); HM2_ERR("inm %d slowscans must be less than 1023, resetting to %d \n", i,1023); } - if (hm2->inm.instance[i].hal.param.fast_scans < 1 ) { - hm2->inm.instance[i].hal.param.fast_scans = 1; + if (fast_scans < 1 ) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 1); HM2_ERR("inm %d fastscans must be greater than 0, resetting to %d \n", i,1); } - if (hm2->inm.instance[i].hal.param.slow_scans < 1) { - hm2->inm.instance[i].hal.param.slow_scans = 1; + if (slow_scans < 1) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1); HM2_ERR("inm %d slowscans must be greater than 0, resetting to %d \n", i,1); } - hm2->inm.control_reg[i] = (1 << 5) + -// global invert bit(5) fixed to true for now as this matches all existing hardware) - (divisor << 6) + - (hm2->inm.instance[i].hal.param.fast_scans << 16) + - (hm2->inm.instance[i].hal.param.slow_scans << 22); - if (hm2->inm.control_reg[i] != hm2->inm.instance[i].written_control_reg) { + // global invert bit(5) fixed to true for now as this matches all existing hardware) + hm2->inm.control_reg[i] = (1 << 5) + (divisor << 6) + (fast_scans << 16) + (slow_scans << 22); + if (hm2->inm.control_reg[i] != inst->written_control_reg) { hm2->llio->write(hm2->llio, hm2->inm.control_addr, hm2->inm.control_reg, size); - hm2->inm.instance[i].written_control_reg = hm2->inm.control_reg[i]; + inst->written_control_reg = hm2->inm.control_reg[i]; // HM2_PRINT(" Debug: updating inm control reg to = 0x%08X\n", hm2->inm.control_reg[i]); } hm2->inm.filter_reg[i] = 0; for (j = 0; j < hm2->num_pins; j++){ if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; - hm2->inm.filter_reg[i] |= (*hm2->inm.instance[i].hal.pin.slow[inm_number] << inm_number); + hm2->inm.filter_reg[i] |= (hal_get_bool(inst->hal.pin.slow[inm_number]) << inm_number); } } - if (hm2->inm.filter_reg[i] != hm2->inm.instance[i].written_filter_reg) { + if (hm2->inm.filter_reg[i] != inst->written_filter_reg) { hm2->llio->write(hm2->llio, hm2->inm.filter_addr, hm2->inm.filter_reg, size); - hm2->inm.instance[i].written_filter_reg = hm2->inm.filter_reg[i]; + inst->written_filter_reg = hm2->inm.filter_reg[i]; // HM2_PRINT(" Debug: updating inm filter reg to = 0x%08X\n", hm2->inm.filter_reg[i]); } hm2->inm.mpg_mode_reg[i] = 0; - if (hm2->inm.instance[i].enc0_present) { hm2->inm.mpg_mode_reg[i] = hm2->inm.instance[i].hal.param.enc0_mode << 0; } - if (hm2->inm.instance[i].enc1_present) { hm2->inm.mpg_mode_reg[i] |= hm2->inm.instance[i].hal.param.enc1_mode << 8; } - if (hm2->inm.instance[i].enc2_present) { hm2->inm.mpg_mode_reg[i] |= hm2->inm.instance[i].hal.param.enc2_mode << 16; } - if (hm2->inm.instance[i].enc3_present) { hm2->inm.mpg_mode_reg[i] |= hm2->inm.instance[i].hal.param.enc3_mode << 24; } - if (hm2->inm.mpg_mode_reg[i] != hm2->inm.instance[i].written_mpg_mode_reg) { + if (inst->enc0_present) { hm2->inm.mpg_mode_reg[i] = hal_get_bool(inst->hal.param.enc0_mode) << 0; } + if (inst->enc1_present) { hm2->inm.mpg_mode_reg[i] |= hal_get_bool(inst->hal.param.enc1_mode) << 8; } + if (inst->enc2_present) { hm2->inm.mpg_mode_reg[i] |= hal_get_bool(inst->hal.param.enc2_mode) << 16; } + if (inst->enc3_present) { hm2->inm.mpg_mode_reg[i] |= hal_get_bool(inst->hal.param.enc3_mode) << 24; } + if (hm2->inm.mpg_mode_reg[i] != inst->written_mpg_mode_reg) { hm2->llio->write(hm2->llio, hm2->inm.mpg_mode_addr, hm2->inm.mpg_mode_reg, size); - hm2->inm.instance[i].written_mpg_mode_reg = hm2->inm.mpg_mode_reg[i]; + inst->written_mpg_mode_reg = hm2->inm.mpg_mode_reg[i]; // HM2_PRINT(" Debug: updating inm mpg mode reg to = 0x%08X\n", hm2->inm.mpg_mode_reg[i]); } } @@ -547,7 +520,7 @@ void hm2_inm_prepare_tram_write(hostmot2_t *hm2) { for (j = 0; j < hm2->num_pins; j++){ if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; - hm2->inm.filter_reg[i] |= (*hm2->inm.instance[i].hal.pin.slow[inm_number] << inm_number); + hm2->inm.filter_reg[i] |= (hal_get_bool(hm2->inm.instance[i].hal.pin.slow[inm_number]) << inm_number); } } } @@ -564,60 +537,69 @@ void hm2_inm_process_tram_read(hostmot2_t *hm2) { return; } for (i = 0; i < hm2->inm.num_instances; i ++) { + hm2_inm_instance_t *inst = &hm2->inm.instance[i]; for (j = 0; j < hm2->num_pins; j++){ if (hm2->pin[j].sec_tag == HM2_GTAG_INM && hm2->pin[j].sec_unit == i) { inm_number = (hm2->pin[j].sec_pin & 0x7f) - 1; - *hm2->inm.instance[i].hal.pin.filt_data[inm_number] = (hm2->inm.filt_data_reg[i] >> inm_number) &1; - *hm2->inm.instance[i].hal.pin.raw_data[inm_number] = (hm2->inm.raw_data_reg[i] >> inm_number) &1; - *hm2->inm.instance[i].hal.pin.filt_data_not[inm_number] = !((hm2->inm.filt_data_reg[i] >> inm_number) &1); - *hm2->inm.instance[i].hal.pin.raw_data_not[inm_number] = !((hm2->inm.raw_data_reg[i] >> inm_number) &1); + hal_set_bool(inst->hal.pin.filt_data[inm_number], (hm2->inm.filt_data_reg[i] >> inm_number) & 1); + hal_set_bool(inst->hal.pin.raw_data[inm_number], (hm2->inm.raw_data_reg[i] >> inm_number) & 1); + hal_set_bool(inst->hal.pin.filt_data_not[inm_number], !((hm2->inm.filt_data_reg[i] >> inm_number) & 1)); + hal_set_bool(inst->hal.pin.raw_data_not[inm_number], !((hm2->inm.raw_data_reg[i] >> inm_number) & 1)); + } + } + + if (inst->enc0_present) { + raw_count = hm2->inm.mpg_read_reg[i] & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc0_count; + inst->prev_enc0_count = inst->prev_enc0_count + count_diff; + if (count_diff > 128) count_diff -= 256; + if (count_diff < -128) count_diff += 256; + if (!hal_get_bool(inst->hal.pin.enc0_reset)) { + hal_set_si32(inst->hal.pin.enc0_count, hal_get_si32(inst->hal.pin.enc0_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc0_count, 0); } } - if (hm2->inm.instance[i].enc0_present) { - raw_count = hm2->inm.mpg_read_reg[i] & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inm.instance[i].prev_enc0_count; - hm2->inm.instance[i].prev_enc0_count = hm2->inm.instance[i].prev_enc0_count + count_diff; - if (count_diff > 128) count_diff -= 256; - if (count_diff < -128) count_diff += 256; - if (*hm2->inm.instance[i].hal.pin.enc0_reset == 0) { - *hm2->inm.instance[i].hal.pin.enc0_count = *hm2->inm.instance[i].hal.pin.enc0_count + count_diff; - } else { *hm2->inm.instance[i].hal.pin.enc0_count = 0;} - } - - if (hm2->inm.instance[i].enc1_present) { - raw_count = (hm2->inm.mpg_read_reg[i] >> 8) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inm.instance[i].prev_enc1_count; - hm2->inm.instance[i].prev_enc1_count = hm2->inm.instance[i].prev_enc1_count + count_diff; - if (count_diff > 128) count_diff -= 256; - if (count_diff < -128) count_diff += 256; - if (*hm2->inm.instance[i].hal.pin.enc1_reset == 0) { - *hm2->inm.instance[i].hal.pin.enc1_count = *hm2->inm.instance[i].hal.pin.enc1_count + count_diff; - } else { *hm2->inm.instance[i].hal.pin.enc1_count = 0;} - } - - if (hm2->inm.instance[i].enc2_present) { - raw_count = (hm2->inm.mpg_read_reg[i] >> 16) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inm.instance[i].prev_enc2_count; - hm2->inm.instance[i].prev_enc2_count = hm2->inm.instance[i].prev_enc2_count + count_diff; - if (count_diff > 128) count_diff -= 256; - if (count_diff < -128) count_diff += 256; - if (*hm2->inm.instance[i].hal.pin.enc2_reset == 0) { - *hm2->inm.instance[i].hal.pin.enc2_count = *hm2->inm.instance[i].hal.pin.enc2_count + count_diff; - } else { *hm2->inm.instance[i].hal.pin.enc2_count = 0;} - } - - if (hm2->inm.instance[i].enc3_present) { - raw_count = (hm2->inm.mpg_read_reg[i] >> 24) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inm.instance[i].prev_enc3_count; - hm2->inm.instance[i].prev_enc3_count = hm2->inm.instance[i].prev_enc3_count + count_diff; - if (count_diff > 128) count_diff -= 256; - if (count_diff < -128) count_diff += 256; - if (*hm2->inm.instance[i].hal.pin.enc3_reset == 0) { - *hm2->inm.instance[i].hal.pin.enc3_count = *hm2->inm.instance[i].hal.pin.enc3_count + count_diff; - } else { *hm2->inm.instance[i].hal.pin.enc3_count = 0;} - } - } + if (inst->enc1_present) { + raw_count = (hm2->inm.mpg_read_reg[i] >> 8) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc1_count; + inst->prev_enc1_count = inst->prev_enc1_count + count_diff; + if (count_diff > 128) count_diff -= 256; + if (count_diff < -128) count_diff += 256; + if (!hal_get_bool(inst->hal.pin.enc1_reset)) { + hal_set_si32(inst->hal.pin.enc1_count, hal_get_si32(inst->hal.pin.enc1_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc1_count, 0); + } + } + + if (inst->enc2_present) { + raw_count = (hm2->inm.mpg_read_reg[i] >> 16) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc2_count; + inst->prev_enc2_count = inst->prev_enc2_count + count_diff; + if (count_diff > 128) count_diff -= 256; + if (count_diff < -128) count_diff += 256; + if (!hal_get_bool(inst->hal.pin.enc2_reset)) { + hal_set_si32(inst->hal.pin.enc2_count, hal_get_si32(inst->hal.pin.enc2_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc2_count, 0); + } + } + + if (inst->enc3_present) { + raw_count = (hm2->inm.mpg_read_reg[i] >> 24) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc3_count; + inst->prev_enc3_count = inst->prev_enc3_count + count_diff; + if (count_diff > 128) count_diff -= 256; + if (count_diff < -128) count_diff += 256; + if (!hal_get_bool(inst->hal.pin.enc3_reset)) { + hal_set_si32(inst->hal.pin.enc3_count, hal_get_si32(inst->hal.pin.enc3_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc3_count, 0); + } + } + } } void hm2_inm_cleanup(hostmot2_t *hm2) { diff --git a/src/hal/drivers/mesa-hostmot2/inmux.c b/src/hal/drivers/mesa-hostmot2/inmux.c index 5c26b7c6608..eee23922016 100644 --- a/src/hal/drivers/mesa-hostmot2/inmux.c +++ b/src/hal/drivers/mesa-hostmot2/inmux.c @@ -96,7 +96,7 @@ int hm2_inmux_parse_md(hostmot2_t *hm2, int md_index) { hm2->inmux.clock_frequency = md->clock_freq; hm2->inmux.version = md->version; - hm2->inmux.instance = (hm2_inmux_instance_t *)hal_malloc(hm2->inmux.num_instances * sizeof(hm2_inmux_instance_t)); + hm2->inmux.instance = hal_malloc(hm2->inmux.num_instances * sizeof(*hm2->inmux.instance)); if (hm2->inmux.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -154,199 +154,168 @@ int hm2_inmux_parse_md(hostmot2_t *hm2, int md_index) { // { - int i; - int temp; - char name[HAL_NAME_LEN + 1]; - - for (i = 0; i < hm2->inmux.num_instances; i ++) { - - + for (int i = 0; i < hm2->inmux.num_instances; i ++) { + hm2_inmux_instance_t *inst = &hm2->inmux.instance[i]; // first do a low level read to determine the per instance scanwidth + rtapi_u32 temp; hm2->llio->read(hm2->llio,hm2->inmux.control_addr + (i * md->instance_stride),&temp, sizeof(rtapi_u32)); temp = (temp & 0x0000001f) +1; - hm2->inmux.instance[i].scanwidth = temp; - hm2->inmux.instance[i].hal.param.scan_width = temp; + inst->scanwidth = temp; - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.scan_rate", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.scan_rate), hm2->llio->comp_id); + // init=20000: 20 KHz = 50 usec/scan + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.scan_rate), + 20000, "%s.inmux.%02d.scan_rate", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.scan_rate', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.slow_scans", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.slow_scans), hm2->llio->comp_id); + // init=500: 500*50 usec = 25 ms + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.slow_scans), + 500, "%s.inmux.%02d.slow_scans", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.slow_scans', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.fast_scans", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.fast_scans), hm2->llio->comp_id); + // init=5: 5*50 usec = 250 usec + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.fast_scans), + 5, "%s.inmux.%02d.fast_scans", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.fast_scans', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc0_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.enc0_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc0_mode), + 0, "%s.inmux.%02d.enc0_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.enc0_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc1_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.enc1_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc1_mode), + 0, "%s.inmux.%02d.enc1_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.enc1_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc2_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.enc2_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc2_mode), + 0, "%s.inmux.%02d.enc2_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.enc2_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc3_4xmode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->inmux.instance[i].hal.param.enc3_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(inst->hal.param.enc3_mode), + 0, "%s.inmux.%02d.enc3_4xmode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.enc3_4xmode', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.scan_width", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RO, &(hm2->inmux.instance[i].hal.param.scan_width), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RO, &(inst->hal.param.scan_width), + temp, "%s.inmux.%02d.scan_width", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.inmux.%02d.scan_width', aborting\n", r, hm2->llio->name, i); goto fail1; } - { - unsigned j = 0; - for (j = 0; j < hm2->inmux.instance[i].scanwidth; j++){ - - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.input-%02u", hm2->llio->name, i, j); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.filt_data[j]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.raw-input-%02u", hm2->llio->name, i, j); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.raw_data[j]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.input-%02u-not", hm2->llio->name, i, j); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.filt_data_not[j]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.raw-input-%02u-not", hm2->llio->name, i, j); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.raw_data_not[j]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.input-%02u-slow", hm2->llio->name, i, j); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inmux.instance[i].hal.pin.slow[j]), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } - } - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc0-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.enc0_count), hm2->llio->comp_id); + for (unsigned j = 0; j < inst->scanwidth; j++) { + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.filt_data[j]), + 0, "%s.inmux.%02d.input-%02u", hm2->llio->name, i, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inmux.%02d.input-%02u', aborting\n", r, hm2->llio->name, i, j); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc1-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.enc1_count), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.raw_data[j]), + 0, "%s.inmux.%02d.raw-input-%02u", hm2->llio->name, i, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inmux.%02d.raw-input-%02u', aborting\n", r, hm2->llio->name, i, j); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc2-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.enc2_count), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.filt_data_not[j]), + 0, "%s.inmux.%02d.input-%02u-not", hm2->llio->name, i, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inmux.%02d.input-%02u-not', aborting\n", r, hm2->llio->name, i, j); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc3-count", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->inmux.instance[i].hal.pin.enc3_count), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.raw_data_not[j]), + 0, "%s.inmux.%02d.raw-input-%02u-not", hm2->llio->name, i, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inmux.%02d.raw-input-%02u-not', aborting\n", r, hm2->llio->name, i, j); goto fail1; } - - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc0-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inmux.instance[i].hal.pin.enc0_reset), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.slow[j]), + 0, "%s.inmux.%02d.input-%02u-slow", hm2->llio->name, i, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.inmux.%02d.input-%02u-slow', aborting\n", r, hm2->llio->name, i, j); goto fail1; } + } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc1-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inmux.instance[i].hal.pin.enc1_reset), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc0_count), + 0, "%s.inmux.%02d.enc0-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc0-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc2-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inmux.instance[i].hal.pin.enc2_reset), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc1_count), + 0, "%s.inmux.%02d.enc1-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc1-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } - rtapi_snprintf(name, sizeof(name), "%s.inmux.%02d.enc3-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->inmux.instance[i].hal.pin.enc3_reset), hm2->llio->comp_id); - if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; - goto fail1; - } + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc2_count), + 0, "%s.inmux.%02d.enc2-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc2-count', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->hal.pin.enc3_count), + 0, "%s.inmux.%02d.enc3-count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc3-count', aborting\n", r, hm2->llio->name, i); + goto fail1; } - } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc0_reset), + 0, "%s.inmux.%02d.enc0-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc0-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc1_reset), + 0, "%s.inmux.%02d.enc1-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc1-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc2_reset), + 0, "%s.inmux.%02d.enc2-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc2-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->hal.pin.enc3_reset), + 0, "%s.inmux.%02d.enc3-reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.inmux.%02d.enc3-reset', aborting\n", r, hm2->llio->name, i); + goto fail1; + } + } } // // Set inmux default scanrate and filter values // and remove initial MPG offset - { - int i; - int rawmpgs; - for (i = 0; i < hm2->inmux.num_instances; i ++) { - hm2->inmux.instance[i].hal.param.scan_rate = 20000; // 20 KHz = 50 usec/scan - hm2->inmux.instance[i].hal.param.slow_scans = 500; // 500*50 usec = 25 ms - hm2->inmux.instance[i].hal.param.fast_scans = 5; // 5*50 usec = 250 usec - hm2->llio->read(hm2->llio,hm2->inmux.mpg_read_addr + (i * md->instance_stride),&rawmpgs, sizeof(rtapi_u32)); - hm2->inmux.instance[i].prev_enc0_count = (rtapi_s32)((rawmpgs >> 0) & 0x000000FF); - hm2->inmux.instance[i].prev_enc1_count = (rtapi_s32)((rawmpgs >> 8) & 0x000000FF); - hm2->inmux.instance[i].prev_enc2_count = (rtapi_s32)((rawmpgs >> 16) & 0x000000FF); - hm2->inmux.instance[i].prev_enc3_count = (rtapi_s32)((rawmpgs >> 24) & 0x000000FF); - - } - + for (int i = 0; i < hm2->inmux.num_instances; i ++) { + rtapi_u32 rawmpgs; + hm2->llio->read(hm2->llio,hm2->inmux.mpg_read_addr + (i * md->instance_stride), &rawmpgs, sizeof(rtapi_u32)); + hm2->inmux.instance[i].prev_enc0_count = (rtapi_s32)((rawmpgs >> 0) & 0x000000FF); + hm2->inmux.instance[i].prev_enc1_count = (rtapi_s32)((rawmpgs >> 8) & 0x000000FF); + hm2->inmux.instance[i].prev_enc2_count = (rtapi_s32)((rawmpgs >> 16) & 0x000000FF); + hm2->inmux.instance[i].prev_enc3_count = (rtapi_s32)((rawmpgs >> 24) & 0x000000FF); } return hm2->inmux.num_instances; @@ -373,24 +342,24 @@ void hm2_inmux_force_write(hostmot2_t *hm2) { // setup control register and mpg_write for (i = 0; i < hm2->inmux.num_instances; i ++) { - muxrate = hm2->inmux.instance[i].scanwidth * hm2->inmux.instance[i].hal.param.scan_rate; + hm2_inmux_instance_t *inst = &hm2->inmux.instance[i]; + muxrate = inst->scanwidth * hal_get_ui32(inst->hal.param.scan_rate); if (muxrate > 5000000) { muxrate = 5000000; - hm2->inmux.instance[i].hal.param.scan_rate = muxrate/hm2->inmux.instance[i].scanwidth; + hal_set_ui32(inst->hal.param.scan_rate, muxrate/inst->scanwidth); } divisor = (hm2->inmux.clock_frequency / (4 * muxrate)) - 1; - if (hm2->inmux.instance[i].hal.param.fast_scans > 63) { - hm2->inmux.instance[i].hal.param.fast_scans = 63; + rtapi_u32 fast_scans = hal_get_ui32(inst->hal.param.fast_scans); + if (fast_scans > 63) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 63); } - if (hm2->inmux.instance[i].hal.param.slow_scans > 1023) { - hm2->inmux.instance[i].hal.param.slow_scans = 1023; + rtapi_u32 slow_scans = hal_get_ui32(inst->hal.param.slow_scans); + if (slow_scans > 1023) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1023); } - hm2->inmux.control_reg[i] = (1 << 5) + -// global invert bit(5) fixed to true for now as this matches all existing hardware - (divisor << 6) + - (hm2->inmux.instance[i].hal.param.fast_scans << 16) + - (hm2->inmux.instance[i].hal.param.slow_scans << 22); + // global invert bit(5) fixed to true for now as this matches all existing hardware + hm2->inmux.control_reg[i] = (1 << 5) + (divisor << 6) + (fast_scans << 16) + (slow_scans << 22); } size = hm2->inmux.num_instances * sizeof(rtapi_u32); @@ -404,7 +373,6 @@ void hm2_inmux_force_write(hostmot2_t *hm2) { for (i = 0; i < hm2->inmux.num_instances; i ++) { hm2->inmux.instance[i].written_control_reg = hm2->inmux.control_reg[i]; hm2->inmux.instance[i].written_mpg_mode_reg = hm2->inmux.mpg_mode_reg[i]; - } } @@ -418,66 +386,66 @@ void hm2_inmux_write(hostmot2_t *hm2) { for (i = 0; i < hm2->inmux.num_instances; i ++) { - muxrate = hm2->inmux.instance[i].scanwidth * hm2->inmux.instance[i].hal.param.scan_rate; + hm2_inmux_instance_t *inst = &hm2->inmux.instance[i]; + muxrate = inst->scanwidth * hal_get_ui32(inst->hal.param.scan_rate); // bound muxrate maximum frequency if (muxrate > 5000000) { muxrate = 5000000; - hm2->inmux.instance[i].hal.param.scan_rate = muxrate/hm2->inmux.instance[i].scanwidth; - HM2_ERR("InMux %d scanrate too high, resetting to %d \n", i,hm2->inmux.instance[i].hal.param.scan_rate); + hal_set_ui32(inst->hal.param.scan_rate, muxrate/inst->scanwidth); + HM2_ERR("InMux %d scanrate too high, resetting to %d \n", i, hal_get_ui32(inst->hal.param.scan_rate)); } divisor = (hm2->inmux.clock_frequency / (4 * muxrate)) - 1; // bound divisor so we dont splatter into other fields if ((divisor > 1023 ) | (muxrate == 0 )) { divisor = 1023; - hm2->inmux.instance[i].hal.param.scan_rate = (hm2->inmux.clock_frequency/4)/(divisor +1) - /hm2->inmux.instance[i].scanwidth; - HM2_ERR("InMux %d scanrate too low, resetting to %d \n", i,hm2->inmux.instance[i].hal.param.scan_rate); + hal_set_ui32(inst->hal.param.scan_rate, + (hm2->inmux.clock_frequency/4) / (divisor +1) / inst->scanwidth); + HM2_ERR("InMux %d scanrate too low, resetting to %d \n", i, hal_get_ui32(inst->hal.param.scan_rate)); } - if (hm2->inmux.instance[i].hal.param.fast_scans > 63) { - hm2->inmux.instance[i].hal.param.fast_scans = 63; + rtapi_u32 fast_scans = hal_get_ui32(inst->hal.param.fast_scans); + if (fast_scans > 63) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 63); HM2_ERR("InMux %d fastscans must be less than 63, resetting to %d \n", i,63); } - if (hm2->inmux.instance[i].hal.param.slow_scans > 1023) { - hm2->inmux.instance[i].hal.param.slow_scans = 1023; + rtapi_u32 slow_scans = hal_get_ui32(inst->hal.param.slow_scans); + if (slow_scans > 1023) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1023); HM2_ERR("InMux %d slowscans must be less than 1023, resetting to %d \n", i,1023); } - if (hm2->inmux.instance[i].hal.param.fast_scans < 1 ) { - hm2->inmux.instance[i].hal.param.fast_scans = 1; + if (fast_scans < 1 ) { + fast_scans = hal_set_ui32(inst->hal.param.fast_scans, 1); HM2_ERR("InMux %d fastscans must be greater than 0, resetting to %d \n", i,1); } - if (hm2->inmux.instance[i].hal.param.slow_scans < 1) { - hm2->inmux.instance[i].hal.param.slow_scans = 1; + if (slow_scans < 1) { + slow_scans = hal_set_ui32(inst->hal.param.slow_scans, 1); HM2_ERR("InMux %d slowscans must be greater than 0, resetting to %d \n", i,1); } - hm2->inmux.control_reg[i] = (1 << 5) + -// global invert bit(5) fixed to true for now as this matches all existing hardware) - (divisor << 6) + - (hm2->inmux.instance[i].hal.param.fast_scans << 16) + - (hm2->inmux.instance[i].hal.param.slow_scans << 22); - if (hm2->inmux.control_reg[i] != hm2->inmux.instance[i].written_control_reg) { + // global invert bit(5) fixed to true for now as this matches all existing hardware) + hm2->inmux.control_reg[i] = (1 << 5) + (divisor << 6) + (fast_scans << 16) + (slow_scans << 22); + if (hm2->inmux.control_reg[i] != inst->written_control_reg) { hm2->llio->write(hm2->llio, hm2->inmux.control_addr, hm2->inmux.control_reg, size); - hm2->inmux.instance[i].written_control_reg = hm2->inmux.control_reg[i]; + inst->written_control_reg = hm2->inmux.control_reg[i]; // HM2_PRINT(" Debug: updating inmux control reg to = 0x%08X\n", hm2->inmux.control_reg[i]); } hm2->inmux.filter_reg[i] = 0; - for (unsigned j = 0; j < hm2->inmux.instance[i].scanwidth; j ++) { - hm2->inmux.filter_reg[i] |= (*hm2->inmux.instance[i].hal.pin.slow[j] << j); + for (unsigned j = 0; j < inst->scanwidth; j ++) { + hm2->inmux.filter_reg[i] |= (hal_get_bool(inst->hal.pin.slow[j]) << j); } - if (hm2->inmux.filter_reg[i] != hm2->inmux.instance[i].written_filter_reg) { + if (hm2->inmux.filter_reg[i] != inst->written_filter_reg) { hm2->llio->write(hm2->llio, hm2->inmux.filter_addr, hm2->inmux.filter_reg, size); - hm2->inmux.instance[i].written_filter_reg = hm2->inmux.filter_reg[i]; + inst->written_filter_reg = hm2->inmux.filter_reg[i]; // HM2_PRINT(" Debug: updating inmux filter reg to = 0x%08X\n", hm2->inmux.filter_reg[i]); } hm2->inmux.mpg_mode_reg[i] = - hm2->inmux.instance[i].hal.param.enc0_mode << 0 | - hm2->inmux.instance[i].hal.param.enc1_mode << 8 | - hm2->inmux.instance[i].hal.param.enc2_mode << 16 | - hm2->inmux.instance[i].hal.param.enc3_mode << 24; - if (hm2->inmux.mpg_mode_reg[i] != hm2->inmux.instance[i].written_mpg_mode_reg) { + hal_get_bool(inst->hal.param.enc0_mode) << 0 | + hal_get_bool(inst->hal.param.enc1_mode) << 8 | + hal_get_bool(inst->hal.param.enc2_mode) << 16 | + hal_get_bool(inst->hal.param.enc3_mode) << 24; + if (hm2->inmux.mpg_mode_reg[i] != inst->written_mpg_mode_reg) { hm2->llio->write(hm2->llio, hm2->inmux.mpg_mode_addr, hm2->inmux.mpg_mode_reg, size); - hm2->inmux.instance[i].written_mpg_mode_reg = hm2->inmux.mpg_mode_reg[i]; + inst->written_mpg_mode_reg = hm2->inmux.mpg_mode_reg[i]; // HM2_PRINT(" Debug: updating inmux mpg mode reg to = 0x%08X\n", hm2->inmux.mpg_mode_reg[i]); } } @@ -491,7 +459,7 @@ void hm2_inmux_prepare_tram_write(hostmot2_t *hm2) { for (i = 0; i < hm2->inmux.num_instances; i ++) { hm2->inmux.filter_reg[i] = 0; for (unsigned j = 0; j < hm2->inmux.instance[i].scanwidth; j ++) { - hm2->inmux.filter_reg[i] |= (*hm2->inmux.instance[i].hal.pin.slow[j] << j); + hm2->inmux.filter_reg[i] |= (hal_get_bool(hm2->inmux.instance[i].hal.pin.slow[j]) << j); } } } @@ -505,45 +473,54 @@ void hm2_inmux_process_tram_read(hostmot2_t *hm2) { return; } for (i = 0; i < hm2->inmux.num_instances; i ++) { - for (unsigned j = 0; j < hm2->inmux.instance[i].scanwidth; j ++) { - *hm2->inmux.instance[i].hal.pin.filt_data[j] = (hm2->inmux.filt_data_reg[i] >> j) &1; - *hm2->inmux.instance[i].hal.pin.raw_data[j] = (hm2->inmux.raw_data_reg[i] >> j) &1; - *hm2->inmux.instance[i].hal.pin.filt_data_not[j] = !((hm2->inmux.filt_data_reg[i] >> j) &1); - *hm2->inmux.instance[i].hal.pin.raw_data_not[j] = !((hm2->inmux.raw_data_reg[i] >> j) &1); + hm2_inmux_instance_t *inst = &hm2->inmux.instance[i]; + for (unsigned j = 0; j < inst->scanwidth; j ++) { + hal_set_bool(inst->hal.pin.filt_data[j], (hm2->inmux.filt_data_reg[i] >> j) & 1); + hal_set_bool(inst->hal.pin.raw_data[j], (hm2->inmux.raw_data_reg[i] >> j) & 1); + hal_set_bool(inst->hal.pin.filt_data_not[j], !((hm2->inmux.filt_data_reg[i] >> j) & 1)); + hal_set_bool(inst->hal.pin.raw_data_not[j], !((hm2->inmux.raw_data_reg[i] >> j) & 1)); } - raw_count = hm2->inmux.mpg_read_reg[i] & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inmux.instance[i].prev_enc0_count; - hm2->inmux.instance[i].prev_enc0_count = hm2->inmux.instance[i].prev_enc0_count + count_diff; + raw_count = hm2->inmux.mpg_read_reg[i] & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc0_count; + inst->prev_enc0_count = inst->prev_enc0_count + count_diff; if (count_diff > 128) count_diff -= 256; if (count_diff < -128) count_diff += 256; - if (*hm2->inmux.instance[i].hal.pin.enc0_reset == 0) { - *hm2->inmux.instance[i].hal.pin.enc0_count = *hm2->inmux.instance[i].hal.pin.enc0_count + count_diff; - } else { *hm2->inmux.instance[i].hal.pin.enc0_count = 0;} - raw_count = (hm2->inmux.mpg_read_reg[i] >> 8) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inmux.instance[i].prev_enc1_count; - hm2->inmux.instance[i].prev_enc1_count = hm2->inmux.instance[i].prev_enc1_count + count_diff; + if (!hal_get_bool(inst->hal.pin.enc0_reset)) { + hal_set_si32(inst->hal.pin.enc0_count, hal_get_si32(inst->hal.pin.enc0_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc0_count, 0); + } + raw_count = (hm2->inmux.mpg_read_reg[i] >> 8) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc1_count; + inst->prev_enc1_count = inst->prev_enc1_count + count_diff; if (count_diff > 128) count_diff -= 256; if (count_diff < -128) count_diff += 256; - if (*hm2->inmux.instance[i].hal.pin.enc1_reset == 0) { - *hm2->inmux.instance[i].hal.pin.enc1_count = *hm2->inmux.instance[i].hal.pin.enc1_count + count_diff; - } else { *hm2->inmux.instance[i].hal.pin.enc1_count = 0;} - raw_count = (hm2->inmux.mpg_read_reg[i] >> 16) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inmux.instance[i].prev_enc2_count; - hm2->inmux.instance[i].prev_enc2_count = hm2->inmux.instance[i].prev_enc2_count + count_diff; + if (!hal_get_bool(inst->hal.pin.enc1_reset)) { + hal_set_si32(inst->hal.pin.enc1_count, hal_get_si32(inst->hal.pin.enc1_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc1_count, 0); + } + raw_count = (hm2->inmux.mpg_read_reg[i] >> 16) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc2_count; + inst->prev_enc2_count = inst->prev_enc2_count + count_diff; if (count_diff > 128) count_diff -= 256; if (count_diff < -128) count_diff += 256; - if (*hm2->inmux.instance[i].hal.pin.enc2_reset == 0) { - *hm2->inmux.instance[i].hal.pin.enc2_count = *hm2->inmux.instance[i].hal.pin.enc2_count + count_diff; - } else { *hm2->inmux.instance[i].hal.pin.enc2_count = 0;} - raw_count = (hm2->inmux.mpg_read_reg[i] >> 24) & 0x000000FF; - count_diff = (rtapi_s32)raw_count - hm2->inmux.instance[i].prev_enc3_count; - hm2->inmux.instance[i].prev_enc3_count = hm2->inmux.instance[i].prev_enc3_count + count_diff; + if (!hal_get_bool(inst->hal.pin.enc2_reset)) { + hal_set_si32(inst->hal.pin.enc2_count, hal_get_si32(inst->hal.pin.enc2_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc2_count, 0); + } + raw_count = (hm2->inmux.mpg_read_reg[i] >> 24) & 0x000000FF; + count_diff = (rtapi_s32)raw_count - inst->prev_enc3_count; + inst->prev_enc3_count = inst->prev_enc3_count + count_diff; if (count_diff > 128) count_diff -= 256; if (count_diff < -128) count_diff += 256; - if (*hm2->inmux.instance[i].hal.pin.enc3_reset == 0) { - *hm2->inmux.instance[i].hal.pin.enc3_count = *hm2->inmux.instance[i].hal.pin.enc3_count + count_diff; - } else { *hm2->inmux.instance[i].hal.pin.enc3_count = 0;} + if (!hal_get_bool(inst->hal.pin.enc3_reset)) { + hal_set_si32(inst->hal.pin.enc3_count, hal_get_si32(inst->hal.pin.enc3_count) + count_diff); + } else { + hal_set_si32(inst->hal.pin.enc3_count, 0); + } } } diff --git a/src/hal/drivers/mesa-hostmot2/ioport.c b/src/hal/drivers/mesa-hostmot2/ioport.c index 4cb43c90c57..8756efca828 100644 --- a/src/hal/drivers/mesa-hostmot2/ioport.c +++ b/src/hal/drivers/mesa-hostmot2/ioport.c @@ -246,7 +246,7 @@ int hm2_ioport_gpio_export_hal(hostmot2_t *hm2) { for (i = 0; i < hm2->num_pins; i ++) { // all pins get *some* gpio HAL presence - hm2->pin[i].instance = (hm2_gpio_instance_t *)hal_malloc(sizeof(hm2_gpio_instance_t)); + hm2->pin[i].instance = hal_malloc(sizeof(*hm2->pin[i].instance)); if (hm2->pin[i].instance == NULL) { HM2_ERR("out of memory!\n"); return -ENOMEM; @@ -259,29 +259,17 @@ int hm2_ioport_gpio_export_hal(hostmot2_t *hm2) { // // pins - r = hal_pin_bit_newf( - HAL_OUT, - &(hm2->pin[i].instance->hal.pin.in), - hm2->llio->comp_id, - "%s.gpio.%03d.in", - hm2->llio->name, - i - ); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->pin[i].instance->hal.pin.in), + 0, "%s.gpio.%03d.in", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio pin, aborting\n", r); + HM2_ERR("error %d adding pin '%s.gpio.%03d.in', aborting\n", r, hm2->llio->name, i); return -EINVAL; } - r = hal_pin_bit_newf( - HAL_OUT, - &(hm2->pin[i].instance->hal.pin.in_not), - hm2->llio->comp_id, - "%s.gpio.%03d.in_not", - hm2->llio->name, - i - ); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->pin[i].instance->hal.pin.in_not), + 0, "%s.gpio.%03d.in_not", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio pin, aborting\n", r); + HM2_ERR("error %d adding pin '%s.gpio.%03d.in_not', aborting\n", r, hm2->llio->name, i); return -EINVAL; } @@ -295,34 +283,19 @@ int hm2_ioport_gpio_export_hal(hostmot2_t *hm2) { || (hm2->pin[i].direction_at_start == HM2_PIN_DIR_IS_OUTPUT) ) { - r = hal_param_bit_newf( - HAL_RW, - &(hm2->pin[i].instance->hal.param.invert_output), - hm2->llio->comp_id, - "%s.gpio.%03d.invert_output", - hm2->llio->name, - i - ); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->pin[i].instance->hal.param.invert_output), + 0, "%s.gpio.%03d.invert_output", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio param, aborting\n", r); + HM2_ERR("error %d adding param '%s.gpio.%03d.invert_output', aborting\n", r, hm2->llio->name, i); return -EINVAL; } - r = hal_param_bit_newf( - HAL_RW, - &(hm2->pin[i].instance->hal.param.is_opendrain), - hm2->llio->comp_id, - "%s.gpio.%03d.is_opendrain", - hm2->llio->name, - i - ); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->pin[i].instance->hal.param.is_opendrain), + 0, "%s.gpio.%03d.is_opendrain", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio param, aborting\n", r); + HM2_ERR("error %d adding param '%s.gpio.%03d.is_opendrain', aborting\n", r, hm2->llio->name, i); return -EINVAL; } - - hm2->pin[i].instance->hal.param.invert_output = 0; - hm2->pin[i].instance->hal.param.is_opendrain = 0; } @@ -332,36 +305,20 @@ int hm2_ioport_gpio_export_hal(hostmot2_t *hm2) { if (hm2->pin[i].gtag == HM2_GTAG_IOPORT) { - r = hal_pin_bit_newf( - HAL_IN, - &(hm2->pin[i].instance->hal.pin.out), - hm2->llio->comp_id, - "%s.gpio.%03d.out", - hm2->llio->name, - i - ); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->pin[i].instance->hal.pin.out), + 0, "%s.gpio.%03d.out", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio pin, aborting\n", r); + HM2_ERR("error %d adding pin '%s.gpio.%03d.out', aborting\n", r, hm2->llio->name, i); return -EINVAL; } - *(hm2->pin[i].instance->hal.pin.out) = 0; - // parameters - r = hal_param_bit_newf( - HAL_RW, - &(hm2->pin[i].instance->hal.param.is_output), - hm2->llio->comp_id, - "%s.gpio.%03d.is_output", - hm2->llio->name, - i - ); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->pin[i].instance->hal.param.is_output), + 0, "%s.gpio.%03d.is_output", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error %d adding gpio param, aborting\n", r); + HM2_ERR("error %d adding param '%s.gpio.%03d.is_output', aborting\n", r, hm2->llio->name, i); return -EINVAL; } - - hm2->pin[i].instance->hal.param.is_output = 0; } // it's an output of some other module @@ -492,7 +449,7 @@ void hm2_ioport_update(hostmot2_t *hm2) { int io_pin = (port * hm2->idrom.port_width) + port_pin; if (hm2->pin[io_pin].gtag == HM2_GTAG_IOPORT) { - if (hm2->pin[io_pin].instance->hal.param.is_output) { + if (hal_get_bool(hm2->pin[io_pin].instance->hal.param.is_output)) { hm2->pin[io_pin].direction = HM2_PIN_DIR_IS_OUTPUT; } else { hm2->pin[io_pin].direction = HM2_PIN_DIR_IS_INPUT; @@ -503,14 +460,14 @@ void hm2_ioport_update(hostmot2_t *hm2) { hm2->ioport.ddr_reg[port] |= (1 << port_pin); // set the bit in the ddr register // Open Drain Register - if (hm2->pin[io_pin].instance->hal.param.is_opendrain) { + if (hal_get_bool(hm2->pin[io_pin].instance->hal.param.is_opendrain)) { hm2->ioport.open_drain_reg[port] |= (1 << port_pin); // set the bit in the open drain register } else { hm2->ioport.open_drain_reg[port] &= ~(1 << port_pin); // clear the bit in the open drain register } // Invert Output Register - if (hm2->pin[io_pin].instance->hal.param.invert_output) { + if (hal_get_bool(hm2->pin[io_pin].instance->hal.param.invert_output)) { hm2->ioport.output_invert_reg[port] |= (1 << port_pin); // set the bit in the output invert register } else { hm2->ioport.output_invert_reg[port] &= ~(1 << port_pin); // clear the bit in the output invert register @@ -598,11 +555,9 @@ void hm2_ioport_gpio_process_tram_read(hostmot2_t *hm2) { for (port = 0; port < hm2->ioport.num_instances; port ++) { for (unsigned port_pin = 0; port_pin < hm2->idrom.port_width; port_pin ++) { int io_pin = (port * hm2->idrom.port_width) + port_pin; - hal_bit_t bit; - - bit = (hm2->ioport.data_read_reg[port] >> port_pin) & 0x1; - *hm2->pin[io_pin].instance->hal.pin.in = bit; - *hm2->pin[io_pin].instance->hal.pin.in_not = !bit; + rtapi_bool bit = (hm2->ioport.data_read_reg[port] >> port_pin) & 0x1; + hal_set_bool(hm2->pin[io_pin].instance->hal.pin.in, bit); + hal_set_bool(hm2->pin[io_pin].instance->hal.pin.in_not, !bit); } } } @@ -629,7 +584,7 @@ void hm2_ioport_gpio_prepare_tram_write(hostmot2_t *hm2) { if (hm2->pin[io_pin].gtag != HM2_GTAG_IOPORT) continue; hm2->ioport.data_write_reg[port] &= ~(1 << port_pin); // zero the bit - if(*(hm2->pin[io_pin].instance->hal.pin.out)) + if(hal_get_bool(hm2->pin[io_pin].instance->hal.pin.out)) hm2->ioport.data_write_reg[port] |= (1 << port_pin); // and set if appropriate } } @@ -654,13 +609,12 @@ void hm2_ioport_gpio_read(hostmot2_t *hm2) { for (port = 0; port < hm2->ioport.num_instances; port ++) { for (unsigned port_pin = 0; port_pin < hm2->idrom.port_width; port_pin ++) { int io_pin = (port * hm2->idrom.port_width) + port_pin; - hal_bit_t bit; if (hm2->pin[io_pin].direction != HM2_PIN_DIR_IS_INPUT) continue; - bit = (hm2->ioport.data_read_reg[port] >> port_pin) & 0x1; - *hm2->pin[io_pin].instance->hal.pin.in = bit; - *hm2->pin[io_pin].instance->hal.pin.in_not = !bit; + rtapi_bool bit = (hm2->ioport.data_read_reg[port] >> port_pin) & 0x1; + hal_set_bool(hm2->pin[io_pin].instance->hal.pin.in, bit); + hal_set_bool(hm2->pin[io_pin].instance->hal.pin.in_not, !bit); } } } @@ -682,7 +636,7 @@ void hm2_ioport_gpio_write(hostmot2_t *hm2) { if (hm2->pin[io_pin].gtag != HM2_GTAG_IOPORT) continue; hm2->ioport.data_write_reg[port] &= ~(1 << port_pin); // zero the bit - hm2->ioport.data_write_reg[port] |= (*(hm2->pin[io_pin].instance->hal.pin.out) << port_pin); // and set it as appropriate + hm2->ioport.data_write_reg[port] |= (hal_get_bool(hm2->pin[io_pin].instance->hal.pin.out) << port_pin); // and set it as appropriate } } diff --git a/src/hal/drivers/mesa-hostmot2/led.c b/src/hal/drivers/mesa-hostmot2/led.c index 48bbf661f83..e4866f7b79a 100644 --- a/src/hal/drivers/mesa-hostmot2/led.c +++ b/src/hal/drivers/mesa-hostmot2/led.c @@ -64,7 +64,7 @@ int hm2_led_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->led.instance = (hm2_led_instance_t *)hal_malloc(hm2->config.num_leds * sizeof(hm2_led_instance_t)); + hm2->led.instance = hal_malloc(hm2->config.num_leds * sizeof(*hm2->led.instance)); if (hm2->led.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -84,13 +84,11 @@ int hm2_led_parse_md(hostmot2_t *hm2, int md_index) { // export to HAL { - int i; - char name[HAL_NAME_LEN+1]; - for (i = 0 ; i < hm2->config.num_leds ; i++) { - rtapi_snprintf(name, sizeof(name), "%s.led.CR%02d", hm2->llio->name, i + 1 ); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->led.instance[i].led), hm2->llio->comp_id); + for (int i = 0 ; i < hm2->config.num_leds ; i++) { + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->led.instance[i].led), + 0, "%s.led.CR%02d", hm2->llio->name, i + 1); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.led.CR%02d', aborting\n", r, hm2->llio->name, i + 1); goto fail1; } } @@ -111,7 +109,7 @@ void hm2_led_write(hostmot2_t *hm2) { int i; for (i = 0 ; i < hm2->config.num_leds; i++ ) { - if (*hm2->led.instance[i].led) { + if (hal_get_bool(hm2->led.instance[i].led)) { regval |= 1 << (31 - i); } } diff --git a/src/hal/drivers/mesa-hostmot2/modbus/mesa_modbus.c.tmpl b/src/hal/drivers/mesa-hostmot2/modbus/mesa_modbus.c.tmpl index 146adfd7e1d..31c8cd43f31 100644 --- a/src/hal/drivers/mesa-hostmot2/modbus/mesa_modbus.c.tmpl +++ b/src/hal/drivers/mesa-hostmot2/modbus/mesa_modbus.c.tmpl @@ -114,19 +114,19 @@ enum { }; typedef struct { - hal_data_u **pins; - hal_float_t **scale; - hal_data_u **pin2; + hal_refs_u *pins; + hal_real_t *scale; + hal_refs_u *pin2; rtapi_s64 *buff; - hal_bit_t *fault; - hal_u32_t *last_err; - hal_s32_t address; - hal_s32_t baudrate; - hal_s32_t parity; - hal_s32_t txdelay; - hal_s32_t rxdelay; - hal_s32_t drive_delay; - hal_float_t rate; + hal_bool_t fault; + hal_uint_t last_err; + hal_sint_t address; + hal_sint_t baudrate; + hal_sint_t parity; + hal_sint_t txdelay; + hal_sint_t rxdelay; + hal_sint_t drive_delay; + hal_real_t rate; } hm2_modbus_hal_t; typedef struct { @@ -219,12 +219,12 @@ int rtapi_app_main(void){ inst->num_pins += channels[c].count; } // Malloc structs and pins, some in main or kernel memory, some in HAL - inst->chans = (hm2_modbus_channel_t *)rtapi_kmalloc(inst->num_chans * sizeof(hm2_modbus_channel_t), RTAPI_GFP_KERNEL); - inst->hal = (hm2_modbus_hal_t *) hal_malloc(sizeof(hm2_modbus_hal_t)); - inst->hal->pins = (hal_data_u **) hal_malloc(inst->num_pins * sizeof(hal_data_u)); - inst->hal->scale = (hal_float_t **)hal_malloc(inst->num_pins * sizeof(hal_float_t)); - inst->hal->pin2 = (hal_data_u **) hal_malloc(inst->num_pins * sizeof(hal_data_u)); - inst->hal->buff = (rtapi_s64 *) hal_malloc(inst->num_pins * sizeof(rtapi_s64)); + inst->chans = (hm2_modbus_channel_t *)rtapi_kmalloc(inst->num_chans * sizeof(*inst->chans), RTAPI_GFP_KERNEL); + inst->hal = hal_malloc(sizeof(*inst->hal)); + inst->hal->pins = hal_malloc(inst->num_pins * sizeof(*inst->hal->pins)); + inst->hal->scale = hal_malloc(inst->num_pins * sizeof(*inst->hal->scale)); + inst->hal->pin2 = hal_malloc(inst->num_pins * sizeof(*inst->hal->pin2)); + inst->hal->buff = hal_malloc(inst->num_pins * sizeof(*inst->hal->buff)); rtapi_strlcpy(inst->port, ports[i], HAL_NAME_LEN); @@ -234,29 +234,20 @@ int rtapi_app_main(void){ goto fail0; } - retval = hal_param_s32_newf(HAL_RW, &(inst->hal->address), comp_id, COMP_NAME".%02i.address", i); - retval += hal_param_s32_newf(HAL_RW, &(inst->hal->baudrate), comp_id, COMP_NAME".%02i.baudrate", i); - retval += hal_param_s32_newf(HAL_RW, &(inst->hal->parity), comp_id, COMP_NAME".%02i.parity", i); - retval += hal_param_s32_newf(HAL_RW, &(inst->hal->txdelay), comp_id, COMP_NAME".%02i.txdelay", i); - retval += hal_param_s32_newf(HAL_RW, &(inst->hal->rxdelay), comp_id, COMP_NAME".%02i.rxdelay", i); - retval += hal_param_s32_newf(HAL_RW, &(inst->hal->drive_delay), comp_id, COMP_NAME".%02i.drive-delay", i); - retval += hal_param_float_newf(HAL_RW, &(inst->hal->rate), comp_id, COMP_NAME".%02i.update-hz", i); - retval += hal_pin_bit_newf(HAL_OUT, &(inst->hal->fault), comp_id, COMP_NAME".%02i.fault", i); - retval += hal_pin_u32_newf(HAL_OUT, &(inst->hal->last_err), comp_id, COMP_NAME".%02i.last-error", i); + retval = hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->address), 0x01, COMP_NAME".%02i.address", i); + retval += hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->baudrate), 9600, COMP_NAME".%02i.baudrate", i); + retval += hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->parity), 0, COMP_NAME".%02i.parity", i); + retval += hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->txdelay), 20, COMP_NAME".%02i.txdelay", i); + retval += hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->rxdelay), 15, COMP_NAME".%02i.rxdelay", i); + retval += hal_param_new_si32(comp_id, HAL_RW, &(inst->hal->drive_delay), 0, COMP_NAME".%02i.drive-delay", i); + retval += hal_param_new_real(comp_id, HAL_RW, &(inst->hal->rate), 0.0, COMP_NAME".%02i.update-hz", i); + retval += hal_pin_new_bool(comp_id, HAL_OUT, &(inst->hal->fault), 0, COMP_NAME".%02i.fault", i); + retval += hal_pin_new_ui32(comp_id, HAL_OUT, &(inst->hal->last_err), 0, COMP_NAME".%02i.last-error", i); if (retval < 0) { rtapi_print_msg(RTAPI_MSG_ERR, COMP_NAME" ERROR: failed to create one or more pins/parameters\n"); goto fail0; } - inst->hal->address = 0x01; - inst->hal->baudrate = 9600; - inst->hal->parity = 0; - inst->hal->txdelay = 20; // should generally be larger than Rx Delay - inst->hal->rxdelay = 15; - inst->hal->drive_delay = 0; // delay between setting drive enable and sending data - *(inst->hal->fault) = 0; - *(inst->hal->last_err) = 0; - inst->state = START; do_setup(inst); @@ -295,15 +286,15 @@ int rtapi_app_main(void){ case 2: // read inputs if (ch->count > 1){ for (j = 0; j < ch->count; j++){ - retval = hal_pin_bit_newf(dir, - (hal_bit_t**)&(inst->hal->pins[p++]), - comp_id, COMP_NAME".%02i.%s-%02i", + retval = hal_pin_new_bool(comp_id, dir, + &(inst->hal->pins[p++].b), + 0, COMP_NAME".%02i.%s-%02i", i, channels[c].name, j); } } else { - retval = hal_pin_bit_newf(dir, - (hal_bit_t**)&(inst->hal->pins[p++]), - comp_id, COMP_NAME".%02i.%s", + retval = hal_pin_new_bool(comp_id, dir, + &(inst->hal->pins[p++].b), + 0, COMP_NAME".%02i.%s", i, channels[c].name); } break; @@ -331,79 +322,77 @@ int rtapi_app_main(void){ switch (ch->type){ case HAL_U32: if (ch->count > 1) { - retval = hal_pin_u32_newf(dir, - (hal_u32_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s-%02i", + retval = hal_pin_new_ui32(comp_id, dir, + &(inst->hal->pins[p].u), + 0, COMP_NAME".%02i.%s-%02i", i, channels[c].name, j); } else { - retval = hal_pin_u32_newf(dir, - (hal_u32_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s", + retval = hal_pin_new_ui32(comp_id, dir, + &(inst->hal->pins[p].u), + 0, COMP_NAME".%02i.%s", i, channels[c].name); } p++; break; case HAL_S32: if (ch->count > 1) { - retval = hal_pin_s32_newf(dir, - (hal_s32_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s-%02i", + retval = hal_pin_new_si32(comp_id, dir, + &(inst->hal->pins[p].s), + 0, COMP_NAME".%02i.%s-%02i", i, channels[c].name, j); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->scale[p]), - comp_id, COMP_NAME".%02i.%s-%02i-scale", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->scale[p]), + 1.0, COMP_NAME".%02i.%s-%02i-scale", i, channels[c].name, j); - retval = hal_pin_float_newf(dir, - (hal_float_t**)&(inst->hal->pin2[p]), - comp_id, COMP_NAME".%02i.%s-%02i-scaled", + retval = hal_pin_new_real(comp_id, dir, + &(inst->hal->pin2[p].r), + 0.0, COMP_NAME".%02i.%s-%02i-scaled", i, channels[c].name, j); } else { - retval = hal_pin_s32_newf(dir, - (hal_s32_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s", + retval = hal_pin_new_si32(comp_id, dir, + &(inst->hal->pins[p].s), + 0, COMP_NAME".%02i.%s", i, channels[c].name); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->scale[p]), - comp_id, COMP_NAME".%02i.%s-scale", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->scale[p]), + 1.0, COMP_NAME".%02i.%s-scale", i, channels[c].name); - retval = hal_pin_float_newf(dir, - (hal_float_t**)&(inst->hal->pin2[p]), - comp_id, COMP_NAME".%02i.%s-scaled", + retval = hal_pin_new_real(comp_id, dir, + &(inst->hal->pin2[p].r), + 0.0, COMP_NAME".%02i.%s-scaled", i, channels[c].name); } - *inst->hal->scale[p] = 1.0; inst->hal->buff[p] = 0; p++; break; case HAL_FLOAT: if (ch->count > 1) { - retval = hal_pin_float_newf(dir, - (hal_float_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s-%02i", + retval = hal_pin_new_real(comp_id, dir, + &(inst->hal->pins[p].r), + 0.0, COMP_NAME".%02i.%s-%02i", i, channels[c].name, j); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->scale[p]), - comp_id, COMP_NAME".%02i.%s-%02i-scale", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->scale[p]), + 1.0, COMP_NAME".%02i.%s-%02i-scale", i, channels[c].name, j); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->pin2[p]), - comp_id, COMP_NAME".%02i.%s-%02i-offset", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->pin2[p].r), + 0.0, COMP_NAME".%02i.%s-%02i-offset", i, channels[c].name, j); } else { - retval = hal_pin_float_newf(dir, - (hal_float_t**)&(inst->hal->pins[p]), - comp_id, COMP_NAME".%02i.%s", + retval = hal_pin_new_real(comp_id, dir, + &(inst->hal->pins[p].r), + 0.0, COMP_NAME".%02i.%s", i, channels[c].name); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->scale[p]), - comp_id, COMP_NAME".%02i.%s-scale", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->scale[p]), + 1.0, COMP_NAME".%02i.%s-scale", i, channels[c].name); - retval = hal_pin_float_newf(HAL_IN, - (hal_float_t**)&(inst->hal->pin2[p]), - comp_id, COMP_NAME".%02i.%s-offset", + retval = hal_pin_new_real(comp_id, HAL_IN, + &(inst->hal->pin2[p].r), + 0.0, COMP_NAME".%02i.%s-offset", i, channels[c].name); } - *(inst->hal->scale[p]) = 1; p++; break; default: @@ -435,19 +424,19 @@ static int do_setup(hm2_modbus_inst_t *inst){ int retval; - if (inst->baudrate == inst->hal->baudrate - && inst->parity == inst->hal->parity - && inst->txdelay == inst->hal->txdelay - && inst->rxdelay == inst->hal->rxdelay - && inst->drive_delay == inst->hal->drive_delay) return 0; - - if (inst->hal->txdelay > 0xFF) inst->hal->txdelay = 0xFF; - if (inst->hal->rxdelay > 0xFF) inst->hal->rxdelay = 0xFF; - inst->baudrate = inst->hal->baudrate; - inst->parity = inst->hal->parity; - inst->txdelay = inst->hal->txdelay; - inst->rxdelay = inst->hal->rxdelay; - inst->drive_delay = inst->hal->drive_delay; + if (inst->baudrate == hal_get_si32(inst->hal->baudrate) + && inst->parity == hal_get_si32(inst->hal->parity) + && inst->txdelay == hal_get_si32(inst->hal->txdelay) + && inst->rxdelay == hal_get_si32(inst->hal->rxdelay) + && inst->drive_delay == hal_get_si32(inst->hal->drive_delay)) return 0; + + if (hal_get_si32(inst->hal->txdelay) > 0xFF) hal_set_si32(inst->hal->txdelay, 0xFF); + if (hal_get_si32(inst->hal->rxdelay) > 0xFF) hal_set_si32(inst->hal->rxdelay, 0xFF); + inst->baudrate = hal_get_si32(inst->hal->baudrate); + inst->parity = hal_get_si32(inst->hal->parity); + inst->txdelay = hal_get_si32(inst->hal->txdelay); + inst->rxdelay = hal_get_si32(inst->hal->rxdelay); + inst->drive_delay = hal_get_si32(inst->hal->drive_delay); unsigned flg; flg = inst->parity != 0 ? HM2_PKTUART_CONFIG_PARITYEN : 0; @@ -508,8 +497,8 @@ static void do_timeout(hm2_modbus_inst_t *inst){ hm2_pktuart_reset(inst->port); inst->state = RESET_WAIT; inst->iter = 0; - *(inst->hal->last_err) = 11; - *(inst->hal->fault) = 1; + hal_set_ui32(inst->hal->last_err, 11); + hal_set_bool(inst->hal->fault, 1); inst->chans[inst->index].data[1] = 0xFF; // Write invalid data to force re-send } rtapi_print_msg(RTAPI_MSG_INFO, "%i timeout %i\r", inst->iter, inst->state); @@ -518,7 +507,7 @@ static void do_timeout(hm2_modbus_inst_t *inst){ static void process(void *arg, long period) { static long timer = 0; hm2_modbus_inst_t *inst = arg; - real_t rate; + rtapi_real rate; int r; rtapi_u32 rxstatus = hm2_pktuart_get_rx_status(inst->port); @@ -527,7 +516,7 @@ static void process(void *arg, long period) { switch (inst->state) { case START: - rate = inst->hal->rate; + rate = hal_get_real(inst->hal->rate); if (rate >= RATE_MIN && rate <= RATE_MAX && (timer -= period) > 0) break; rtapi_print_msg(RTAPI_MSG_INFO, "START txstatus = %08X rxstatus = %08X\n", txstatus, rxstatus); @@ -619,7 +608,7 @@ static void process(void *arg, long period) { rtapi_print_msg(RTAPI_MSG_INFO, "\r"); if (rxstatus & 0x200000) break; inst->state = START; - *(inst->hal->fault) = 0; + hal_set_bool(inst->hal->fault, 0); break; case RESET_WAIT: @@ -651,7 +640,7 @@ static int ch_append16(hm2_modbus_channel_t *ch, rtapi_u16 v){ static int ch_init(hm2_modbus_channel_t *ch, hm2_modbus_hal_t hal){ int r; ch->ptr = -1; - r = ch_append8(ch, hal.address); + r = ch_append8(ch, hal_get_si32(hal.address)); r = ch_append8(ch, ch->func); return r; } @@ -679,7 +668,7 @@ static int build_data_frame(hm2_modbus_inst_t *inst){ break; case 5: // Write single coil r += ch_append16(ch, ch->addr); - if (hal.pins[p]->b){ + if (hal_get_bool(hal.pins[p].b)){ r += ch_append16(ch, 0xFF00); } else { r += ch_append16(ch, 0x0000); @@ -689,15 +678,15 @@ static int build_data_frame(hm2_modbus_inst_t *inst){ r += ch_append16(ch, ch->addr); switch (ch->type){ case HAL_U32: - r += ch_append16(ch, (rtapi_u16)hal.pins[p]->u); + r += ch_append16(ch, (rtapi_u16)hal_get_ui32(hal.pins[p].u)); break; case HAL_S32: - r += ch_append16(ch, (rtapi_s16)hal.pins[p]->s); + r += ch_append16(ch, (rtapi_s16)hal_get_si32(hal.pins[p].s)); break; case HAL_FLOAT: - rtapi_print_msg(RTAPI_MSG_INFO, "671 %f %f %f \n", hal.pins[p]->f, hal.pin2[p]->f, *hal.scale[p]); - if (*hal.scale[p] <= -EPSILON || *hal.scale[p] >= +EPSILON){ - r+= ch_append16(ch, (rtapi_u16)((hal.pins[p]->f - hal.pin2[p]->f) / *hal.scale[p])) ; + rtapi_print_msg(RTAPI_MSG_INFO, "671 %f %f %f \n", hal_get_real(hal.pins[p].r), hal_get_real(hal.pin2[p].r), hal_get_real(hal.scale[p])); + if (hal_get_real(hal.scale[p]) <= -EPSILON || hal_get_real(hal.scale[p]) >= +EPSILON){ + r+= ch_append16(ch, (rtapi_u16)((hal_get_real(hal.pins[p].r) - hal_get_real(hal.pin2[p].r)) / hal_get_real(hal.scale[p]))) ; } rtapi_print_msg(RTAPI_MSG_INFO, "678\n"); break; @@ -710,7 +699,7 @@ static int build_data_frame(hm2_modbus_inst_t *inst){ r += ch_append16(ch, ch->count); r += ch_append8(ch, ( ch->count + 8 - 1) / 8); for (i = 0; i < ch->count; i++){ - if (hal.pins[p++]->b) acc += 1 << (i % 8); + if (hal_get_bool(hal.pins[p++].b)) acc += 1 << (i % 8); if (i % 8 == 7 || i == (ch->count -1)) { // time for the next byte r += ch_append8(ch, acc); acc = 0; @@ -724,17 +713,17 @@ static int build_data_frame(hm2_modbus_inst_t *inst){ for (i = 0; i < ch->count; i++){ switch (ch->type){ case HAL_U32: - r += ch_append16(ch, (rtapi_u16)hal.pins[p]->u); + r += ch_append16(ch, (rtapi_u16)hal_get_ui32(hal.pins[p].u)); break; case HAL_S32: - r += ch_append16(ch, (rtapi_s16)hal.pins[p]->s); + r += ch_append16(ch, (rtapi_s16)hal_get_si32(hal.pins[p].s)); break; case HAL_FLOAT: - if (*hal.scale[p] <= -EPSILON || *hal.scale[p] >= +EPSILON){ - r+= ch_append16(ch, (rtapi_u16)((hal.pins[p]->f - hal.pin2[p]->f) / *hal.scale[p])) ; + if (hal_get_real(hal.scale[p]) <= -EPSILON || hal_get_real(hal.scale[p]) >= +EPSILON){ + r+= ch_append16(ch, (rtapi_u16)((hal_get_real(hal.pins[p].r) - hal_get_real(hal.pin2[p].r)) / hal_get_real(hal.scale[p]))) ; } else { // Prevent (near) divide-by-zero and assume scale 1.0 - r+= ch_append16(ch, (rtapi_u16)(hal.pins[p]->f - hal.pin2[p]->f)); + r+= ch_append16(ch, (rtapi_u16)(hal_get_real(hal.pins[p].r) - hal_get_real(hal.pin2[p].r))); } break; default: @@ -791,7 +780,7 @@ static int parse_data_frame(hm2_modbus_inst_t *inst){ w = 3; b = 0; for (i = 0; i < ch->count; i++){ - hal.pins[p++]->b = (bytes[w] & 1 << b); + hal_set_bool(hal.pins[p++].b, (bytes[w] & 1 << b)); if (++b >= 8) { b = 0; w++;} } break; @@ -801,24 +790,24 @@ static int parse_data_frame(hm2_modbus_inst_t *inst){ for (i = 0; i < bytes[2] / 2; i++){ switch (ch->type){ case HAL_U32: - hal.pins[p]->u = 256 * bytes[w] + bytes[w + 1]; + hal_set_ui32(hal.pins[p].u, 256 * bytes[w] + bytes[w + 1]); w += 2; p++; break; case HAL_S32: // wrap the result into the (s32) offset too - tmp = hal.pins[p]->s; - hal.pins[p]->s = bytes[w] * 256 + bytes[w + 1]; + tmp = hal_get_si32(hal.pins[p].s); + hal_set_si32(hal.pins[p].s, bytes[w] * 256 + bytes[w + 1]); w += 2; - tmp = hal.pins[p]->s - tmp; + tmp = hal_get_si32(hal.pins[p].s) - tmp; if (tmp > 32768) tmp -= 65536; if (tmp < -32768) tmp += 65536; hal.buff[p] += tmp; - hal.pin2[p]->f = hal.buff[p] * *hal.scale[p]; + hal_set_real(hal.pin2[p].r, hal.buff[p] * hal_get_real(hal.scale[p])); p++; break; case HAL_FLOAT: - hal.pins[p]->f = (256 * bytes[w] + bytes[w + 1]) - * *(hal.scale[p]) + hal.pin2[p]->f; + hal_set_real(hal.pins[p].r, (256 * bytes[w] + bytes[w + 1]) + * hal_get_real(hal.scale[p]) + hal_get_real(hal.pin2[p].r)); w += 2; p++; break; diff --git a/src/hal/drivers/mesa-hostmot2/oneshot.c b/src/hal/drivers/mesa-hostmot2/oneshot.c index f56fd522095..3b4bf89fd1f 100644 --- a/src/hal/drivers/mesa-hostmot2/oneshot.c +++ b/src/hal/drivers/mesa-hostmot2/oneshot.c @@ -32,74 +32,74 @@ void hm2_oneshot_update_width1(hostmot2_t *hm2, int i) { // widths are in ms - hm2->oneshot.width1_reg[i] = (double)*hm2->oneshot.instance[i].hal.pin.width1 * ((double)hm2->oneshot.clock_frequency / (double)1e3); + hm2->oneshot.width1_reg[i] = hal_get_real(hm2->oneshot.instance[i].hal.pin.width1) * ((double)hm2->oneshot.clock_frequency / (double)1e3); if (hm2->oneshot.width1_reg[i] > 0x7FFFFFFF) { HM2_ERR("oneshot %d has invalid width1, resetting to max\n", i); hm2->oneshot.width1_reg[i] = 0x7FFFFFFF; - *hm2->oneshot.instance[i].hal.pin.width1 = (double)hm2->oneshot.width1_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency); + hal_set_real(hm2->oneshot.instance[i].hal.pin.width1, (double)hm2->oneshot.width1_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency)); } } void hm2_oneshot_update_width2(hostmot2_t *hm2, int i) { // widths are in ms - hm2->oneshot.width2_reg[i] = (double)*hm2->oneshot.instance[i].hal.pin.width2 * ((double)hm2->oneshot.clock_frequency / (double)1e3); + hm2->oneshot.width2_reg[i] = hal_get_real(hm2->oneshot.instance[i].hal.pin.width2) * ((double)hm2->oneshot.clock_frequency / (double)1e3); if (hm2->oneshot.width2_reg[i] > 0x7FFFFFFF) { HM2_ERR("oneshot %d has invalid width1, resetting to max\n", i); hm2->oneshot.width2_reg[i] = 0x7FFFFFFF; - *hm2->oneshot.instance[i].hal.pin.width2 = (double)hm2->oneshot.width2_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency); + hal_set_real(hm2->oneshot.instance[i].hal.pin.width2, (double)hm2->oneshot.width2_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency)); } } void hm2_oneshot_update_filter1(hostmot2_t *hm2, int i) { // widths are in ms - hm2->oneshot.filter1_reg[i] = (double)*hm2->oneshot.instance[i].hal.pin.filter1 * ((double)hm2->oneshot.clock_frequency / (double)1e3); + hm2->oneshot.filter1_reg[i] = hal_get_real(hm2->oneshot.instance[i].hal.pin.filter1) * ((double)hm2->oneshot.clock_frequency / (double)1e3); if (hm2->oneshot.filter1_reg[i] > 0xFFFFFF) { HM2_ERR("oneshot %d has invalid filter1 time, resetting to max\n", i); hm2->oneshot.width1_reg[i] = 0xFFFFFF; - *hm2->oneshot.instance[i].hal.pin.filter1 = (double)hm2->oneshot.filter1_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency); + hal_set_real(hm2->oneshot.instance[i].hal.pin.filter1, (double)hm2->oneshot.filter1_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency)); } } void hm2_oneshot_update_filter2(hostmot2_t *hm2, int i) { // widths are in ms - hm2->oneshot.filter2_reg[i] = (double)*hm2->oneshot.instance[i].hal.pin.filter2 * ((double)hm2->oneshot.clock_frequency / (double)1e3); + hm2->oneshot.filter2_reg[i] = hal_get_real(hm2->oneshot.instance[i].hal.pin.filter2) * ((double)hm2->oneshot.clock_frequency / (double)1e3); if (hm2->oneshot.filter2_reg[i] > 0xFFFFFF) { HM2_ERR("oneshot %d has invalid filter2 time, resetting to max\n", i); hm2->oneshot.width2_reg[i] = 0xFFFFFF; - *hm2->oneshot.instance[i].hal.pin.filter2 = (double)hm2->oneshot.filter2_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency); + hal_set_real(hm2->oneshot.instance[i].hal.pin.filter2, (double)hm2->oneshot.filter2_reg[i] * ((double)1e3 / (double)hm2->oneshot.clock_frequency)); } } void hm2_oneshot_update_rate(hostmot2_t *hm2, int i) { - hm2->oneshot.rate_reg[i] = (uint32_t)(*hm2->oneshot.instance[i].hal.pin.rate * (4294967296.0 / (double)hm2->oneshot.clock_frequency)); + hm2->oneshot.rate_reg[i] = (uint32_t)(hal_get_real(hm2->oneshot.instance[i].hal.pin.rate) * (4294967296.0 / (double)hm2->oneshot.clock_frequency)); } void hm2_oneshot_update_control(hostmot2_t *hm2, int i) { rtapi_u32 controlbuff; - if(*hm2->oneshot.instance[i].hal.pin.trigselect1 > 7) { + if(hal_get_ui32(hm2->oneshot.instance[i].hal.pin.trigselect1) > 7) { HM2_ERR("oneshot %d has invalid trigger 1 select value , resetting to 0\n", i); - *hm2->oneshot.instance[i].hal.pin.trigselect1 = 0; + hal_set_ui32(hm2->oneshot.instance[i].hal.pin.trigselect1, 0); } - if(*hm2->oneshot.instance[i].hal.pin.trigselect2 > 7) { + if(hal_get_ui32(hm2->oneshot.instance[i].hal.pin.trigselect2) > 7) { HM2_ERR("oneshot %d has invalid trigger 2 select value , resetting to 0\n", i); - *hm2->oneshot.instance[i].hal.pin.trigselect2 = 0; + hal_set_ui32(hm2->oneshot.instance[i].hal.pin.trigselect2, 0); } controlbuff = 0; - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigselect1 << 0); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigrise1 << 3); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigfall1 << 4); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.retrig1 << 5); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.enable1 << 6); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.reset1 << 7); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.swtrig1 << 10); - controlbuff |= ((*hm2->oneshot.instance[i].hal.pin.dpll_timer_num & 7) << 12); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigselect2 << 16); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigrise2 << 19); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.trigfall2 << 20); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.retrig2 << 21); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.enable2 << 22); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.reset2 << 23); - controlbuff |= (*hm2->oneshot.instance[i].hal.pin.swtrig2 << 26); + controlbuff |= (hal_get_ui32(hm2->oneshot.instance[i].hal.pin.trigselect1) << 0); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.trigrise1) << 3); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.trigfall1) << 4); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.retrig1) << 5); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.enable1) << 6); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.reset1) << 7); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.swtrig1) << 10); + controlbuff |= ((hal_get_si32(hm2->oneshot.instance[i].hal.pin.dpll_timer_num) & 7) << 12); + controlbuff |= (hal_get_ui32(hm2->oneshot.instance[i].hal.pin.trigselect2) << 16); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.trigrise2) << 19); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.trigfall2) << 20); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.retrig2) << 21); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.enable2) << 22); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.reset2) << 23); + controlbuff |= (hal_get_bool(hm2->oneshot.instance[i].hal.pin.swtrig2) << 26); hm2->oneshot.control_reg[i] = controlbuff; } @@ -132,7 +132,7 @@ void hm2_oneshot_force_write(hostmot2_t *hm2) { hm2->llio->write(hm2->llio, hm2->oneshot.control_addr, hm2->oneshot.control_reg, (hm2->oneshot.num_instances * sizeof(rtapi_u32))); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; } @@ -201,7 +201,7 @@ int hm2_oneshot_parse_md(hostmot2_t *hm2, int md_index) { - hm2->oneshot.instance = (hm2_oneshot_instance_t *)hal_malloc(hm2->oneshot.num_instances * sizeof(hm2_oneshot_instance_t)); + hm2->oneshot.instance = hal_malloc(hm2->oneshot.num_instances * sizeof(*hm2->oneshot.instance)); if (hm2->oneshot.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -263,204 +263,176 @@ int hm2_oneshot_parse_md(hostmot2_t *hm2, int md_index) { // export to HAL - // FIXME: r hides the r in enclosing function, and it returns the wrong thing { - int i; - int r; - char name[HAL_NAME_LEN + 1]; - - - for (i = 0; i < hm2->oneshot.num_instances; i ++) { + for (int i = 0; i < hm2->oneshot.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.width1", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.width1), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.width1), + 1.0, "%s.oneshot.%02d.width1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.width1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.width2", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.width2), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.width2), + 1.0, "%s.oneshot.%02d.width2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.width2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.filter1", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.filter1), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.filter1), + 0.1, "%s.oneshot.%02d.filter1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.filter1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.filter2", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.filter2), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.filter2), + 0.1, "%s.oneshot.%02d.filter2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.filter2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.rate", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.rate), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.rate), + 1000.0, "%s.oneshot.%02d.rate", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.rate', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_select1", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigselect1), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigselect1), + 0, "%s.oneshot.%02d.trigger_select1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_select1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_select2", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigselect2), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigselect2), + 0, "%s.oneshot.%02d.trigger_select2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_select2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.dpll_timer_number", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.dpll_timer_num), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.dpll_timer_num), + 0, "%s.oneshot.%02d.dpll_timer_number", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.dpll_timer_number', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_on_rise1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigrise1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigrise1), + 0, "%s.oneshot.%02d.trigger_on_rise1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_on_rise1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_on_rise2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigrise2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigrise2), + 0, "%s.oneshot.%02d.trigger_on_rise2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_on_rise2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_on_fall1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigfall1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigfall1), + 0, "%s.oneshot.%02d.trigger_on_fall1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_on_fall1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.trigger_on_fall2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigfall2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.trigfall2), + 0, "%s.oneshot.%02d.trigger_on_fall2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.trigger_on_fall2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.retriggerable1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.retrig1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.retrig1), + 0, "%s.oneshot.%02d.retriggerable1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.retriggerable1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.retriggerable2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.retrig2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.retrig2), + 0, "%s.oneshot.%02d.retriggerable2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.retriggerable2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.enable1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.enable1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.enable1), + 0, "%s.oneshot.%02d.enable1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.enable1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.enable2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.enable2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.enable2), + 0, "%s.oneshot.%02d.enable2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.enable2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.reset1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.reset1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.reset1), + 0, "%s.oneshot.%02d.reset1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.reset1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.reset2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.reset2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.reset2), + 0, "%s.oneshot.%02d.reset2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.reset2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.swtrigger1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.swtrig1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.swtrig1), + 0, "%s.oneshot.%02d.swtrigger1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.swtrigger1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.swtrigger2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.swtrig2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->oneshot.instance[i].hal.pin.swtrig2), + 0, "%s.oneshot.%02d.swtrigger2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.swtrigger2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.exttrigger1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.exttrig1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.exttrig1), + 0, "%s.oneshot.%02d.exttrigger1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.exttrigger1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.exttrigger2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.exttrig2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.exttrig2), + 0, "%s.oneshot.%02d.exttrigger2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.exttrigger2', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.out1", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.out1), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.out1), + 0, "%s.oneshot.%02d.out1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.out1', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.oneshot.%02d.out2", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.out2), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->oneshot.instance[i].hal.pin.out2), + 0, "%s.oneshot.%02d.out2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.oneshot.%02d.out2', aborting\n", r, hm2->llio->name, i); goto fail1; } - - - // init hal objects - *(hm2->oneshot.instance[i].hal.pin.width1) = 1.0; - *(hm2->oneshot.instance[i].hal.pin.width2) = 1.0; - *(hm2->oneshot.instance[i].hal.pin.filter1) = 0.1; - *(hm2->oneshot.instance[i].hal.pin.filter2) = 0.1; - *(hm2->oneshot.instance[i].hal.pin.rate) = 1000.0; - *(hm2->oneshot.instance[i].hal.pin.trigselect1) = 0; - *(hm2->oneshot.instance[i].hal.pin.trigselect2) = 0; - *(hm2->oneshot.instance[i].hal.pin.trigrise1) = 0; - *(hm2->oneshot.instance[i].hal.pin.trigrise2) = 0; - *(hm2->oneshot.instance[i].hal.pin.trigfall1) = 0; - *(hm2->oneshot.instance[i].hal.pin.trigfall2) = 0; - *(hm2->oneshot.instance[i].hal.pin.retrig1) = 0; - *(hm2->oneshot.instance[i].hal.pin.retrig2) = 0; - *(hm2->oneshot.instance[i].hal.pin.enable1) = 0; - *(hm2->oneshot.instance[i].hal.pin.enable2) = 0; - *(hm2->oneshot.instance[i].hal.pin.reset1) = 0; - *(hm2->oneshot.instance[i].hal.pin.reset2) = 0; - *(hm2->oneshot.instance[i].hal.pin.swtrig1) = 0; - *(hm2->oneshot.instance[i].hal.pin.swtrig2) = 0; } } @@ -530,10 +502,10 @@ void hm2_oneshot_process_tram_read(hostmot2_t *hm2) { rtapi_u32 control = 0; for (i = 0; i < hm2->oneshot.num_instances; i ++) { control = hm2->oneshot.control_read_reg[i]; - *hm2->oneshot.instance[i].hal.pin.out1 = ((control & (1 << 8)) != 0); - *hm2->oneshot.instance[i].hal.pin.out2 = ((control & (1 << 24)) != 0); - *hm2->oneshot.instance[i].hal.pin.exttrig1 = ((control & (1 << 9)) != 0); - *hm2->oneshot.instance[i].hal.pin.exttrig2 = ((control & (1 << 25)) != 0); + hal_set_bool(hm2->oneshot.instance[i].hal.pin.out1, ((control & (1 << 8)) != 0)); + hal_set_bool(hm2->oneshot.instance[i].hal.pin.out2, ((control & (1 << 24)) != 0)); + hal_set_bool(hm2->oneshot.instance[i].hal.pin.exttrig1, ((control & (1 << 9)) != 0)); + hal_set_bool(hm2->oneshot.instance[i].hal.pin.exttrig2, ((control & (1 << 25)) != 0)); } } diff --git a/src/hal/drivers/mesa-hostmot2/outm.c b/src/hal/drivers/mesa-hostmot2/outm.c index 41f4a4ba427..4bc32a78445 100644 --- a/src/hal/drivers/mesa-hostmot2/outm.c +++ b/src/hal/drivers/mesa-hostmot2/outm.c @@ -77,7 +77,7 @@ int hm2_outm_parse_md(hostmot2_t *hm2, int md_index) { hm2->outm.clock_freq = md->clock_freq; hm2->outm.version = md->version; - hm2->outm.instance = (hm2_outm_instance_t *)hal_malloc(hm2->outm.num_instances * sizeof(hm2_outm_instance_t)); + hm2->outm.instance = hal_malloc(hm2->outm.num_instances * sizeof(*hm2->outm.instance)); if (hm2->outm.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -115,10 +115,7 @@ int hm2_outm_parse_md(hostmot2_t *hm2, int md_index) { // { - int i; - char name[HAL_NAME_LEN + 1]; - - for (i = 0; i < hm2->outm.num_instances; i ++) { + for (int i = 0; i < hm2->outm.num_instances; i ++) { int j = 0; int outm_number; for (j = 0; j < hm2->num_pins; j++){ @@ -134,17 +131,17 @@ int hm2_outm_parse_md(hostmot2_t *hm2, int md_index) { r = -EINVAL; goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.outm.%02d.out-%02d", hm2->llio->name, i, outm_number); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->outm.instance[i].hal.pin.out[outm_number]), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->outm.instance[i].hal.pin.out[outm_number]), + 0, "%s.outm.%02d.out-%02d", hm2->llio->name, i, outm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.outm.%02d.out-%02d', aborting\n", r, hm2->llio->name, i, outm_number); r = -ENOMEM; goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.outm.%02d.invert-%02d", hm2->llio->name, i, outm_number); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->outm.instance[i].hal.pin.invert[outm_number]), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->outm.instance[i].hal.pin.invert[outm_number]), + 0, "%s.outm.%02d.invert-%02d", hm2->llio->name, i, outm_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.outm.%02d.invert-%02d', aborting\n", r, hm2->llio->name, i, outm_number); r = -ENOMEM; goto fail0; } @@ -164,16 +161,7 @@ int hm2_outm_parse_md(hostmot2_t *hm2, int md_index) { { int i; for (i = 0; i < hm2->outm.num_instances; i ++) { - int pin; rtapi_u32 zero = 0; - - - for (pin = 0; pin < 32; pin ++) { - if (hm2->outm.instance[i].hal.pin.out[pin] != NULL) { - *hm2->outm.instance[i].hal.pin.out[pin] = 0; - *hm2->outm.instance[i].hal.pin.invert[pin] = 0; - } - } hm2->llio->write(hm2->llio, hm2->outm.data_addr + (i * md->instance_stride), &zero, sizeof(zero)); } } @@ -207,8 +195,8 @@ void hm2_outm_force_write(hostmot2_t *hm2) { hm2->outm.data_reg[i] = 0; for (pin = 0; pin < 32; pin ++) { if (hm2->outm.instance[i].hal.pin.out[pin] != NULL) { - hm2->outm.data_reg[i] |= *hm2->outm.instance[i].hal.pin.out[pin] << pin; - hm2->outm.data_reg[i] ^= *hm2->outm.instance[i].hal.pin.invert[pin] << pin; + hm2->outm.data_reg[i] |= hal_get_bool(hm2->outm.instance[i].hal.pin.out[pin]) << pin; + hm2->outm.data_reg[i] ^= hal_get_bool(hm2->outm.instance[i].hal.pin.invert[pin]) << pin; } } } @@ -238,8 +226,8 @@ void hm2_outm_prepare_tram_write(hostmot2_t *hm2) { hm2->outm.data_reg[i] = 0; for (pin = 0; pin < 32; pin ++) { if (hm2->outm.instance[i].hal.pin.out[pin] != NULL) { - hm2->outm.data_reg[i] |= *hm2->outm.instance[i].hal.pin.out[pin] << pin; - hm2->outm.data_reg[i] ^= *hm2->outm.instance[i].hal.pin.invert[pin] << pin; + hm2->outm.data_reg[i] |= hal_get_bool(hm2->outm.instance[i].hal.pin.out[pin]) << pin; + hm2->outm.data_reg[i] ^= hal_get_bool(hm2->outm.instance[i].hal.pin.invert[pin]) << pin; } } if (hm2->outm.data_reg[i] != hm2->outm.instance[i].written_data) { diff --git a/src/hal/drivers/mesa-hostmot2/periodm.c b/src/hal/drivers/mesa-hostmot2/periodm.c index 9c589f7b325..632edf6cfe7 100644 --- a/src/hal/drivers/mesa-hostmot2/periodm.c +++ b/src/hal/drivers/mesa-hostmot2/periodm.c @@ -33,36 +33,37 @@ void hm2_periodm_update_limit(hostmot2_t *hm2, int i) { - hm2->periodm.limit_reg[i] = ((double)hm2->periodm.clock_frequency / (double)*hm2->periodm.instance[i].hal.pin.minfreq) * *hm2->periodm.instance[i].hal.pin.averages; - if ((((double)hm2->periodm.clock_frequency / (double)*hm2->periodm.instance[i].hal.pin.minfreq) * *hm2->periodm.instance[i].hal.pin.averages ) > 0xFFFFFFFF) { + rtapi_u32 averages = hal_get_ui32(hm2->periodm.instance[i].hal.pin.averages); + rtapi_real minfreq = hal_get_real(hm2->periodm.instance[i].hal.pin.minfreq); + hm2->periodm.limit_reg[i] = ((double)hm2->periodm.clock_frequency / minfreq) * averages; + if ((((double)hm2->periodm.clock_frequency / minfreq) * averages ) > 0xFFFFFFFF) { HM2_ERR("periodm %d has invalid min freq time, resetting to min\n", i); - *hm2->periodm.instance[i].hal.pin.minfreq = (0.025 * *hm2->periodm.instance[i].hal.pin.averages); - hm2->periodm.limit_reg[i] = ((double)hm2->periodm.clock_frequency / (double)*hm2->periodm.instance[i].hal.pin.minfreq) * *hm2->periodm.instance[i].hal.pin.averages; + minfreq = hal_set_real(hm2->periodm.instance[i].hal.pin.minfreq, 0.025 * averages); + hm2->periodm.limit_reg[i] = ((double)hm2->periodm.clock_frequency / minfreq) * averages; } } void hm2_periodm_update_mode(hostmot2_t *hm2, int i) { rtapi_u32 modebuff; rtapi_u32 filterclocks; - rtapi_u32 averages; - filterclocks = (double)*hm2->periodm.instance[i].hal.pin.filtertc * ((double)hm2->periodm.clock_frequency / (double)1e6); + rtapi_u32 averages = hal_get_ui32(hm2->periodm.instance[i].hal.pin.averages); + filterclocks = (double)hal_get_real(hm2->periodm.instance[i].hal.pin.filtertc) * ((double)hm2->periodm.clock_frequency / (double)1e6); if (filterclocks > 0xFFFF) { HM2_ERR("periodm %d has invalid filter time constant, resetting to max\n", i); filterclocks = 0xFFFF; - *hm2->periodm.instance[i].hal.pin.filtertc = (double)filterclocks * ((double)1e6 / (double)hm2->periodm.clock_frequency); + hal_set_real(hm2->periodm.instance[i].hal.pin.filtertc, (double)filterclocks * ((double)1e6 / (double)hm2->periodm.clock_frequency)); } - if (*hm2->periodm.instance[i].hal.pin.averages > 0xFFF) { + if (averages > 0xFFF) { HM2_ERR("periodm %d has invalid averages number, resetting to max\n", i); - *hm2->periodm.instance[i].hal.pin.averages = 0xFFF; + averages = hal_set_ui32(hm2->periodm.instance[i].hal.pin.averages, 0xFFF); } - if (*hm2->periodm.instance[i].hal.pin.averages < 1) { + if (averages < 1) { HM2_ERR("periodm %d has invalid averages number, resetting to min\n", i); - *hm2->periodm.instance[i].hal.pin.averages = 1; + averages = hal_set_ui32(hm2->periodm.instance[i].hal.pin.averages, 1); } - averages = *hm2->periodm.instance[i].hal.pin.averages -1; modebuff = 0; - modebuff |= (*hm2->periodm.instance[i].hal.pin.polarity << 0); - modebuff |= (averages << 4); + modebuff |= (hal_get_bool(hm2->periodm.instance[i].hal.pin.polarity) << 0); + modebuff |= ((averages-1) << 4); modebuff |= (filterclocks << 16); hm2->periodm.mode_write_reg[i] = modebuff; @@ -86,7 +87,7 @@ void hm2_periodm_force_write(hostmot2_t *hm2) { hm2->llio->write(hm2->llio, hm2->periodm.mode_write_addr, hm2->periodm.mode_write_reg, (hm2->periodm.num_instances * sizeof(rtapi_u32))); hm2->llio->write(hm2->llio, hm2->periodm.limit_addr, hm2->periodm.limit_reg, (hm2->periodm.num_instances * sizeof(rtapi_u32))); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; } @@ -152,7 +153,7 @@ int hm2_periodm_parse_md(hostmot2_t *hm2, int md_index) { - hm2->periodm.instance = (hm2_periodm_instance_t *)hal_malloc(hm2->periodm.num_instances * sizeof(hm2_periodm_instance_t)); + hm2->periodm.instance = hal_malloc(hm2->periodm.num_instances * sizeof(*hm2->periodm.instance)); if (hm2->periodm.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -200,107 +201,92 @@ int hm2_periodm_parse_md(hostmot2_t *hm2, int md_index) { // export to HAL - // FIXME: r hides the r in enclosing function, and it returns the wrong thing { - int i; - int r; - char name[HAL_NAME_LEN + 1]; - - - for (i = 0; i < hm2->periodm.num_instances; i ++) { + for (int i = 0; i < hm2->periodm.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.period_us", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.period), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.period), + 0.0, "%s.periodm.%02d.period_us", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.period_us', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.width_us", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.width), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.width), + 0.0, "%s.periodm.%02d.width_us", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.width_us', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.duty_cycle", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.dutycycle), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.dutycycle), + 0.0, "%s.periodm.%02d.duty_cycle", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.duty_cycle', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.duty_cycle_scale", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->periodm.instance[i].hal.pin.dutyscale), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->periodm.instance[i].hal.pin.dutyscale), + 100.0, "%s.periodm.%02d.duty_cycle_scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.duty_cycle_scale', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.duty_cycle_offset", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->periodm.instance[i].hal.pin.dutyoffset), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->periodm.instance[i].hal.pin.dutyoffset), + 0.0, "%s.periodm.%02d.duty_cycle_offset", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.duty_cycle_offset', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.frequency", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.frequency), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.frequency), + 0.0, "%s.periodm.%02d.frequency", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.frequency', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.filtertc_us", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->periodm.instance[i].hal.pin.filtertc), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->periodm.instance[i].hal.pin.filtertc), + 1.0, "%s.periodm.%02d.filtertc_us", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.filtertc_us', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.minimum_frequency", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->periodm.instance[i].hal.pin.minfreq), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->periodm.instance[i].hal.pin.minfreq), + 1.0, "%s.periodm.%02d.minimum_frequency", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.minimum_frequency', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.averages", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IO, &(hm2->periodm.instance[i].hal.pin.averages), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IO, &(hm2->periodm.instance[i].hal.pin.averages), + 1, "%s.periodm.%02d.averages", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.averages', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.invert", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IO, &(hm2->periodm.instance[i].hal.pin.polarity), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->periodm.instance[i].hal.pin.polarity), + 0, "%s.periodm.%02d.invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.invert', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.valid", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.valid), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.valid), + 0, "%s.periodm.%02d.valid", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.valid', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.periodm.%02d.input_status", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.input), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->periodm.instance[i].hal.pin.input), + 0, "%s.periodm.%02d.input_status", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.periodm.%02d.input_status', aborting\n", r, hm2->llio->name, i); goto fail1; } - - // init hal objects - *(hm2->periodm.instance[i].hal.pin.polarity) = 0; - *(hm2->periodm.instance[i].hal.pin.filtertc) = 1.0; - *(hm2->periodm.instance[i].hal.pin.averages) = 1; - *(hm2->periodm.instance[i].hal.pin.minfreq) = 1.0; - *(hm2->periodm.instance[i].hal.pin.dutyscale) = 100; - *(hm2->periodm.instance[i].hal.pin.dutyoffset) = 0; - } } @@ -361,19 +347,23 @@ void hm2_periodm_process_tram_read(hostmot2_t *hm2) { int i; rtapi_u32 mode = 0; for (i = 0; i < hm2->periodm.num_instances; i ++) { + rtapi_u32 averages = hal_get_ui32(hm2->periodm.instance[i].hal.pin.averages); mode = hm2->periodm.mode_read_reg[i]; -// *hm2->periodm.instance[i].hal.pin.polarity = ((mode & (1 << 0)) != 0); - *hm2->periodm.instance[i].hal.pin.valid = ((mode & (1 << 1)) != 0); - *hm2->periodm.instance[i].hal.pin.input = ((mode & (1 << 2)) != 0); - - *hm2->periodm.instance[i].hal.pin.period = (hm2->periodm.period_reg[i] / ((double)hm2->periodm.clock_frequency)) * (double)1e6 / *hm2->periodm.instance[i].hal.pin.averages; - *hm2->periodm.instance[i].hal.pin.width = (hm2->periodm.width_reg[i] / ((double)hm2->periodm.clock_frequency)) * (double)1e6 / *hm2->periodm.instance[i].hal.pin.averages; - if (*hm2->periodm.instance[i].hal.pin.period != 0) { - *hm2->periodm.instance[i].hal.pin.dutycycle = (((double)*hm2->periodm.instance[i].hal.pin.width - / (double)*hm2->periodm.instance[i].hal.pin.period) * (double)*hm2->periodm.instance[i].hal.pin.dutyscale) + *hm2->periodm.instance[i].hal.pin.dutyoffset; - *hm2->periodm.instance[i].hal.pin.frequency = (1.0 / (hm2->periodm.period_reg[i] / (double)hm2->periodm.clock_frequency)) * *hm2->periodm.instance[i].hal.pin.averages; - } - +// hal_set_bool(hm2->periodm.instance[i].hal.pin.polarity, (mode & (1 << 0)) != 0); + hal_set_bool(hm2->periodm.instance[i].hal.pin.valid, (mode & (1 << 1)) != 0); + hal_set_bool(hm2->periodm.instance[i].hal.pin.input, (mode & (1 << 2)) != 0); + + rtapi_real period = hal_set_real(hm2->periodm.instance[i].hal.pin.period, + (hm2->periodm.period_reg[i] / ((double)hm2->periodm.clock_frequency)) * (double)1e6 / averages); + rtapi_real width = hal_set_real(hm2->periodm.instance[i].hal.pin.width, + (hm2->periodm.width_reg[i] / ((double)hm2->periodm.clock_frequency)) * (double)1e6 / averages); + if (period != 0) { + hal_set_real(hm2->periodm.instance[i].hal.pin.dutycycle, + ((width / period) * hal_get_real(hm2->periodm.instance[i].hal.pin.dutyscale)) + + hal_get_real(hm2->periodm.instance[i].hal.pin.dutyoffset)); + hal_set_real(hm2->periodm.instance[i].hal.pin.frequency, + (1.0 / (hm2->periodm.period_reg[i] / (double)hm2->periodm.clock_frequency)) * averages); + } } } diff --git a/src/hal/drivers/mesa-hostmot2/pktuart.c b/src/hal/drivers/mesa-hostmot2/pktuart.c index 2c325cfd452..2198f4b7c5f 100644 --- a/src/hal/drivers/mesa-hostmot2/pktuart.c +++ b/src/hal/drivers/mesa-hostmot2/pktuart.c @@ -99,8 +99,7 @@ int hm2_pktuart_parse_md(hostmot2_t *hm2, int md_index) hm2->pktuart.num_instances = hm2->config.num_pktuarts; } - hm2->pktuart.instance = (hm2_pktuart_instance_t *)hal_malloc(hm2->pktuart.num_instances - * sizeof(hm2_pktuart_instance_t)); + hm2->pktuart.instance = hal_malloc(hm2->pktuart.num_instances * sizeof(*hm2->pktuart.instance)); if(hm2->pktuart.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -440,7 +439,7 @@ EXPORT_SYMBOL_GPL(hm2_pktuart_config); static void perform_reset(const char *name, int queue) { hostmot2_t *hm2; - hm2_pktuart_instance_t *inst = 0; + hm2_pktuart_instance_t *inst = NULL; rtapi_u32 buff = HM2_PKTUART_CLEAR; int i = hm2_get_pktuart(&hm2, name); if(i < 0) { @@ -496,7 +495,7 @@ EXPORT_SYMBOL_GPL(hm2_pktuart_queue_reset); int hm2_pktuart_setup(const char *name, unsigned bitrate, rtapi_s32 tx_mode, rtapi_s32 rx_mode, int txclear, int rxclear) { hostmot2_t *hm2; - hm2_pktuart_instance_t *inst = 0; + hm2_pktuart_instance_t *inst = NULL; rtapi_u32 buff; int i; int r = 0; diff --git a/src/hal/drivers/mesa-hostmot2/pwmgen.c b/src/hal/drivers/mesa-hostmot2/pwmgen.c index 5601b3aac2b..a136d335f4f 100644 --- a/src/hal/drivers/mesa-hostmot2/pwmgen.c +++ b/src/hal/drivers/mesa-hostmot2/pwmgen.c @@ -34,9 +34,9 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { rtapi_u32 dds; - if (hm2->pwmgen.hal->param.pwm_frequency < 1) { - HM2_ERR("pwmgen.pwm_frequency %d is too low, setting to 1\n", hm2->pwmgen.hal->param.pwm_frequency); - hm2->pwmgen.hal->param.pwm_frequency = 1; + if (hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) < 1) { + HM2_ERR("pwmgen.pwm_frequency %d is too low, setting to 1\n", hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency)); + hal_set_ui32(hm2->pwmgen.hal->param.pwm_frequency, 1); } @@ -65,7 +65,7 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { // // can we do it with 12 bits? - dds = ((double)hm2->pwmgen.hal->param.pwm_frequency * 65536.0 * 4096.0) / (double)hm2->pwmgen.clock_frequency; + dds = ((double)hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) * 65536.0 * 4096.0) / (double)hm2->pwmgen.clock_frequency; if (dds < 65536) { hm2->pwmgen.pwmgen_master_rate_dds_reg = dds; hm2->pwmgen.pwm_bits = 12; @@ -73,7 +73,7 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { } // try 11 bits - dds = ((double)hm2->pwmgen.hal->param.pwm_frequency * 65536.0 * 2048.0) / (double)hm2->pwmgen.clock_frequency; + dds = ((double)hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) * 65536.0 * 2048.0) / (double)hm2->pwmgen.clock_frequency; if (dds < 65536) { hm2->pwmgen.pwmgen_master_rate_dds_reg = dds; hm2->pwmgen.pwm_bits = 11; @@ -81,7 +81,7 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { } // try 10 bits - dds = ((double)hm2->pwmgen.hal->param.pwm_frequency * 65536.0 * 1024.0) / (double)hm2->pwmgen.clock_frequency; + dds = ((double)hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) * 65536.0 * 1024.0) / (double)hm2->pwmgen.clock_frequency; if (dds < 65536) { hm2->pwmgen.pwmgen_master_rate_dds_reg = dds; hm2->pwmgen.pwm_bits = 10; @@ -89,7 +89,7 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { } // try 9 bits - dds = ((double)hm2->pwmgen.hal->param.pwm_frequency * 65536.0 * 512.0) / (double)hm2->pwmgen.clock_frequency; + dds = ((double)hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) * 65536.0 * 512.0) / (double)hm2->pwmgen.clock_frequency; if (dds < 65536) { hm2->pwmgen.pwmgen_master_rate_dds_reg = dds; hm2->pwmgen.pwm_bits = 9; @@ -99,8 +99,8 @@ void hm2_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { // no joy, lower frequency until it'll work with 9 bits // From above: // PWMFreq = (ClockHigh * DDS) / (65536 * 2^PWMBits) - hm2->pwmgen.hal->param.pwm_frequency = ((double)hm2->pwmgen.clock_frequency * 65535.0) / (65536.0 * 512.0); - HM2_ERR("max PWM frequency is %d Hz\n", hm2->pwmgen.hal->param.pwm_frequency); + hal_set_ui32(hm2->pwmgen.hal->param.pwm_frequency, ((double)hm2->pwmgen.clock_frequency * 65535.0) / (65536.0 * 512.0)); + HM2_ERR("max PWM frequency is %d Hz\n", hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency)); hm2->pwmgen.pwmgen_master_rate_dds_reg = 65535; hm2->pwmgen.pwm_bits = 9; } @@ -110,9 +110,9 @@ void hm2_pwmgen_handle_pdm_frequency(hostmot2_t *hm2) { rtapi_u32 dds; - if (hm2->pwmgen.hal->param.pdm_frequency < 1) { - HM2_ERR("pwmgen.pdm_frequency %d is too low, setting to 1\n", hm2->pwmgen.hal->param.pdm_frequency); - hm2->pwmgen.hal->param.pdm_frequency = 1; + if (hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency) < 1) { + HM2_ERR("pwmgen.pdm_frequency %d is too low, setting to 1\n", hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency)); + hal_set_ui32(hm2->pwmgen.hal->param.pdm_frequency, 1); } @@ -151,14 +151,14 @@ void hm2_pwmgen_handle_pdm_frequency(hostmot2_t *hm2) { // // can we do it with 12 bits? - dds = ((double)hm2->pwmgen.hal->param.pdm_frequency * 65536.0) / (double)hm2->pwmgen.clock_frequency; + dds = ((double)hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency) * 65536.0) / (double)hm2->pwmgen.clock_frequency; if (dds == 0) { // too slow, set frequency to minimum // From above: // PulseFreq = (ClockHigh * DDS) / 65536 dds = 1; - hm2->pwmgen.hal->param.pdm_frequency = ((double)hm2->pwmgen.clock_frequency * (double)dds) / 65536.0; - HM2_ERR("min PDM frequency is %d Hz\n", hm2->pwmgen.hal->param.pdm_frequency); + hal_set_ui32(hm2->pwmgen.hal->param.pdm_frequency, ((double)hm2->pwmgen.clock_frequency * (double)dds) / 65536.0); + HM2_ERR("min PDM frequency is %d Hz\n", hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency)); hm2->pwmgen.pdmgen_master_rate_dds_reg = 1; return; } @@ -172,8 +172,8 @@ void hm2_pwmgen_handle_pdm_frequency(hostmot2_t *hm2) { // user wants too much, lower frequency until it'll work with 12 bits // From above: // PulseFreq = (ClockHigh * DDS) / 65536 - hm2->pwmgen.hal->param.pdm_frequency = ((double)hm2->pwmgen.clock_frequency * 65535.0) / 65536.0; - HM2_ERR("max PDM frequency is %d Hz\n", hm2->pwmgen.hal->param.pdm_frequency); + hal_set_ui32(hm2->pwmgen.hal->param.pdm_frequency, ((double)hm2->pwmgen.clock_frequency * 65535.0) / 65536.0); + HM2_ERR("max PDM frequency is %d Hz\n", hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency)); hm2->pwmgen.pdmgen_master_rate_dds_reg = 65535; } @@ -219,7 +219,7 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { hm2->pwmgen.pwm_mode_reg[i] = pwm_width; - switch (hm2->pwmgen.instance[i].hal.param.output_type) { + switch (hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type)) { case HM2_PWMGEN_OUTPUT_TYPE_PWM: { // leave the Output Mode bits 0 double_buffered = 1; @@ -247,7 +247,7 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { default: { // unknown pwm mode! complain and switch to pwm/dir HM2_ERR( "invalid pwmgen output_type %d requested\n", - hm2->pwmgen.instance[i].hal.param.output_type + hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type) ); HM2_ERR( "supported .output-type values are: %d (PWM & Dir), %d (Up & Down), %d (PDM & Dir), and %d (Dir & PWM)\n", @@ -257,7 +257,7 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { HM2_PWMGEN_OUTPUT_TYPE_PWM_SWAPPED ); HM2_ERR("switching to 1 (PWM & Dir)\n"); - hm2->pwmgen.instance[i].hal.param.output_type = HM2_PWMGEN_OUTPUT_TYPE_PWM; + hal_set_si32(hm2->pwmgen.instance[i].hal.param.output_type, HM2_PWMGEN_OUTPUT_TYPE_PWM); double_buffered = 1; // leave the Output Mode bits 0 break; @@ -265,7 +265,7 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { } hm2->pwmgen.pwm_mode_reg[i] |= (double_buffered << 5); - if (hm2->pwmgen.instance[i].hal.param.dither) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.param.dither)) { hm2->pwmgen.pwm_mode_reg[i] |= (1 << 6); } @@ -276,7 +276,7 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { // update enable register hm2->pwmgen.enable_reg = 0; for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - if (*(hm2->pwmgen.instance[i].hal.pin.enable)) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.pin.enable)) { hm2->pwmgen.enable_reg |= (1 << i); } } @@ -287,17 +287,17 @@ void hm2_pwmgen_force_write(hostmot2_t *hm2) { hm2->llio->write(hm2->llio, hm2->pwmgen.pwmgen_master_rate_dds_addr, &hm2->pwmgen.pwmgen_master_rate_dds_reg, sizeof(rtapi_u32)); hm2->llio->write(hm2->llio, hm2->pwmgen.pdmgen_master_rate_dds_addr, &hm2->pwmgen.pdmgen_master_rate_dds_reg, sizeof(rtapi_u32)); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - hm2->pwmgen.instance[i].written_output_type = hm2->pwmgen.instance[i].hal.param.output_type; - hm2->pwmgen.instance[i].written_offset_mode = hm2->pwmgen.instance[i].hal.param.offset_mode; - hm2->pwmgen.instance[i].written_dither = hm2->pwmgen.instance[i].hal.param.dither; - hm2->pwmgen.instance[i].written_enable = *hm2->pwmgen.instance[i].hal.pin.enable; + hm2->pwmgen.instance[i].written_output_type = hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type); + hm2->pwmgen.instance[i].written_offset_mode = hal_get_bool(hm2->pwmgen.instance[i].hal.param.offset_mode); + hm2->pwmgen.instance[i].written_dither = hal_get_bool(hm2->pwmgen.instance[i].hal.param.dither); + hm2->pwmgen.instance[i].written_enable = hal_get_bool(hm2->pwmgen.instance[i].hal.pin.enable); } - hm2->pwmgen.written_pwm_frequency = hm2->pwmgen.hal->param.pwm_frequency; - hm2->pwmgen.written_pdm_frequency = hm2->pwmgen.hal->param.pdm_frequency; + hm2->pwmgen.written_pwm_frequency = hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency); + hm2->pwmgen.written_pdm_frequency = hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency); } @@ -314,30 +314,30 @@ void hm2_pwmgen_write(hostmot2_t *hm2) { // check output type for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - if (hm2->pwmgen.instance[i].hal.param.output_type != hm2->pwmgen.instance[i].written_output_type) { + if (hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type) != hm2->pwmgen.instance[i].written_output_type) { goto force_write; } } // check offset mode for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - if (hm2->pwmgen.instance[i].hal.param.offset_mode != hm2->pwmgen.instance[i].written_offset_mode) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.param.offset_mode) != hm2->pwmgen.instance[i].written_offset_mode) { goto force_write; } } // update dither? for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - if (hm2->pwmgen.instance[i].hal.param.dither != hm2->pwmgen.instance[i].written_dither) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.param.dither) != hm2->pwmgen.instance[i].written_dither) { goto force_write; } // check pwm & pdm frequency - if (hm2->pwmgen.hal->param.pwm_frequency != hm2->pwmgen.written_pwm_frequency) goto force_write; - if (hm2->pwmgen.hal->param.pdm_frequency != hm2->pwmgen.written_pdm_frequency) goto force_write; + if (hal_get_ui32(hm2->pwmgen.hal->param.pwm_frequency) != hm2->pwmgen.written_pwm_frequency) goto force_write; + if (hal_get_ui32(hm2->pwmgen.hal->param.pdm_frequency) != hm2->pwmgen.written_pdm_frequency) goto force_write; // update enable register? for (i = 0; i < hm2->pwmgen.num_instances; i ++) { - if (*(hm2->pwmgen.instance[i].hal.pin.enable) != hm2->pwmgen.instance[i].written_enable) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.pin.enable) != hm2->pwmgen.instance[i].written_enable) { goto force_write; } } @@ -407,7 +407,7 @@ int hm2_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->pwmgen.hal = (hm2_pwmgen_module_global_t *)hal_malloc(sizeof(hm2_pwmgen_module_global_t)); + hm2->pwmgen.hal = hal_malloc(sizeof(*hm2->pwmgen.hal)); if (hm2->pwmgen.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -415,7 +415,7 @@ int hm2_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { } - hm2->pwmgen.instance = (hm2_pwmgen_instance_t *)hal_malloc(hm2->pwmgen.num_instances * sizeof(hm2_pwmgen_instance_t)); + hm2->pwmgen.instance = hal_malloc(hm2->pwmgen.num_instances * sizeof(*hm2->pwmgen.instance)); if (hm2->pwmgen.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -445,101 +445,71 @@ int hm2_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { } // export to HAL - // FIXME: r hides the r in enclosing function, and it returns the wrong thing { - int i; - int r; - char name[HAL_NAME_LEN + 1]; - - // these hal parameters affect all pwmgen instances - r = hal_param_u32_newf( - HAL_RW, - &(hm2->pwmgen.hal->param.pwm_frequency), - hm2->llio->comp_id, - "%s.pwmgen.pwm_frequency", - hm2->llio->name - ); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.hal->param.pwm_frequency), + 20000, "%s.pwmgen.pwm_frequency", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pwmgen.pwm_frequency param, aborting\n"); + HM2_ERR("error %d adding '%s.pwmgen.pwm_frequency' param, aborting\n", r, hm2->llio->name); goto fail1; } - hm2->pwmgen.hal->param.pwm_frequency = 20000; hm2->pwmgen.written_pwm_frequency = 0; - r = hal_param_u32_newf( - HAL_RW, - &(hm2->pwmgen.hal->param.pdm_frequency), - hm2->llio->comp_id, - "%s.pwmgen.pdm_frequency", - hm2->llio->name - ); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.hal->param.pdm_frequency), + 20000, "%s.pwmgen.pdm_frequency", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pwmgen.pdm_frequency param, aborting\n"); + HM2_ERR("error %d adding '%s.pwmgen.pdm_frequency' param, aborting\n", r, hm2->llio->name); goto fail1; } - hm2->pwmgen.hal->param.pdm_frequency = 20000; hm2->pwmgen.written_pdm_frequency = 0; - for (i = 0; i < hm2->pwmgen.num_instances; i ++) { + for (int i = 0; i < hm2->pwmgen.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.pwmgen.%02d.value", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->pwmgen.instance[i].hal.pin.value), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->pwmgen.instance[i].hal.pin.value), + 0.0, "%s.pwmgen.%02d.value", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.pwmgen.%02d.value', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.pwmgen.%02d.enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->pwmgen.instance[i].hal.pin.enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->pwmgen.instance[i].hal.pin.enable), + 0, "%s.pwmgen.%02d.enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.pwmgen.%02d.enable', aborting\n", r, hm2->llio->name, i); goto fail1; } // parameters - rtapi_snprintf(name, sizeof(name), "%s.pwmgen.%02d.offset-mode", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.offset_mode), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.offset_mode), + 0, "%s.pwmgen.%02d.offset-mode", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.pwmgen.%02d.offset-mode', aborting\n", r, hm2->llio->name, i); goto fail1; } if (hm2->pwmgen.firmware_supports_dither) { - rtapi_snprintf(name, sizeof(name), "%s.pwmgen.%02d.dither", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.dither), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.dither), + 0, "%s.pwmgen.%02d.dither", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.pwmgen.%02d.dither', aborting\n", r, hm2->llio->name, i); goto fail1; } } - rtapi_snprintf(name, sizeof(name), "%s.pwmgen.%02d.scale", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.scale), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.scale), + 1.0, "%s.pwmgen.%02d.scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.pwmgen.%02d.scale', aborting\n", r, hm2->llio->name, i); goto fail1; } - r = hal_param_s32_newf( - HAL_RW, - &(hm2->pwmgen.instance[i].hal.param.output_type), - hm2->llio->comp_id, - "%s.pwmgen.%02d.output-type", - hm2->llio->name, - i - ); + r = hal_param_new_si32(hm2->llio->comp_id, HAL_RW, &(hm2->pwmgen.instance[i].hal.param.output_type), + HM2_PWMGEN_OUTPUT_TYPE_PWM, "%s.pwmgen.%02d.output-type", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param, aborting\n"); + HM2_ERR("error %d adding param '%s.pwmgen.%02d.output-type', aborting\n", r, hm2->llio->name, i); goto fail1; } // init hal objects - *(hm2->pwmgen.instance[i].hal.pin.enable) = 0; - *(hm2->pwmgen.instance[i].hal.pin.value) = 0.0; - hm2->pwmgen.instance[i].hal.param.dither = 0; - hm2->pwmgen.instance[i].hal.param.scale = 1.0; - hm2->pwmgen.instance[i].hal.param.offset_mode = 0; - hm2->pwmgen.instance[i].hal.param.output_type = HM2_PWMGEN_OUTPUT_TYPE_PWM; hm2->pwmgen.instance[i].written_output_type = -666; // force an update at the start hm2->pwmgen.instance[i].written_enable = -666; // force an update at the start hm2->pwmgen.instance[i].written_dither = -666; // force an update at the start @@ -614,7 +584,7 @@ void hm2_pwmgen_prepare_tram_write(hostmot2_t *hm2) { double register_value; int bits; - scaled_value = *hm2->pwmgen.instance[i].hal.pin.value / hm2->pwmgen.instance[i].hal.param.scale; + scaled_value = hal_get_real(hm2->pwmgen.instance[i].hal.pin.value) / hal_get_real(hm2->pwmgen.instance[i].hal.param.scale); if (scaled_value > 1.0) scaled_value = 1.0; if (scaled_value < -1.0) scaled_value = -1.0; @@ -625,16 +595,16 @@ void hm2_pwmgen_prepare_tram_write(hostmot2_t *hm2) { // However, there apparently is equipment that does not behave this // way, and that benefits from having PWM & Dir go low when /Enable // goes high. (note that PWM will go to 50% when offset mode is enabled) - if (*hm2->pwmgen.instance[i].hal.pin.enable == 0) { + if (!hal_get_bool(hm2->pwmgen.instance[i].hal.pin.enable)) { scaled_value = 0.0; } abs_duty_cycle = fabs(scaled_value); // duty_cycle goes from 0.0 to 1.0, and needs to be puffed out to pwm_bits (if it's pwm) or 12 (if it's pdm) - if (hm2->pwmgen.instance[i].hal.param.offset_mode == 0) { + if (hal_get_bool(hm2->pwmgen.instance[i].hal.param.offset_mode) == 0) { //normal PWM/PDM modes - if (hm2->pwmgen.instance[i].hal.param.output_type == HM2_PWMGEN_OUTPUT_TYPE_PDM) { + if (hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type) == HM2_PWMGEN_OUTPUT_TYPE_PDM) { bits = 12; } else { bits = hm2->pwmgen.pwm_bits; @@ -642,7 +612,7 @@ void hm2_pwmgen_prepare_tram_write(hostmot2_t *hm2) { // With normal PWM, the max PWM register value is 0xNFF.X // but for dithered PWM the max value is 0xNFE.F // the topdrop value is chosen to generate these max values - if (hm2->pwmgen.instance[i].hal.param.dither == 0) { + if (!hal_get_bool(hm2->pwmgen.instance[i].hal.param.dither)) { topdrop = 1; } else { topdrop = 1.0625; @@ -651,7 +621,7 @@ void hm2_pwmgen_prepare_tram_write(hostmot2_t *hm2) { } else { // offset PWM/PDM modes where 0 PWM value = 50% duty cycle also choose active low - if (hm2->pwmgen.instance[i].hal.param.output_type == HM2_PWMGEN_OUTPUT_TYPE_PDM) { + if (hal_get_si32(hm2->pwmgen.instance[i].hal.param.output_type) == HM2_PWMGEN_OUTPUT_TYPE_PDM) { bits = 11; } else { bits = hm2->pwmgen.pwm_bits -1; @@ -659,7 +629,7 @@ void hm2_pwmgen_prepare_tram_write(hostmot2_t *hm2) { // With normal PWM, the max PWM register value is 0xNFF.X // but for dithered PWM the max value is 0xNFE.F // the topdrop value is chosen to generate these max values - if (hm2->pwmgen.instance[i].hal.param.dither == 0) { + if (!hal_get_bool(hm2->pwmgen.instance[i].hal.param.dither)) { topdrop = 1; } else { topdrop = 1.0625; diff --git a/src/hal/drivers/mesa-hostmot2/raw.c b/src/hal/drivers/mesa-hostmot2/raw.c index 7fb743b3b58..14a10634aab 100644 --- a/src/hal/drivers/mesa-hostmot2/raw.c +++ b/src/hal/drivers/mesa-hostmot2/raw.c @@ -32,73 +32,61 @@ int hm2_raw_setup(hostmot2_t *hm2) { int r; - char name[HAL_NAME_LEN + 1]; - if (hm2->config.enable_raw == 0) { return 0; } - hm2->raw = (hm2_raw_t *)hal_malloc(sizeof(hm2_raw_t)); + hm2->raw = hal_malloc(sizeof(*hm2->raw)); if (hm2->raw == NULL) { HM2_ERR("out of memory!\n"); hm2->config.enable_raw = 0; return -ENOMEM; } - rtapi_snprintf(name, sizeof(name), "%s.raw.read_address", hm2->llio->name); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->raw->hal.pin.read_address), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->raw->hal.pin.read_address), + 0, "%s.raw.read_address", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.read_address', aborting\n", r, hm2->llio->name); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.raw.read_data", hm2->llio->name); - r = hal_pin_u32_new(name, HAL_OUT, &(hm2->raw->hal.pin.read_data), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(hm2->raw->hal.pin.read_data), + 0, "%s.raw.read_data", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.read_data', aborting\n", r, hm2->llio->name); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.raw.write_address", hm2->llio->name); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->raw->hal.pin.write_address), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->raw->hal.pin.write_address), + 0, "%s.raw.write_address", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.write_address', aborting\n", r, hm2->llio->name); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.raw.write_data", hm2->llio->name); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->raw->hal.pin.write_data), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->raw->hal.pin.write_data), + 0, "%s.raw.write_data", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.write_data', aborting\n", r, hm2->llio->name); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.raw.write_strobe", hm2->llio->name); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->raw->hal.pin.write_strobe), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->raw->hal.pin.write_strobe), + 0, "%s.raw.write_strobe", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.write_strobe', aborting\n", r, hm2->llio->name); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.raw.dump_state", hm2->llio->name); - r = hal_pin_bit_new(name, HAL_IO, &(hm2->raw->hal.pin.dump_state), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->raw->hal.pin.dump_state), + 0, "%s.raw.dump_state", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.raw.dump_state', aborting\n", r, hm2->llio->name); return -EINVAL; } - // init hal objects - *(hm2->raw->hal.pin.read_address) = 0; - *(hm2->raw->hal.pin.read_data) = 0; - - *(hm2->raw->hal.pin.write_address) = 0; - *(hm2->raw->hal.pin.write_data) = 0; - *(hm2->raw->hal.pin.write_strobe) = 0; - - *(hm2->raw->hal.pin.dump_state) = 0; - return 0; } @@ -110,14 +98,14 @@ void hm2_raw_queue_read(hostmot2_t *hm2) { hm2->llio->queue_read( hm2->llio, - *hm2->raw->hal.pin.read_address & 0xffff, + hal_get_ui32(hm2->raw->hal.pin.read_address) & 0xffff, (void *)hm2->raw->hal.pin.read_data, sizeof(rtapi_u32) ); - if (*hm2->raw->hal.pin.dump_state != 0) { + if (hal_get_bool(hm2->raw->hal.pin.dump_state)) { hm2_print_modules(hm2); - *hm2->raw->hal.pin.dump_state = 0; + hal_set_bool(hm2->raw->hal.pin.dump_state, 0); } } @@ -126,15 +114,15 @@ void hm2_raw_queue_read(hostmot2_t *hm2) { void hm2_raw_write(hostmot2_t *hm2) { if (hm2->config.enable_raw == 0) return; - if (*hm2->raw->hal.pin.write_strobe == 0) return; + if (!hal_get_bool(hm2->raw->hal.pin.write_strobe)) return; hm2->llio->write( hm2->llio, - *hm2->raw->hal.pin.write_address & 0xffff, + hal_get_ui32(hm2->raw->hal.pin.write_address) & 0xffff, (void *)hm2->raw->hal.pin.write_data, sizeof(rtapi_u32) ); - *hm2->raw->hal.pin.write_strobe = 0; + hal_set_bool(hm2->raw->hal.pin.write_strobe, 0); } diff --git a/src/hal/drivers/mesa-hostmot2/rcpwmgen.c b/src/hal/drivers/mesa-hostmot2/rcpwmgen.c index b13c60f43eb..4a5b17dfe7e 100644 --- a/src/hal/drivers/mesa-hostmot2/rcpwmgen.c +++ b/src/hal/drivers/mesa-hostmot2/rcpwmgen.c @@ -77,7 +77,7 @@ int hm2_rcpwmgen_parse_md(hostmot2_t *hm2, int md_index) { hm2->rcpwmgen.clock_frequency = md->clock_freq; hm2->rcpwmgen.version = md->version; // allocate the module-instance HAL shared memory - hm2->rcpwmgen.instance = (hm2_rcpwmgen_instance_t *)hal_malloc(hm2->rcpwmgen.num_instances * sizeof(hm2_rcpwmgen_instance_t)); + hm2->rcpwmgen.instance = hal_malloc(hm2->rcpwmgen.num_instances * sizeof(*hm2->rcpwmgen.instance)); if (hm2->rcpwmgen.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -85,7 +85,7 @@ int hm2_rcpwmgen_parse_md(hostmot2_t *hm2, int md_index) { } // allocate the module-global HAL shared memory - hm2->rcpwmgen.hal = (hm2_rcpwmgen_module_global_t *)hal_malloc(sizeof(hm2_rcpwmgen_module_global_t)); + hm2->rcpwmgen.hal = hal_malloc(sizeof(*hm2->rcpwmgen.hal)); if (hm2->rcpwmgen.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -113,51 +113,40 @@ int hm2_rcpwmgen_parse_md(hostmot2_t *hm2, int md_index) { // // Export to HAL. // - + // initialize width to 0, scale to 1, offset 0 and rate to 50 Hz { - int i; - char name[HAL_NAME_LEN + 1]; - for (i = 0; i < hm2->rcpwmgen.num_instances; i ++) { - - rtapi_snprintf(name, sizeof(name), "%s.rcpwmgen.%02d.width", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.width), hm2->llio->comp_id); + for (int i = 0; i < hm2->rcpwmgen.num_instances; i ++) { + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.width), + 0.0, "%s.rcpwmgen.%02d.width", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.rcpwmgen.%02d.width', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.rcpwmgen.%02d.scale", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.scale), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.scale), + 1.0, "%s.rcpwmgen.%02d.scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.rcpwmgen.%02d.scale', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.rcpwmgen.%02d.offset", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.offset), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->rcpwmgen.instance[i].hal.pin.offset), + 0.0, "%s.rcpwmgen.%02d.offset", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.rcpwmgen.%02d.offset', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail1; } } - rtapi_snprintf(name, sizeof(name), "%s.rcpwmgen.rate", hm2->llio->name); - r = hal_pin_float_new(name, HAL_IN, &(hm2->rcpwmgen.hal->pin.rate), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->rcpwmgen.hal->pin.rate), + 50.0, "%s.rcpwmgen.rate", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.rcpwmgen.rate', aborting\n", r, hm2->llio->name); goto fail1; } } - // initialize width to 0, scale to 1, offset 0 and rate to 50 Hz - *hm2->rcpwmgen.hal->pin.rate = 50; - int i; - for (i = 0; i < hm2->rcpwmgen.num_instances; i ++) { - *hm2->rcpwmgen.instance[i].hal.pin.width = 0; - *hm2->rcpwmgen.instance[i].hal.pin.scale = 1.0; - *hm2->rcpwmgen.instance[i].hal.pin.offset = 0; - } hm2->rcpwmgen.error_throttle = 0; return hm2->rcpwmgen.num_instances; @@ -191,9 +180,9 @@ void hm2_rcpwmgen_update_regs(hostmot2_t *hm2) { rtapi_u32 reg; // Set rate - double rate = *hm2->rcpwmgen.hal->pin.rate; + double rate = hal_get_real(hm2->rcpwmgen.hal->pin.rate); if (rate < 0.01) { - *hm2->rcpwmgen.hal->pin.rate = 0.01; + hal_set_real(hm2->rcpwmgen.hal->pin.rate, 0.01); rate = 0.01; if (hm2->rcpwmgen.error_throttle == 0) { HM2_ERR("rcpwmgen frequency must be >= .01, resetting to %.3lf \n",0.01); @@ -202,7 +191,7 @@ void hm2_rcpwmgen_update_regs(hostmot2_t *hm2) { } if (rate > 1000) { - *hm2->rcpwmgen.hal->pin.rate = 1000; + hal_set_real(hm2->rcpwmgen.hal->pin.rate, 1000); rate = 1000; if (hm2->rcpwmgen.error_throttle == 0) { HM2_ERR("rcpwmgen frequency must be <= 1000, resetting to %.3lf \n",1000.0); @@ -219,19 +208,19 @@ void hm2_rcpwmgen_update_regs(hostmot2_t *hm2) { int i; // Set width. for (i = 0; i < hm2->rcpwmgen.num_instances; i ++) { - if (*hm2->rcpwmgen.instance[i].hal.pin.scale == 0) { + if (hal_get_real(hm2->rcpwmgen.instance[i].hal.pin.scale) == 0) { if (hm2->rcpwmgen.error_throttle == 0) { HM2_ERR("rcpwmgen %d zero scale is illegal, resetting to %.3lf \n", i,1.0); hm2->rcpwmgen.error_throttle = 100; } - *hm2->rcpwmgen.instance[i].hal.pin.scale = 1.0; + hal_set_real(hm2->rcpwmgen.instance[i].hal.pin.scale, 1.0); } - double width = (*hm2->rcpwmgen.instance[i].hal.pin.width)/(*hm2->rcpwmgen.instance[i].hal.pin.scale)+(*hm2->rcpwmgen.instance[i].hal.pin.offset); + double width = hal_get_real(hm2->rcpwmgen.instance[i].hal.pin.width) / hal_get_real(hm2->rcpwmgen.instance[i].hal.pin.scale) + hal_get_real(hm2->rcpwmgen.instance[i].hal.pin.offset); // The `width` variable has the desired pulse width in milliseconds. // The width register sets the width to reg*(CLockLow/16+1) if (width < 0) { - *hm2->rcpwmgen.instance[i].hal.pin.width = 0.0; + hal_set_real(hm2->rcpwmgen.instance[i].hal.pin.width, 0.0); width = 0.0; if (hm2->rcpwmgen.error_throttle == 0) { HM2_ERR("rcpwmgen %d width must be >= 0, resetting to %.3lf \n", i,0.0); @@ -240,10 +229,10 @@ void hm2_rcpwmgen_update_regs(hostmot2_t *hm2) { } reg = ((hm2->rcpwmgen.clock_frequency/(16.0*1000.0)))*width -1; if ((reg +1) > 65535 ) { - *hm2->rcpwmgen.instance[i].hal.pin.width = 65535/(hm2->rcpwmgen.clock_frequency/(16.0*1000.0)); + hal_set_real(hm2->rcpwmgen.instance[i].hal.pin.width, 65535/(hm2->rcpwmgen.clock_frequency/(16.0*1000.0))); reg = 65535; if (hm2->rcpwmgen.error_throttle == 0) { - HM2_ERR("rcpwmgen %d width too large,resetting to %.3lf \n", i,*hm2->rcpwmgen.instance[i].hal.pin.width); + HM2_ERR("rcpwmgen %d width too large,resetting to %.3lf \n", i, hal_get_real(hm2->rcpwmgen.instance[i].hal.pin.width)); hm2->rcpwmgen.error_throttle = 100; } } @@ -261,8 +250,8 @@ void hm2_rcpwmgen_write(hostmot2_t *hm2) { // check rate - if ( *hm2->rcpwmgen.hal->pin.rate != hm2->rcpwmgen.written_rate) { - hm2->rcpwmgen.written_rate = *hm2->rcpwmgen.hal->pin.rate; + if ( hal_get_real(hm2->rcpwmgen.hal->pin.rate) != hm2->rcpwmgen.written_rate) { + hm2->rcpwmgen.written_rate = hal_get_real(hm2->rcpwmgen.hal->pin.rate); goto force_write; } diff --git a/src/hal/drivers/mesa-hostmot2/resolver.c b/src/hal/drivers/mesa-hostmot2/resolver.c index 0599eb39ae3..f8c3a064ac2 100644 --- a/src/hal/drivers/mesa-hostmot2/resolver.c +++ b/src/hal/drivers/mesa-hostmot2/resolver.c @@ -94,15 +94,13 @@ int hm2_resolver_parse_md(hostmot2_t *hm2, int md_index) { hm2->resolver.num_instances = md->instances; } - hm2->resolver.hal = (hm2_resolver_global_t *)hal_malloc( - sizeof(hm2_resolver_global_t)); + hm2->resolver.hal = hal_malloc(sizeof(*hm2->resolver.hal)); if (hm2->resolver.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - hm2->resolver.instance = (hm2_resolver_instance_t *)hal_malloc( - hm2->resolver.num_resolvers * sizeof(hm2_resolver_instance_t)); + hm2->resolver.instance = hal_malloc(hm2->resolver.num_resolvers * sizeof(*hm2->resolver.instance)); if (hm2->resolver.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -142,161 +140,112 @@ int hm2_resolver_parse_md(hostmot2_t *hm2, int md_index) { // export the resolvers to HAL { - int i; - int ret; - char name[HAL_NAME_LEN + 1]; - - rtapi_snprintf(name, sizeof(name), "%s.resolver.excitation-khz", - hm2->llio->name); - ret= hal_param_float_new(name, HAL_RW, - &(hm2->resolver.hal->param.excitation_khz), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->resolver.hal->param.excitation_khz), + -1.0, "%s.resolver.excitation-khz", hm2->llio->name); + if (r < 0) { + HM2_ERR("error %d adding param '%s.resolver.excitation-khz', aborting\n", r, hm2->llio->name); goto fail1; } - for (i = 0; i < hm2->resolver.num_resolvers; i ++) { + for (int i = 0; i < hm2->resolver.num_resolvers; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.position", - hm2->llio->name, i); - ret= hal_pin_float_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.position), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.position), + 0.0, "%s.resolver.%02d.position", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.position', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.angle", - hm2->llio->name, i); - ret= hal_pin_float_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.angle), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.angle), + 0.0, "%s.resolver.%02d.angle", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.angle', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.velocity", - hm2->llio->name, i); - ret= hal_pin_float_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.velocity), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.velocity), + 0.0, "%s.resolver.%02d.velocity", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.velocity', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.velocity-rpm", - hm2->llio->name, i); - ret= hal_pin_float_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.velocity_rpm), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.velocity_rpm), + 0.0, "%s.resolver.%02d.velocity-rpm", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.velocity-rpm', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.count", - hm2->llio->name, i); - ret= hal_pin_s32_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.count), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.count), + 0, "%s.resolver.%02d.count", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.count', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.rawcounts", - hm2->llio->name, i); - ret= hal_pin_s32_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.rawcounts), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.rawcounts), + 0, "%s.resolver.%02d.rawcounts", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.rawcounts', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.reset", - hm2->llio->name, i); - ret= hal_pin_bit_new(name, HAL_IN, - &(hm2->resolver.instance[i].hal.pin.reset), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->resolver.instance[i].hal.pin.reset), + 0, "%s.resolver.%02d.reset", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.reset', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.index-enable", - hm2->llio->name, i); - ret= hal_pin_bit_new(name, HAL_IO, - &(hm2->resolver.instance[i].hal.pin.index_enable), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->resolver.instance[i].hal.pin.index_enable), + 0, "%s.resolver.%02d.index-enable", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.index-enable', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.error", - hm2->llio->name, i); - ret= hal_pin_bit_new(name, HAL_OUT, - &(hm2->resolver.instance[i].hal.pin.error), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->resolver.instance[i].hal.pin.error), + 0, "%s.resolver.%02d.error", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.error', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.joint-pos-fb", - hm2->llio->name, i); - ret= hal_pin_float_new(name, HAL_IN, - &(hm2->resolver.instance[i].hal.pin.joint_pos_fb), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->resolver.instance[i].hal.pin.joint_pos_fb), + 0.0, "%s.resolver.%02d.joint-pos-fb", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding pin '%s.resolver.%02d.joint-pos-fb', aborting\n", r, hm2->llio->name, i); goto fail1; } // parameters - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.scale", - hm2->llio->name, i); - ret= hal_param_float_new(name, HAL_RW, - &(hm2->resolver.instance[i].hal.param.scale), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->resolver.instance[i].hal.param.scale), + 1.0, "%s.resolver.%02d.scale", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.resolver.%02d.scale', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.velocity-scale", - hm2->llio->name, i); - ret= hal_param_float_new(name, HAL_RW, - &(hm2->resolver.instance[i].hal.param.vel_scale), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->resolver.instance[i].hal.param.vel_scale), + 1.0, "%s.resolver.%02d.velocity-scale", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.resolver.%02d.velocity-scale', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.index-divisor", - hm2->llio->name, i); - ret= hal_param_u32_new(name, HAL_RW, - &(hm2->resolver.instance[i].hal.param.index_div), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->resolver.instance[i].hal.param.index_div), + 1, "%s.resolver.%02d.index-divisor", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.resolver.%02d.index-divisor', aborting\n", r, hm2->llio->name, i); goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.resolver.%02d.use-position-file", - hm2->llio->name, i); - ret= hal_param_bit_new(name, HAL_RW, - &(hm2->resolver.instance[i].hal.param.use_abs), - hm2->llio->comp_id); - if (ret < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->resolver.instance[i].hal.param.use_abs), + 0, "%s.resolver.%02d.use-position-file", hm2->llio->name, i); + if (r < 0) { + HM2_ERR("error %d adding param '%s.resolver.%02d.use-position-file', aborting\n", r, hm2->llio->name, i); goto fail1; } @@ -304,12 +253,6 @@ int hm2_resolver_parse_md(hostmot2_t *hm2, int md_index) { // init the hal objects that need it // the things not initialized here will be set by hm2_resolver_tram_init() // - - *hm2->resolver.instance[i].hal.pin.reset = 0; - hm2->resolver.instance[i].hal.param.scale = 1.0; - hm2->resolver.instance[i].hal.param.vel_scale = 1.0; - hm2->resolver.instance[i].hal.param.index_div = 1; - hm2->resolver.hal->param.excitation_khz = -1; // don't-write hm2->resolver.kHz = (hm2->resolver.clock_frequency / 5000); } } @@ -341,23 +284,23 @@ void hm2_resolver_process_tram_read(hostmot2_t *hm2, long period) { res = &hm2->resolver.instance[i]; + scale = hal_get_real(res->hal.param.scale); + // sanity check - if (res->hal.param.scale == 0.0) { + if (scale == 0.0) { HM2_ERR("resolver.%02d.scale == 0.0, bogus, setting to 1.0\n", i); - res->hal.param.scale = 1.0; + scale = hal_set_real(res->hal.param.scale, 1.0); } - if (res->hal.param.vel_scale == 0.0) { + if (hal_get_real(res->hal.param.vel_scale) == 0.0) { HM2_ERR("resolver.%02d.velocity-scale == 0.0, bogus, setting to 1.0\n", i); - res->hal.param.vel_scale = 1.0; + hal_set_real(res->hal.param.vel_scale, 1.0); } - scale = res->hal.param.scale; - - if (res->hal.param.use_abs){ // pseudo-absolute behaviour enabled but not initialised + if (hal_get_bool(res->hal.param.use_abs)){ // pseudo-absolute behaviour enabled but not initialised double new_pos; int turns; - old_pos = *res->hal.pin.joint_pos_fb; + old_pos = hal_get_real(res->hal.pin.joint_pos_fb); if (old_pos == 0 && cycle_count++ < 5000 ) { // position.txt not updated yet. Or (small probability) position.txt = 0 continue; // stop and process next resolver } @@ -373,7 +316,7 @@ void hm2_resolver_process_tram_read(hostmot2_t *hm2, long period) { res->offset = -((turns * scale) - old_pos) * (0x1p32 / scale); res->old_reg = hm2->resolver.position_reg[i]; // prevent wrap detection at init. res->accum = hm2->resolver.position_reg[i]; //necessary to allow rawcounts to still work for commutation - res->hal.param.use_abs = 0; // tag as initialised + hal_set_bool(res->hal.param.use_abs, 0); // tag as initialised } // PROCESS THE REGISTERS, SET THE PINS @@ -382,38 +325,39 @@ void hm2_resolver_process_tram_read(hostmot2_t *hm2, long period) { if ((res->old_reg > hm2->resolver.position_reg[i]) && (res->old_reg - hm2->resolver.position_reg[i] > 0x80000000)){ res->index_cnts++; - if (*res->hal.pin.index_enable){ - int r = (res->index_cnts % res->hal.param.index_div); - if ((res->hal.param.index_div > 1 && r == 1) - || (res->hal.param.index_div == 1 && r == 0)){ + if (hal_get_bool(res->hal.pin.index_enable)){ + rtapi_u32 index_div = hal_get_ui32(res->hal.param.index_div); + int r = (res->index_cnts % index_div); + if ((index_div > 1 && r == 1) + || (index_div == 1 && r == 0)){ res->offset = (res->accum - hm2->resolver.position_reg[i]); - *res->hal.pin.index_enable = 0; + hal_set_bool(res->hal.pin.index_enable, 0); } } } else if ((res->old_reg < hm2->resolver.position_reg[i]) && (hm2->resolver.position_reg[i] - res->old_reg > 0x80000000)){ res->index_cnts--; - if (*res->hal.pin.index_enable && (res->index_cnts % res->hal.param.index_div == 0)){ + if (hal_get_bool(res->hal.pin.index_enable) && (res->index_cnts % hal_get_ui32(res->hal.param.index_div) == 0)){ res->offset = (res->accum - hm2->resolver.position_reg[i] + 0x100000000LL); - *res->hal.pin.index_enable = 0; + hal_set_bool(res->hal.pin.index_enable, 0); } } - if (*res->hal.pin.reset){ + if (hal_get_bool(res->hal.pin.reset)){ res->offset = res->accum; } res->old_reg = hm2->resolver.position_reg[i]; - *res->hal.pin.angle = hm2->resolver.position_reg[i] / 0x1P32; - *res->hal.pin.rawcounts = (res->accum >> 8); - *res->hal.pin.count = (res->accum - res->offset) >> 8; - *res->hal.pin.position = (res->accum - res->offset) / 0x1P32 - * res->hal.param.scale; - *res->hal.pin.velocity = ((hm2->resolver.velocity_reg[i] / 0x1P32) - * hm2->resolver.kHz * res->hal.param.vel_scale); - *res->hal.pin.velocity_rpm = *res->hal.pin.velocity * 60.0; - *res->hal.pin.error = *hm2->resolver.status_reg & (1 << i); + hal_set_real(res->hal.pin.angle, hm2->resolver.position_reg[i] / 0x1P32); + hal_set_si32(res->hal.pin.rawcounts, (res->accum >> 8)); + hal_set_si32(res->hal.pin.count, (res->accum - res->offset) >> 8); + hal_set_real(res->hal.pin.position, (res->accum - res->offset) / 0x1P32 + * hal_get_real(res->hal.param.scale)); + hal_set_real(res->hal.pin.velocity, ((hm2->resolver.velocity_reg[i] / 0x1P32) + * hm2->resolver.kHz * hal_get_real(res->hal.param.vel_scale))); + hal_set_real(res->hal.pin.velocity_rpm, hal_get_real(res->hal.pin.velocity) * 60.0); + hal_set_bool(res->hal.pin.error, *hm2->resolver.status_reg & (1 << i)); } } @@ -424,27 +368,29 @@ void hm2_resolver_write(hostmot2_t *hm2, long period){ static rtapi_u32 cmd_val, data_val; static rtapi_u32 timer; rtapi_u32 buff; + rtapi_real exc; if (hm2->resolver.num_instances <= 0) return; switch (state){ case 0: // Idle/waiting - if (hm2->resolver.hal->param.excitation_khz < 0){ + exc = hal_get_real(hm2->resolver.hal->param.excitation_khz); + if (exc < 0){ return; } - if (hm2->resolver.hal->param.excitation_khz != hm2->resolver.written_khz){ - if (hm2->resolver.hal->param.excitation_khz > 8){ - hm2->resolver.hal->param.excitation_khz = 10; + if (exc != hm2->resolver.written_khz){ + if (exc > 8){ + hal_set_real(hm2->resolver.hal->param.excitation_khz, 10); hm2->resolver.written_khz = 10; hm2->resolver.kHz = (hm2->resolver.clock_frequency / 5000); cmd_val = 0x803; - } else if (hm2->resolver.hal->param.excitation_khz > 4){ - hm2->resolver.hal->param.excitation_khz = 5; + } else if (exc > 4){ + hal_set_real(hm2->resolver.hal->param.excitation_khz, 5); hm2->resolver.written_khz = 5; hm2->resolver.kHz = (hm2->resolver.clock_frequency / 10000); cmd_val = 0x802; }else{ - hm2->resolver.hal->param.excitation_khz = 2.5; + hal_set_real(hm2->resolver.hal->param.excitation_khz, 2.5); hm2->resolver.written_khz = 2.5; hm2->resolver.kHz= (hm2->resolver.clock_frequency / 20000); cmd_val = 0x801; diff --git a/src/hal/drivers/mesa-hostmot2/sserial.c b/src/hal/drivers/mesa-hostmot2/sserial.c index 97d4fc2f033..b99f7a15681 100644 --- a/src/hal/drivers/mesa-hostmot2/sserial.c +++ b/src/hal/drivers/mesa-hostmot2/sserial.c @@ -66,7 +66,7 @@ int hm2_sserial_wait(hostmot2_t *hm2, hm2_sserial_instance_t *inst, long period) // real-time wait function (relies on process data) *inst->command_reg_write = 0x80000000; // mask pointless writes inst->timer -= period; - *inst->debug = inst->timer; + hal_set_si32(inst->debug, inst->timer); if (*inst->command_reg_read != 0) { if (inst->timer > 0) { return 1; @@ -359,30 +359,30 @@ int hm2_sserial_get_param_value(hostmot2_t *hm2, r = hm2_sserial_get_bytes(hm2, chan, (void*)&(p->u32_written), g->ParmAddr, g->DataLength/8); if (r < 0) {HM2_ERR("SSerial Parameter read error\n") ; return -EINVAL;} - if (set_hal) p->u32_param = p->u32_written; - HM2_DBG("LBP_UNSIGNED %i %i \n", p->u32_param, p->u32_written); - if ((strcmp(g->NameString, "swrevision") == 0) && (p->u32_param < 14)) { + if (set_hal) hal_set_ui32(p->param.u, p->u32_written); + HM2_DBG("LBP_UNSIGNED %i %i \n", hal_get_ui32(p->param.u), p->u32_written); + if ((strcmp(g->NameString, "swrevision") == 0) && (hal_get_ui32(p->param.u) < 14)) { HM2_ERR("Warning: sserial remote device %s channel %d has old firmware that should be updated\n", chan->raw_name, chan->index); } break; case LBP_SIGNED: r = hm2_sserial_get_bytes(hm2, chan, (void*)&(p->s32_written), g->ParmAddr, g->DataLength/8); - if (set_hal) p->s32_param = p->s32_written; - HM2_DBG("LBP_SIGNED %i %i \n", p->s32_param, p->s32_written); + if (set_hal) hal_set_si32(p->param.s, p->s32_written); + HM2_DBG("LBP_SIGNED %i %i \n", hal_get_si32(p->param.s), p->s32_written); break; case LBP_NONVOL_UNSIGNED: r = hm2_sserial_read_nvram_word(hm2, chan, (void*)&(p->u32_written), g->ParmAddr, g->DataLength/8); - if (set_hal) p->u32_param = p->u32_written; - HM2_DBG("LBP_NONVOL_UNSIGNED %i %i \n", p->u32_param, p->u32_written); + if (set_hal) hal_set_ui32(p->param.u, p->u32_written); + HM2_DBG("LBP_NONVOL_UNSIGNED %i %i \n", hal_get_ui32(p->param.u), p->u32_written); break; case LBP_NONVOL_SIGNED: r = hm2_sserial_read_nvram_word(hm2, chan, (void*)&(p->s32_written), g->ParmAddr, g->DataLength/8); - if (set_hal) p->s32_param = p->s32_written; + if (set_hal) hal_set_si32(p->param.s, p->s32_written); case LBP_STREAM: break; // Have not seen a stream type yet case LBP_BOOLEAN: @@ -405,8 +405,8 @@ int hm2_sserial_get_param_value(hostmot2_t *hm2, HM2_ERR("sserial get param value: LBP_FLOAT of bit-length %i not handled\n", g->DataLength); } } - if (set_hal) p->float_param = p->float_written; - HM2_DBG("LBP_FLOAT %f %f \n", p->float_param, p->float_written); + if (set_hal) hal_set_real(p->param.r, p->float_written); + HM2_DBG("LBP_FLOAT %f %f \n", hal_get_real(p->param.r), p->float_written); break; case LBP_ENCODER_H: case LBP_ENCODER_L: @@ -423,7 +423,7 @@ int hm2_sserial_create_params(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ hm2_sserial_data_t global; int hal_dir; - chan->params = hal_malloc(chan->num_globals * sizeof(hm2_sserial_params_t)); + chan->params = hal_malloc(chan->num_globals * sizeof(*chan->params)); for (i = 0 ; i < chan->num_globals ; i++){ global = chan->globals[i]; @@ -437,9 +437,9 @@ int hm2_sserial_create_params(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ break; case LBP_UNSIGNED: case LBP_NONVOL_UNSIGNED: - r = hal_param_u32_newf(hal_dir, - &(chan->params[i].u32_param), - hm2->llio->comp_id, + r = hal_param_new_ui32(hm2->llio->comp_id, hal_dir, + &(chan->params[i].param.u), + 0, "%s.%s", chan->name, global.NameString); @@ -447,9 +447,9 @@ int hm2_sserial_create_params(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ break; case LBP_SIGNED: case LBP_NONVOL_SIGNED: - r = hal_param_s32_newf(hal_dir, - &(chan->params[i].s32_param), - hm2->llio->comp_id, + r = hal_param_new_si32(hm2->llio->comp_id, hal_dir, + &(chan->params[i].param.s), + 0, "%s.%s", chan->name, global.NameString); @@ -457,9 +457,9 @@ int hm2_sserial_create_params(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ break; case LBP_FLOAT: case LBP_NONVOL_FLOAT: - r = hal_param_float_newf(hal_dir, - &(chan->params[i].float_param), - hm2->llio->comp_id, + r = hal_param_new_real(hm2->llio->comp_id, hal_dir, + &(chan->params[i].param.r), + 0.0, "%s.%s", chan->name, global.NameString); @@ -628,8 +628,7 @@ int hm2_sserial_parse_md(hostmot2_t *hm2, int md_index){ HM2_DBG("sserial_num_instances = %i\n", hm2->sserial.num_instances); // allocate the per-instance HAL shared memory - hm2->sserial.instance = (hm2_sserial_instance_t *) - hal_malloc(hm2->sserial.num_instances * sizeof(hm2_sserial_instance_t)); + hm2->sserial.instance = hal_malloc(hm2->sserial.num_instances * sizeof(*hm2->sserial.instance)); if (hm2->sserial.instance == NULL) { HM2_ERR("hm2_sserial_parse_md: hm2_sserial_instance: out of memory!\n"); r = -ENOMEM; @@ -849,97 +848,74 @@ int hm2_sserial_parse_md(hostmot2_t *hm2, int md_index){ int hm2_sserial_setup_channel(hostmot2_t *hm2, hm2_sserial_instance_t *inst, int index){ int r; - r = hal_pin_s32_newf(HAL_OUT, &(inst->debug), - hm2->llio->comp_id, - "%s.%i.debug", - hm2->llio->name, index); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(inst->debug), + 0, "%s.%i.debug", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.run. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.run. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - r = hal_pin_bit_newf(HAL_IN, &(inst->run), - hm2->llio->comp_id, - "%s.sserial.port-%1d.run", - hm2->llio->name, index); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(inst->run), + true, "%s.sserial.port-%1d.run", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.run. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.run. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - *inst->run = true; - r = hal_pin_u32_newf(HAL_OUT, &(inst->state), - hm2->llio->comp_id, - "%s.sserial.port-%1d.port_state", - hm2->llio->name, index); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(inst->state), + 0, "%s.sserial.port-%1d.port_state", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.port_state. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.port_state. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - r = hal_pin_u32_newf(HAL_OUT, &(inst->state2), - hm2->llio->comp_id, - "%s.sserial.port-%1d.port_state2", - hm2->llio->name, index); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(inst->state2), + 0, "%s.sserial.port-%1d.port_state2", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.port_state. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.port_state. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - r = hal_pin_u32_newf(HAL_OUT, &(inst->state3), - hm2->llio->comp_id, - "%s.sserial.port-%1d.port_state3", - hm2->llio->name, index); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(inst->state3), + 0, "%s.sserial.port-%1d.port_state3", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.port_state. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.port_state. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - r = hal_pin_u32_newf(HAL_OUT, &(inst->fault_count), - hm2->llio->comp_id, - "%s.sserial.port-%1d.fault-count", - hm2->llio->name, index); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(inst->fault_count), + 0, "%s.sserial.port-%1d.fault-count", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding pin %s.sserial.%1d.fault-count. aborting\n", - hm2->llio->name, index); + HM2_ERR("error %d adding pin %s.sserial.%1d.fault-count. aborting\n", + r, hm2->llio->name, index); return -EINVAL; } - r = hal_param_u32_newf(HAL_RW, &(inst->fault_inc), - hm2->llio->comp_id, - "%s.sserial.port-%1d.fault-inc", - hm2->llio->name, index); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->fault_inc), + 10, "%s.sserial.port-%1d.fault-inc", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding parameter %s.sserial.port-%1d.fault-inc" - " aborting\n",hm2->llio->name, index); + HM2_ERR("error %d adding parameter %s.sserial.port-%1d.fault-inc" + " aborting\n", r, hm2->llio->name, index); return -EINVAL; } - r = hal_param_u32_newf(HAL_RW, &(inst->fault_dec), - hm2->llio->comp_id, - "%s.sserial.port-%1d.fault-dec", - hm2->llio->name, index); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->fault_dec), + 1, "%s.sserial.port-%1d.fault-dec", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding parameter %s.sserial.port-%1d.fault-dec" - " aborting\n",hm2->llio->name, index); + HM2_ERR("error %d adding parameter %s.sserial.port-%1d.fault-dec" + " aborting\n", r, hm2->llio->name, index); return -EINVAL; } - r = hal_param_u32_newf(HAL_RW, &(inst->fault_lim), - hm2->llio->comp_id, - "%s.sserial.port-%1d.fault-lim", - hm2->llio->name, index); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(inst->fault_lim), + 200, "%s.sserial.port-%1d.fault-lim", hm2->llio->name, index); if (r < 0) { - HM2_ERR("error adding parameter %s.sserial.port-%1d.fault-lim" - " aborting\n",hm2->llio->name, index); + HM2_ERR("error %d adding parameter %s.sserial.port-%1d.fault-lim" + " aborting\n", r, hm2->llio->name, index); return -EINVAL; } - //parameter defaults; - inst->fault_dec = 1; - inst->fault_inc = 10; - inst->fault_lim = 200; // setup read-back in all modes @@ -1118,10 +1094,8 @@ int hm2_sserial_read_configs(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ int hm2_sserial_create_pins(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ int i, j; int r = 0; - char name[HAL_NAME_LEN + 1]; int data_dir; - chan->pins = (hm2_sserial_pins_t*)hal_malloc(chan->num_confs - * sizeof(hm2_sserial_pins_t)); + chan->pins = hal_malloc(chan->num_confs * sizeof(*chan->pins)); chan->num_read_bits = 0 ; chan->num_write_bits = 0; @@ -1173,51 +1147,31 @@ int hm2_sserial_create_pins(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ case LBP_PAD: break; case LBP_BITS: - chan->pins[i].bit_pins = (hal_bit_t**) - hal_malloc(chan->confs[i].DataLength * sizeof(hal_bit_t*)); - chan->pins[i].bit_pins_not = (hal_bit_t**) - hal_malloc(chan->confs[i].DataLength * sizeof(hal_bit_t*)); - chan->pins[i].invert = (hal_bit_t*) - hal_malloc(chan->confs[i].DataLength * sizeof(hal_bit_t)); + chan->pins[i].bit_pins = hal_malloc(chan->confs[i].DataLength * sizeof(*chan->pins[i].bit_pins)); + chan->pins[i].bit_pins_not = hal_malloc(chan->confs[i].DataLength * sizeof(*chan->pins[i].bit_pins_not)); + chan->pins[i].invert = hal_malloc(chan->confs[i].DataLength * sizeof(*chan->pins[i].invert)); for (j = 0; j < chan->confs[i].DataLength ; j++){ - rtapi_snprintf(name, sizeof(name), "%s.%s-%02d", - chan->name, - chan->confs[i].NameString, - j); - r = hal_pin_bit_new(name, - data_dir, - &(chan->pins[i].bit_pins[j]), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, data_dir, &(chan->pins[i].bit_pins[j]), + 0, "%s.%s-%02d", chan->name, chan->confs[i].NameString, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-%02d', aborting\n", r, chan->name, chan->confs[i].NameString, j); return r; } if (data_dir == HAL_OUT) { - rtapi_snprintf(name, sizeof(name), "%s.%s-%02d-not", - chan->name, - chan->confs[i].NameString, - j); - r = hal_pin_bit_new(name, - data_dir, - &(chan->pins[i].bit_pins_not[j]), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, data_dir, &(chan->pins[i].bit_pins_not[j]), + 0, "%s.%s-%02d-not", chan->name, chan->confs[i].NameString, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-%02d-not', aborting\n", r, chan->name, chan->confs[i].NameString, j); return r; } } if (data_dir == HAL_IN){ - rtapi_snprintf(name, sizeof(name), "%s.%s-%02d-invert", - chan->name, - chan->confs[i].NameString, - j); - r = hal_param_bit_new(name, - HAL_RW, - &(chan->pins[i].invert[j]), - hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].invert[j]), + 0, "%s.%s-%02d-invert", chan->name, chan->confs[i].NameString, j); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-%02d-invert', aborting\n", + r, chan->name, chan->confs[i].NameString, j); return r; } } @@ -1225,54 +1179,31 @@ int hm2_sserial_create_pins(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ break; case LBP_UNSIGNED: case LBP_SIGNED: - rtapi_snprintf(name, sizeof(name), "%s.%s", - chan->name, - chan->confs[i].NameString); - r = hal_pin_float_new(name, - data_dir, - &(chan->pins[i].float_pin), - hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, data_dir, &(chan->pins[i].float_pin), + 0.0, "%s.%s", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } - rtapi_snprintf(name, sizeof(name), "%s.%s-scalemax", - chan->name, - chan->confs[i].NameString); - r = hal_param_float_new(name, - HAL_RW, - &(chan->pins[i].fullscale), - hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].fullscale), + chan->confs[i].ParmMax, "%s.%s-scalemax", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-scalemax', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } - chan->pins[i].fullscale = chan->confs[i].ParmMax; if (data_dir == HAL_OUT) {break;} - rtapi_snprintf(name, sizeof(name), "%s.%s-maxlim", - chan->name, - chan->confs[i].NameString); - r = hal_param_float_new(name, - HAL_RW, - &(chan->pins[i].maxlim), - hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].maxlim), + chan->confs[i].ParmMax, "%s.%s-maxlim", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-maxlim', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } - chan->pins[i].maxlim = chan->confs[i].ParmMax; - rtapi_snprintf(name, sizeof(name), "%s.%s-minlim", - chan->name, - chan->confs[i].NameString); - r = hal_param_float_new(name, - HAL_RW, - &(chan->pins[i].minlim), - hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].minlim), + chan->confs[i].ParmMin, "%s.%s-minlim", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-minlim', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } - chan->pins[i].minlim = chan->confs[i].ParmMin; break; case LBP_NONVOL_UNSIGNED: case LBP_NONVOL_SIGNED: @@ -1280,156 +1211,95 @@ int hm2_sserial_create_pins(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ "never happen. Aborting"); return r; case LBP_STREAM: - rtapi_snprintf(name, sizeof(name), "%s.%s", - chan->name, - chan->confs[i].NameString); - r = hal_pin_u32_new(name, - data_dir, - &(chan->pins[i].u32_pin), - hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, data_dir, &(chan->pins[i].u32_pin), + 0, "%s.%s", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } break; case LBP_BOOLEAN: - rtapi_snprintf(name, sizeof(name), "%s.%s", - chan->name, - chan->confs[i].NameString); - r = hal_pin_bit_new(name, - data_dir, - &(chan->pins[i].boolean), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, data_dir, &(chan->pins[i].boolean), + 0, "%s.%s", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } if (data_dir == HAL_OUT) { - rtapi_snprintf(name, sizeof(name), "%s.%s-not", - chan->name, - chan->confs[i].NameString); - r = hal_pin_bit_new(name, - data_dir, - &(chan->pins[i].boolean2), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, data_dir, &(chan->pins[i].boolean2), + 0, "%s.%s-not", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-not', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } } if (data_dir == HAL_IN) { - chan->pins[i].invert = hal_malloc(sizeof(hal_bit_t)); - rtapi_snprintf(name, sizeof(name), "%s.%s-invert", - chan->name, - chan->confs[i].NameString); - r = hal_param_bit_new(name, - HAL_RW, - chan->pins[i].invert, - hm2->llio->comp_id); + chan->pins[i].invert = hal_malloc(sizeof(*chan->pins[i].invert)); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, chan->pins[i].invert, + 0, "%s.%s-invert", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s-invert', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } } break; case LBP_ENCODER: case LBP_ENCODER_H: - - rtapi_snprintf(name, sizeof(name), "%s.%s.count", - chan->name, - chan->confs[i].NameString); - r = hal_pin_s32_new(name, - HAL_OUT, - &(chan->pins[i].s32_pin), - hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(chan->pins[i].s32_pin), + 0, "%s.%s.count", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.count', aborting\n", r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.rawcounts", - chan->name, - chan->confs[i].NameString); - r = hal_pin_s32_new(name, - HAL_OUT, - &(chan->pins[i].s32_pin2), - hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(chan->pins[i].s32_pin2), + 0, "%s.%s.rawcounts", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.rawcounts', aborting\n", r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.position", - chan->name, - chan->confs[i].NameString); - r = hal_pin_float_new(name, - HAL_OUT, - &(chan->pins[i].float_pin), - hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(chan->pins[i].float_pin), + 0.0, "%s.%s.position", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.position', aborting\n", r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.index-enable", - chan->name, - chan->confs[i].NameString); - r = hal_pin_bit_new(name, - HAL_IO, - &(chan->pins[i].boolean), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(chan->pins[i].boolean), + 0, "%s.%s.index-enable", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.index-enable', aborting\n", r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.reset", - chan->name, - chan->confs[i].NameString); - r = hal_pin_bit_new(name, - HAL_IO, - &(chan->pins[i].boolean2), - hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(chan->pins[i].boolean2), + 0, "%s.%s.reset", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.reset', aborting\n", r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.scale", - chan->name, - chan->confs[i].NameString); - r = hal_param_float_new(name, - HAL_RW, - &(chan->pins[i].fullscale), - hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].fullscale), + chan->confs[i].ParmMax, "%s.%s.scale", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.scale', aborting\n", + r, chan->name, chan->confs[i].NameString); return -EINVAL; } - rtapi_snprintf(name, sizeof(name), "%s.%s.counts-per-rev", - chan->name, - chan->confs[i].NameString); - r = hal_param_u32_new(name, - HAL_RW, - &(chan->pins[i].u32_param), - hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(chan->pins[i].u32_param), + 256, "%s.%s.counts-per-rev", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s.counts-per-rev', aborting\n", + r, chan->name, chan->confs[i].NameString); return -EINVAL; } - chan->pins[i].fullscale = chan->confs[i].ParmMax; - chan->pins[i].u32_param = 256; break; case LBP_ENCODER_L: //No pins for encoder L break; case LBP_FLOAT: - rtapi_snprintf(name, sizeof(name), "%s.%s", - chan->name, - chan->confs[i].NameString); - r = hal_pin_float_new(name, - data_dir, - &(chan->pins[i].float_pin), - hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, data_dir, &(chan->pins[i].float_pin), + 0.0, "%s.%s", chan->name, chan->confs[i].NameString); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.%s', aborting\n", r, chan->name, chan->confs[i].NameString); return r; } break; @@ -1499,11 +1369,11 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ hm2_sserial_data_t *g; int shift; // used for floating point comparisons - switch (*inst->state2){ + switch (hal_get_ui32(inst->state2)){ case 0: // init loop counters inst->r_index = 0; inst->g_index = 0; - *inst->state2 = 1; + hal_set_ui32(inst->state2, 1); /* Fallthrough */ case 1: if (inst->num_remotes == 0) return 0; @@ -1512,29 +1382,27 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ p = &(r->params[inst->g_index]); g = &(r->globals[inst->g_index]); } else { - *inst->state2 = 2; + hal_set_ui32(inst->state2, 2); break; } - switch (*inst->state3){ + switch (hal_get_ui32(inst->state3)){ //Commands are queued for TRAM write, so every change in //command needs a break to poll the thread int ret; default: - HM2_ERR("Unhandled state %i", *inst->state3); + HM2_ERR("Unhandled state %i", hal_get_ui32(inst->state3)); return 1; case 0: HM2_DBG("Checking Param %s datatype %02X\n", g->NameString, p->type); switch (p->type){ case LBP_SIGNED: case LBP_NONVOL_SIGNED: - if (p->s32_param != p->s32_written) break; - *inst->state2 = 2; // increment indices - return *inst->state2; + if (hal_get_si32(p->param.s) != p->s32_written) break; + return hal_set_ui32(inst->state2, 2); // increment indices case LBP_UNSIGNED: case LBP_NONVOL_UNSIGNED: - if (p->u32_param != p->u32_written) break; - *inst->state2 = 2; // increment indices - return *inst->state2; + if (hal_get_ui32(p->param.u) != p->u32_written) break; + return hal_set_ui32(inst->state2, 2); // increment indices case LBP_FLOAT: case LBP_NONVOL_FLOAT: // comparing floats that might have different sizes is not trivial @@ -1554,30 +1422,31 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ case 64: shift = 0; } - if (xlabs((p->s64_param - p->s64_written) >> shift) > 2) break; - *inst->state2 = 2; // increment indices - return *inst->state2; + // FIXME: This overlayed s64 read is very wrong! + if (xlabs((hal_get_sint(p->param.s) - p->s64_written) >> shift) > 2) break; + return hal_set_ui32(inst->state2, 2); // increment indices default: - *inst->state2 = 2; // increment indices - return *inst->state2; + return hal_set_ui32(inst->state2, 2); // increment indices } HM2_WARN("Writing value of %s datatype %02X\n", g->NameString, p->type); - *inst->state3 = 1; + hal_set_ui32(inst->state3, 1); inst->timer = 20000000; *inst->command_reg_write = 0x800; // stop all break; case 1: ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up - *inst->state3 = 2; + // FIXME: Assigns 100 to state3 and then unconditionally assigns 2 + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up + hal_set_ui32(inst->state3, 2); inst->timer = 20000000; *inst->command_reg_write = 0xF00 | (1 << r->index); // channel in setup mode break; case 2: // Unlock Nonvol access ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up + // FIXME: Assigns 100 to state3 and then 3 or 4 inside the if/else. + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up if ( p->type == LBP_NONVOL_FLOAT || p->type == LBP_NONVOL_UNSIGNED || p->type == LBP_NONVOL_SIGNED){ @@ -1585,38 +1454,39 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ *r->write[0] = LBPNONVOLEEPROM; *inst->command_reg_write = 0x1000 | (1 << r->index); // doit command inst->timer = 20000000; - *inst->state3 = 3; + hal_set_ui32(inst->state3, 3); HM2_PRINT("A non-volatile smart-serial parameter has been changed\n" "A full power-cycle will be needed before the effect is seen\n"); } else { - *inst->state3 = 4; + hal_set_ui32(inst->state3, 4); } break; case 3: // wait for doit clear ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up + // FIXME: Assigns 100 to state3 and then unconditionally assigns 4 + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up // NV access now enabled. HM2_DBG("NV Access unlocked: param %s\n", g->NameString); - *inst->state3 = 4; + hal_set_ui32(inst->state3, 4); break; case 4: // Now send the data switch (p->type){ case LBP_SIGNED: case LBP_NONVOL_SIGNED: - *r->write[0] = (rtapi_u32) p->s32_param; + *r->write[0] = (rtapi_u32)hal_get_si32(p->param.s); break; case LBP_UNSIGNED: case LBP_NONVOL_UNSIGNED: - *r->write[0] = p->u32_param; + *r->write[0] = hal_get_ui32(p->param.u); break; case LBP_FLOAT: case LBP_NONVOL_FLOAT: if (g->DataLength == sizeof(float) * 8 ){ - float temp = p->float_param; + float temp = hal_get_real(p->param.r); memcpy(r->write[0], &temp, sizeof(float)); // Data Value } else if (g->DataLength == sizeof(double) * 8){ - double temp = p->float_param; + double temp = hal_get_real(p->param.r); memcpy(r->write[0], &temp, sizeof(double)); } else { HM2_ERR("sserial write: LBP_FLOAT of bit-length %i not handled\n", g->DataLength); @@ -1642,26 +1512,27 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ } *inst->command_reg_write = 0x1000 | (1 << r->index); // doit command inst->timer = 200000000; - *inst->state3 = 5; + hal_set_ui32(inst->state3, 5); break; case 5: // wait for doit clear ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up + // FIXME: Assigns 100 to state3 and then 7 or 8 inside the if/else. + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up // success? Set the written = param switch (p->type){ case LBP_SIGNED: case LBP_NONVOL_SIGNED: - p->s32_written = p->s32_param; + p->s32_written = hal_get_si32(p->param.s); break; case LBP_UNSIGNED: case LBP_NONVOL_UNSIGNED: - p->u32_written = p->u32_param; + p->u32_written = hal_get_ui32(p->param.u); break; case LBP_FLOAT: case LBP_NONVOL_FLOAT: - p->float_written = p->float_param; + p->float_written = hal_get_real(p->param.r); break; default: break; @@ -1676,52 +1547,54 @@ int hm2_sserial_register_tram(hostmot2_t *hm2, hm2_sserial_remote_t *chan){ *r->write[0] = LBPNONVOLCLEAR; *inst->command_reg_write = 0x1000 | (1 << r->index); // doit command inst->timer = 0x2000000; - *inst->state3 = 7; + hal_set_ui32(inst->state3, 7); } else { - *inst->state3 = 8; + hal_set_ui32(inst->state3, 8); } break; case 7: // wait for doit clear ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up + // FIXME: Assigns 100 to state3 and then unconditionally assigns 8 + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up // NV access now cleared HM2_DBG("NV Access Cleared: param %s\n", g->NameString); - * inst->state3 = 8; + hal_set_ui32(inst->state3, 8); break; case 8: // stop-all inst->timer = 0x2000000; *inst->command_reg_write = 0x800; //stop - *inst->state3 = 9; + hal_set_ui32(inst->state3, 9); break; case 9: //wait for final stop-all ret = hm2_sserial_wait(hm2, inst, period); if (ret > 0) break; - if (ret < 0) *inst->state3 = 100; // quit and tidy up + // FIXME: Assigns 100 to state3 and then unconditionally assigns 0 + if (ret < 0) hal_set_ui32(inst->state3, 100); // quit and tidy up // NV access now cleared HM2_DBG("Board out of setup mode: param %s\n", g->NameString); - *inst->state3 = 0; - *inst->state2 = 2; // increment indices + hal_set_ui32(inst->state3, 0); + hal_set_ui32(inst->state2, 2); // increment indices break; case 100: // error recovery HM2_ERR("Problem found writing sserial parameter %s\n", g->NameString); *inst->command_reg_write = 0x800; //stop all command - *inst->state3 = 0; - *inst->state2 = 2; // increment indices + hal_set_ui32(inst->state3, 0); + hal_set_ui32(inst->state2, 2); // increment indices break; } // End of switch(inst->state3) break; case 2: - *inst->state2 = 1; + hal_set_ui32(inst->state2, 1); if ((int)++inst->g_index >= inst->remotes[inst->r_index].num_globals){ inst->g_index = 0; if ((int)++inst->r_index >= inst->num_remotes){//checked them all - *inst->state2 = 0; + hal_set_ui32(inst->state2, 0); } } break; } // end of switch(inst->state2) - return *inst->state2; + return hal_get_ui32(inst->state2); } void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ @@ -1733,7 +1606,8 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ // the side effect of reporting this error will suffice (void)hm2_sserial_check_remote_errors(hm2, inst); - if (*inst->fault_count > inst->fault_lim) { + rtapi_u32 fault_count = hal_get_ui32(inst->fault_count); + if (fault_count > hal_get_ui32(inst->fault_lim)) { // If there have been a large percentage of misses, for quite // a long time, it's time to take it seriously. hm2_sserial_check_local_errors(hm2, inst); @@ -1741,9 +1615,9 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ "There have been more than %i errors in %i " "thread executions at least %i times. " "See other error messages for details.\n", - inst->fault_dec, - inst->fault_inc, - inst->fault_lim); + hal_get_ui32(inst->fault_dec), + hal_get_ui32(inst->fault_inc), + hal_get_ui32(inst->fault_lim)); HM2_ERR("***Smart Serial Port %i will be stopped***\n",inst->index); static bool printed; if(!inst->ever_read && !printed) { @@ -1753,7 +1627,7 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ "This error message will not repeat.\n"); printed = true; } - *inst->state = 10; + hal_set_ui32(inst->state, 10); *inst->command_reg_write = 0x800; // stop command return; } @@ -1767,20 +1641,20 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ "if this is happening frequently.\n", inst->index, hm2->llio->name, inst->index); } - *inst->fault_count += inst->fault_inc; + fault_count = hal_set_ui32(inst->fault_count, fault_count + hal_get_ui32(inst->fault_inc)); *inst->command_reg_write = 0x80000000; // set bit31 for ignored cmd return; // give the register chance to clear } if (*inst->data_reg_read & 0xff) { // indicates a failed transfer - *inst->fault_count += inst->fault_inc; + fault_count = hal_set_ui32(inst->fault_count, fault_count + hal_get_ui32(inst->fault_inc)); } - if (*inst->fault_count > inst->fault_dec) { - *inst->fault_count -= inst->fault_dec; + if (fault_count > hal_get_ui32(inst->fault_dec)) { + fault_count = hal_set_ui32(inst->fault_count, fault_count - hal_get_ui32(inst->fault_dec)); } else { - *inst->fault_count = 0; + fault_count = hal_set_ui32(inst->fault_count, 0); } // All seems well, handle the pins. @@ -1805,32 +1679,32 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ case LBP_BITS: buff = 0; for (b = 0 ; b < conf->DataLength ; b++){ - buff |= ((rtapi_u64)(*pin->bit_pins[b] != 0) << b) - ^ ((rtapi_u64)(pin->invert[b] != 0) << b); + buff |= ((rtapi_u64)(hal_get_bool(pin->bit_pins[b])) << b) + ^ ((rtapi_u64)hal_get_bool(pin->invert[b]) << b); } break; case LBP_UNSIGNED: - val = *pin->float_pin; - if (val > pin->maxlim) val = pin->maxlim; - if (val < pin->minlim) val = pin->minlim; - buff = (rtapi_u64)((val / pin->fullscale) + val = hal_get_real(pin->float_pin); + if (val > hal_get_real(pin->maxlim)) val = hal_get_real(pin->maxlim); + if (val < hal_get_real(pin->minlim)) val = hal_get_real(pin->minlim); + buff = (rtapi_u64)((val / hal_get_real(pin->fullscale)) * (~0ull >> (64 - conf->DataLength))); break; case LBP_SIGNED: //this only works if DataLength <= 32 - val = *pin->float_pin; - if (val > pin->maxlim) val = pin->maxlim; - if (val < pin->minlim) val = pin->minlim; - buff = (((rtapi_s32)(val / pin->fullscale * 2147483647)) + val = hal_get_real(pin->float_pin); + if (val > hal_get_real(pin->maxlim)) val = hal_get_real(pin->maxlim); + if (val < hal_get_real(pin->minlim)) val = hal_get_real(pin->minlim); + buff = (((rtapi_s32)(val / hal_get_real(pin->fullscale) * 2147483647)) >> (32 - conf->DataLength)) & (~0ull >> (64 - conf->DataLength)); break; case LBP_STREAM: - buff = *pin->u32_pin & (~0ull >> (64 - conf->DataLength)); + buff = hal_get_ui32(pin->u32_pin) & (~0ull >> (64 - conf->DataLength)); break; case LBP_BOOLEAN: buff = 0; - if (*pin->boolean ^ ((conf->DataDir == LBP_OUT)?(*pin->invert):0)){ + if (hal_get_bool(pin->boolean) ^ ((conf->DataDir == LBP_OUT)?(hal_get_bool(*pin->invert)):0)){ buff = (~0ull >> (64 - conf->DataLength)); } break; @@ -1840,10 +1714,10 @@ void hm2_sserial_write_pins(hostmot2_t *hm2, hm2_sserial_instance_t *inst){ break; case LBP_FLOAT: if (conf->DataLength == sizeof(float) * 8 ){ - float temp = *pin->float_pin; + float temp = hal_get_real(pin->float_pin); memcpy(&buff, &temp, sizeof(float)); } else if (conf->DataLength == sizeof(double) * 8){ - double temp = *pin->float_pin; + double temp = hal_get_real(pin->float_pin); memcpy(&buff, &temp, sizeof(double)); } else { HM2_ERR_NO_LL("sserial write: LBP_FLOAT of bit-length %i not handled\n", conf->DataLength); @@ -1877,28 +1751,28 @@ void hm2_sserial_prepare_tram_write(hostmot2_t *hm2, long period){ hm2_sserial_instance_t *inst = &(hm2->sserial.instance[i]); - switch ((*inst->state) & 0xFF){ + switch (hal_get_ui32(inst->state) & 0xFF){ case 0: // Idle - if (! *inst->run){ break; } + if (! hal_get_bool(inst->run)){ break; } // Check for any changed parameters if (hm2_sserial_update_params(hm2, inst, period) > 0) break; //set the modes for the cards hm2_sserial_setmode(hm2, inst); *inst->command_reg_write = 0x900 | inst->tag; HM2_DBG("Enabled Remotes tag = = %x\n", inst->tag); - *inst->fault_count = 0; + hal_set_ui32(inst->fault_count, 0); inst->doit_err_count = 0; inst->timer = 2100000000; - *inst->state = 2; + hal_set_ui32(inst->state, 2); break; case 2: // just transitioning to running if (hm2_sserial_wait(hm2, inst, period) > 0) break; - *inst->state = 3; + hal_set_ui32(inst->state, 3); break; case 3: // normal running - if (!*inst->run){ - *inst->state = 4; + if (!hal_get_bool(inst->run)){ + hal_set_ui32(inst->state, 4); break; } hm2_sserial_write_pins(hm2, inst); @@ -1906,21 +1780,21 @@ void hm2_sserial_prepare_tram_write(hostmot2_t *hm2, long period){ case 4: // run to stop transition *inst->command_reg_write = 0x800; inst->timer = 2100000000; - *inst->state = 5; + hal_set_ui32(inst->state, 5); break; case 5: if (hm2_sserial_wait(hm2, inst, period) > 0) break; - *inst->state = 0; + hal_set_ui32(inst->state, 0); break; case 10:// Do-nothing state for serious errors. require run pin to cycle *inst->command_reg_write = 0x80000000; // set bit31 for ignored cmd - if ( ! *inst->run){*inst->state = 0;} + if ( !hal_get_bool(inst->run)){hal_set_ui32(inst->state, 0);} break; default: // Should never happen HM2_ERR("Unhandled run/stop configuration in \n" "hm2_sserial_write (%x)\n", - *inst->state); - *inst->state = 0; + hal_get_ui32(inst->state)); + hal_set_ui32(inst->state, 0); } } } @@ -1948,8 +1822,8 @@ int hm2_sserial_read_pins(hm2_sserial_remote_t *chan){ break; case LBP_BITS: for (b = 0 ; b < conf->DataLength ; b++){ - *pin->bit_pins[b] = ((buff & (1LL << b)) != 0); - *pin->bit_pins_not[b] = ! *pin->bit_pins[b]; + rtapi_bool _v = hal_set_bool(pin->bit_pins[b], (buff & (1LL << b)) != 0); + hal_set_bool(pin->bit_pins_not[b], !_v); } break; case LBP_UNSIGNED: @@ -1961,21 +1835,19 @@ int hm2_sserial_read_pins(hm2_sserial_remote_t *chan){ } } - *pin->float_pin = (buff * pin->fullscale) - / ((1 << conf->DataLength) - 1); + hal_set_real(pin->float_pin, (buff * hal_get_real(pin->fullscale)) / ((1 << conf->DataLength) - 1)); break; case LBP_SIGNED: buff32 = (buff & 0xFFFFFFFFL) << (32 - conf->DataLength); - *pin->float_pin = (buff32 / 2147483647.0 ) - * pin->fullscale; + hal_set_real(pin->float_pin, (buff32 / 2147483647.0 ) * hal_get_real(pin->fullscale)); break; case LBP_STREAM: - *pin->u32_pin = buff & (~0ull >> (64 - conf->DataLength)); + hal_set_ui32(pin->u32_pin, buff & (~0ull >> (64 - conf->DataLength))); break; case LBP_BOOLEAN: - *pin->boolean = (buff != 0); + hal_set_bool(pin->boolean, buff != 0); if(conf->DataDir == LBP_IN){ - *pin->boolean2 = (buff == 0); + hal_set_bool(pin->boolean2, buff == 0); } break; case LBP_ENCODER_H: @@ -1998,7 +1870,7 @@ int hm2_sserial_read_pins(hm2_sserial_remote_t *chan){ int bitlength; rtapi_s32 rem1, rem2; rtapi_s64 previous; - rtapi_u32 ppr = pin->u32_param; + rtapi_u32 ppr = hal_get_ui32(pin->u32_param); if (conf->DataType == LBP_ENCODER){ bitlength = conf->DataLength; @@ -2031,10 +1903,10 @@ int hm2_sserial_read_pins(hm2_sserial_remote_t *chan){ pin->accum += (buff64 - pin->oldval); //reset - if (*pin->boolean2){pin->offset = pin->accum;} + if (hal_get_bool(pin->boolean2)){pin->offset = pin->accum;} //index-enable - if (*pin->boolean && ppr > 0){ // index-enable set + if (hal_get_bool(pin->boolean) && ppr > 0){ // index-enable set rtapi_div_s64_rem(previous, ppr, &rem1); rtapi_div_s64_rem(pin->accum, ppr, &rem2); if ((unsigned)abs(rem1 - rem2) > ppr / 2 @@ -2057,23 +1929,23 @@ int hm2_sserial_read_pins(hm2_sserial_remote_t *chan){ pin->offset = 0; } } - *pin->boolean = 0; + hal_set_bool(pin->boolean, 0); } } pin->oldval = buff64; - *pin->s32_pin = pin->accum - pin->offset; - *pin->s32_pin2 = pin->accum; - *pin->float_pin = (double)(pin->accum - pin->offset) / pin->fullscale ; + hal_set_si32(pin->s32_pin, pin->accum - pin->offset); + hal_set_si32(pin->s32_pin2, pin->accum); + hal_set_real(pin->float_pin, (double)(pin->accum - pin->offset) / hal_get_real(pin->fullscale)); break; case LBP_FLOAT: if (conf->DataLength == sizeof(float) * 8){ float temp; memcpy(&temp, &buff, sizeof(float)); - *pin->float_pin = temp; + hal_set_real(pin->float_pin, temp); } else if (conf->DataLength == sizeof(double) * 8){ double temp; memcpy(&temp, &buff, sizeof(double)); - *pin->float_pin = temp; + hal_set_real(pin->float_pin, temp); } else { HM2_ERR_NO_LL("sserial read: LBP_FLOAT of bit-length %i not handled\n", conf->DataLength); conf->DataType = 0; // Only warn once, then ignore @@ -2099,7 +1971,7 @@ void hm2_sserial_process_tram_read(hostmot2_t *hm2, long period){ for (i = 0 ; i < hm2->sserial.num_instances ; i++){ hm2_sserial_instance_t *inst = &hm2->sserial.instance[i]; inst->ever_read = true; - if (*inst->state != 3) continue ; // Only work on running instances + if (hal_get_ui32(inst->state) != 3) continue ; // Only work on running instances for (c = 0 ; c < inst->num_remotes ; c++ ) { hm2_sserial_remote_t *chan = &inst->remotes[c]; hm2_sserial_read_pins(chan); diff --git a/src/hal/drivers/mesa-hostmot2/sserial.h b/src/hal/drivers/mesa-hostmot2/sserial.h index e6391f30eb4..18583f0b318 100644 --- a/src/hal/drivers/mesa-hostmot2/sserial.h +++ b/src/hal/drivers/mesa-hostmot2/sserial.h @@ -110,21 +110,21 @@ typedef struct { }hm2_sserial_mode_t; typedef struct { - hal_u32_t *u32_pin; - hal_s32_t *s32_pin; - hal_s32_t *s32_pin2; - hal_float_t *float_pin; - hal_bit_t **bit_pins; - hal_bit_t **bit_pins_not; - hal_bit_t *invert; - hal_bit_t *boolean; - hal_bit_t *boolean2; - hal_float_t maxlim; - hal_float_t minlim; - hal_float_t fullscale; - hal_u32_t u32_param; - hal_bit_t graycode; - hal_bit_t nowrap; + hal_uint_t u32_pin; + hal_sint_t s32_pin; + hal_sint_t s32_pin2; + hal_real_t float_pin; + hal_bool_t *bit_pins; + hal_bool_t *bit_pins_not; + hal_bool_t *invert; + hal_bool_t boolean; + hal_bool_t boolean2; + hal_real_t maxlim; + hal_real_t minlim; + hal_real_t fullscale; + hal_uint_t u32_param; + rtapi_bool graycode; + rtapi_bool nowrap; rtapi_s64 oldval; // not pins, but this way every pin can have one rtapi_s64 accum; // these two are only currently used by encoders rtapi_s64 offset; @@ -132,22 +132,16 @@ typedef struct { typedef struct { int type; + hal_refs_u param; union { - long long s64_param; - hal_u32_t u32_param; - hal_s32_t s32_param; - hal_float_t float_param; - hal_bit_t bit_param; + rtapi_u64 u64_written; + rtapi_s64 s64_written; + rtapi_u32 u32_written; + rtapi_s32 s32_written; + rtapi_real float_written; }; - union { - long long s64_written; - hal_u32_t u32_written; - hal_s32_t s32_written; - hal_float_t float_written; - hal_bit_t bit_written; - }; - hal_u32_t timer_num; - hal_bit_t *error; + hal_uint_t timer_num; + hal_bool_t error; }hm2_sserial_params_t; typedef struct { @@ -164,8 +158,9 @@ typedef struct { hm2_sserial_data_t *globals; hm2_sserial_pins_t *pins; hm2_sserial_params_t *params; - hal_u32_t serialnumber; - hal_u32_t status, seen_remote_errors; + rtapi_u32 serialnumber; + rtapi_u32 status; + rtapi_u32 seen_remote_errors; rtapi_u32 *reg_cs_read; rtapi_u32 *reg_cs_write; @@ -196,18 +191,18 @@ typedef struct { rtapi_u32 data_reg_addr; rtapi_u32 *data_reg_read; rtapi_u32 *data_reg_write; - hal_u32_t *fault_count; - hal_u32_t fault_inc; - hal_u32_t fault_dec; - hal_u32_t fault_lim; + hal_uint_t fault_count; + hal_uint_t fault_inc; + hal_uint_t fault_dec; + hal_uint_t fault_lim; - hal_bit_t *run; - hal_u32_t *state; - hal_u32_t *state2; - hal_u32_t *state3; - hal_s32_t *debug; - hal_u32_t r_index; - hal_u32_t g_index; + hal_bool_t run; + hal_uint_t state; + hal_uint_t state2; + hal_uint_t state3; + hal_sint_t debug; + rtapi_u32 r_index; + rtapi_u32 g_index; int doit_err_count; rtapi_s32 timer; bool ever_read; diff --git a/src/hal/drivers/mesa-hostmot2/ssr.c b/src/hal/drivers/mesa-hostmot2/ssr.c index fb44c7dcafc..095b927ad82 100644 --- a/src/hal/drivers/mesa-hostmot2/ssr.c +++ b/src/hal/drivers/mesa-hostmot2/ssr.c @@ -82,7 +82,7 @@ int hm2_ssr_parse_md(hostmot2_t *hm2, int md_index) { hm2->ssr.clock_freq = md->clock_freq; hm2->ssr.version = md->version; - hm2->ssr.instance = (hm2_ssr_instance_t *)hal_malloc(hm2->ssr.num_instances * sizeof(hm2_ssr_instance_t)); + hm2->ssr.instance = hal_malloc(hm2->ssr.num_instances * sizeof(*hm2->ssr.instance)); if (hm2->ssr.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -126,22 +126,18 @@ int hm2_ssr_parse_md(hostmot2_t *hm2, int md_index) { // { - int i; - char name[HAL_NAME_LEN + 1]; - - for (i = 0; i < hm2->ssr.num_instances; i ++) { - rtapi_snprintf(name, sizeof(name), "%s.ssr.%02d.rate", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->ssr.instance[i].hal.pin.rate), hm2->llio->comp_id); + for (int i = 0; i < hm2->ssr.num_instances; i ++) { + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->ssr.instance[i].hal.pin.rate), + 1000*1000, "%s.ssr.%02d.rate", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.ssr.%02d.rate', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail1; } { - int j = 0; int ssr_number; - for (j = 0; j < hm2->num_pins; j++){ + for (int j = 0; j < hm2->num_pins; j++){ if (hm2->pin[j].sec_tag == HM2_GTAG_SSR && hm2->pin[j].sec_unit == i) { if ((hm2->pin[j].sec_pin & 0x80) != 0x80) { HM2_ERR("Pin Descriptor %d has an SSR pin that's not an output!\n", j); @@ -160,17 +156,17 @@ int hm2_ssr_parse_md(hostmot2_t *hm2, int md_index) { goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.ssr.%02d.out-%02d", hm2->llio->name, i, ssr_number); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->ssr.instance[i].hal.pin.out[ssr_number]), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->ssr.instance[i].hal.pin.out[ssr_number]), + 0, "%s.ssr.%02d.out-%02d", hm2->llio->name, i, ssr_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.ssr.%02d.out-%02d', aborting\n", r, hm2->llio->name, i, ssr_number); r = -ENOMEM; goto fail1; } - rtapi_snprintf(name, sizeof(name), "%s.ssr.%02d.invert-%02d", hm2->llio->name, i, ssr_number); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->ssr.instance[i].hal.pin.invert[ssr_number]), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->ssr.instance[i].hal.pin.invert[ssr_number]), + 0, "%s.ssr.%02d.invert-%02d", hm2->llio->name, i, ssr_number); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.ssr.%02d.invert-%02d', aborting\n", r, hm2->llio->name, i, ssr_number); r = -ENOMEM; goto fail1; } @@ -192,17 +188,7 @@ int hm2_ssr_parse_md(hostmot2_t *hm2, int md_index) { { int i; for (i = 0; i < hm2->ssr.num_instances; i ++) { - int pin; rtapi_u32 zero = 0; - - *hm2->ssr.instance[i].hal.pin.rate = 1000*1000; - - for (pin = 0; pin < 32; pin ++) { - if (hm2->ssr.instance[i].hal.pin.out[pin] != NULL) { - *hm2->ssr.instance[i].hal.pin.out[pin] = 0; - *hm2->ssr.instance[i].hal.pin.invert[pin] = 0; - } - } hm2->llio->write(hm2->llio, hm2->ssr.rate_addr + (i * md->instance_stride), &zero, sizeof(zero)); hm2->llio->write(hm2->llio, hm2->ssr.data_addr + (i * md->instance_stride), &zero, sizeof(zero)); } @@ -232,16 +218,17 @@ static void hm2_ssr_compute_rate_regs(hostmot2_t *hm2) { for (i = 0; i < hm2->ssr.num_instances; i ++) { rtapi_u32 reg; - if (*hm2->ssr.instance[i].hal.pin.rate <= 0) { + rtapi_u32 urate = hal_get_ui32(hm2->ssr.instance[i].hal.pin.rate); + if (urate <= 0) { // Writing all bits zero to the Rate register clears bit 12, // the enable bit. reg = 0; } else { - double rate = *hm2->ssr.instance[i].hal.pin.rate; + double rate = urate; - if (*hm2->ssr.instance[i].hal.pin.rate < 25000) { + if (urate < 25000) { rate = 25000; - } else if (*hm2->ssr.instance[i].hal.pin.rate > (25*1000*1000)) { + } else if (urate > (25*1000*1000)) { rate = 25*1000*1000; } @@ -286,8 +273,8 @@ void hm2_ssr_force_write(hostmot2_t *hm2) { hm2->ssr.data_reg[i] = 0; for (pin = 0; pin < 32; pin ++) { if (hm2->ssr.instance[i].hal.pin.out[pin] != NULL) { - hm2->ssr.data_reg[i] |= *hm2->ssr.instance[i].hal.pin.out[pin] << pin; - hm2->ssr.data_reg[i] ^= *hm2->ssr.instance[i].hal.pin.invert[pin] << pin; + hm2->ssr.data_reg[i] |= hal_get_bool(hm2->ssr.instance[i].hal.pin.out[pin]) << pin; + hm2->ssr.data_reg[i] ^= hal_get_bool(hm2->ssr.instance[i].hal.pin.invert[pin]) << pin; } } } @@ -330,8 +317,8 @@ void hm2_ssr_prepare_tram_write(hostmot2_t *hm2) { hm2->ssr.data_reg[i] = 0; for (pin = 0; pin < 32; pin ++) { if (hm2->ssr.instance[i].hal.pin.out[pin] != NULL) { - hm2->ssr.data_reg[i] |= *hm2->ssr.instance[i].hal.pin.out[pin] << pin; - hm2->ssr.data_reg[i] ^= *hm2->ssr.instance[i].hal.pin.invert[pin] << pin; + hm2->ssr.data_reg[i] |= hal_get_bool(hm2->ssr.instance[i].hal.pin.out[pin]) << pin; + hm2->ssr.data_reg[i] ^= hal_get_bool(hm2->ssr.instance[i].hal.pin.invert[pin]) << pin; } } if (hm2->ssr.data_reg[i] != hm2->ssr.instance[i].written_data) { diff --git a/src/hal/drivers/mesa-hostmot2/stepgen.c b/src/hal/drivers/mesa-hostmot2/stepgen.c index 4ec1122f805..8da334f72b7 100644 --- a/src/hal/drivers/mesa-hostmot2/stepgen.c +++ b/src/hal/drivers/mesa-hostmot2/stepgen.c @@ -43,6 +43,7 @@ void hm2_stepgen_process_tram_read(hostmot2_t *hm2, long l_period_ns) { rtapi_u32 mode = 0; rtapi_u32 latch = 0; for (i = 0; i < hm2->stepgen.num_instances; i ++) { + hm2_stepgen_instance_t *inst = &hm2->stepgen.instance[i]; rtapi_u32 acc = hm2->stepgen.accumulator_reg[i]; if (hm2->stepgen.firmware_supports_index) { mode = hm2->stepgen.mode_reg[i] & HM2_STEPGEN_MODE_MASK ; @@ -52,12 +53,13 @@ void hm2_stepgen_process_tram_read(hostmot2_t *hm2, long l_period_ns) { rtapi_s64 latch_delta; // those tricky users are always trying to get us to divide by zero - if (fabs(hm2->stepgen.instance[i].hal.param.position_scale) < 1e-6) { - if (hm2->stepgen.instance[i].hal.param.position_scale >= 0.0) { - hm2->stepgen.instance[i].hal.param.position_scale = 1.0; + rtapi_real position_scale = hal_get_real(inst->hal.param.position_scale); + if (fabs(position_scale) < 1e-6) { + if (position_scale >= 0.0) { + position_scale = hal_set_real(inst->hal.param.position_scale, 1.0); HM2_ERR("stepgen %d position_scale is too close to 0, resetting to 1.0\n", i); } else { - hm2->stepgen.instance[i].hal.param.position_scale = -1.0; + position_scale = hal_set_real(inst->hal.param.position_scale, -1.0); HM2_ERR("stepgen %d position_scale is too close to 0, resetting to -1.0\n", i); } } @@ -66,7 +68,7 @@ void hm2_stepgen_process_tram_read(hostmot2_t *hm2, long l_period_ns) { // representation of the current stepper position. // The fractional part gives accurate velocity at low speeds, and // sub-step position feedback (like sw stepgen). - acc_delta = (rtapi_s64)acc - (rtapi_s64)hm2->stepgen.instance[i].prev_accumulator; + acc_delta = (rtapi_s64)acc - (rtapi_s64)inst->prev_accumulator; if (acc_delta > RTAPI_INT32_MAX) { acc_delta -= RTAPI_UINT32_MAX; } else if (acc_delta < RTAPI_INT32_MIN) { @@ -76,49 +78,49 @@ void hm2_stepgen_process_tram_read(hostmot2_t *hm2, long l_period_ns) { if (hm2->stepgen.firmware_supports_index) { - if (hm2->stepgen.instance[i].written_index_enable) { // searching for index + if (inst->written_index_enable) { // searching for index if ((mode & HM2_STEPGEN_LATCH_ON_INDEX) == 0) { // hardware index detected and position at index latched - latch_delta = (rtapi_s64)latch - (rtapi_s64)hm2->stepgen.instance[i].prev_accumulator; + latch_delta = (rtapi_s64)latch - (rtapi_s64)inst->prev_accumulator; if (latch_delta > RTAPI_INT32_MAX) { latch_delta -= RTAPI_UINT32_MAX; } else if (latch_delta < RTAPI_INT32_MIN) { latch_delta += RTAPI_UINT32_MAX; } - *hm2->stepgen.instance[i].hal.pin.position_latch = ((double)(hm2->stepgen.instance[i].subcounts+latch_delta) / 65536.0) / hm2->stepgen.instance[i].hal.param.position_scale; + hal_set_real(inst->hal.pin.position_latch, ((double)(inst->subcounts+latch_delta) / 65536.0) / position_scale); acc_delta -= latch_delta; - hm2->stepgen.instance[i].subcounts = 0; - *hm2->stepgen.instance[i].hal.pin.index_enable = 0; - hm2->stepgen.instance[i].written_index_enable = 0; + inst->subcounts = 0; + hal_set_bool(inst->hal.pin.index_enable, 0); + inst->written_index_enable = 0; } } - else if (hm2->stepgen.instance[i].written_probe_enable) { + else if (inst->written_probe_enable) { if ((mode & HM2_STEPGEN_LATCH_ON_PROBE) == 0) { - latch_delta = (rtapi_s64)latch - (rtapi_s64)hm2->stepgen.instance[i].prev_accumulator; + latch_delta = (rtapi_s64)latch - (rtapi_s64)inst->prev_accumulator; if (latch_delta > RTAPI_INT32_MAX) { latch_delta -= RTAPI_UINT32_MAX; } else if (latch_delta < RTAPI_INT32_MIN) { latch_delta += RTAPI_UINT32_MAX; } - *hm2->stepgen.instance[i].hal.pin.position_latch = ((double)(hm2->stepgen.instance[i].subcounts+latch_delta) / 65536.0) / hm2->stepgen.instance[i].hal.param.position_scale; - *hm2->stepgen.instance[i].hal.pin.latch_enable = 0; - hm2->stepgen.instance[i].written_probe_enable = 0; + hal_set_real(inst->hal.pin.position_latch, ((double)(inst->subcounts+latch_delta) / 65536.0) / position_scale); + hal_set_bool(inst->hal.pin.latch_enable, 0); + inst->written_probe_enable = 0; } } } - hm2->stepgen.instance[i].subcounts += acc_delta; + inst->subcounts += acc_delta; - if ((*hm2->stepgen.instance[i].hal.pin.position_reset) != 0) { - hm2->stepgen.instance[i].subcounts = 0; + if (hal_get_bool(inst->hal.pin.position_reset)) { + inst->subcounts = 0; } - *(hm2->stepgen.instance[i].hal.pin.counts) = hm2->stepgen.instance[i].subcounts >> 16; + hal_set_si32(inst->hal.pin.counts, inst->subcounts >> 16); // note that it's important to use "subcounts/65536.0" instead of just // "counts" when computing position_fb, because position_fb needs sub-count // precision - *(hm2->stepgen.instance[i].hal.pin.position_fb) = ((double)hm2->stepgen.instance[i].subcounts / 65536.0) / hm2->stepgen.instance[i].hal.param.position_scale; - hm2->stepgen.instance[i].prev_accumulator = acc; + hal_set_real(inst->hal.pin.position_fb, ((double)inst->subcounts / 65536.0) / position_scale); + inst->prev_accumulator = acc; } } @@ -144,16 +146,18 @@ static void hm2_stepgen_instance_position_control(hostmot2_t *hm2, long l_period hm2_stepgen_instance_t *s = &hm2->stepgen.instance[i]; - (*s->hal.pin.dbg_pos_minus_prev_cmd) = (*s->hal.pin.position_fb) - s->old_position_cmd; + hal_set_real(s->hal.pin.dbg_pos_minus_prev_cmd, hal_get_real(s->hal.pin.position_fb) - s->old_position_cmd); // calculate feed-forward velocity in machine units per second - ff_vel = ((*s->hal.pin.position_cmd) - s->old_position_cmd) / f_period_s; - (*s->hal.pin.dbg_ff_vel) = ff_vel; + rtapi_real position_cmd = hal_get_real(s->hal.pin.position_cmd); + ff_vel = (position_cmd - s->old_position_cmd) / f_period_s; + hal_set_real(s->hal.pin.dbg_ff_vel, ff_vel); - s->old_position_cmd = (*s->hal.pin.position_cmd); + s->old_position_cmd = position_cmd; - velocity_error = (*s->hal.pin.velocity_fb) - ff_vel; - (*s->hal.pin.dbg_vel_error) = velocity_error; + rtapi_real velocity_fb = hal_get_real(s->hal.pin.velocity_fb); + velocity_error = velocity_fb - ff_vel; + hal_set_real(s->hal.pin.dbg_vel_error, velocity_error); // Do we need to change speed to match the speed of position-cmd? // If maxaccel is 0, there's no accel limit: fix this velocity error @@ -162,16 +166,18 @@ static void hm2_stepgen_instance_position_control(hostmot2_t *hm2, long l_period // If maxaccel is not zero, the user has specified a maxaccel and we // adhere to that. if (velocity_error > 0.0) { - if (s->hal.param.maxaccel == 0) { + rtapi_real maxaccel = hal_get_real(s->hal.param.maxaccel); + if (maxaccel == 0) { match_accel = -velocity_error / f_period_s; } else { - match_accel = -s->hal.param.maxaccel; + match_accel = -maxaccel; } } else if (velocity_error < 0.0) { - if (s->hal.param.maxaccel == 0) { + rtapi_real maxaccel = hal_get_real(s->hal.param.maxaccel); + if (maxaccel == 0) { match_accel = velocity_error / f_period_s; } else { - match_accel = s->hal.param.maxaccel; + match_accel = maxaccel; } } else { match_accel = 0; @@ -183,21 +189,21 @@ static void hm2_stepgen_instance_position_control(hostmot2_t *hm2, long l_period } else { seconds_to_vel_match = -velocity_error / match_accel; } - *s->hal.pin.dbg_s_to_match = seconds_to_vel_match; + hal_set_real(s->hal.pin.dbg_s_to_match, seconds_to_vel_match); // compute expected position at the time of velocity match // Note: this is "feedback position at the beginning of the servo period after we attain velocity match" { double avg_v; - avg_v = (ff_vel + *s->hal.pin.velocity_fb) * 0.5; - position_at_match = *s->hal.pin.position_fb + (avg_v * (seconds_to_vel_match + f_period_s)); + avg_v = (ff_vel + velocity_fb) * 0.5; + position_at_match = hal_get_real(s->hal.pin.position_fb) + (avg_v * (seconds_to_vel_match + f_period_s)); } // Note: this assumes that position-cmd keeps the current velocity - position_cmd_at_match = *s->hal.pin.position_cmd + (ff_vel * seconds_to_vel_match); + position_cmd_at_match = position_cmd + (ff_vel * seconds_to_vel_match); error_at_match = position_at_match - position_cmd_at_match; - *s->hal.pin.dbg_err_at_match = error_at_match; + hal_set_real(s->hal.pin.dbg_err_at_match, error_at_match); if (seconds_to_vel_match < f_period_s) { // we can match velocity in one period @@ -205,11 +211,12 @@ static void hm2_stepgen_instance_position_control(hostmot2_t *hm2, long l_period velocity_cmd = ff_vel - (0.5 * error_at_match / f_period_s); // apply accel limits? - if (s->hal.param.maxaccel > 0) { - if (velocity_cmd > (*s->hal.pin.velocity_fb + (s->hal.param.maxaccel * f_period_s))) { - velocity_cmd = *s->hal.pin.velocity_fb + (s->hal.param.maxaccel * f_period_s); - } else if (velocity_cmd < (*s->hal.pin.velocity_fb - (s->hal.param.maxaccel * f_period_s))) { - velocity_cmd = *s->hal.pin.velocity_fb - (s->hal.param.maxaccel * f_period_s); + rtapi_real maxaccel = hal_get_real(s->hal.param.maxaccel); + if (maxaccel > 0) { + if (velocity_cmd > (velocity_fb + (maxaccel * f_period_s))) { + velocity_cmd = velocity_fb + (maxaccel * f_period_s); + } else if (velocity_cmd < (velocity_fb - (maxaccel * f_period_s))) { + velocity_cmd = velocity_fb - (maxaccel * f_period_s); } } @@ -230,7 +237,7 @@ static void hm2_stepgen_instance_position_control(hostmot2_t *hm2, long l_period } /* and do it */ - velocity_cmd = *s->hal.pin.velocity_fb + (match_accel * f_period_s); + velocity_cmd = velocity_fb + (match_accel * f_period_s); } *new_vel = velocity_cmd; @@ -263,47 +270,50 @@ static void hm2_stepgen_instance_prepare_tram_write(hostmot2_t *hm2, long l_peri // maxvel must be >= 0.0, and may not be faster than 1 step per (steplen+stepspace) seconds { - double min_ns_per_step = s->hal.param.steplen + s->hal.param.stepspace; + double min_ns_per_step = hal_get_ui32(s->hal.param.steplen) + hal_get_ui32(s->hal.param.stepspace); double max_steps_per_s = 1.0e9 / min_ns_per_step; - physical_maxvel = max_steps_per_s / fabs(s->hal.param.position_scale); + physical_maxvel = max_steps_per_s / fabs(hal_get_real(s->hal.param.position_scale)); physical_maxvel = force_precision(physical_maxvel); - if (s->hal.param.maxvel < 0.0) { + rtapi_real pmaxvel = hal_get_real(s->hal.param.maxvel); + if (pmaxvel < 0.0) { HM2_ERR("stepgen.%02d.maxvel < 0, setting to its absolute value\n", i); - s->hal.param.maxvel = fabs(s->hal.param.maxvel); + pmaxvel = hal_set_real(s->hal.param.maxvel, fabs(pmaxvel)); } - if (s->hal.param.maxvel > physical_maxvel) { + if (pmaxvel > physical_maxvel) { HM2_ERR("stepgen.%02d.maxvel is too big for current step timings & position-scale, clipping to max possible\n", i); - s->hal.param.maxvel = physical_maxvel; + pmaxvel= hal_set_real(s->hal.param.maxvel, physical_maxvel); } - if (s->hal.param.maxvel == 0.0) { + if (pmaxvel == 0.0) { maxvel = physical_maxvel; } else { - maxvel = s->hal.param.maxvel; + maxvel = pmaxvel; } } // maxaccel may not be negative - if (s->hal.param.maxaccel < 0.0) { + rtapi_real maxaccel = hal_get_real(s->hal.param.maxaccel); + if (maxaccel < 0.0) { HM2_ERR("stepgen.%02d.maxaccel < 0, setting to its absolute value\n", i); - s->hal.param.maxaccel = fabs(s->hal.param.maxaccel); + maxaccel = hal_set_real(s->hal.param.maxaccel, fabs(maxaccel)); } // select the new velocity we want - if (*s->hal.pin.control_type == 0) { + if (!hal_get_bool(s->hal.pin.control_type)) { hm2_stepgen_instance_position_control(hm2, l_period_ns, i, &new_vel); } else { // velocity-mode control is easy - new_vel = *s->hal.pin.velocity_cmd; - if (s->hal.param.maxaccel > 0.0) { - if (((new_vel - *s->hal.pin.velocity_fb) / f_period_s) > s->hal.param.maxaccel) { - new_vel = (*s->hal.pin.velocity_fb) + (s->hal.param.maxaccel * f_period_s); - } else if (((new_vel - *s->hal.pin.velocity_fb) / f_period_s) < -s->hal.param.maxaccel) { - new_vel = (*s->hal.pin.velocity_fb) - (s->hal.param.maxaccel * f_period_s); + new_vel = hal_get_real(s->hal.pin.velocity_cmd); + rtapi_real velocity_fb = hal_get_real(s->hal.pin.velocity_fb); + if (maxaccel > 0.0) { + if (((new_vel - velocity_fb) / f_period_s) > maxaccel) { + new_vel = velocity_fb + (maxaccel * f_period_s); + } else if (((new_vel - velocity_fb) / f_period_s) < -maxaccel) { + new_vel = velocity_fb - (maxaccel * f_period_s); } } } @@ -316,26 +326,26 @@ static void hm2_stepgen_instance_prepare_tram_write(hostmot2_t *hm2, long l_peri } - *s->hal.pin.velocity_fb = (hal_float_t)new_vel; + hal_set_real(s->hal.pin.velocity_fb, (rtapi_real)new_vel); - steps_per_sec_cmd = new_vel * s->hal.param.position_scale; + steps_per_sec_cmd = new_vel * hal_get_real(s->hal.param.position_scale); // the double cast here is intentional. (uint32_t)(-1.0) is undefined in // C (and in practice it gives the undesired value 0 on arm systems), but // (uint32_t)(int32-t)(-1.0) is defined and gives the desired value on all // systems. hm2->stepgen.step_rate_reg[i] = (uint32_t)(int32_t)(steps_per_sec_cmd * (4294967296.0 / (double)hm2->stepgen.clock_frequency)); - *s->hal.pin.dbg_step_rate = hm2->stepgen.step_rate_reg[i]; + hal_set_si32(s->hal.pin.dbg_step_rate, hm2->stepgen.step_rate_reg[i]); } void hm2_stepgen_prepare_tram_write(hostmot2_t *hm2, long l_period_ns) { int i; for (i = 0; i < hm2->stepgen.num_instances; i ++) { - if (*(hm2->stepgen.instance[i].hal.pin.enable) == 0) { + if (!hal_get_bool(hm2->stepgen.instance[i].hal.pin.enable)) { hm2->stepgen.step_rate_reg[i] = 0; - hm2->stepgen.instance[i].old_position_cmd = *(hm2->stepgen.instance[i].hal.pin.position_cmd); - *(hm2->stepgen.instance[i].hal.pin.velocity_fb) = 0; + hm2->stepgen.instance[i].old_position_cmd = hal_get_real(hm2->stepgen.instance[i].hal.pin.position_cmd); + hal_set_real(hm2->stepgen.instance[i].hal.pin.velocity_fb, 0); } else { hm2_stepgen_instance_prepare_tram_write(hm2, l_period_ns, i); } @@ -346,46 +356,50 @@ void hm2_stepgen_prepare_tram_write(hostmot2_t *hm2, long l_period_ns) { static void hm2_stepgen_update_dir_setup_time(hostmot2_t *hm2, int i) { - hm2->stepgen.dir_setup_time_reg[i] = (double)hm2->stepgen.instance[i].hal.param.dirsetup * ((double)hm2->stepgen.clock_frequency / (double)1e9); + rtapi_u32 dirsetup = hal_get_ui32(hm2->stepgen.instance[i].hal.param.dirsetup); + hm2->stepgen.dir_setup_time_reg[i] = (double)dirsetup * ((double)hm2->stepgen.clock_frequency / (double)1e9); if (hm2->stepgen.dir_setup_time_reg[i] > 0x3FFF) { HM2_ERR("stepgen %d has invalid dirsetup, resetting to max\n", i); hm2->stepgen.dir_setup_time_reg[i] = 0x3FFF; - hm2->stepgen.instance[i].hal.param.dirsetup = (double)hm2->stepgen.dir_setup_time_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency); + dirsetup = hal_set_ui32(hm2->stepgen.instance[i].hal.param.dirsetup, (double)hm2->stepgen.dir_setup_time_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency)); } - hm2->stepgen.instance[i].written_dirsetup = hm2->stepgen.instance[i].hal.param.dirsetup; + hm2->stepgen.instance[i].written_dirsetup = dirsetup; } static void hm2_stepgen_update_dir_hold_time(hostmot2_t *hm2, int i) { - hm2->stepgen.dir_hold_time_reg[i] = (double)hm2->stepgen.instance[i].hal.param.dirhold * ((double)hm2->stepgen.clock_frequency / (double)1e9); + rtapi_u32 dirhold = hal_get_ui32(hm2->stepgen.instance[i].hal.param.dirhold); + hm2->stepgen.dir_hold_time_reg[i] = (double)dirhold * ((double)hm2->stepgen.clock_frequency / (double)1e9); if (hm2->stepgen.dir_hold_time_reg[i] > 0x3FFF) { HM2_ERR("stepgen %d has invalid dirhold, resetting to max\n", i); hm2->stepgen.dir_hold_time_reg[i] = 0x3FFF; - hm2->stepgen.instance[i].hal.param.dirhold = (double)hm2->stepgen.dir_hold_time_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency); + dirhold = hal_set_ui32(hm2->stepgen.instance[i].hal.param.dirhold, (double)hm2->stepgen.dir_hold_time_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency)); } - hm2->stepgen.instance[i].written_dirhold = hm2->stepgen.instance[i].hal.param.dirhold; + hm2->stepgen.instance[i].written_dirhold = dirhold; } static void hm2_stepgen_update_pulse_idle_width(hostmot2_t *hm2, int i) { - hm2->stepgen.pulse_idle_width_reg[i] = (double)hm2->stepgen.instance[i].hal.param.stepspace * ((double)hm2->stepgen.clock_frequency / (double)1e9); + rtapi_u32 stepspace = hal_get_ui32(hm2->stepgen.instance[i].hal.param.stepspace); + hm2->stepgen.pulse_idle_width_reg[i] = (double)stepspace * ((double)hm2->stepgen.clock_frequency / (double)1e9); if (hm2->stepgen.pulse_idle_width_reg[i] > 0x3FFF) { HM2_ERR("stepgen %d has invalid stepspace, resetting to max\n", i); hm2->stepgen.pulse_idle_width_reg[i] = 0x3FFF; - hm2->stepgen.instance[i].hal.param.stepspace = (double)hm2->stepgen.pulse_idle_width_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency); + stepspace = hal_set_ui32(hm2->stepgen.instance[i].hal.param.stepspace, (double)hm2->stepgen.pulse_idle_width_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency)); } - hm2->stepgen.instance[i].written_stepspace = hm2->stepgen.instance[i].hal.param.stepspace; + hm2->stepgen.instance[i].written_stepspace = stepspace; } static void hm2_stepgen_update_pulse_width(hostmot2_t *hm2, int i) { - hm2->stepgen.pulse_width_reg[i] = (double)hm2->stepgen.instance[i].hal.param.steplen * ((double)hm2->stepgen.clock_frequency / (double)1e9); + rtapi_u32 steplen = hal_get_ui32(hm2->stepgen.instance[i].hal.param.steplen); + hm2->stepgen.pulse_width_reg[i] = (double)steplen * ((double)hm2->stepgen.clock_frequency / (double)1e9); if (hm2->stepgen.pulse_width_reg[i] > 0x3FFF) { HM2_ERR("stepgen %d has invalid steplen, resetting to max\n", i); hm2->stepgen.pulse_width_reg[i] = 0x3FFF; - hm2->stepgen.instance[i].hal.param.steplen = (double)hm2->stepgen.pulse_width_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency); + steplen = hal_set_ui32(hm2->stepgen.instance[i].hal.param.steplen, (double)hm2->stepgen.pulse_width_reg[i] * ((double)1e9 / (double)hm2->stepgen.clock_frequency)); } - hm2->stepgen.instance[i].written_steplen = hm2->stepgen.instance[i].hal.param.steplen; + hm2->stepgen.instance[i].written_steplen = steplen; } @@ -396,40 +410,41 @@ static void hm2_stepgen_update_mode(hostmot2_t *hm2, int i) { hm2_stepgen_instance_t *inst = &hm2->stepgen.instance[i]; // No point coming back unless something changes - inst->written_step_type = inst->hal.param.step_type; + rtapi_u32 step_type = hal_get_ui32(inst->hal.param.step_type); + inst->written_step_type = step_type; if (hm2->stepgen.firmware_supports_swap) { - inst->written_swap_step_dir = inst->hal.param.swap_step_dir; + inst->written_swap_step_dir = hal_get_bool(inst->hal.param.swap_step_dir); } if (hm2->stepgen.firmware_supports_index) { - inst->written_index_polarity = *inst->hal.pin.index_polarity; - inst->written_probe_polarity = *inst->hal.pin.latch_polarity; + inst->written_index_polarity = hal_get_bool(inst->hal.pin.index_polarity); + inst->written_probe_polarity = hal_get_bool(inst->hal.pin.latch_polarity); } - inst->hal.param.table[4] = (((inst->hal.param.table[0] ^ inst->hal.param.table[1]) - ^ inst->hal.param.table[2]) ^ inst->hal.param.table[3]); + inst->tablehash = (((hal_get_ui32(inst->hal.param.table[0]) ^ hal_get_ui32(inst->hal.param.table[1])) + ^ hal_get_ui32(inst->hal.param.table[2])) ^ hal_get_ui32(inst->hal.param.table[3])); - modebuff = inst->hal.param.step_type; // start with the step mode + modebuff = step_type; // start with the step mode if (hm2->stepgen.firmware_supports_index) { // or in the index/probe control bits if needed - if (*inst->hal.pin.index_enable) { + if (hal_get_bool(inst->hal.pin.index_enable)) { modebuff |= HM2_STEPGEN_LATCH_ON_INDEX; } - if (*inst->hal.pin.index_polarity) { + if (hal_get_bool(inst->hal.pin.index_polarity)) { modebuff |= HM2_STEPGEN_INDEX_POLARITY; } - if (*inst->hal.pin.latch_enable) { + if (hal_get_bool(inst->hal.pin.latch_enable)) { modebuff |= HM2_STEPGEN_LATCH_ON_PROBE; } - if (*inst->hal.pin.latch_polarity) { + if (hal_get_bool(inst->hal.pin.latch_polarity)) { modebuff |= HM2_STEPGEN_PROBE_POLARITY; } } - if (inst->hal.param.step_type <= 2) { + if (step_type <= 2) { if (hm2->stepgen.firmware_supports_swap) { - if (inst->hal.param.swap_step_dir) { + if (hal_get_bool(inst->hal.param.swap_step_dir)) { modebuff |= HM2_STEPGEN_SWAP_STEP_DIR; } } @@ -437,32 +452,32 @@ static void hm2_stepgen_update_mode(hostmot2_t *hm2, int i) { return; } - if (inst->table_width < inst->hal.param.step_type){ + if (inst->table_width < step_type){ HM2_ERR("the firmware only supports %i pins in the step pattern for " "stepgen instance %i, you asked for %i. Reverting to step type 0\n", inst->table_width, i, - inst->hal.param.step_type); + step_type); hm2->stepgen.mode_reg[i] = 0; } - if (inst->hal.param.step_type > 16){ + if (step_type > 16){ HM2_ERR("the firmware only supports tables up to a depth of 16, you" "requested %i. Reverting to step type 0\n", - inst->hal.param.step_type); + step_type); hm2->stepgen.mode_reg[i] = 0; } // In that case, we can assume that we have been fed a step table and the // step_type is actually the table length. - for (j = inst->hal.param.step_type - 1; j >= 0 ; j--){ - buff = ((inst->hal.param.table[j / 4] >> ((j % 4) * 8)) & 0xFF); + for (j = step_type - 1; j >= 0 ; j--){ + buff = ((hal_get_ui32(inst->hal.param.table[j / 4]) >> ((j % 4) * 8)) & 0xFF); hm2->llio->write(hm2->llio, hm2->stepgen.table_sequence_data_setup_addr + (i * sizeof(rtapi_u32)), &buff, sizeof(rtapi_u32)); } hm2->stepgen.mode_reg[i] = 3 | modebuff; // force 2 LSbs to 1,1 to select table mode in stepgen hardware - buff = inst->hal.param.step_type -1; + buff = step_type -1; hm2->llio->write(hm2->llio, hm2->stepgen.table_sequence_length_addr + (i * sizeof(rtapi_u32)), &buff, sizeof(rtapi_u32)); @@ -471,15 +486,15 @@ static void hm2_stepgen_update_mode(hostmot2_t *hm2, int i) { static void hm2_stepgen_set_dpll_timer(hostmot2_t *hm2) { rtapi_u32 data = 0; - - if ((*hm2->stepgen.hal->pin.dpll_timer_num < -1) || (*hm2->stepgen.hal->pin.dpll_timer_num > 4)) { - *hm2->stepgen.hal->pin.dpll_timer_num = 0; + rtapi_s32 dpll_timer_num = hal_get_si32(hm2->stepgen.hal->pin.dpll_timer_num); + if ((dpll_timer_num < -1) || (dpll_timer_num > 4)) { + dpll_timer_num = hal_set_si32(hm2->stepgen.hal->pin.dpll_timer_num, 0); } - if (*hm2->stepgen.hal->pin.dpll_timer_num > -1) { - data = (*hm2->stepgen.hal->pin.dpll_timer_num << 12) | (1 << 15); + if (dpll_timer_num > -1) { + data = (dpll_timer_num << 12) | (1 << 15); } hm2->llio->write(hm2->llio, hm2->stepgen.dpll_timer_num_addr, &data, sizeof(rtapi_u32)); - hm2->stepgen.written_dpll_timer_num = *hm2->stepgen.hal->pin.dpll_timer_num; + hm2->stepgen.written_dpll_timer_num = dpll_timer_num; } @@ -490,46 +505,46 @@ void hm2_stepgen_write(hostmot2_t *hm2) { // FIXME for (i = 0; i < hm2->stepgen.num_instances; i ++) { hm2_stepgen_instance_t *inst = &hm2->stepgen.instance[i]; - if (inst->hal.param.dirsetup != inst->written_dirsetup) { + if (hal_get_ui32(inst->hal.param.dirsetup) != inst->written_dirsetup) { hm2_stepgen_update_dir_setup_time(hm2, i); hm2->llio->write(hm2->llio, hm2->stepgen.dir_setup_time_addr + (i * sizeof(rtapi_u32)), &hm2->stepgen.dir_setup_time_reg[i], sizeof(rtapi_u32)); } - if (inst->hal.param.dirhold != inst->written_dirhold) { + if (hal_get_ui32(inst->hal.param.dirhold) != inst->written_dirhold) { hm2_stepgen_update_dir_hold_time(hm2, i); hm2->llio->write(hm2->llio, hm2->stepgen.dir_hold_time_addr + (i * sizeof(rtapi_u32)), &hm2->stepgen.dir_hold_time_reg[i], sizeof(rtapi_u32)); } - if (inst->hal.param.steplen != inst->written_steplen) { + if (hal_get_ui32(inst->hal.param.steplen) != inst->written_steplen) { hm2_stepgen_update_pulse_width(hm2, i); hm2->llio->write(hm2->llio, hm2->stepgen.pulse_width_addr + (i * sizeof(rtapi_u32)), &hm2->stepgen.pulse_width_reg[i], sizeof(rtapi_u32)); } - if (inst->hal.param.stepspace != inst->written_stepspace) { + if (hal_get_ui32(inst->hal.param.stepspace) != inst->written_stepspace) { hm2_stepgen_update_pulse_idle_width(hm2, i); hm2->llio->write(hm2->llio, hm2->stepgen.pulse_idle_width_addr + (i * sizeof(rtapi_u32)), &hm2->stepgen.pulse_idle_width_reg[i], sizeof(rtapi_u32)); } need_mode_update=0; - if ((inst->hal.param.step_type != inst->written_step_type) - || (((inst->hal.param.table[0] ^ inst->hal.param.table[1]) - ^ inst->hal.param.table[2]) ^ inst->hal.param.table[3]) - != inst->hal.param.table[4]) { + if ((hal_get_ui32(inst->hal.param.step_type) != inst->written_step_type) + || (((hal_get_ui32(inst->hal.param.table[0]) ^ hal_get_ui32(inst->hal.param.table[1])) + ^ hal_get_ui32(inst->hal.param.table[2])) ^ hal_get_ui32(inst->hal.param.table[3])) + != inst->tablehash) { need_mode_update = 1; } if (hm2->stepgen.firmware_supports_swap) { - if (inst->hal.param.swap_step_dir != inst->written_swap_step_dir) { + if (hal_get_bool(inst->hal.param.swap_step_dir) != inst->written_swap_step_dir) { need_mode_update |= 1; } } if (hm2->stepgen.firmware_supports_index) { - if ((*inst->hal.pin.index_enable != inst->written_index_enable) - || (*inst->hal.pin.latch_enable != inst->written_probe_enable) - || (*inst->hal.pin.index_polarity != inst->written_index_polarity) - || (*inst->hal.pin.latch_polarity != inst->written_probe_polarity)) { + if ((hal_get_bool(inst->hal.pin.index_enable) != inst->written_index_enable) + || (hal_get_bool(inst->hal.pin.latch_enable) != inst->written_probe_enable) + || (hal_get_bool(inst->hal.pin.index_polarity) != inst->written_index_polarity) + || (hal_get_bool(inst->hal.pin.latch_polarity) != inst->written_probe_polarity)) { need_mode_update |= 1; } } @@ -537,14 +552,14 @@ void hm2_stepgen_write(hostmot2_t *hm2) { hm2_stepgen_update_mode(hm2, i); hm2->llio->write(hm2->llio, hm2->stepgen.mode_addr + (i * sizeof(rtapi_u32)), &hm2->stepgen.mode_reg[i], sizeof(rtapi_u32)); if (hm2->stepgen.firmware_supports_index) { - inst->written_index_enable = *inst->hal.pin.index_enable; // we need to update these only after the write has occurred - inst->written_probe_enable = *inst->hal.pin.latch_enable; // to avoid a race condition (index detected before index enable has been set) + inst->written_index_enable = hal_get_bool(inst->hal.pin.index_enable); // we need to update these only after the write has occurred + inst->written_probe_enable = hal_get_bool(inst->hal.pin.latch_enable); // to avoid a race condition (index detected before index enable has been set) } } } if (hm2->stepgen.num_instances > 0 && hm2->dpll_module_present) { - if (*hm2->stepgen.hal->pin.dpll_timer_num != (int)hm2->stepgen.written_dpll_timer_num) { + if (hal_get_si32(hm2->stepgen.hal->pin.dpll_timer_num) != (int)hm2->stepgen.written_dpll_timer_num) { hm2_stepgen_set_dpll_timer(hm2); } } @@ -658,7 +673,7 @@ void hm2_stepgen_tram_init(hostmot2_t *hm2) { for (i = 0; i < hm2->stepgen.num_instances; i ++) { hm2->stepgen.instance[i].prev_accumulator = hm2->stepgen.accumulator_reg[i]; - hm2->stepgen.instance[i].old_position_cmd = *hm2->stepgen.instance[i].hal.pin.position_cmd; + hm2->stepgen.instance[i].old_position_cmd = hal_get_real(hm2->stepgen.instance[i].hal.pin.position_cmd); } } @@ -757,14 +772,14 @@ int hm2_stepgen_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->stepgen.hal = (hm2_stepgen_module_global_t *)hal_malloc(sizeof(hm2_stepgen_module_global_t)); + hm2->stepgen.hal = hal_malloc(sizeof(*hm2->stepgen.hal)); if (hm2->stepgen.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - hm2->stepgen.instance = (hm2_stepgen_instance_t *)hal_malloc(hm2->stepgen.num_instances * sizeof(hm2_stepgen_instance_t)); + hm2->stepgen.instance = hal_malloc(hm2->stepgen.num_instances * sizeof(*hm2->stepgen.instance)); if (hm2->stepgen.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -853,26 +868,21 @@ int hm2_stepgen_parse_md(hostmot2_t *hm2, int md_index) { // export to HAL { - int i; - char name[HAL_NAME_LEN + 1]; - if (hm2->dpll_module_present) { - rtapi_snprintf(name, sizeof(name), "%s.stepgen.timer-number", hm2->llio->name); - r = hal_pin_s32_new(name, HAL_IN, &(hm2->stepgen.hal->pin.dpll_timer_num), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.hal->pin.dpll_timer_num), + -1, "%s.stepgen.timer-number", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding timer number param, aborting\n"); + HM2_ERR("error %d adding pin '%s.stepgen.timer-number', aborting\n", r, hm2->llio->name); return -EINVAL; } - *(hm2->stepgen.hal->pin.dpll_timer_num) = -1; } - for (i = 0; i < hm2->stepgen.num_instances; i ++) { + for (int i = 0; i < hm2->stepgen.num_instances; i ++) { // Work out if table setup registers are needed. { - int j = 0; hm2->stepgen.instance[i].table_width = 0; - for (j = 0; j < hm2->num_pins; j++){ + for (int j = 0; j < hm2->num_pins; j++){ if (hm2->pin[j].sec_tag == HM2_GTAG_STEPGEN && hm2->pin[j].sec_unit == i){ if (hm2->pin[j].sec_pin > hm2->stepgen.instance[i].table_width){ hm2->stepgen.instance[i].table_width = hm2->pin[j].sec_pin; @@ -881,108 +891,108 @@ int hm2_stepgen_parse_md(hostmot2_t *hm2, int md_index) { } } // pins - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.position-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.position_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.position_cmd), + 0.0, "%s.stepgen.%02d.position-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.position-cmd', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.velocity-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.velocity_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.velocity_cmd), + 0.0, "%s.stepgen.%02d.velocity-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.velocity-cmd', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.velocity-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.velocity_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.velocity_fb), + 0.0, "%s.stepgen.%02d.velocity-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.velocity-fb', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.position-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.position_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.position_fb), + 0.0, "%s.stepgen.%02d.position-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.position-fb', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.counts", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.counts), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.counts), + 0, "%s.stepgen.%02d.counts", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.counts', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.enable), + 0, "%s.stepgen.%02d.enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.enable', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.control-type", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.control_type), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.control_type), + 0, "%s.stepgen.%02d.control-type", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.control-type', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.position-reset", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.position_reset), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.position_reset), + 0, "%s.stepgen.%02d.position-reset", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.position-reset', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } if (hm2->stepgen.firmware_supports_index) { - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.position-latch", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.position_latch), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.position_latch), + 0.0, "%s.stepgen.%02d.position-latch", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.position-latch', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.index-enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IO, &(hm2->stepgen.instance[i].hal.pin.index_enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->stepgen.instance[i].hal.pin.index_enable), + 0, "%s.stepgen.%02d.index-enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.index-enable', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.probe-enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IO, &(hm2->stepgen.instance[i].hal.pin.latch_enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IO, &(hm2->stepgen.instance[i].hal.pin.latch_enable), + 0, "%s.stepgen.%02d.probe-enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.probe-enable', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.index-invert", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.index_polarity), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.index_polarity), + 0, "%s.stepgen.%02d.index-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.index-invert', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.probe-invert", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.latch_polarity), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->stepgen.instance[i].hal.pin.latch_polarity), + 0, "%s.stepgen.%02d.probe-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.probe-invert', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } @@ -990,156 +1000,158 @@ int hm2_stepgen_parse_md(hostmot2_t *hm2, int md_index) { // debug pins - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_pos_minus_prev_cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_pos_minus_prev_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_pos_minus_prev_cmd), + 0.0, "%s.stepgen.%02d.dbg_pos_minus_prev_cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_pos_minus_prev_cmd', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_ff_vel", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_ff_vel), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_ff_vel), + 0.0, "%s.stepgen.%02d.dbg_ff_vel", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_ff_vel', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_s_to_match", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_s_to_match), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_s_to_match), + 0.0, "%s.stepgen.%02d.dbg_s_to_match", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_s_to_match', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_vel_error", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_vel_error), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_vel_error), + 0.0, "%s.stepgen.%02d.dbg_vel_error", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_vel_error', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_err_at_match", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_err_at_match), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_err_at_match), + 0.0, "%s.stepgen.%02d.dbg_err_at_match", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_err_at_match', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dbg_step_rate", hm2->llio->name, i); - r = hal_pin_s32_new(name, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_step_rate), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_OUT, &(hm2->stepgen.instance[i].hal.pin.dbg_step_rate), + 0, "%s.stepgen.%02d.dbg_step_rate", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.stepgen.%02d.dbg_step_rate', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } // parameters - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.position-scale", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.position_scale), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.position_scale), + 1.0, "%s.stepgen.%02d.position-scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.position-scale', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.maxvel", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.maxvel), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.maxvel), + 0.0, "%s.stepgen.%02d.maxvel", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.maxvel', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.maxaccel", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.maxaccel), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.maxaccel), + 1.0, "%s.stepgen.%02d.maxaccel", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.maxaccel', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.steplen", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.steplen), hm2->llio->comp_id); + // start out the slowest possible, let the user speed up if they want + rtapi_u32 v = (double)0x3FFF * ((double)1e9 / (double)hm2->stepgen.clock_frequency); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.steplen), + v, "%s.stepgen.%02d.steplen", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.steplen', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.stepspace", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.stepspace), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.stepspace), + v, "%s.stepgen.%02d.stepspace", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.stepspace', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dirsetup", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.dirsetup), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.dirsetup), + v, "%s.stepgen.%02d.dirsetup", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.dirsetup', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.dirhold", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.dirhold), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.dirhold), + v, "%s.stepgen.%02d.dirhold", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.dirhold', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.step_type", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.step_type), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.step_type), + 0, "%s.stepgen.%02d.step_type", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.step_type', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } if (hm2->stepgen.firmware_supports_swap) { - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.swap_step_dir", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.swap_step_dir), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.swap_step_dir), + 0, "%s.stepgen.%02d.swap_step_dir", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.swap_step_dir', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } } if (hm2->stepgen.instance[i].table_width > 2){ - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.table-data-0", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[0]), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[0]), + 0, "%s.stepgen.%02d.table-data-0", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.table-data-0', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.table-data-1", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[1]), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[1]), + 0, "%s.stepgen.%02d.table-data-1", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.table-data-1', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.table-data-2", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[2]), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[2]), + 0, "%s.stepgen.%02d.table-data-2", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.table-data-2', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } - rtapi_snprintf(name, sizeof(name), "%s.stepgen.%02d.table-data-3", hm2->llio->name, i); - r = hal_param_u32_new(name, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[3]), hm2->llio->comp_id); + r = hal_param_new_ui32(hm2->llio->comp_id, HAL_RW, &(hm2->stepgen.instance[i].hal.param.table[3]), + 0, "%s.stepgen.%02d.table-data-3", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.stepgen.%02d.table-data-3', aborting\n", r, hm2->llio->name, i); r = -ENOMEM; goto fail5; } @@ -1147,49 +1159,16 @@ int hm2_stepgen_parse_md(hostmot2_t *hm2, int md_index) { } // init - *(hm2->stepgen.instance[i].hal.pin.position_cmd) = 0.0; - *(hm2->stepgen.instance[i].hal.pin.counts) = 0; - *(hm2->stepgen.instance[i].hal.pin.position_fb) = 0.0; - *(hm2->stepgen.instance[i].hal.pin.velocity_fb) = 0.0; - *(hm2->stepgen.instance[i].hal.pin.enable) = 0; - *(hm2->stepgen.instance[i].hal.pin.control_type) = 0; - *(hm2->stepgen.instance[i].hal.pin.position_reset) = 0; - if (hm2->stepgen.firmware_supports_index) { - *(hm2->stepgen.instance[i].hal.pin.index_enable) = 0; - *(hm2->stepgen.instance[i].hal.pin.latch_enable) = 0; - *(hm2->stepgen.instance[i].hal.pin.index_polarity) = 0; - *(hm2->stepgen.instance[i].hal.pin.latch_polarity) = 0; - } - hm2->stepgen.instance[i].hal.param.position_scale = 1.0; - hm2->stepgen.instance[i].hal.param.maxvel = 0.0; - hm2->stepgen.instance[i].hal.param.maxaccel = 1.0; - hm2->stepgen.instance[i].subcounts = 0; - // start out the slowest possible, let the user speed up if they want - hm2->stepgen.instance[i].hal.param.steplen = (double)0x3FFF * ((double)1e9 / (double)hm2->stepgen.clock_frequency); - hm2->stepgen.instance[i].hal.param.stepspace = (double)0x3FFF * ((double)1e9 / (double)hm2->stepgen.clock_frequency); - hm2->stepgen.instance[i].hal.param.dirsetup = (double)0x3FFF * ((double)1e9 / (double)hm2->stepgen.clock_frequency); - hm2->stepgen.instance[i].hal.param.dirhold = (double)0x3FFF * ((double)1e9 / (double)hm2->stepgen.clock_frequency); - - hm2->stepgen.instance[i].hal.param.step_type = 0; // step & dir - - if (hm2->stepgen.firmware_supports_swap) { - hm2->stepgen.instance[i].hal.param.swap_step_dir = 0; // no swap - } hm2->stepgen.instance[i].written_steplen = 0; hm2->stepgen.instance[i].written_stepspace = 0; hm2->stepgen.instance[i].written_dirsetup = 0; hm2->stepgen.instance[i].written_dirhold = 0; hm2->stepgen.instance[i].written_step_type = 0xffffffff; - hm2->stepgen.instance[i].hal.param.table[0] = 0; - hm2->stepgen.instance[i].hal.param.table[1] = 0; - hm2->stepgen.instance[i].hal.param.table[2] = 0; - hm2->stepgen.instance[i].hal.param.table[3] = 0; hm2->stepgen.instance[i].prev_accumulator = 0; - } } @@ -1237,15 +1216,15 @@ void hm2_stepgen_print_module(hostmot2_t *hm2) { HM2_PRINT(" master_dds_addr: 0x%04X\n", hm2->stepgen.master_dds_addr); for (i = 0; i < hm2->stepgen.num_instances; i ++) { HM2_PRINT(" instance %d:\n", i); - HM2_PRINT(" enable = %d\n", *hm2->stepgen.instance[i].hal.pin.enable); + HM2_PRINT(" enable = %d\n", (int)hal_get_bool(hm2->stepgen.instance[i].hal.pin.enable)); HM2_PRINT(" hw:\n"); HM2_PRINT(" step_rate = 0x%08X\n", hm2->stepgen.step_rate_reg[i]); HM2_PRINT(" accumulator = 0x%08X\n", hm2->stepgen.accumulator_reg[i]); HM2_PRINT(" mode = 0x%08X\n", hm2->stepgen.mode_reg[i]); - HM2_PRINT(" dir_setup_time = 0x%08X (%u ns)\n", hm2->stepgen.dir_setup_time_reg[i], hm2->stepgen.instance[i].hal.param.dirsetup); - HM2_PRINT(" dir_hold_time = 0x%08X (%u ns)\n", hm2->stepgen.dir_hold_time_reg[i], hm2->stepgen.instance[i].hal.param.dirhold); - HM2_PRINT(" pulse_width = 0x%08X (%u ns)\n", hm2->stepgen.pulse_width_reg[i], hm2->stepgen.instance[i].hal.param.steplen); - HM2_PRINT(" pulse_idle_width = 0x%08X (%u ns)\n", hm2->stepgen.pulse_idle_width_reg[i], hm2->stepgen.instance[i].hal.param.stepspace); + HM2_PRINT(" dir_setup_time = 0x%08X (%u ns)\n", hm2->stepgen.dir_setup_time_reg[i], hal_get_ui32(hm2->stepgen.instance[i].hal.param.dirsetup)); + HM2_PRINT(" dir_hold_time = 0x%08X (%u ns)\n", hm2->stepgen.dir_hold_time_reg[i], hal_get_ui32(hm2->stepgen.instance[i].hal.param.dirhold)); + HM2_PRINT(" pulse_width = 0x%08X (%u ns)\n", hm2->stepgen.pulse_width_reg[i], hal_get_ui32(hm2->stepgen.instance[i].hal.param.steplen)); + HM2_PRINT(" pulse_idle_width = 0x%08X (%u ns)\n", hm2->stepgen.pulse_idle_width_reg[i], hal_get_ui32(hm2->stepgen.instance[i].hal.param.stepspace)); } } diff --git a/src/hal/drivers/mesa-hostmot2/tp_pwmgen.c b/src/hal/drivers/mesa-hostmot2/tp_pwmgen.c index b5539e96a04..1be71efbf8c 100644 --- a/src/hal/drivers/mesa-hostmot2/tp_pwmgen.c +++ b/src/hal/drivers/mesa-hostmot2/tp_pwmgen.c @@ -33,10 +33,10 @@ void hm2_tp_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { int deadtime; int i; - if (hm2->tp_pwmgen.hal->param.pwm_frequency < 1) { - HM2_ERR("3pwmgen.pwm_frequency %d is too low, setting to 1\n", - hm2->tp_pwmgen.hal->param.pwm_frequency); - hm2->tp_pwmgen.hal->param.pwm_frequency = 1; + rtapi_u32 pwm_frequency = hal_get_ui32(hm2->tp_pwmgen.hal->param.pwm_frequency); + if (pwm_frequency < 1) { + HM2_ERR("3pwmgen.pwm_frequency %d is too low, setting to 1\n", pwm_frequency); + pwm_frequency = hal_set_ui32(hm2->tp_pwmgen.hal->param.pwm_frequency, 1); } @@ -57,7 +57,7 @@ void hm2_tp_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { // // check that the frequency is achievable - dds = ((double)hm2->tp_pwmgen.hal->param.pwm_frequency * 65536.0 * 2048.0) + dds = ((double)pwm_frequency * 65536.0 * 2048.0) / (double)hm2->tp_pwmgen.clock_frequency; if (dds < 65536) { hm2->tp_pwmgen.pwmgen_master_rate_dds_reg = dds; @@ -65,11 +65,10 @@ void hm2_tp_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { // not possible so try the fastest we can // PWMFreq = (ClockHigh * DDS) / (65536 * 2048) dds = 65535; - hm2->tp_pwmgen.hal->param.pwm_frequency = + pwm_frequency = hal_set_ui32(hm2->tp_pwmgen.hal->param.pwm_frequency, ((double)hm2->tp_pwmgen.clock_frequency * 65535.0) - / (65536.0 * 2048.0); - HM2_ERR("max PWM frequency is %d Hz\n", - hm2->tp_pwmgen.hal->param.pwm_frequency); + / (65536.0 * 2048.0)); + HM2_ERR("max PWM frequency is %d Hz\n", pwm_frequency); hm2->tp_pwmgen.pwmgen_master_rate_dds_reg = dds; } @@ -78,37 +77,38 @@ void hm2_tp_pwmgen_handle_pwm_frequency(hostmot2_t *hm2) { // = (2*65536*1e9 / ClockHigh*dds)nS for (i=0; i < hm2->tp_pwmgen.num_instances; i++) { - if (hm2->tp_pwmgen.instance[i].hal.param.sampletime > 1){ + rtapi_real sampletime = hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.sampletime); + if (sampletime > 1){ HM2_ERR("Max sampletime is 1 (end of PWM cycle"); - hm2->tp_pwmgen.instance[i].hal.param.sampletime = 1; + sampletime = hal_set_real(hm2->tp_pwmgen.instance[i].hal.param.sampletime, 1); } - else if (hm2->tp_pwmgen.instance[i].hal.param.sampletime < 0){ + else if (sampletime < 0){ HM2_ERR("Min sampletime is 0 (beginning of PWM cycle"); - hm2->tp_pwmgen.instance[i].hal.param.sampletime = 0; + sampletime = hal_set_real(hm2->tp_pwmgen.instance[i].hal.param.sampletime, 0); } - deadtime = (hm2->tp_pwmgen.instance[i].hal.param.deadzone + deadtime = (hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.deadzone) * hm2->tp_pwmgen.clock_frequency * dds) / (2 * 65536 * 1e9); if (deadtime > 511){ deadtime = 511; - hm2->tp_pwmgen.instance[i].hal.param.deadzone = + hal_set_real(hm2->tp_pwmgen.instance[i].hal.param.deadzone, ((double)deadtime * 2.0 * 65536.0 * 1.0e9) - /((double)hm2->tp_pwmgen.clock_frequency * dds); + /((double)hm2->tp_pwmgen.clock_frequency * dds)); HM2_ERR("At this PWM frequency the maximum deadtime is %dnS\n", - (int)hm2->tp_pwmgen.instance[i].hal.param.deadzone); + (int)hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.deadzone)); } else if (deadtime < 0) { HM2_ERR("Deadtime must be positive"); deadtime = 0; - hm2->tp_pwmgen.instance[i].hal.param.deadzone = 0; + hal_set_real(hm2->tp_pwmgen.instance[i].hal.param.deadzone, 0); } // Now setup the control register hm2->tp_pwmgen.setup_reg[i] = ( - ((int)(hm2->tp_pwmgen.instance[i].hal.param.sampletime*1023) << 16) - +((hm2->tp_pwmgen.instance[i].hal.param.faultpolarity != 0) << 15) + ((int)(sampletime*1023) << 16) + +(hal_get_bool(hm2->tp_pwmgen.instance[i].hal.param.faultpolarity) << 15) +(deadtime)); } } @@ -125,7 +125,7 @@ void hm2_tp_pwmgen_force_write(hostmot2_t *hm2) { // update enable and setup registers for (i = 0; i < hm2->tp_pwmgen.num_instances; i ++) { - if (*hm2->tp_pwmgen.instance[i].hal.pin.enable) + if (hal_get_bool(hm2->tp_pwmgen.instance[i].hal.pin.enable)) hm2->tp_pwmgen.enable_reg[i] = 1; else hm2->tp_pwmgen.enable_reg[i] = 0; @@ -136,15 +136,15 @@ void hm2_tp_pwmgen_force_write(hostmot2_t *hm2) { hm2->llio->write(hm2->llio, hm2->tp_pwmgen.enable_addr, hm2->tp_pwmgen.enable_reg, (hm2->tp_pwmgen.num_instances * sizeof(rtapi_u32))); hm2->llio->write(hm2->llio, hm2->tp_pwmgen.pwmgen_master_rate_dds_addr, &hm2->tp_pwmgen.pwmgen_master_rate_dds_reg, sizeof(rtapi_u32)); - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; for (i = 0; i < hm2->tp_pwmgen.num_instances; i ++) { - hm2->tp_pwmgen.instance[i].written_faultpolarity = hm2->tp_pwmgen.instance[i].hal.param.faultpolarity; - hm2->tp_pwmgen.instance[i].written_deadzone = hm2->tp_pwmgen.instance[i].hal.param.deadzone; - hm2->tp_pwmgen.instance[i].written_sampletime = hm2->tp_pwmgen.instance[i].hal.param.sampletime; + hm2->tp_pwmgen.instance[i].written_faultpolarity = hal_get_bool(hm2->tp_pwmgen.instance[i].hal.param.faultpolarity); + hm2->tp_pwmgen.instance[i].written_deadzone = hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.deadzone); + hm2->tp_pwmgen.instance[i].written_sampletime = hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.sampletime); } - hm2->tp_pwmgen.written_pwm_frequency = hm2->tp_pwmgen.hal->param.pwm_frequency; + hm2->tp_pwmgen.written_pwm_frequency = hal_get_ui32(hm2->tp_pwmgen.hal->param.pwm_frequency); } @@ -158,13 +158,14 @@ void hm2_tp_pwmgen_write(hostmot2_t *hm2) { if (hm2->tp_pwmgen.num_instances == 0) return; // check pwm frequency - if (hm2->tp_pwmgen.hal->param.pwm_frequency != hm2->tp_pwmgen.written_pwm_frequency) goto force_write; + if (hal_get_ui32(hm2->tp_pwmgen.hal->param.pwm_frequency) != hm2->tp_pwmgen.written_pwm_frequency) goto force_write; // update enable register? for (i = 0; i < hm2->tp_pwmgen.num_instances; i ++) { - if ((hm2->tp_pwmgen.instance[i].hal.param.deadzone != hm2->tp_pwmgen.instance[i].written_deadzone) - || (hm2->tp_pwmgen.instance[i].hal.param.sampletime != hm2->tp_pwmgen.instance[i].written_sampletime) - || (hm2->tp_pwmgen.instance[i].hal.param.faultpolarity != hm2->tp_pwmgen.instance[i].written_faultpolarity)) + hm2_tp_pwmgen_instance_t *inst = &hm2->tp_pwmgen.instance[i]; + if ((hal_get_real(inst->hal.param.deadzone) != inst->written_deadzone) + || (hal_get_real(inst->hal.param.sampletime) != inst->written_sampletime) + || (hal_get_bool(inst->hal.param.faultpolarity) != inst->written_faultpolarity)) goto force_write; // The enable register is a little odd. Writing a 1 to bit0 of the @@ -174,7 +175,7 @@ void hm2_tp_pwmgen_write(hostmot2_t *hm2) { // enable if there is a mismatch between the hal-pin and the enable // bit. - if ((*hm2->tp_pwmgen.instance[i].hal.pin.enable != (hm2->tp_pwmgen.enable_reg[i] & 1))) + if ((hal_get_bool(inst->hal.pin.enable) != (hm2->tp_pwmgen.enable_reg[i] & 1))) goto force_write; } @@ -194,8 +195,7 @@ void hm2_tp_pwmgen_queue_read(hostmot2_t *hm2) { void hm2_tp_pwmgen_process_read(hostmot2_t *hm2) { int i; for (i = 0 ; i < hm2->tp_pwmgen.num_instances ; i++) { - *hm2->tp_pwmgen.instance[i].hal.pin.fault - = (hm2->tp_pwmgen.enable_reg[i] & 2); + hal_set_bool(hm2->tp_pwmgen.instance[i].hal.pin.fault, (hm2->tp_pwmgen.enable_reg[i] & 2)); } } @@ -249,14 +249,14 @@ int hm2_tp_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->tp_pwmgen.instance = (hm2_tp_pwmgen_instance_t *)hal_malloc(hm2->tp_pwmgen.num_instances * sizeof(hm2_tp_pwmgen_instance_t)); + hm2->tp_pwmgen.instance = hal_malloc(hm2->tp_pwmgen.num_instances * sizeof(*hm2->tp_pwmgen.instance)); if (hm2->tp_pwmgen.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - hm2->tp_pwmgen.hal = (hm2_tp_pwmgen_global_hal_t *)hal_malloc(sizeof(hm2_tp_pwmgen_global_hal_t)); + hm2->tp_pwmgen.hal = hal_malloc(sizeof(*hm2->tp_pwmgen.hal)); if (hm2->tp_pwmgen.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -294,17 +294,13 @@ int hm2_tp_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { } // export to HAL - // FIXME: r hides the r in enclosing function, and it returns the wrong thing { - int i; - int r; - char name[HAL_NAME_LEN + 1]; - // this hal parameter affects all the 3-Phase pwmgen instances - r = hal_param_u32_newf( + r = hal_param_new_ui32( + hm2->llio->comp_id, HAL_RW, &(hm2->tp_pwmgen.hal->param.pwm_frequency), - hm2->llio->comp_id, + 20000, "%s.3pwmgen.frequency", hm2->llio->name ); @@ -313,89 +309,76 @@ int hm2_tp_pwmgen_parse_md(hostmot2_t *hm2, int md_index) { goto fail2; } - hm2->tp_pwmgen.hal->param.pwm_frequency = 20000; hm2->tp_pwmgen.written_pwm_frequency = 0; // force a write - for (i = 0; i < hm2->tp_pwmgen.num_instances; i ++) { + for (int i = 0; i < hm2->tp_pwmgen.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.A-value", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Avalue), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Avalue), + 0.0, "%s.3pwmgen.%02d.A-value", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.3pwmgen.%02d.A-value', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.B-value", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Bvalue), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Bvalue), + 0.0, "%s.3pwmgen.%02d.B-value", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.3pwmgen.%02d.B-value', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.C-value", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Cvalue), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.Cvalue), + 0.0, "%s.3pwmgen.%02d.C-value", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.3pwmgen.%02d.C-value', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->tp_pwmgen.instance[i].hal.pin.enable), + 0, "%s.3pwmgen.%02d.enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.3pwmgen.%02d.enable', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.fault", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->tp_pwmgen.instance[i].hal.pin.fault), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->tp_pwmgen.instance[i].hal.pin.fault), + 0, "%s.3pwmgen.%02d.fault", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); + HM2_ERR("error %d adding pin '%s.3pwmgen.%02d.fault', aborting\n", r, hm2->llio->name, i); goto fail2; } // parameters - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.scale", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.scale), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.scale), + 1.0, "%s.3pwmgen.%02d.scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.3pwmgen.%02d.scale', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.deadtime", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.deadzone), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.deadzone), + 5000.0, "%s.3pwmgen.%02d.deadtime", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.3pwmgen.%02d.deadtime', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.fault-invert", hm2->llio->name, i); - r = hal_param_bit_new(name, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.faultpolarity), hm2->llio->comp_id); + r = hal_param_new_bool(hm2->llio->comp_id, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.faultpolarity), + 0, "%s.3pwmgen.%02d.fault-invert", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.3pwmgen.%02d.fault-invert', aborting\n", r, hm2->llio->name, i); goto fail2; } - rtapi_snprintf(name, sizeof(name), "%s.3pwmgen.%02d.sample-time", hm2->llio->name, i); - r = hal_param_float_new(name, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.sampletime), hm2->llio->comp_id); + r = hal_param_new_real(hm2->llio->comp_id, HAL_RW, &(hm2->tp_pwmgen.instance[i].hal.param.sampletime), + 0.5, "%s.3pwmgen.%02d.sample-time", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding param '%s', aborting\n", name); + HM2_ERR("error %d adding param '%s.3pwmgen.%02d.sample-time', aborting\n", r, hm2->llio->name, i); goto fail2; } - - // init hal objects - *(hm2->tp_pwmgen.instance[i].hal.pin.enable) = 0; - *(hm2->tp_pwmgen.instance[i].hal.pin.Avalue) = 0.0; - *(hm2->tp_pwmgen.instance[i].hal.pin.Bvalue) = 0.0; - *(hm2->tp_pwmgen.instance[i].hal.pin.Cvalue) = 0.0; - - hm2->tp_pwmgen.instance[i].hal.param.scale = 1.0; - hm2->tp_pwmgen.instance[i].hal.param.sampletime = 0.5; - hm2->tp_pwmgen.instance[i].hal.param.faultpolarity = 0.0; //active low - hm2->tp_pwmgen.instance[i].hal.param.deadzone = 5000; // 5000nS conservative deadzone for safety - hm2->tp_pwmgen.instance[i].written_sampletime = -666; // force an update at the start } } @@ -448,14 +431,15 @@ void hm2_tp_pwmgen_prepare_tram_write(hostmot2_t *hm2) { // pwmgen) // Check for /0 problems - if (hm2->tp_pwmgen.instance[i].hal.param.scale ==0) { - hm2->tp_pwmgen.instance[i].hal.param.scale = 1; - HM2_ERR("3pwmgen scale must be greater than zero. Scale set to %i", (int)hm2->tp_pwmgen.instance[i].hal.param.scale); + rtapi_real scale = hal_get_real(hm2->tp_pwmgen.instance[i].hal.param.scale); + if (scale ==0) { + scale = hal_set_real(hm2->tp_pwmgen.instance[i].hal.param.scale, 1); + HM2_ERR("3pwmgen scale must be greater than zero. Scale set to %i", (int)scale); } - scaled_Avalue = (*hm2->tp_pwmgen.instance[i].hal.pin.Avalue / hm2->tp_pwmgen.instance[i].hal.param.scale); - scaled_Bvalue = (*hm2->tp_pwmgen.instance[i].hal.pin.Bvalue / hm2->tp_pwmgen.instance[i].hal.param.scale); - scaled_Cvalue = (*hm2->tp_pwmgen.instance[i].hal.pin.Cvalue / hm2->tp_pwmgen.instance[i].hal.param.scale); + scaled_Avalue = hal_get_real(hm2->tp_pwmgen.instance[i].hal.pin.Avalue) / scale; + scaled_Bvalue = hal_get_real(hm2->tp_pwmgen.instance[i].hal.pin.Bvalue) / scale; + scaled_Cvalue = hal_get_real(hm2->tp_pwmgen.instance[i].hal.pin.Cvalue) / scale; if (scaled_Avalue > 1.0) scaled_Avalue = 1.0; else if (scaled_Avalue < -1.0) scaled_Avalue = -1.0; diff --git a/src/hal/drivers/mesa-hostmot2/uart.c b/src/hal/drivers/mesa-hostmot2/uart.c index 609835b18f9..426f4b08511 100644 --- a/src/hal/drivers/mesa-hostmot2/uart.c +++ b/src/hal/drivers/mesa-hostmot2/uart.c @@ -79,8 +79,7 @@ int hm2_uart_parse_md(hostmot2_t *hm2, int md_index) hm2->uart.num_instances = hm2->config.num_uarts; } - hm2->uart.instance = (hm2_uart_instance_t *)hal_malloc(hm2->uart.num_instances - * sizeof(hm2_uart_instance_t)); + hm2->uart.instance = hal_malloc(hm2->uart.num_instances * sizeof(*hm2->uart.instance)); if (hm2->uart.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -141,7 +140,7 @@ EXPORT_SYMBOL_GPL(hm2_uart_setup); // use -1 for tx_mode and rx_mode to leave the mode unchanged int hm2_uart_setup(char *name, int bitrate, rtapi_s32 tx_mode, rtapi_s32 rx_mode){ hostmot2_t *hm2; - hm2_uart_instance_t *inst = 0; + hm2_uart_instance_t *inst = NULL; rtapi_u32 buff; int i,r; diff --git a/src/hal/drivers/mesa-hostmot2/watchdog.c b/src/hal/drivers/mesa-hostmot2/watchdog.c index 07422bdfdd3..b1512e60904 100644 --- a/src/hal/drivers/mesa-hostmot2/watchdog.c +++ b/src/hal/drivers/mesa-hostmot2/watchdog.c @@ -35,7 +35,7 @@ void hm2_watchdog_process_tram_read(hostmot2_t *hm2) { if (hm2->watchdog.num_instances == 0) return; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; // if we've already noticed the board needs to be reset, don't re-read // the watchdog has-bit bit @@ -48,7 +48,7 @@ void hm2_watchdog_process_tram_read(hostmot2_t *hm2) { // see if the watchdog has bit since then if (hm2->watchdog.status_reg[0] & 0x1) { HM2_ERR("Watchdog has bit! (set the .has-bit pin to False to resume)\n"); - *hm2->watchdog.instance[0].hal.pin.has_bit = 1; + hal_set_bool(hm2->watchdog.instance[0].hal.pin.has_bit, 1); hm2->llio->needs_reset = 1; } } @@ -93,7 +93,7 @@ int hm2_watchdog_parse_md(hostmot2_t *hm2, int md_index) { hm2->watchdog.num_instances = 1; - hm2->watchdog.instance = (hm2_watchdog_instance_t *)hal_malloc(hm2->watchdog.num_instances * sizeof(hm2_watchdog_instance_t)); + hm2->watchdog.instance = hal_malloc(hm2->watchdog.num_instances * sizeof(*hm2->watchdog.instance)); if (hm2->watchdog.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -137,10 +137,11 @@ int hm2_watchdog_parse_md(hostmot2_t *hm2, int md_index) { // // pins - r = hal_pin_bit_newf( + r = hal_pin_new_bool( + hm2->llio->comp_id, HAL_IO, &(hm2->watchdog.instance[0].hal.pin.has_bit), - hm2->llio->comp_id, + 0, "%s.watchdog.has_bit", hm2->llio->name ); @@ -151,10 +152,12 @@ int hm2_watchdog_parse_md(hostmot2_t *hm2, int md_index) { } // params - r = hal_param_u32_newf( + // default timeout is 5 milliseconds (5*1000*1000 nanoseconds) + r = hal_param_new_ui32( + hm2->llio->comp_id, HAL_RW, &(hm2->watchdog.instance[0].hal.param.timeout_ns), - hm2->llio->comp_id, + 5 * 1000 * 1000, "%s.watchdog.timeout_ns", hm2->llio->name ); @@ -168,8 +171,6 @@ int hm2_watchdog_parse_md(hostmot2_t *hm2, int md_index) { // initialize the watchdog // - *hm2->watchdog.instance[0].hal.pin.has_bit = 0; - hm2->watchdog.instance[0].hal.param.timeout_ns = 5 * 1000 * 1000; // default timeout is 5 milliseconds hm2->watchdog.instance[0].enable = 0; // the first pet_watchdog will turn it on return hm2->watchdog.num_instances; @@ -195,8 +196,8 @@ void hm2_watchdog_print_module(hostmot2_t *hm2) { HM2_PRINT(" reset_addr: 0x%04X\n", hm2->watchdog.reset_addr); for (i = 0; i < hm2->watchdog.num_instances; i ++) { HM2_PRINT(" instance %d:\n", i); - HM2_PRINT(" param timeout_ns = %u\n", hm2->watchdog.instance[i].hal.param.timeout_ns); - HM2_PRINT(" pin has_bit = %d\n", (*hm2->watchdog.instance[i].hal.pin.has_bit)); + HM2_PRINT(" param timeout_ns = %u\n", hal_get_ui32(hm2->watchdog.instance[i].hal.param.timeout_ns)); + HM2_PRINT(" pin has_bit = %d\n", (int)hal_get_bool(hm2->watchdog.instance[i].hal.pin.has_bit)); HM2_PRINT(" reg timer = 0x%08X\n", hm2->watchdog.timer_reg[i]); } } @@ -222,25 +223,27 @@ void hm2_watchdog_force_write(hostmot2_t *hm2) { if (hm2->watchdog.num_instances != 1) return; + rtapi_u32 timeout_ns = hal_get_ui32(hm2->watchdog.instance[0].hal.param.timeout_ns); if (hm2->watchdog.instance[0].enable == 0) { // watchdog is disabled, MSb=1 is secret handshake with FPGA hm2->watchdog.timer_reg[0] = 0x80000000; } else { - tmp = (hm2->watchdog.instance[0].hal.param.timeout_ns * ((double)hm2->watchdog.clock_frequency / (double)(1000 * 1000 * 1000))) - 1; + tmp = (timeout_ns * ((double)hm2->watchdog.clock_frequency / (double)(1000 * 1000 * 1000))) - 1; if (tmp < 0x80000000) { hm2->watchdog.timer_reg[0] = tmp; } else { // truncate watchdog timeout tmp = 0x7FFFFFFF; hm2->watchdog.timer_reg[0] = tmp; - hm2->watchdog.instance[0].hal.param.timeout_ns = (tmp + 1) / ((double)hm2->watchdog.clock_frequency / (double)(1000 * 1000 * 1000)); - HM2_ERR("requested watchdog timeout is out of range, setting it to max: %u ns\n", hm2->watchdog.instance[0].hal.param.timeout_ns); + timeout_ns = hal_set_ui32(hm2->watchdog.instance[0].hal.param.timeout_ns, + (tmp + 1) / ((double)hm2->watchdog.clock_frequency / (double)(1000 * 1000 * 1000))); + HM2_ERR("requested watchdog timeout is out of range, setting it to max: %u ns\n", timeout_ns); } } // set the watchdog timeout (we'll check for i/o errors later) hm2->llio->write(hm2->llio, hm2->watchdog.timer_addr, hm2->watchdog.timer_reg, (hm2->watchdog.num_instances * sizeof(rtapi_u32))); - hm2->watchdog.instance[0].written_timeout_ns = hm2->watchdog.instance[0].hal.param.timeout_ns; + hm2->watchdog.instance[0].written_timeout_ns = timeout_ns; hm2->watchdog.instance[0].written_enable = hm2->watchdog.instance[0].enable; // clear the has-bit bit @@ -253,10 +256,10 @@ void hm2_watchdog_write(hostmot2_t *hm2, long period_ns) { if (hm2->watchdog.num_instances != 1) return; // if there are comm problems, wait for the user to fix it - if ((*hm2->llio->io_error) != 0) return; + if (hal_get_bool(*hm2->llio->io_error)) return; // if the watchdog has bit, wait for the user to reset it - if (*hm2->watchdog.instance[0].hal.pin.has_bit) return; + if (hal_get_bool(hm2->watchdog.instance[0].hal.pin.has_bit)) return; // writing to the watchdog wakes it up, and now we can't stop or it will bite! hm2->watchdog.instance[0].enable = 1; @@ -271,7 +274,7 @@ void hm2_watchdog_write(hostmot2_t *hm2, long period_ns) { // write all settings out to the FPGA hm2_force_write(hm2); - if ((*hm2->llio->io_error) != 0) { + if (hal_get_bool(*hm2->llio->io_error)) { HM2_PRINT("error recovery failed\n"); return; } @@ -281,8 +284,9 @@ void hm2_watchdog_write(hostmot2_t *hm2, long period_ns) { hm2->llio->needs_reset = hm2->llio->needs_soft_reset = 0; } + rtapi_u32 timeout_ns = hal_get_ui32(hm2->watchdog.instance[0].hal.param.timeout_ns); if ( - (hm2->watchdog.instance[0].hal.param.timeout_ns == hm2->watchdog.instance[0].written_timeout_ns) + (timeout_ns == hm2->watchdog.instance[0].written_timeout_ns) && (hm2->watchdog.instance[0].enable == hm2->watchdog.instance[0].written_enable) ) { @@ -290,10 +294,10 @@ void hm2_watchdog_write(hostmot2_t *hm2, long period_ns) { } // if the requested timeout is dangerously short compared to the petting-period, warn the user once - if (hm2->watchdog.instance[0].hal.param.timeout_ns < (1.5 * period_ns)) { + if (timeout_ns < (1.5 * period_ns)) { HM2_PRINT( "Watchdog timeout (%u ns) is dangerously short compared to hm2_write() period (%ld ns)\n", - hm2->watchdog.instance[0].hal.param.timeout_ns, + timeout_ns, period_ns ); } diff --git a/src/hal/drivers/mesa-hostmot2/xy2mod.c b/src/hal/drivers/mesa-hostmot2/xy2mod.c index 42f0508feeb..cdfd5f3c717 100644 --- a/src/hal/drivers/mesa-hostmot2/xy2mod.c +++ b/src/hal/drivers/mesa-hostmot2/xy2mod.c @@ -47,22 +47,24 @@ void hm2_xy2mod_process_tram_read(hostmot2_t *hm2) { rtapi_u32 status = hm2->xy2mod.status_reg[i]; // those tricky users are always trying to get us to divide by zero - if (fabs(*s->hal.pin.posx_scale) < 1e-6) { - if (*s->hal.pin.posx_scale >= 0.0) { - *s->hal.pin.posx_scale = 1.0; + rtapi_real posx_scale = hal_get_real(s->hal.pin.posx_scale); + if (fabs(posx_scale) < 1e-6) { + if (posx_scale >= 0.0) { + posx_scale = hal_set_real(s->hal.pin.posx_scale, 1.0); HM2_ERR("xy2mod %d position_scalex is too close to 0, resetting to 1.0\n", i); } else { - *s->hal.pin.posx_scale = -1.0; + posx_scale = hal_set_real(s->hal.pin.posx_scale, -1.0); HM2_ERR("xy2mod %d position_scalxe is too close to 0, resetting to -1.0\n", i); } } - if (fabs(*s->hal.pin.posy_scale) < 1e-6) { - if (*s->hal.pin.posy_scale >= 0.0) { - *s->hal.pin.posy_scale = 1.0; + rtapi_real posy_scale = hal_get_real(s->hal.pin.posy_scale); + if (fabs(posy_scale) < 1e-6) { + if (posy_scale >= 0.0) { + posy_scale = hal_set_real(s->hal.pin.posy_scale, 1.0); HM2_ERR("xy2mod %d position_scaley is too close to 0, resetting to 1.0\n", i); } else { - *s->hal.pin.posy_scale = -1.0; + posy_scale = hal_set_real(s->hal.pin.posy_scale, -1.0); HM2_ERR("xy2mod %d position_scaley is too close to 0, resetting to -1.0\n", i); } } @@ -75,19 +77,19 @@ void hm2_xy2mod_process_tram_read(hostmot2_t *hm2) { // need to "unscale" the position registers to return to machine units - *(s->hal.pin.posx_fb) = ((double)(int32_t)(posx) / 2147483647.0) / *s->hal.pin.posx_scale; - *(s->hal.pin.posy_fb) = ((double)(int32_t)(posy) / 2147483647.0) / *s->hal.pin.posy_scale; + hal_set_real(s->hal.pin.posx_fb, ((double)(int32_t)(posx) / 2147483647.0) / posx_scale); + hal_set_real(s->hal.pin.posy_fb, ((double)(int32_t)(posy) / 2147483647.0) / posy_scale); // need to "unscale" the velocity registers to return to machine units - *(s->hal.pin.velx_fb) = ((double)(int32_t)velx) / (*s->hal.pin.posx_scale * (256*2147483647.0/(double)hm2->xy2mod.clock_frequency)); - *(s->hal.pin.vely_fb) = ((double)(int32_t)vely) / (*s->hal.pin.posy_scale * (256*2147483647.0/(double)hm2->xy2mod.clock_frequency)); + hal_set_real(s->hal.pin.velx_fb, ((double)(int32_t)velx) / (posx_scale * (256*2147483647.0/(double)hm2->xy2mod.clock_frequency))); + hal_set_real(s->hal.pin.vely_fb, ((double)(int32_t)vely) / (posy_scale * (256*2147483647.0/(double)hm2->xy2mod.clock_frequency))); - *(s->hal.pin.posx_overflow) = (mode & (1 << 6)); - *(s->hal.pin.posy_overflow) = (mode & (1 << 7)); - *(s->hal.pin.velx_overflow) = (mode & (1 << 8)); - *(s->hal.pin.vely_overflow) = (mode & (1 << 9)); - *(s->hal.pin.status) = (status & 0x000FFFFF); + hal_set_bool(s->hal.pin.posx_overflow, mode & (1 << 6)); + hal_set_bool(s->hal.pin.posy_overflow, mode & (1 << 7)); + hal_set_bool(s->hal.pin.velx_overflow, mode & (1 << 8)); + hal_set_bool(s->hal.pin.vely_overflow, mode & (1 << 9)); + hal_set_ui32(s->hal.pin.status, status & 0x000FFFFF); } @@ -113,98 +115,106 @@ static void hm2_xy2mod_instance_write(hostmot2_t *hm2, int i) { hm2_xy2mod_instance_t *s = &hm2->xy2mod.instance[i]; istride = i * sizeof(rtapi_u32); - if (*s->hal.pin.enable != 0) { + if (hal_get_bool(s->hal.pin.enable)) { // position setting - stepsx_cmd =( *s->hal.pin.posx_cmd * 2147483647.0) / *s->hal.pin.posx_scale; - stepsy_cmd =( *s->hal.pin.posy_cmd * 2147483647.0) / *s->hal.pin.posy_scale; + rtapi_real posx_scale = hal_get_real(s->hal.pin.posx_scale); + rtapi_real posy_scale = hal_get_real(s->hal.pin.posy_scale); + rtapi_real posx_cmd = hal_get_real(s->hal.pin.posx_cmd); + rtapi_real posy_cmd = hal_get_real(s->hal.pin.posy_cmd); + stepsx_cmd = (posx_cmd * 2147483647.0) / posx_scale; + stepsy_cmd = (posy_cmd * 2147483647.0) / posy_scale; // the double cast here is intentional. (uint32_t)(-1.0) is undefined in // C (and in practice it gives the undesired value 0 on arm systems), but // (uint32_t)(int32-t)(-1.0) is defined and gives the desired value on all // systems. - if (*s->hal.pin.posx_cmd != s->prev_posx_cmd) { + if (posx_cmd != s->prev_posx_cmd) { lposx_reg = (int32_t)(stepsx_cmd); hm2->xy2mod.posx_reg[i] = lposx_reg; // HM2_PRINT("StepsX register set to: %f\n",stepsx_cmd); // HM2_PRINT("POSX register set to:0x%08X\n",lposx_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.posx_addr + istride, &hm2->xy2mod.posx_reg[i], sizeof(rtapi_u32)); - s->prev_posx_cmd = *s->hal.pin.posx_cmd; + s->prev_posx_cmd = posx_cmd; } - if (*s->hal.pin.posy_cmd != s->prev_posy_cmd) { + if (posy_cmd != s->prev_posy_cmd) { lposy_reg = (int32_t)(stepsy_cmd); hm2->xy2mod.posy_reg[i] = lposy_reg; // HM2_PRINT("Stepsy register set to: %fhalcmd\n",stepsy_cmd); // HM2_PRINT("POSY register set to:0x%08X\n",lposy_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.posy_addr + istride, &hm2->xy2mod.posy_reg[i], sizeof(rtapi_u32)); - s->prev_posy_cmd = *s->hal.pin.posy_cmd; + s->prev_posy_cmd = posy_cmd; } // velocity setting - steps_per_secx_cmd = *s->hal.pin.velx_cmd * *s->hal.pin.posx_scale; - steps_per_secy_cmd = *s->hal.pin.vely_cmd * *s->hal.pin.posy_scale; + rtapi_real velx_cmd = hal_get_real(s->hal.pin.velx_cmd); + rtapi_real vely_cmd = hal_get_real(s->hal.pin.vely_cmd); + steps_per_secx_cmd = velx_cmd * posx_scale; + steps_per_secy_cmd = vely_cmd * posy_scale; // the double cast here is intentional. (uint32_t)(-1.0) is undefined in // C (and in practice it gives the undesired value 0 on arm systems), but // (uint32_t)(int32-t)(-1.0) is defined and gives the desired value on all // systems. // Note 256 factor is from velocity scaling in xy2mod hardware (velocity added only every 256 clocks) - if (*s->hal.pin.velx_cmd != s->prev_velx_cmd) { + if (velx_cmd != s->prev_velx_cmd) { lvelx_reg = (uint32_t)(int32_t)(steps_per_secx_cmd * (256*2147483648.0 / (double)hm2->xy2mod.clock_frequency)); hm2->xy2mod.velx_reg[i] = lvelx_reg; // HM2_PRINT("VELX register set to:0x%08X\n",lvelx_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.velx_addr + istride, &hm2->xy2mod.velx_reg[i], sizeof(rtapi_u32)); - s->prev_velx_cmd = *s->hal.pin.velx_cmd; + s->prev_velx_cmd = velx_cmd; } - if (*s->hal.pin.vely_cmd != s->prev_vely_cmd) { + if (vely_cmd != s->prev_vely_cmd) { lvely_reg = (uint32_t)(int32_t)(steps_per_secy_cmd * (256*2147483648.0 / (double)hm2->xy2mod.clock_frequency)); hm2->xy2mod.vely_reg[i] = lvely_reg; // HM2_PRINT("VELY register set to:0x%08X\n",lvely_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.vely_addr + istride, &hm2->xy2mod.vely_reg[i], sizeof(rtapi_u32)); - s->prev_vely_cmd = *s->hal.pin.vely_cmd; + s->prev_vely_cmd = vely_cmd; } // acceleration setting no idea if anywhere near reality - steps_per_sec2x_cmd = *s->hal.pin.accx_cmd * *s->hal.pin.posx_scale; - steps_per_sec2y_cmd = *s->hal.pin.accy_cmd * *s->hal.pin.posy_scale; + rtapi_real accx_cmd = hal_get_real(s->hal.pin.accx_cmd); + rtapi_real accy_cmd = hal_get_real(s->hal.pin.accy_cmd); + steps_per_sec2x_cmd = accx_cmd * posx_scale; + steps_per_sec2y_cmd = accy_cmd * posy_scale; // the double cast here is intentional. (uint32_t)(-1.0) is undefined in // C (and in practice it gives the undesired value 0 on arm systems), but // (uint32_t)(int32-t)(-1.0) is defined and gives the desired value on all // systems. - if (*s->hal.pin.accx_cmd != s->prev_accx_cmd) { + if (accx_cmd != s->prev_accx_cmd) { laccx_reg = (uint32_t)(int32_t)(steps_per_sec2x_cmd * (double)(4096.0*4294967296.0*32768.0) / ((double)(hm2->xy2mod.clock_frequency*(double)hm2->xy2mod.clock_frequency*256))); hm2->xy2mod.accx_reg[i] = laccx_reg; // HM2_PRINT("ACCX register set to:0x%08X\n",laccx_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.accx_addr + istride, &hm2->xy2mod.accx_reg[i], sizeof(rtapi_u32)); - s->prev_accx_cmd = *s->hal.pin.accx_cmd; + s->prev_accx_cmd = accx_cmd; } - if (*s->hal.pin.accy_cmd != s->prev_accy_cmd) { + if (accy_cmd != s->prev_accy_cmd) { laccy_reg = (uint32_t)(int32_t)(steps_per_sec2y_cmd * (double)(4096.0*4294967296.0*32768.0) / ((double)(hm2->xy2mod.clock_frequency*(double)hm2->xy2mod.clock_frequency*256))); hm2->xy2mod.accy_reg[i] = laccy_reg; // HM2_PRINT("ACCY register set to:0x%08X\n",laccy_reg); hm2->llio->write(hm2->llio, hm2->xy2mod.accy_addr + istride, &hm2->xy2mod.accy_reg[i], sizeof(rtapi_u32)); - s->prev_accy_cmd = *s->hal.pin.accy_cmd; + s->prev_accy_cmd = accy_cmd; } - *s->hal.pin.controlx = (*s->hal.pin.controlx & 7); - *s->hal.pin.controly = (*s->hal.pin.controly & 7); + hal_set_ui32(s->hal.pin.controlx, hal_get_ui32(s->hal.pin.controlx) & 7); + hal_set_ui32(s->hal.pin.controly, hal_get_ui32(s->hal.pin.controly) & 7); hm2->xy2mod.mode_reg[i] = - *s->hal.pin.controlx << 0 | - *s->hal.pin.controly << 3 | - *s->hal.pin.mode18bitx<< 10 | - *s->hal.pin.mode18bity<< 11 | - *s->hal.pin.commandmodex<< 12 | - *s->hal.pin.commandmodey<< 13; + (hal_get_ui32(s->hal.pin.controlx) << 0) | + (hal_get_ui32(s->hal.pin.controly) << 3) | + (hal_get_bool(s->hal.pin.mode18bitx)<< 10) | + (hal_get_bool(s->hal.pin.mode18bity)<< 11) | + (hal_get_bool(s->hal.pin.commandmodex)<< 12) | + (hal_get_bool(s->hal.pin.commandmodey)<< 13); hm2->llio->write(hm2->llio,hm2->xy2mod.mode_addr + istride, &hm2->xy2mod.mode_reg[i], sizeof(rtapi_u32)); - *s->hal.pin.commandx = (*s->hal.pin.commandx & 0xFFFF); - *s->hal.pin.commandy = (*s->hal.pin.commandy & 0xFFFF); + hal_set_ui32(s->hal.pin.commandx, hal_get_ui32(s->hal.pin.commandx) & 0xFFFF); + hal_set_ui32(s->hal.pin.commandy, hal_get_ui32(s->hal.pin.commandy) & 0xFFFF); hm2->xy2mod.command_reg[i] = - *s->hal.pin.commandx << 0 | - *s->hal.pin.commandy << 16; + (hal_get_ui32(s->hal.pin.commandx) << 0) | + (hal_get_ui32(s->hal.pin.commandy) << 16); hm2->llio->write(hm2->llio,hm2->xy2mod.command_addr + istride, &hm2->xy2mod.command_reg[i], sizeof(rtapi_u32)); @@ -213,43 +223,43 @@ static void hm2_xy2mod_instance_write(hostmot2_t *hm2, int i) { // may eventually want to spilt out resetting the overflow flags // reset position registers - *s->hal.pin.posx_cmd = 0; + hal_set_real(s->hal.pin.posx_cmd, 0); s->prev_posx_cmd = 0; hm2->xy2mod.posx_reg[i] =0; hm2->llio->write(hm2->llio, hm2->xy2mod.posx_addr + istride, &hm2->xy2mod.posx_reg[i], sizeof(rtapi_u32)); - *s->hal.pin.posy_cmd = 0; + hal_set_real(s->hal.pin.posy_cmd, 0); s->prev_posy_cmd = 0; hm2->xy2mod.posy_reg[i] =0; hm2->llio->write(hm2->llio, hm2->xy2mod.posy_addr + istride, &hm2->xy2mod.posy_reg[i], sizeof(rtapi_u32)); // reset velocity registers - *s->hal.pin.velx_cmd = 0; + hal_set_real(s->hal.pin.velx_cmd, 0); s->prev_velx_cmd = 0; hm2->xy2mod.velx_reg[i] = 0; hm2->llio->write(hm2->llio, hm2->xy2mod.velx_addr + istride, &hm2->xy2mod.velx_reg[i], sizeof(rtapi_u32)); - *s->hal.pin.vely_cmd = 0; + hal_set_real(s->hal.pin.vely_cmd, 0); s->prev_vely_cmd = 0; hm2->xy2mod.vely_reg[i] = 0; hm2->llio->write(hm2->llio, hm2->xy2mod.vely_addr + istride, &hm2->xy2mod.vely_reg[i], sizeof(rtapi_u32)); // reset acceleration registers - *s->hal.pin.accx_cmd = 0; + hal_set_real(s->hal.pin.accx_cmd, 0); s->prev_accx_cmd = 0; hm2->xy2mod.accx_reg[i] = 0; hm2->llio->write(hm2->llio, hm2->xy2mod.accx_addr + istride, &hm2->xy2mod.accx_reg[i], sizeof(rtapi_u32)); - *s->hal.pin.accy_cmd = 0; + hal_set_real(s->hal.pin.accy_cmd, 0); s->prev_accy_cmd = 0; hm2->xy2mod.accy_reg[i] = 0; hm2->llio->write(hm2->llio, hm2->xy2mod.accy_addr + istride, &hm2->xy2mod.accy_reg[i], sizeof(rtapi_u32)); //reset control bits and overflow flags - *s->hal.pin.controlx = 1; // default to 16 bit mode - *s->hal.pin.controly = 1; + hal_set_ui32(s->hal.pin.controlx, 1); // default to 16 bit mode + hal_set_ui32(s->hal.pin.controly, 1); hm2->xy2mod.mode_reg[i] = 0x000003C9; // reset X and Y overflow bits when disabled hm2->llio->write(hm2->llio, hm2->xy2mod.mode_addr + istride, &hm2->xy2mod.mode_reg[i], sizeof(rtapi_u32)); } @@ -258,28 +268,30 @@ static void hm2_xy2mod_instance_write(hostmot2_t *hm2, int i) { static void hm2_xy2mod_set_dpll_rtimer(hostmot2_t *hm2) { rtapi_u32 data = 0; + rtapi_s32 dpll_rtimer_num = hal_get_si32(hm2->xy2mod.hal->pin.dpll_rtimer_num); - if ((*hm2->xy2mod.hal->pin.dpll_rtimer_num < -1) || (*hm2->xy2mod.hal->pin.dpll_rtimer_num > 4)) { - *hm2->xy2mod.hal->pin.dpll_rtimer_num = 0; + if ((dpll_rtimer_num < -1) || (dpll_rtimer_num > 4)) { + dpll_rtimer_num = hal_set_si32(hm2->xy2mod.hal->pin.dpll_rtimer_num, 0); } - if (*hm2->xy2mod.hal->pin.dpll_rtimer_num > -1) { - data = (*hm2->xy2mod.hal->pin.dpll_rtimer_num << 12) | (1 << 15); + if (dpll_rtimer_num > -1) { + data = (dpll_rtimer_num << 12) | (1 << 15); } hm2->llio->write(hm2->llio, hm2->xy2mod.dpll_rtimer_num_addr, &data, sizeof(rtapi_u32)); - hm2->xy2mod.written_dpll_rtimer_num = *hm2->xy2mod.hal->pin.dpll_rtimer_num; + hm2->xy2mod.written_dpll_rtimer_num = dpll_rtimer_num; } static void hm2_xy2mod_set_dpll_wtimer(hostmot2_t *hm2) { rtapi_u32 data = 0; + rtapi_s32 dpll_wtimer_num = hal_get_si32(hm2->xy2mod.hal->pin.dpll_wtimer_num); - if ((*hm2->xy2mod.hal->pin.dpll_wtimer_num < -1) || (*hm2->xy2mod.hal->pin.dpll_wtimer_num > 4)) { - *hm2->xy2mod.hal->pin.dpll_wtimer_num = 0; + if ((dpll_wtimer_num < -1) || (dpll_wtimer_num > 4)) { + dpll_wtimer_num = hal_set_si32(hm2->xy2mod.hal->pin.dpll_wtimer_num, 0); } - if (*hm2->xy2mod.hal->pin.dpll_wtimer_num > -1) { - data = (*hm2->xy2mod.hal->pin.dpll_wtimer_num << 12) | (1 << 15); + if (dpll_wtimer_num > -1) { + data = (dpll_wtimer_num << 12) | (1 << 15); } hm2->llio->write(hm2->llio, hm2->xy2mod.dpll_wtimer_num_addr, &data, sizeof(rtapi_u32)); - hm2->xy2mod.written_dpll_wtimer_num = *hm2->xy2mod.hal->pin.dpll_wtimer_num; + hm2->xy2mod.written_dpll_wtimer_num = dpll_wtimer_num; } @@ -289,10 +301,10 @@ void hm2_xy2mod_write(hostmot2_t *hm2) { hm2_xy2mod_instance_write(hm2, i); } if (hm2->xy2mod.num_instances > 0 && hm2->dpll_module_present) { - if (*hm2->xy2mod.hal->pin.dpll_rtimer_num != (int)hm2->xy2mod.written_dpll_rtimer_num) { + if (hal_get_si32(hm2->xy2mod.hal->pin.dpll_rtimer_num) != hm2->xy2mod.written_dpll_rtimer_num) { hm2_xy2mod_set_dpll_rtimer(hm2); } - if (*hm2->xy2mod.hal->pin.dpll_wtimer_num != (int)hm2->xy2mod.written_dpll_wtimer_num) { + if (hal_get_si32(hm2->xy2mod.hal->pin.dpll_wtimer_num) != hm2->xy2mod.written_dpll_wtimer_num) { hm2_xy2mod_set_dpll_wtimer(hm2); } } @@ -322,16 +334,13 @@ void hm2_xy2mod_force_write(hostmot2_t *hm2) { void hm2_xy2mod_tram_init(hostmot2_t *hm2) { - int i; - - for (i = 0; i < hm2->xy2mod.num_instances; i ++) { - - *hm2->xy2mod.instance[i].hal.pin.posx_cmd = 0; - *hm2->xy2mod.instance[i].hal.pin.posy_cmd = 0; - *hm2->xy2mod.instance[i].hal.pin.velx_cmd = 0; - *hm2->xy2mod.instance[i].hal.pin.vely_cmd = 0; - *hm2->xy2mod.instance[i].hal.pin.accx_cmd = 0; - *hm2->xy2mod.instance[i].hal.pin.accy_cmd = 0; + for (int i = 0; i < hm2->xy2mod.num_instances; i ++) { + hal_set_real(hm2->xy2mod.instance[i].hal.pin.posx_cmd, 0); + hal_set_real(hm2->xy2mod.instance[i].hal.pin.posy_cmd, 0); + hal_set_real(hm2->xy2mod.instance[i].hal.pin.velx_cmd, 0); + hal_set_real(hm2->xy2mod.instance[i].hal.pin.vely_cmd, 0); + hal_set_real(hm2->xy2mod.instance[i].hal.pin.accx_cmd, 0); + hal_set_real(hm2->xy2mod.instance[i].hal.pin.accy_cmd, 0); } } @@ -417,14 +426,14 @@ int hm2_xy2mod_parse_md(hostmot2_t *hm2, int md_index) { // allocate the module-global HAL shared memory - hm2->xy2mod.hal = (hm2_xy2mod_module_global_t *)hal_malloc(sizeof(hm2_xy2mod_module_global_t)); + hm2->xy2mod.hal = hal_malloc(sizeof(*hm2->xy2mod.hal)); if (hm2->xy2mod.hal == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; goto fail0; } - hm2->xy2mod.instance = (hm2_xy2mod_instance_t *)hal_malloc(hm2->xy2mod.num_instances * sizeof(hm2_xy2mod_instance_t)); + hm2->xy2mod.instance = hal_malloc(hm2->xy2mod.num_instances * sizeof(*hm2->xy2mod.instance)); if (hm2->xy2mod.instance == NULL) { HM2_ERR("out of memory!\n"); r = -ENOMEM; @@ -513,268 +522,208 @@ int hm2_xy2mod_parse_md(hostmot2_t *hm2, int md_index) { // export to HAL { - int i; - char name[HAL_NAME_LEN + 1]; - if (hm2->dpll_module_present) { - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.read-timer-number", hm2->llio->name); - r = hal_pin_s32_new(name, HAL_IN, &(hm2->xy2mod.hal->pin.dpll_rtimer_num), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.hal->pin.dpll_rtimer_num), + -1, "%s.xy2mod.read-timer-number", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding read timer number param, aborting\n"); + HM2_ERR("error %d adding pin '%s.xy2mod.read-timer-number', aborting\n", r, hm2->llio->name); return -EINVAL; } - *(hm2->xy2mod.hal->pin.dpll_rtimer_num) = -1; - } - if (hm2->dpll_module_present) { - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.write-timer-number", hm2->llio->name); - r = hal_pin_s32_new(name, HAL_IN, &(hm2->xy2mod.hal->pin.dpll_wtimer_num), hm2->llio->comp_id); + r = hal_pin_new_si32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.hal->pin.dpll_wtimer_num), + -1, "%s.xy2mod.write-timer-number", hm2->llio->name); if (r < 0) { - HM2_ERR("error adding write timer number param, aborting\n"); + HM2_ERR("error %d adding pin '%s.xy2mod.write-timer-number', aborting\n", r, hm2->llio->name); return -EINVAL; } - *(hm2->xy2mod.hal->pin.dpll_wtimer_num) = -1; } - for (i = 0; i < hm2->xy2mod.num_instances; i ++) { - + for (int i = 0; i < hm2->xy2mod.num_instances; i ++) { // pins - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posx-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posx_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posx_cmd), + 0.0, "%s.xy2mod.%02d.posx-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posx-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posy-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posy_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posy_cmd), + 0.0, "%s.xy2mod.%02d.posy-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posy-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.velx-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.velx_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.velx_cmd), + 0.0, "%s.xy2mod.%02d.velx-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.velx-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.vely-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.vely_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.vely_cmd), + 0.0, "%s.xy2mod.%02d.vely-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.vely-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.accx-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.accx_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.accx_cmd), + 0.0, "%s.xy2mod.%02d.accx-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.accx-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.accy-cmd", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.accy_cmd), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.accy_cmd), + 0.0, "%s.xy2mod.%02d.accy-cmd", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.accy-cmd', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.velx-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.velx_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.velx_fb), + 0.0, "%s.xy2mod.%02d.velx-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.velx-fb', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.vely-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.vely_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.vely_fb), + 0.0, "%s.xy2mod.%02d.vely-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.vely-fb', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posx-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posx_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posx_fb), + 0.0, "%s.xy2mod.%02d.posx-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posx-fb', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posy-fb", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posy_fb), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posy_fb), + 0.0, "%s.xy2mod.%02d.posy-fb", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posy-fb', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posx-scale", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posx_scale), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posx_scale), + 1.0, "%s.xy2mod.%02d.posx-scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posx-scale', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posy-scale", hm2->llio->name, i); - r = hal_pin_float_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posy_scale), hm2->llio->comp_id); + r = hal_pin_new_real(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.posy_scale), + 1.0, "%s.xy2mod.%02d.posy-scale", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posy-scale', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.enable", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.enable), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.enable), + 0, "%s.xy2mod.%02d.enable", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.enable', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.controlx", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.controlx), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.controlx), + 1, "%s.xy2mod.%02d.controlx", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.controlx', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.controly", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.controly), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.controly), + 1, "%s.xy2mod.%02d.controly", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.controly', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.commandx", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandx), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandx), + 0, "%s.xy2mod.%02d.commandx", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.commandx', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.commandy", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandy), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandy), + 0, "%s.xy2mod.%02d.commandy", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.commandy', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.18bitmodex", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.mode18bitx), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.mode18bitx), + 0, "%s.xy2mod.%02d.18bitmodex", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.18bitmodex', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.18bitmodey", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.mode18bity), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.mode18bity), + 0, "%s.xy2mod.%02d.18bitmodey", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.18bitmodey', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.commandmodex", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandmodex), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandmodex), + 0, "%s.xy2mod.%02d.commandmodex", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.commandmodex', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.commandmodey", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandmodey), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_IN, &(hm2->xy2mod.instance[i].hal.pin.commandmodey), + 0, "%s.xy2mod.%02d.commandmodey", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.commandmodey', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posx-overflow", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posx_overflow), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posx_overflow), + 0, "%s.xy2mod.%02d.posx-overflow", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posx-overflow', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.posy-overflow", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posy_overflow), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.posy_overflow), + 0, "%s.xy2mod.%02d.posy-overflow", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.posy-overflow', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.velx-overflow", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.velx_overflow), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.velx_overflow), + 0, "%s.xy2mod.%02d.velx-overflow", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.velx-overflow', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.vely-overflow", hm2->llio->name, i); - r = hal_pin_bit_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.vely_overflow), hm2->llio->comp_id); + r = hal_pin_new_bool(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.vely_overflow), + 0, "%s.xy2mod.%02d.vely-overflow", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.vely-overflow', aborting\n", r, hm2->llio->name, i); goto fail0; } - rtapi_snprintf(name, sizeof(name), "%s.xy2mod.%02d.status", hm2->llio->name, i); - r = hal_pin_u32_new(name, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.status), hm2->llio->comp_id); + r = hal_pin_new_ui32(hm2->llio->comp_id, HAL_OUT, &(hm2->xy2mod.instance[i].hal.pin.status), + 0, "%s.xy2mod.%02d.status", hm2->llio->name, i); if (r < 0) { - HM2_ERR("error adding pin '%s', aborting\n", name); - r = -ENOMEM; + HM2_ERR("error %d adding pin '%s.xy2mod.%02d.status', aborting\n", r, hm2->llio->name, i); goto fail0; } - - - // init - *(hm2->xy2mod.instance[i].hal.pin.posx_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.posy_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.velx_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.vely_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.accx_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.accy_cmd) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.posx_fb) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.posy_fb) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.velx_fb) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.vely_fb) = 0.0; - *(hm2->xy2mod.instance[i].hal.pin.posx_scale) = 1.0; - *(hm2->xy2mod.instance[i].hal.pin.posy_scale) = 1.0; - *(hm2->xy2mod.instance[i].hal.pin.enable) = 0; - *(hm2->xy2mod.instance[i].hal.pin.controlx) = 1; - *(hm2->xy2mod.instance[i].hal.pin.controly) = 1; - *(hm2->xy2mod.instance[i].hal.pin.commandx) = 0; - *(hm2->xy2mod.instance[i].hal.pin.commandy) = 0; - *(hm2->xy2mod.instance[i].hal.pin.mode18bitx) = 0; - *(hm2->xy2mod.instance[i].hal.pin.mode18bity) = 0; - *(hm2->xy2mod.instance[i].hal.pin.commandmodex) = 0; - *(hm2->xy2mod.instance[i].hal.pin.commandmodey) = 0; - - } } @@ -810,7 +759,7 @@ void hm2_xy2mod_print_module(hostmot2_t *hm2) { HM2_PRINT(" status_addr: 0x%04X\n", hm2->xy2mod.status_addr); for (i = 0; i < hm2->xy2mod.num_instances; i ++) { HM2_PRINT(" instance %d:\n", i); - HM2_PRINT(" enable = %d\n", *hm2->xy2mod.instance[i].hal.pin.enable); + HM2_PRINT(" enable = %d\n", hal_get_bool(hm2->xy2mod.instance[i].hal.pin.enable)); HM2_PRINT(" hw:\n"); HM2_PRINT(" accx = 0x%08X\n", hm2->xy2mod.accx_reg[i]); HM2_PRINT(" accy = 0x%08X\n", hm2->xy2mod.accy_reg[i]); diff --git a/src/hal/drivers/mesa_7i65.comp b/src/hal/drivers/mesa_7i65.comp index e52b7b4f8b7..0a3f4c0b7fc 100644 --- a/src/hal/drivers/mesa_7i65.comp +++ b/src/hal/drivers/mesa_7i65.comp @@ -13,16 +13,16 @@ sequence, one for each bspi instance included in the bitfile loaded to each installed card during the Hostmot2 setup sequence. Type "dmesg" at the terminal prompt to view the output."""; -pin in float analogue.#.out [8] """Analogue output values. The value will be +pin in real analogue.#.out [8] """Analogue output values. The value will be limited to a -1.0 to +1.0 range"""; -pin out float analogue.#.in [8] "Analogue outputs read by the 7i65 (in Volts)"; -pin out bit digital.#.in [4] "Miscellaneous Digital Inputs"; -pin in bit enable.#.out [8] "Amplifier-enable control pins"; -pin out bit watchdog.has-bit """Indicates the status of the 7i65 Watchdog (which +pin out real analogue.#.in [8] "Analogue outputs read by the 7i65 (in Volts)"; +pin out bool digital.#.in [4] "Miscellaneous Digital Inputs"; +pin in bool enable.#.out [8] "Amplifier-enable control pins"; +pin out bool watchdog.has-bit """Indicates the status of the 7i65 Watchdog (which is separate from the FPGA card watchdog"""; -param rw float scale-# [8] = 10 """Analogue output scale factor. For example if +param rw real scale-# [8] = 10 """Analogue output scale factor. For example if the scale is 7 then an input of 1.0 will give 7V on the output terminals"""; -param rw bit is-bipolar-# [8] = 1 """Set this value to TRUE for a plus/minus +param rw bool is-bipolar-# [8] = 1 """Set this value to TRUE for a plus/minus "scale" output. Set to 0 for a 0-"scale" output"""; option extra_setup yes; @@ -50,7 +50,7 @@ include ; ;; // to parse the modparam -char *bspi_chans[16] = {0,}; +char *bspi_chans[16] = {}; RTAPI_MP_ARRAY_STRING(bspi_chans, 16, "BSPI Channel names"); static int read(void *subdata) { @@ -78,9 +78,9 @@ static int read(void *subdata) { // Limit DAC Outputs for (i = 0 ; i < 8 ; i++) { if (scale(i) > 10) - scale(i) = 10; + scale_set(i, 10); if (scale(i) < -10) - scale(i) = -10; + scale_set(i, -10); aout[i] = analogue_out(i); if (aout[i] > 1) @@ -147,15 +147,15 @@ static int read(void *subdata) { } // Read Misc IO and Watchdog from CPLD - digital_in(0) = (*CPLD_read & 0x1) ? 1:0; - digital_in(1) = (*CPLD_read & 0x2) ? 1:0; - digital_in(2) = (*CPLD_read & 0x4) ? 1:0; - digital_in(3) = (*CPLD_read & 0x8) ? 1:0; - watchdog_has_bit = (*CPLD_read & 0x100) ? 1:0; + digital_in_set(0, (*CPLD_read & 0x1) ? 1:0); + digital_in_set(1, (*CPLD_read & 0x2) ? 1:0); + digital_in_set(2, (*CPLD_read & 0x4) ? 1:0); + digital_in_set(3, (*CPLD_read & 0x8) ? 1:0); + watchdog_has_bit_set((*CPLD_read & 0x100) ? 1:0); // Read ADC's into Pins for(i=0; i < 8; i++) { - analogue_in(i) = (double)((int16_t)((*AD7329_read[i] & 0x1FFF) << 3)) / 3276.8; + analogue_in_set(i, (double)((int16_t)((*AD7329_read[i] & 0x1FFF) << 3)) / 3276.8); } return 0; } @@ -231,14 +231,14 @@ EXTRA_SETUP(){ } // analog outputs - r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1A,0); - r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1B,0); - r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1C,0); - r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1D,0); - r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2A,0); - r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2B,0); - r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2C,0); - r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2D,0); + r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1A, NULL); + r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1B, NULL); + r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1C, NULL); + r += hm2_tram_add_bspi_frame(name, 1, &AD5754_1D, NULL); + r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2A, NULL); + r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2B, NULL); + r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2C, NULL); + r += hm2_tram_add_bspi_frame(name, 2, &AD5754_2D, NULL); // This is required, or nothing happens. r += hm2_allocate_bspi_tram(name); diff --git a/src/hal/drivers/mesa_uart.comp b/src/hal/drivers/mesa_uart.comp index 5bfe30e88f8..b62d5b84d54 100644 --- a/src/hal/drivers/mesa_uart.comp +++ b/src/hal/drivers/mesa_uart.comp @@ -41,10 +41,10 @@ license "GPL"; include ; -pin in u32 tx-data-##[16] "Data to be transmitted"; -pin out u32 rx-data-##[16] "Data received"; -pin in s32 tx-bytes "Number of bytes to transmit"; -pin out s32 rx-bytes "Number of Bytes received"; +pin in ui32 tx-data-##[16] "Data to be transmitted"; +pin out ui32 rx-data-##[16] "Data received"; +pin in si32 tx-bytes "Number of bytes to transmit"; +pin out si32 rx-bytes "Number of Bytes received"; variable char *name; // UART name @@ -59,7 +59,7 @@ function receive; /* This uses the RTAPI_MP_ARRAY_STRING macro to load the list of UART channels into an array. This is copied into the *name string of each */ -char *uart_chans[18] = {0,}; +char *uart_chans[18] = {}; RTAPI_MP_ARRAY_STRING(uart_chans, 16, "UART Channel names"); FUNCTION(send){ @@ -82,9 +82,9 @@ FUNCTION(receive){ int i; unsigned char data[16]; - rx_bytes = hm2_uart_read(name, data); + rx_bytes_set(hm2_uart_read(name, data)); for (i = 0 ; i < rx_bytes ; i++){ - rx_data(i) = data[i]; + rx_data_set(i, data[i]); } } diff --git a/src/hal/drivers/motenc.h b/src/hal/drivers/motenc.h index 27b775abe71..efdd4f5f8c7 100644 --- a/src/hal/drivers/motenc.h +++ b/src/hal/drivers/motenc.h @@ -64,11 +64,11 @@ typedef struct { - hal_s32_t encoderCount[MOTENC_FPGA_NUM_ENCODER_CHANNELS]; - hal_u32_t digitalIo; - hal_u32_t statusControl; - hal_u32_t reserved; - hal_u32_t boardVersion; + volatile rtapi_s32 encoderCount[MOTENC_FPGA_NUM_ENCODER_CHANNELS]; + volatile rtapi_u32 digitalIo; + volatile rtapi_u32 statusControl; + volatile rtapi_u32 reserved; + volatile rtapi_u32 boardVersion; } volatile MotencFpgaRegMap; // For use with digitalIo reg. @@ -96,16 +96,16 @@ typedef struct { typedef struct { MotencFpgaRegMap fpga[MOTENC_NUM_FPGA]; - hal_u32_t timerCompare; - hal_u32_t timerIrqDisable; - hal_u32_t timerIrqEnable; - hal_u32_t watchdogControl; - hal_u32_t watchdogReset; - hal_u32_t reserved1[3]; - hal_u32_t dac[MOTENC_NUM_DAC_CHANNELS]; - hal_u32_t adcDataCommand; - hal_u32_t reserved2[7]; - hal_u32_t adcStartConversion; + volatile rtapi_u32 timerCompare; + volatile rtapi_u32 timerIrqDisable; + volatile rtapi_u32 timerIrqEnable; + volatile rtapi_u32 watchdogControl; + volatile rtapi_u32 watchdogReset; + volatile rtapi_u32 reserved1[3]; + volatile rtapi_u32 dac[MOTENC_NUM_DAC_CHANNELS]; + volatile rtapi_u32 adcDataCommand; + volatile rtapi_u32 reserved2[7]; + volatile rtapi_u32 adcStartConversion; } volatile MotencRegMap; // For use with watchdogControl reg. diff --git a/src/hal/drivers/opto_ac5.c b/src/hal/drivers/opto_ac5.c index 856a3ad70ec..cb90507bf1b 100644 --- a/src/hal/drivers/opto_ac5.c +++ b/src/hal/drivers/opto_ac5.c @@ -247,17 +247,13 @@ static int Device_ExportDigitalInPinsParametersFunctions(board_data_t *this, int if ((this->port[portnum].mask & mask)==0)//physical input? { // Pins. - if((halError = hal_pin_bit_newf(HAL_OUT, &(this->port[portnum].io[channel].pValue), - comp_id, "opto-ac5.%d.port%d.in-%02d", boardId, portnum, channel)) != 0) + if((halError = hal_pin_new_bool(comp_id, HAL_OUT, &(this->port[portnum].io[channel].pValue), + 0, "opto-ac5.%d.port%d.in-%02d", boardId, portnum, channel)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_OUT, &(this->port[portnum].io[channel].pValueNot), - comp_id, "opto-ac5.%d.port%d.in-%02d-not", boardId, portnum, channel)) != 0) + if((halError = hal_pin_new_bool(comp_id, HAL_OUT, &(this->port[portnum].io[channel].pValueNot), + 1, "opto-ac5.%d.port%d.in-%02d-not", boardId, portnum, channel)) != 0) break; - - // Init pin. - *(this->port[portnum].io[channel].pValue) = 0; - *(this->port[portnum].io[channel].pValueNot) = 1; } mask <<=1; } @@ -299,18 +295,14 @@ static int Device_ExportDigitalOutPinsParametersFunctions(board_data_t *this, in if ((this->port[portnum].mask & mask)!=0)//phyical output? { // Pins. - if((halError = hal_pin_bit_newf(HAL_IN, &(this->port[portnum].io[channel].pValue), - comp_id, "opto-ac5.%d.port%d.out-%02d", boardId, portnum, channel)) != 0) + if((halError = hal_pin_new_bool(comp_id, HAL_IN, &(this->port[portnum].io[channel].pValue), + 0, "opto-ac5.%d.port%d.out-%02d", boardId, portnum, channel)) != 0) break; // Parameters. - if((halError = hal_param_bit_newf(HAL_RW, &(this->port[portnum].io[channel].invert), - comp_id, "opto-ac5.%d.port%d.out-%02d-invert", boardId, portnum, channel)) != 0) + if((halError = hal_param_new_bool(comp_id, HAL_RW, &(this->port[portnum].io[channel].invert), + 0, "opto-ac5.%d.port%d.out-%02d-invert", boardId, portnum, channel)) != 0) break; - - // Init pin. - *(this->port[portnum].io[channel].pValue) = 0; - this->port[portnum].io[channel].invert = 0; } mask <<=1; } @@ -320,12 +312,12 @@ static int Device_ExportDigitalOutPinsParametersFunctions(board_data_t *this, in portnum=0; for(channel = 0; channel < 2; channel++) { - if((halError = hal_pin_bit_newf(HAL_IN, &(this->port[portnum].io[24].pValue), - comp_id, "opto-ac5.%d.led%d", boardId, channel+portnum)) != 0) + if((halError = hal_pin_new_bool(comp_id, HAL_IN, &(this->port[portnum].io[24].pValue), + 0, "opto-ac5.%d.led%d", boardId, channel+portnum)) != 0) break; - if((halError = hal_pin_bit_newf(HAL_IN, &(this->port[portnum].io[25].pValue), - comp_id, "opto-ac5.%d.led%d", boardId, channel+portnum+1)) != 0) + if((halError = hal_pin_new_bool(comp_id, HAL_IN, &(this->port[portnum].io[25].pValue), + 0, "opto-ac5.%d.led%d", boardId, channel+portnum+1)) != 0) break; portnum++; } @@ -370,10 +362,10 @@ Device_DigitalInRead(void *arg, long period) { if ((pboard->port[portnum].mask & mask) ==0) // is it an input bit ? { - if ((pins & mask) !=0){ *(pDigital->pValue) =0; - }else{ *(pDigital->pValue) = 1; } + if ((pins & mask) !=0){ hal_set_bool(pDigital->pValue, 0); + }else{ hal_set_bool(pDigital->pValue, 1); } // Update not pin. - *(pDigital->pValueNot) = !*(pDigital->pValue); + hal_set_bool(pDigital->pValueNot, !hal_get_bool(pDigital->pValue)); } mask <<=1;// shift mask } @@ -414,8 +406,8 @@ Device_DigitalOutWrite(void *arg, long period) if ((pboard->port[portnum].mask & mask) !=0) //is it an output? { // add mask to pins if HAL pin + invert =true. - if( (!*(pDigital->pValue) && !(pDigital->invert) ) || - ( *(pDigital->pValue) && (pDigital->invert) )) + if( (!hal_get_bool(pDigital->pValue) && !hal_get_bool(pDigital->invert) ) || + ( hal_get_bool(pDigital->pValue) && hal_get_bool(pDigital->invert) )) { pins |= mask; } } mask <<=1; // shift mask @@ -429,7 +421,7 @@ Device_DigitalOutWrite(void *arg, long period) mask = (unsigned int) 1 << (31-i); pDigital++; - if ( *(pDigital->pValue) == 0 ) { pins |= mask; } + if ( hal_get_bool(pDigital->pValue) == 0 ) { pins |= mask; } } // Write digital I/O register. writel(pins,pboard->base + (offset)); diff --git a/src/hal/drivers/opto_ac5.h b/src/hal/drivers/opto_ac5.h index 029ca01bfe2..eab07dac2a9 100644 --- a/src/hal/drivers/opto_ac5.h +++ b/src/hal/drivers/opto_ac5.h @@ -33,10 +33,10 @@ Copyright (C) 2008 Chris Morley *************************************************************************/ typedef struct DigitalPinsParams { // Pins. - hal_bit_t *pValue; - hal_bit_t *pValueNot; + hal_bool_t pValue; + hal_bool_t pValueNot; // Parameters. - hal_bit_t invert; + hal_bool_t invert; } DigitalPinsParams; diff --git a/src/hal/drivers/pci_8255.c b/src/hal/drivers/pci_8255.c index e116dbb1070..4527cdd358d 100644 --- a/src/hal/drivers/pci_8255.c +++ b/src/hal/drivers/pci_8255.c @@ -28,24 +28,24 @@ RTAPI_MP_ARRAY_INT(dir, MAX, "I/O direction of 8255s"); static int comp_id; -union inv { hal_bit_t *not_; hal_bit_t invert; }; +union inv { hal_bool_t not_; hal_bool_t invert; }; struct port { - hal_bit_t *a[8]; - hal_bit_t *b[8]; - hal_bit_t *c[8]; + hal_bool_t a[8]; + hal_bool_t b[8]; + hal_bool_t c[8]; union inv ai[8]; union inv bi[8]; union inv ci[8]; - hal_u32_t dir_; - hal_u32_t ioaddr; + hal_uint_t dir_; + hal_uint_t ioaddr; }; struct state { struct port ports[3]; - hal_bit_t *relay; - hal_bit_t relay_invert; - hal_u32_t ioaddr; + hal_bool_t relay; + hal_bool_t relay_invert; + hal_uint_t ioaddr; }; static void read(struct port *inst, long period); @@ -58,13 +58,13 @@ static void extra_cleanup(void); #include #define SHIFT 4 -static inline void pci_8255_outb(int value, hal_u32_t base, int offset) { +static inline void pci_8255_outb(int value, rtapi_u32 base, int offset) { // int *mem = (int*) base; outb(value, base + SHIFT*offset); // mem[offset] = value; } -static inline int pci_8255_inb(hal_u32_t base, int offset) { +static inline int pci_8255_inb(rtapi_u32 base, int offset) { return inb(base + SHIFT*offset); // int *mem = (int*) base; // return mem[offset]; @@ -77,58 +77,57 @@ static int export(char *prefix, struct port *inst, int ioaddr, int dir) { hal_pin_dir_t direction; int sz = sizeof(struct port); memset(inst, 0, sz); - inst->dir_ = dir; - inst->ioaddr = ioaddr; + hal_set_ui32(inst->ioaddr, ioaddr); - if(inst->dir_ & 8) direction = HAL_OUT; else direction = HAL_IN; + if(dir & 8) direction = HAL_OUT; else direction = HAL_IN; for(i=0; i<8; i++) { - r = hal_pin_bit_newf(direction, &(inst->a[i]), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->a[i]), 0, "%s.a%d", prefix, i); if(r != 0) return r; if(direction == HAL_OUT) { - r = hal_pin_bit_newf(direction, &(inst->ai[i].not_), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->ai[i].not_), 0, "%s.a%d-not", prefix, i); } else { - r = hal_param_bit_newf(HAL_RW, &(inst->ai[i].invert), comp_id, + r = hal_param_new_bool(comp_id, HAL_RW, &(inst->ai[i].invert), 0, "%s.a%d-invert", prefix, i); } if(r != 0) return r; } - if(inst->dir_ & 2) direction = HAL_OUT; else direction = HAL_IN; + if(dir & 2) direction = HAL_OUT; else direction = HAL_IN; for(i=0; i<8; i++) { - r = hal_pin_bit_newf(direction, &(inst->b[i]), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->b[i]), 0, "%s.b%d", prefix, i); if(r != 0) return r; if(direction == HAL_OUT) { - r = hal_pin_bit_newf(direction, &(inst->bi[i].not_), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->bi[i].not_), 0, "%s.b%d-not", prefix, i); } else { - r = hal_param_bit_newf(HAL_RW, &(inst->bi[i].invert), comp_id, + r = hal_param_new_bool(comp_id, HAL_RW, &(inst->bi[i].invert), 0, "%s.b%d-invert", prefix, i); } if(r != 0) return r; } for(i=0; i<8; i++) { if(i < 4) { - if(inst->dir_ & 1) direction = HAL_OUT; + if(dir & 1) direction = HAL_OUT; else direction = HAL_IN; } else { - if(inst->dir_ & 4) direction = HAL_OUT; + if(dir & 4) direction = HAL_OUT; else direction = HAL_IN; } - r = hal_pin_bit_newf(direction, &(inst->c[i]), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->c[i]), 0, "%s.c%d", prefix, i); if(r != 0) return r; if(direction == HAL_OUT) { - r = hal_pin_bit_newf(direction, &(inst->ci[i].not_), comp_id, + r = hal_pin_new_bool(comp_id, direction, &(inst->ci[i].not_), 0, "%s.c%d-not", prefix, i); } else { - r = hal_param_bit_newf(HAL_RW, &(inst->ci[i].invert), comp_id, + r = hal_param_new_bool(comp_id, HAL_RW, &(inst->ci[i].invert), 0, "%s.c%d-invert", prefix, i); } if(r != 0) return r; } - r = hal_param_u32_newf(HAL_RO, &(inst->dir_), comp_id, + r = hal_param_new_ui32(comp_id, HAL_RO, &(inst->dir_), dir, "%s.dir", prefix); if(r != 0) return r; r = hal_export_functf((void(*)(void *inst, long))read, inst, 0, 0, comp_id, "%s.read", prefix); @@ -148,12 +147,12 @@ static struct state *inst = 0; static int count = 0; static void write_relay(struct state *inst, long period) { - int val = (!*inst->relay) ^ (!inst->relay_invert); + int val = (!hal_get_bool(inst->relay)) ^ (!hal_get_bool(inst->relay_invert)); // relay is active low if(val) { - pci_8255_outb(0, inst->ioaddr, 3); + pci_8255_outb(0, hal_get_ui32(inst->ioaddr), 3); } else { - pci_8255_outb(0x10, inst->ioaddr, 3); + pci_8255_outb(0x10, hal_get_ui32(inst->ioaddr), 3); } } @@ -196,19 +195,18 @@ int rtapi_app_main(void) { // relay, CS# as outputs pci_8255_outb(0x11, io[i]+2, 0); + r = hal_param_new_ui32(comp_id, HAL_RO, &(inst->ioaddr), io[i], + "pci8255.%d.io-addr", i); for(j=0; j<3; j++) { rtapi_snprintf(buf, sizeof(buf), "pci8255.%d.%d", i, j); r = export(buf, &inst[i].ports[j], io[i] + 0xc0 + 16*j, (dir[i] >> (4*j)) & 0xf); if(r != 0) goto out_error; } - hal_pin_bit_newf(HAL_IN, &(inst[i].relay), comp_id, "pci8255.%d.relay", i); - hal_param_bit_newf(HAL_RW, &(inst[i].relay_invert), comp_id, + hal_pin_new_bool(comp_id, HAL_IN, &(inst[i].relay), 0, "pci8255.%d.relay", i); + hal_param_new_bool(comp_id, HAL_RW, &(inst[i].relay_invert), 0, "pci8255.%d.relay-invert", i); r = hal_export_functf((void(*)(void *inst, long))write_relay, &inst[i], 0, 0, comp_id, "pci8255.%d.write-relay", i); - r = hal_param_u32_newf(HAL_RO, &(inst->ioaddr), comp_id, - "pci8255.%d.io-addr", i); - inst->ioaddr = io[i]; if(r != 0) return r; } r = hal_export_funct("pci8255.read-all", (void(*)(void *inst, long))read_all, inst, 0, 0, comp_id); @@ -231,15 +229,18 @@ void rtapi_app_exit(void) { #define FUNCTION(name) static void name(struct state *inst, long period) #define EXTRA_CLEANUP() static void extra_cleanup(void) #define fperiod (period * 1e-9) -#define a(i) (*inst->a[i]) -#define b(i) (*inst->b[i]) -#define c(i) (*inst->c[i]) -#define ai_invert(i) (inst->ai[i].invert) -#define bi_invert(i) (inst->bi[i].invert) -#define ci_invert(i) (inst->ci[i].invert) -#define ai_not(i) (*inst->ai[i].not_) -#define bi_not(i) (*inst->bi[i].not_) -#define ci_not(i) (*inst->ci[i].not_) +#define a(i) (hal_get_bool(inst->a[(i)])) +#define b(i) (hal_get_bool(inst->b[(i)])) +#define c(i) (hal_get_bool(inst->c[(i)])) +#define a_set(i,v) (hal_set_bool(inst->a[(i)], (v))) +#define b_set(i,v) (hal_set_bool(inst->b[(i)], (v))) +#define c_set(i,v) (hal_set_bool(inst->c[(i)], (v))) +#define ai_invert(i) (hal_get_bool(inst->ai[i].invert)) +#define bi_invert(i) (hal_get_bool(inst->bi[i].invert)) +#define ci_invert(i) (hal_get_bool(inst->ci[i].invert)) +#define ai_not_set(i,v) (hal_set_bool(inst->ai[(i)].not_, (v))) +#define bi_not_set(i,v) (hal_set_bool(inst->bi[(i)].not_, (v))) +#define ci_not_set(i,v) (hal_set_bool(inst->ci[(i)].not_, (v))) #define ioaddr (inst->ioaddr) #define dir_ (inst->dir_) @@ -286,7 +287,8 @@ static void extra_cleanup(void) { } static void write(struct port *inst, long period) { - int p = dir_; + int p = hal_get_ui32(dir_); + rtapi_u32 xioaddr = hal_get_ui32(ioaddr); static int first=1; int i; @@ -296,7 +298,7 @@ static void write(struct port *inst, long period) { int t = (c(i) != 0) ^ (ci_invert(i) != 0); if(t) byte |= 1 << i; } - pci_8255_outb(byte, ioaddr, 2); + pci_8255_outb(byte, xioaddr, 2); if(first) rtapi_print_msg(RTAPI_MSG_DBG, "write: 2a %02x\n", byte); } else if((p & 5) == 4) { int byte = 0; @@ -304,7 +306,7 @@ static void write(struct port *inst, long period) { int t = (c(i) != 0) ^ (ci_invert(i) != 0); if(t) byte |= 1 << i; } - pci_8255_outb(byte, ioaddr, 2); + pci_8255_outb(byte, xioaddr, 2); if(first) rtapi_print_msg(RTAPI_MSG_DBG, "write: 2b %02x\n", byte); } else if((p & 5) == 1) { int byte = 0; @@ -312,7 +314,7 @@ static void write(struct port *inst, long period) { int t = (c(i) != 0) ^ (ci_invert(i) != 0); if(t) byte |= 1 << i; } - pci_8255_outb(byte, ioaddr, 2); + pci_8255_outb(byte, xioaddr, 2); if(first) rtapi_print_msg(RTAPI_MSG_DBG, "write: 2c %02x\n", byte); } @@ -322,7 +324,7 @@ static void write(struct port *inst, long period) { int t = (b(i) != 0) ^ (bi_invert(i) != 0); if(t) byte |= 1 << i; } - pci_8255_outb(byte, ioaddr, 1); + pci_8255_outb(byte, xioaddr, 1); if(first) rtapi_print_msg(RTAPI_MSG_DBG, "write: 1 %02x\n", byte); } @@ -332,53 +334,54 @@ static void write(struct port *inst, long period) { int t = (a(i) != 0) ^ (ai_invert(i) != 0); if(t) byte |= 1 << i; } - pci_8255_outb(byte, ioaddr, 0); + pci_8255_outb(byte, xioaddr, 0); if(first) rtapi_print_msg(RTAPI_MSG_DBG, "write: 0 %02x\n", byte); } first = 0; } static void read(struct port *inst, long period) { - int p = dir_; + int p = hal_get_ui32(dir_); + rtapi_u32 xioaddr = hal_get_ui32(ioaddr); int i; if((p & 5) == 5) { - int byte = pci_8255_inb(ioaddr, 2); + int byte = pci_8255_inb(xioaddr, 2); for(i=0; i<8; i++) { int t = (byte & (1< period/4) reset_time = period/4; + if(reset_time > period/4) reset_time_set(period/4); //compensate for any time elapsed since the write rtapi_delay(reset_time - (rtapi_get_time() - write_time)); diff --git a/src/hal/drivers/pluto_servo.comp b/src/hal/drivers/pluto_servo.comp index 1987783d6fd..000d5580776 100644 --- a/src/hal/drivers/pluto_servo.comp +++ b/src/hal/drivers/pluto_servo.comp @@ -47,29 +47,29 @@ described in the HAL manual. The digital input pins conform to the `canonical digital input' interface described in the HAL manual. """; -pin out s32 encoder.#.count[4]; -pin out float encoder.#.position[4]; -pin out float encoder.#.velocity[4]; -pin in bit encoder.#.reset[4]; -pin io bit encoder.#.index-enable[4] """encoder.\\fIM\\fR corresponds to the +pin out si32 encoder.#.count[4]; +pin out real encoder.#.position[4]; +pin out real encoder.#.velocity[4]; +pin in bool encoder.#.reset[4]; +pin io bool encoder.#.index-enable[4] """encoder.\\fIM\\fR corresponds to the pins labeled QA\\fIM\\fR, QB\\fIM\\fR, and QZ\\fIM\\fR on the pinout diagram"""; -param rw float encoder.#.scale[4] =1; +param rw real encoder.#.scale[4] =1; -param rw bit encoder.z-polarity "Set to TRUE if the index pulse is active low, FALSE if it is active high. Affects all encoders."; +param rw bool encoder.z-polarity "Set to TRUE if the index pulse is active low, FALSE if it is active high. Affects all encoders."; -pin in float pwm.#.value[4]; -pin in bit pwm.#.enable[4] "pwm.\\fIM\\fR corresponds to the pins labeled UP\\fIM\\fR and DN\\fIM\\fR on the pinout diagram"; -param rw float pwm.#.offset[4]; -param rw float pwm.#.scale[4]=1; -param rw float pwm.#.max-dc[4]=1; -param rw float pwm.#.min-dc[4]=0; -param rw bit pwm.#.pwmdir[4]=0 +pin in real pwm.#.value[4]; +pin in bool pwm.#.enable[4] "pwm.\\fIM\\fR corresponds to the pins labeled UP\\fIM\\fR and DN\\fIM\\fR on the pinout diagram"; +param rw real pwm.#.offset[4]; +param rw real pwm.#.scale[4]=1; +param rw real pwm.#.max-dc[4]=1; +param rw real pwm.#.min-dc[4]=0; +param rw bool pwm.#.pwmdir[4]=0 "Set to TRUE use PWM+direction mode. Set to FALSE to use Up/Down mode."; -param rw bit pwm.is-pdm "Set to TRUE to use PDM (also called interleaved PWM) mode. Set to FALSE to use traditional PWM mode. Affects all PWM outputs."; +param rw bool pwm.is-pdm "Set to TRUE to use PDM (also called interleaved PWM) mode. Set to FALSE to use traditional PWM mode. Affects all PWM outputs."; -pin in bit dout.##[20] +pin in bool dout.##[20] """dout.\\fI0M\\fR corresponds to the pin labeled OUT\\fIM\\fR on the pinout diagram. Other pins are shared with the PWM function, as follows: @@ -100,11 +100,11 @@ dout.19\tDOWN3 .PP .RE .DT"""; -param rw bit dout.##-invert[20] +param rw bool dout.##-invert[20] "If TRUE, the output on the corresponding \\fBdout.\\fIMM\\fR is inverted."; -pin out bit din.##[20]; -pin out bit din.##_not[20] +pin out bool din.##[20]; +pin out bool din.##_not[20] """For M=0 through 7, din.\\fI0M\\fR corresponds to the pin labeled IN\\fIM\\fR on the pinout diagram. Other pins are shared with the encoder function, as follows: @@ -142,7 +142,7 @@ din.19\tQA3 .RE .DT"""; -param rw u32 communication_error """Incremented each time +param rw ui32 communication_error """Incremented each time pluto-servo.read detects an error code in the EPP status register. While this register is nonzero, new values are not being written to the Pluto-P board, and the status of digital outputs and the PWM duty cycle of the PWM @@ -150,8 +150,8 @@ outputs will remain unchanged. If the watchdog is enabled, it will activate soon after the communication error is detected. To continue after a communication error, set this parameter back to zero."""; -param rw s32 debug_0; -param rw s32 debug_1 """These parameters can display values which are useful to developers or for debugging the driver and firmware. They are not useful for integrators or users."""; +param rw si32 debug_0; +param rw si32 debug_1 """These parameters can display values which are useful to developers or for debugging the driver and firmware. They are not useful for integrators or users."""; option singleton; option extra_setup; @@ -236,10 +236,10 @@ FUNCTION(write) { EPP_ADDR(0); for(i=0; i<4; i++) { - if(pwm_max_dc(i) > 1) pwm_max_dc(i) = 1; - else if(pwm_max_dc(i) < 0) pwm_max_dc(i) = 0; - if(pwm_min_dc(i) < 0) pwm_min_dc(i) = 0; - else if(pwm_min_dc(i) > pwm_max_dc(i)) pwm_min_dc(i) = pwm_max_dc(i); + if(pwm_max_dc(i) > 1) pwm_max_dc_set(i, 1); + else if(pwm_max_dc(i) < 0) pwm_max_dc_set(i, 0); + if(pwm_min_dc(i) < 0) pwm_min_dc_set(i, 0); + else if(pwm_min_dc(i) > pwm_max_dc(i)) pwm_min_dc_set(i, pwm_max_dc(i)); } #define D(x) (!dout(x) ^ !dout_invert(x)) @@ -273,7 +273,7 @@ FUNCTION(read) { if(i == 0) { int status = inb(ioaddr+1) & 1; if(status) { - communication_error ++; + communication_error_set(communication_error + 1); pluto_clear_error_register(); } if(communication_error) { EPP_DIR_WRITE(); return; } @@ -290,20 +290,20 @@ FUNCTION(read) { index = data.last_index[i]; if(encoder_index_enable(i) && indexed) { - encoder_index_enable(i) = 0; + encoder_index_enable_set(i, 0); data.reset_count[i] = index; } - if(reset) encoder_velocity(i) = 0; - else encoder_velocity(i) = (count - data.last_count[i]) / - encoder_scale(i) / fperiod; + if(reset) encoder_velocity_set(i, 0); + else encoder_velocity_set(i, (count - data.last_count[i]) / + encoder_scale(i) / fperiod); data.last_index[i] = index; data.last_count[i] = count; if(reset) data.reset_count[i] = count; - encoder_count(i) = count - data.reset_count[i]; - encoder_position(i) = encoder_count(i) / encoder_scale(i); + encoder_count_set(i, count - data.reset_count[i]); + encoder_position_set(i, encoder_count(i) / encoder_scale(i)); if(i == 0) { - debug_0 = ppdata; debug_1 = count; + debug_0_set(ppdata); debug_1_set(count); } } @@ -311,7 +311,7 @@ FUNCTION(read) { for(i=0; i< 20; i++) { int b = ppdata & (1< TMAX) { @@ -193,7 +193,7 @@ FUNCTION(write) { "Requested direction change time %dns decreased to %dns " "due to hardware limitations\n", stepgen_dirtime, TMAX * PLUTO_SPEED_NS); - stepgen_dirtime = TMAX * PLUTO_SPEED_NS; + stepgen_dirtime_set(TMAX * PLUTO_SPEED_NS); } // Speed limits come from several sources @@ -224,7 +224,7 @@ FUNCTION(write) { data.old_position_cmd[i] = new_position_cmd; data.old_velocity_cmd[i] = v; actual_max = fmax / scale_abs; - if(stepgen_maxvel(i) < 0) stepgen_maxvel(i) = -stepgen_maxvel(i); + if(stepgen_maxvel(i) < 0) stepgen_maxvel_set(i, -stepgen_maxvel(i)); if(stepgen_maxvel(i) != 0 && stepgen_maxvel(i) > actual_max) { static int message_printed[4] = {0,0,0,0}; if(!message_printed[i]) { @@ -235,7 +235,7 @@ FUNCTION(write) { (int)(fmax)); message_printed[i] = 1; } - stepgen_maxvel(i) = actual_max; + stepgen_maxvel_set(i, actual_max); } if(stepgen_maxvel(i) == 0) { @@ -251,7 +251,7 @@ FUNCTION(write) { if(rate < -maxrate) rate = -maxrate; if(!stepgen_enable(i)) rate = 0; - if(i == 0) debug_1 = rate; + if(i == 0) debug_1_set(rate); write16(rate); } @@ -284,7 +284,7 @@ FUNCTION(read) { if(i == 0) { int status = inb(ioaddr+1) & 1; if(status) { - communication_error ++; + communication_error_set(communication_error + 1); pluto_clear_error_register(); } if(communication_error) { EPP_DIR_WRITE(); return; } @@ -293,21 +293,21 @@ FUNCTION(read) { newlow = ppdata & MASK; count = extend(data.last_count[i], newlow, W+F); - stepgen_velocity_fb(i) = (count - data.last_count[i]) / stepgen_scale(i) / fperiod / (1 << F); + stepgen_velocity_fb_set(i, (count - data.last_count[i]) / stepgen_scale(i) / fperiod / (1 << F)); data.last_count[i] = count; if(reset) data.reset_count[i] = count; fcount = (count - data.reset_count[i]) * 1. / (1<) and map +// the shared HAL memory segment. +// Only user-space applications linking to hal_lib can initialize the library +// in this way. This is useful for any program wishing to do set[ps], get[ps] +// and the like, which do not need a component. Any hal_lib function that does +// not require an associated component can be executed with HAL shared memory +// mapped. +// Note: A caller who creates a component with hal_init() does not need to call +// hal_lib_init(). The initialization is automatically performed on +// component creation. +// +// 'hal_lib_exit()' will unmap the shared HAL memory segment and de-register +// the rtapi application (HAL_LIB_). +// The de-initialization will only occur if no references are left in this +// instance. A reference is any call to hal_init() with an unmatched hal_exit() +// (i.e. a component exists). An error message will be emitted when you call +// hal_lib_exit() while there still are components referenced. +// +// Only user-space applications linking to hal_lib can de-init the library. +// This is useful for any program that accesses HAL constructs but does itself +// not need any components. +// Note: A caller is not required to call hal_lib_exit() when the library was +// finalized through a call matching call pair to hal_init()/hal_exit. +// The last component exit will invoke hal_lib_exit() automatically. +// +int hal_lib_init(void); +void hal_lib_exit(void); +#endif + /** 'hal_exit()' must be called before a HAL component exits, to free resources associated with the component. 'comp_id' is the ID of the component as returned from its initial @@ -233,11 +270,15 @@ extern int hal_set_unready(int comp_id); */ extern int hal_unready(int comp_id); +// hal_strerror() returns a brief textual description string about the error +// identified. The argument should be the negative errno value, as returned by +// most HAL functions. +const char *hal_strerror(int err); /** hal_comp_name() returns the name of the given component, or NULL if comp_id is not a loaded component */ -extern char* hal_comp_name(int comp_id); +extern const char *hal_comp_name(int comp_id); /** hal_get_realtime_type() returns the type of the running real time */ @@ -355,15 +396,15 @@ static inline __HAL_ALWAYS_INLINE bool hal_pdir_is_neither(hal_pdir_t v) { // compiler. // ==> Remove when we get rid of old hal_*_t typedefs. <== typedef rtapi_real real_t; -typedef rtapi_u64 ireal_t __attribute__((aligned(8))); // integral type as wide as real_t / hal_float_t +typedef rtapi_u64 ireal_t __attribute__((aligned(8))) __attribute__((deprecated)); // integral type as wide as real_t / hal_float_t typedef volatile bool hal_bit_t; typedef volatile rtapi_u32 hal_u32_t; typedef volatile rtapi_s32 hal_s32_t; typedef volatile rtapi_u64 hal_u64_t; typedef volatile rtapi_s64 hal_s64_t; -typedef volatile real_t hal_float_t; -typedef volatile int hal_port_t; +typedef volatile rtapi_real hal_float_t; +typedef volatile rtapi_port hal_port_t; /** HAL "data union" structure ** This structure may hold any type of hal data @@ -548,7 +589,8 @@ int hal_pin_new_sint(int compid, hal_pdir_t dir, hal_sint_t *ref, rtapi_sint def int hal_pin_new_uint(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_uint def, const char *fmt, ...) __HAL_PFMT(5,6); int hal_pin_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, rtapi_real def, const char *fmt, ...) __HAL_PFMT(5,6); // Note: port has no initial default as it is an 'internal' reference -//int hal_pin_new_port(int compid, hal_pin_dir_t dir, hal_port_t *ref, const char *fmt, ...) __HAL_PFMT(4,5); +// FIXME: This needs to change into hal_port_t argument when we break the API +int hal_pin_new_port(int compid, hal_pin_dir_t dir, hal_sint_t *ref, const char *fmt, ...) __HAL_PFMT(4,5); int hal_param_new_bool(int compid, hal_pdir_t dir, hal_bool_t *ref, rtapi_bool def, const char *fmt, ...) __HAL_PFMT(5,6); int hal_param_new_si32(int compid, hal_pdir_t dir, hal_sint_t *ref, rtapi_s32 def, const char *fmt, ...) __HAL_PFMT(5,6); @@ -556,6 +598,7 @@ int hal_param_new_ui32(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_u32 d int hal_param_new_sint(int compid, hal_pdir_t dir, hal_sint_t *ref, rtapi_sint def, const char *fmt, ...) __HAL_PFMT(5,6); int hal_param_new_uint(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_uint def, const char *fmt, ...) __HAL_PFMT(5,6); int hal_param_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, rtapi_real def, const char *fmt, ...) __HAL_PFMT(5,6); +int hal_param_new_fake(int compid, hal_refs_u *refs); #undef __HAL_PFMT /*********************************************************************** @@ -844,12 +887,12 @@ extern int hal_param_new(const char *name, hal_type_t type, hal_param_dir_t dir, On success, the hal_param_xxx_set() functions return 0, and on failure they return a negative error code. */ -extern int hal_param_bit_set(const char *name, int value); -extern int hal_param_float_set(const char *name, double value); -extern int hal_param_u32_set(const char *name, unsigned long value); -extern int hal_param_s32_set(const char *name, signed long value); -extern int hal_param_u64_set(const char *name, unsigned long value); -extern int hal_param_s64_set(const char *name, signed long value); +int hal_param_bit_set(const char *name, int value) __attribute__((deprecated("Use hal_set_p()"))); +int hal_param_float_set(const char *name, double value) __attribute__((deprecated("Use hal_set_p()"))); +int hal_param_u32_set(const char *name, unsigned long value) __attribute__((deprecated("Use hal_set_p()"))); +int hal_param_s32_set(const char *name, signed long value) __attribute__((deprecated("Use hal_set_p()"))); +int hal_param_u64_set(const char *name, unsigned long value) __attribute__((deprecated("Use hal_set_p()"))); +int hal_param_s64_set(const char *name, signed long value) __attribute__((deprecated("Use hal_set_p()"))); /** 'hal_param_alias()' assigns an alternate name, aka an alias, to a parameter. Once assigned, the parameter can be referred to by @@ -873,7 +916,7 @@ extern int hal_param_alias(const char *pin_name, const char *alias); If successful, hal_param_set() returns 0. On failure it returns a negative error code. */ -extern int hal_param_set(const char *name, hal_type_t type, void *value_addr); +int hal_param_set(const char *name, hal_type_t type, void *value_addr) __attribute__((deprecated("Use hal_set_p()"))); /*********************************************************************** * PIN/SIG/PARAM GETTER FUNCTIONS * @@ -888,7 +931,7 @@ extern int hal_param_set(const char *name, hal_type_t type, void *value_addr); */ extern int hal_get_pin_value_by_name( - const char *name, hal_type_t *type, hal_data_u **data, bool *connected); + const char *name, hal_type_t *type, hal_data_u **data, bool *connected) __attribute__((deprecated("Use hal_get_p()"))); /** 'hal_get_signal_value_by_name()' returns the value of any arbitrary HAL * signal by signal name. @@ -899,7 +942,7 @@ extern int hal_get_pin_value_by_name( */ extern int hal_get_signal_value_by_name( - const char *name, hal_type_t *type, hal_data_u **data, bool *has_writers); + const char *name, hal_type_t *type, hal_data_u **data, bool *has_writers) __attribute__((deprecated("Use hal_get_s()"))); /** 'hal_get_param_value_by_name()' returns the value of any arbitrary HAL * parameter by parameter name. @@ -909,7 +952,7 @@ extern int hal_get_signal_value_by_name( */ extern int hal_get_param_value_by_name( - const char *name, hal_type_t *type, hal_data_u **data); + const char *name, hal_type_t *type, hal_data_u **data) __attribute__((deprecated("Use hal_get_p()"))); /*********************************************************************** @@ -1068,7 +1111,7 @@ extern int hal_stop_threads(void); instance of its component. Return value is >=0 for success, <0 for error. */ -typedef int(*constructor)(char *prefix, char *arg); +typedef int(*constructor)(const char *prefix, const char *arg); /** hal_set_constructor() sets the constructor function for this component */ @@ -1173,8 +1216,8 @@ extern void hal_port_wait_writable(hal_port_t** port, unsigned count, sig_atomic */ typedef union hal_stream_data { - real_t f; - bool b; + rtapi_real f; + rtapi_bool b; rtapi_s32 s; rtapi_u32 u; rtapi_s64 l; @@ -1320,6 +1363,263 @@ static inline rtapi_s64 hal_extend_counter(rtapi_s64 old, rtapi_s64 newlow, int return (rtapi_u64)old + (diff_shifted >> nshift); // unsigned to avoid signed overflow } +//*********************************************************************** +// Mapping/umapping HAL memory segment pointers +//*********************************************************************** + +// Pointers into HAL memory are dependent on process memory. Transporting them +// between processes does not work. These need to be handled as offsets from +// where the memory is mapped. +rtapi_intptr_t hal_reference_unmap(const void *ref); +void *hal_reference_map(rtapi_intptr_t ref); + +//*********************************************************************** +// +// User-land only functions to query HAL's internals +// +//*********************************************************************** + +// HAL 'component' type. +// Assigned according to RTAPI and ULAPI definitions. +typedef enum { + HAL_COMP_TYPE_UNKNOWN = -1, + HAL_COMP_TYPE_USER, + HAL_COMP_TYPE_REALTIME, + HAL_COMP_TYPE_OTHER +} hal_comp_type_t; +// These COMPONENT_TYPE_* names are for compatibility. The HAL_COMP_TYPE_* +// versions are better names for what they represent. +#define COMPONENT_TYPE_UNKNOWN HAL_COMP_TYPE_UNKNOWN +#define COMPONENT_TYPE_USER HAL_COMP_TYPE_USER +#define COMPONENT_TYPE_REALTIME HAL_COMP_TYPE_REALTIME +#define COMPONENT_TYPE_OTHER HAL_COMP_TYPE_OTHER + +// Only enable the query API when we are compiling the user-land HAL library +#ifdef ULAPI + +// Query type of a HAL item +typedef enum { + HAL_QTYPE_ANY = 0, + HAL_QTYPE_PIN, + HAL_QTYPE_PARAM, + HAL_QTYPE_SIGNAL, + HAL_QTYPE_COMP, + HAL_QTYPE_FUNCT, + HAL_QTYPE_THREAD, + HAL_QTYPE_THREAD_FUNCT, +} hal_qtype_t; + +typedef struct { + int comp_id; // Return: Component ID (RTAPI module id) + hal_comp_type_t type; // Return: Component type (name in query struct) + int pid; // Return: PID of component (user components only) + bool ready; // Return: True if ready, false if not + const char *insmod; // Return: Arguments passed via insmod or NULL if none present +} hal_query_comp_t; + +typedef struct { + int comp_id; // Return: Component ID + const char *comp; // Return: Component's name + int users; // Return: Number of threads using function + rtapi_intptr_t funct; // Return: Pointer to function code + rtapi_intptr_t arg; // Return: Argument for function + bool reentrant; // Return: True if function is re-entrant +} hal_query_funct_t; + +typedef struct { + int comp_id; // Return: Owning component + const char *comp; // Return: Component's name + int priority; // Return: Thread priority + long int period; // Return: Thread period in nsec + int functidx; // Return: Function iteration counter + const char *funct; // Return: Attached function name + bool is_init; // Return: True if funct is an init function +} hal_query_thread_t; + +typedef union { + rtapi_bool b; // values used in hal_[gs]et_[ps] + rtapi_sint s; + rtapi_uint u; + rtapi_real r; +} hal_query_value_u; + +typedef struct { + hal_type_t type; // Request: Enforce specific type (any when == 0); + // Return: HAL_XXX type + hal_refs_u ref; // Return: Value reference + hal_query_value_u value; // Request: Set in the callback or in advance for set_p with enforced type; + // Return(get_p): value read + hal_pdir_t dir; // Return: pin/param direction + const char *alias; // Return: non-NULL if there is an alias name + const char *signal; // Return: get_p/getref_p/list_p signal name if connected + const char *comp; // Return: Owner's name (component name) + int comp_id; // Return: Owner ID +} hal_query_pp_t; + +typedef struct { + hal_type_t type; // Request: Enforce specific type (any when == 0); + // Return: HAL_XXX type + hal_refs_u ref; // Return: Value reference + hal_query_value_u value; // Request: Set in the callback or in advance for set_s with enforced type; + // Return(get_s): value read + int writers; // Return: Number of writer pins attached to the signal + int readers; // Return: Number of reader pins attached to the signal + int bidirs; // Return: Number of bidirectional pins attached to the signal +} hal_query_sig_t; + +// +// HAL query structure used both for input and output +// +typedef struct { + const char *name; // Request: name to search for; + // Return: name found (live pointer) + hal_qtype_t qtype; // Request: limit search; + // Return: Connection type found + union { + void *vpval; // Generic pointer + const void *cpval; // const pointer (for easier cast'ability) + rtapi_intptr_t ipval; + rtapi_uintptr_t upval; + rtapi_sint sival; + rtapi_uint uival; + } callerdata; // Caller private data additional to 'arg' + union { + // Query data specific according to 'qtype' + // See details above + hal_query_pp_t pp; // Pins, params + hal_query_sig_t sig; // Signals + hal_query_comp_t comp; // Components + hal_query_funct_t funct; // Functions + hal_query_thread_t thread; // Threads + }; +} hal_query_t; + +// Callback prototype +// A callback is invoked while holding the HAL mutex. You are allowed to call +// back into the HAL library from within the callback (the mutex is recursive). +// A fair warning: +// You should not take too long in callbacks and _MUST_NOT_ terminate the +// program inside a callback. Doing so will keep the mutex locked and other +// processes will hang indefinitely when they call into the HAL library. +// Returning non-zero will automatically break any iteration loop. Use negative +// return values to signal error conditions and positive return values to +// simply terminate any iteration loop. The callback's return value is used as +// the iteration function's return value. +typedef int (*hal_query_cb)(hal_query_t *query, void *arg); + +// Pin/Param/Signal setters based on name +// get_p/set_p - get or set pin or param +// get_s/set_s - get or set signal +// getref_p - return only the pin/param reference +// getref_s - return only the signal reference +// +// set_s(): If the type is HAL_PORT, then the action sets the port's +// queue size according to the `query->value.u` setting. +// +// set_p/set_s: The callback function is called after it is determined that the +// name exists and optionally if the type matches. If the setter 'cb' callback +// is NULL, then it is required that you set both the query->{pp,sig}.type to +// the proper type and the matching query->{pp,sig}.value field to its +// associated value. +// +// get_p/get_s: The callback function is called after it is determined that +// the name exists and optionally if the type matches. The getter calls the +// callback with the appropriate query->{pp,sig}.value field set to the value +// read, according to the type. If the getter 'cb' callback is NULL, then it is +// simply skipped and the value is still available in the query structure. +// +// For all query functions: The callback should return zero when it succeeds +// and a negative errno value on error. If the callback returns with a non-zero +// value, then that value is returned. +// Returning a positive value from a callback function in iterations terminates +// the iteration loop. The caller can determine from the return value's sign +// whether it was an error or an intentional iteration loop termination. +// +int hal_getref_p(hal_query_t *query); +int hal_get_p(hal_query_t *query, hal_query_cb cb, void *arg); +int hal_set_p(hal_query_t *query, hal_query_cb cb, void *arg); + +int hal_getref_s(hal_query_t *query); +int hal_get_s(hal_query_t *query, hal_query_cb cb, void *arg); +int hal_set_s(hal_query_t *query, hal_query_cb cb, void *arg); + +// +// *** HAL structure iteration functions *** +// +// Each function will invoke the callback on each of the HAL structures +// of interest: +// hal_list_p - callback on pins and/or params +// hal_list_p_s - callback on pins connected to named signal +// hal_list_s - callback on signals +// hal_list_comp - callback on components +// hal_list_funct - callback on registered functions +// hal_list_thread - callback on registered threads (and its functions) +// +int hal_list_p(hal_query_t *q, hal_query_cb cb, void *arg); +int hal_list_p_s(hal_query_t *q, hal_query_cb cb, void *arg); +int hal_list_s(hal_query_t *q, hal_query_cb cb, void *arg); +int hal_list_comp(hal_query_t *q, hal_query_cb cb, void *arg); +int hal_list_funct(hal_query_t *q, hal_query_cb cb, void *arg); +int hal_list_thread(hal_query_t *q, hal_query_cb cb, void *arg); + +// +// *** Component queries *** +// +// Query components by name or ID +int hal_comp_by_name(const char *name, hal_query_t *q); +int hal_comp_by_id(int comp_id, hal_query_t *q); + +// +// *** General HAL statistics *** +// +typedef struct { + long mem_total; + long mem_free; + int ncomps; + int ncomps_free; + int npins; + int npins_free; + int nparams; + int nparams_free; + int naliases; + int naliases_free; + int nsignals; + int nsignals_free; + int nthreads; + int nthreads_free; + int nfuncts; + int nfuncts_free; +} hal_statistics_t; + +int hal_statistics(hal_statistics_t *sts); + +// +// *** Special functions for rtapi_app and halcmd *** +// +// Invoke the constructor for a new instance +// Uspace/rtapi_app only. Not implemented in halcmd/halrmt. +int hal_comp_invoke_make(const char *compname, const char *newname, const char *arg); + +// Add the insmod arguments to a named (and just loaded) RT component +// The 'args' argument must be in HAL memory. +int hal_comp_insmod_args(const char *compname, const char *args); + +// ----------------------------------------------------- +// Release the HAL mutex with brute force +// WARNING: +// * Do not use this function in normal code. You will +// * probably kill your running instance when you do. +// * It is only to recover from an error and you need +// * to be able to shut down your instance. +int hal_mutex_force_release(void); +// ----------------------------------------------------- + +// HAL will pretend that the exact base period requested is possible. +// This mode is not suitable for running real hardware. +// Returns zero (0) on success or a negative -EACCES error if already set. +int hal_enforce_exact_base_period(void); + +#endif // ULAPI RTAPI_END_DECLS diff --git a/src/hal/hal.hh b/src/hal/hal.hh deleted file mode 100644 index 3e4af13a4e6..00000000000 --- a/src/hal/hal.hh +++ /dev/null @@ -1,166 +0,0 @@ -#ifndef HALXX_HH -#define HALXX_HH - -#include -#include -#include -#include "hal.h" - -enum class hal_dir{ - IN = HAL_IN, - OUT = HAL_OUT, -}; - -#if 0 -// If this class is ever necessary, then it needs to be moved into a new -// header 'hal_priv.hh' because it uses internal access methods from -// 'hal_priv.h' that should not be available to the casual source file. - -#include "hal_priv.h" - -class hal{ - public: - static bool component_exists(const std::string& name){ - return halpr_find_comp_by_name(name.c_str()) != NULL; - } - static bool pin_has_writer(const std::string& name){ - hal_pin_t *pin = halpr_find_pin_by_name(name.c_str()); - if(!pin) {//pin does not exist - return false; - } - if(pin->signal) { - hal_sig_t *signal = (hal_sig_t*)SHMPTR(pin->signal); - return signal->writers > 0; - } - return false; - } - static bool component_is_ready(const std::string& name){ - // Bad form to assume comp name exists - stop crashing! - hal_comp_t *thecomp = halpr_find_comp_by_name(name.c_str()); - return thecomp && (thecomp->ready != 0); - } -}; -#endif - -template -class hal_pin{ - public: - volatile T** ptr; - T operator=(const T& value){ - **ptr = value; - return **ptr; - } - operator T(){ - return **ptr; - } -}; - -using pin_t = std::variant,hal_pin,hal_pin,hal_pin>; - -class hal_comp{ - int comp_id; - std::string comp_name; - std::map map; - int add_pin_(const std::string& name, hal_dir dir, hal_pin pin){ - return hal_pin_new(name.c_str(), HAL_BIT, static_cast(dir), (void **)(pin.ptr), comp_id); - } - int add_pin_(const std::string& name, hal_dir dir, hal_pin pin){ - return hal_pin_new(name.c_str(), HAL_S32, static_cast(dir), (void **)(pin.ptr), comp_id); - } - int add_pin_(const std::string& name, hal_dir dir, hal_pin pin){ - return hal_pin_new(name.c_str(), HAL_U32, static_cast(dir), (void **)(pin.ptr), comp_id); - } - int add_pin_(const std::string& name, hal_dir dir, hal_pin pin){ - return hal_pin_new(name.c_str(), HAL_FLOAT, static_cast(dir), (void **)(pin.ptr), comp_id); - } - public: - int error = 0; - hal_comp(const std::string& name){ - comp_id = hal_init(name.c_str()); - comp_name = name; - if(comp_id < 0){ - error -= 1; - rtapi_print_msg(RTAPI_MSG_ERR, "%s ERROR: hal_init() failed\n", comp_name.c_str()); - hal_exit(comp_id); - } - } - hal_comp() = delete; - - void newpin(const std::string& name, hal_type_t type, hal_dir dir){ - auto& pin = map[name]; - switch(type){ - case HAL_BIT: - pin = hal_pin(); - add_pin(name, dir, std::get>(pin)); - break; - case HAL_FLOAT: - pin = hal_pin(); - add_pin(name, dir, std::get>(pin)); - break; - case HAL_S32: - pin = hal_pin(); - add_pin(name, dir, std::get>(pin)); - break; - case HAL_U32: - pin = hal_pin(); - add_pin(name, dir, std::get>(pin)); - break; - [[fallthrough]]; - default: - break; - } - } - - std::variant getitem(const std::string& name){ - auto pin = map[name]; - if (auto* v = std::get_if>(&pin)) { - return *v; - } else if (auto* v = std::get_if>(&pin)) { - return *v; - } else if (auto* v = std::get_if>(&pin)) { - return *v; - } else if (auto* v = std::get_if>(&pin)) { - return *v; - } - return 0; - } - - template - void setitem(const std::string& name, T value){ - auto pin = map[name]; - if (auto* p = std::get_if>(&pin)) { - *p = value; - } else if (auto* p = std::get_if>(&pin)) { - *p = value; - } else if (auto* p = std::get_if>(&pin)) { - *p = value; - } else if (auto* p = std::get_if>(&pin)) { - *p = value; - } - } - - void ready(){ - hal_ready(comp_id); - } - - template - void add_pin(const std::string& pin_name, hal_dir dir, hal_pin &pin){ - pin.ptr = (volatile T**)hal_malloc(8); - if(!pin.ptr){ - error -= 1; - rtapi_print_msg(RTAPI_MSG_ERR, "%s ERROR: hal_malloc() failed\n", pin_name.c_str()); - hal_exit(comp_id); - } - error += add_pin_(comp_name + "." + pin_name, dir, pin); - if(error < 0){ - rtapi_print_msg(RTAPI_MSG_ERR, "%s ERROR: hal_pin_new() failed\n", pin_name.c_str()); - hal_exit(comp_id); - } - } - - ~hal_comp(){ - hal_exit(comp_id); - } -}; - -#endif diff --git a/src/hal/hal_lib.c b/src/hal/hal_lib.c index f87467935ac..830eff8854a 100644 --- a/src/hal/hal_lib.c +++ b/src/hal/hal_lib.c @@ -53,6 +53,20 @@ */ +// Special case to get gettid() to work properly for recursive mutex. +// Doing this in a rtapi_*.h header is a pain because hal_priv.h is still +// included everywhere and it would fail because of include ordering. +#ifdef __KERNEL__ +#include +#define halpr_gettid() ((int)(get_current()->pid)) +#else +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include +#define halpr_gettid() ((int)gettid()) +#endif + #include /* RTAPI realtime OS API */ #include "hal.h" /* HAL public API decls */ #include "hal_priv.h" /* HAL private decls */ @@ -159,19 +173,209 @@ static void free_thread_struct(hal_thread_t * thread); static void thread_task(void *arg); #endif /* RTAPI */ +// +// Recursive locking/unlocking with a mutex +// The recursion resilience is required because callbacks could potentially +// call back into hal_lib and cause severe problems. We must either prevent +// callbacks from re-entering hal_lib or deal with it and use recursion. The +// lesser evil is recursion. None of the code that is called using the mutex is +// real-time anyway. +// +// ==> The initial state requires the mutex to be in the locked state. +// ==> That is why it uses a 'reverse default' mutex, where zero means +// ==> that it is in the locked state. The shared memory is initialized +// ==> with zeros at creation time so this works as expected. +// +// When a thread acquires the lock, then 'lockcnt' will be increased. The first +// thread will fall-through and set its thread ID and the recursion counter. A +// next thread wanting the lock will see a 'lockcnt' of at least 2 and will +// wait on the mutex if it is not already the owner. If it is the same thread, +// then it will increase the recursion level without waiting. +// The unlock decreases the recursion level and, when the recursion level +// reaches zero, clears the thread ID storage. If then 'lockcnt' is still +// larger than zero after its decrease when the recursion level is zero, then +// we know that there is a thread waiting and the mutex is signalled. +// +// Proper function depends on the interlocked inc/dec operation on 'lockcnt'. +// +int halpr_mutex_acquire(void) +{ + int tid = halpr_gettid(); // Caller thread ID + int cnt = __sync_add_and_fetch(&hal_data->lockcnt, 1); // Interlocked increment + if(cnt > 1) { + // A call to lock beyond the first one + if(tid != hal_data->locktid) + rtapi_mutex_get_rd(&(hal_data->priv_rdmutex)); + } + // Getting here means we have the lock + hal_data->locktid = tid; + return ++hal_data->locklvl; // Increase recursion level and return it +} + +int halpr_mutex_release(void) +{ + int lvl = --hal_data->locklvl; // Decrease recursion level + if(lvl < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "halpr_mutex_release: release at recursion level %d < 0. " + "Prepare for a lockup/crash.\n", lvl); + hal_data->locklvl = lvl = 0; // Try some 'sanity' + } + if(0 == lvl) + hal_data->locktid = 0; // Recursion level reached zero + int cnt = __sync_sub_and_fetch(&hal_data->lockcnt, 1); // Interlocked decrement + if(cnt < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "halpr_mutex_release: lockcnt %d < 0. " + "Prepare for a lockup/crash.\n", lvl); + cnt = __sync_sub_and_fetch(&hal_data->lockcnt, cnt); // Increase to try 'sanity' + } + if(cnt > 0 && 0 == lvl) { + // We are at the lowest recursion level and someone is waiting, + // release the mutex for the waiting thread. That thread will wake up + // and reacquire the mutex. + rtapi_mutex_give_rd(&(hal_data->priv_rdmutex)); + } + return lvl; +} + +void halpr_mutex_force_release(void) +{ + int lvl = hal_data->locklvl; // Save recursion level + hal_data->locktid = 0; // Clear ownership + hal_data->locklvl = 0; // Clear recursion + int cnt = __sync_add_and_fetch(&hal_data->lockcnt, 0); // Get the value + if(lvl > cnt) { + rtapi_print_msg(RTAPI_MSG_ERR, "halpr_mutex_force_release: inconsistent recursion state: lvl=%d > cnt=%d\n", lvl, cnt); + cnt = lvl; // Never subtract more than recursion level + } else if(lvl == cnt && hal_data->priv_rdmutex) { + rtapi_print_msg(RTAPI_MSG_ERR, "halpr_mutex_force_release: inconsistent lock state: locked and lvl=cnt=%d\n", cnt); + } + __sync_sub_and_fetch(&hal_data->lockcnt, lvl); // Interlocked subtract + rtapi_mutex_give_rd(&(hal_data->priv_rdmutex)); // Unconditional release +} + /*********************************************************************** * PUBLIC (API) FUNCTION CODE * ************************************************************************/ static int ref_cnt = 0; +#ifdef ULAPI +static int init_cnt = 0; // Reference count on hal_lib_init()/hal_lib_exit() + +// Only user-space applications linking to hal_lib have access to this part. +// Especially halmodule will call it on import to map the shared memory. +int hal_lib_init(void) +{ + init_cnt++; // Reference count init calls + + if(0 != lib_mem_id) + return 0; // Already initialized and mapped + + rtapi_print_msg(RTAPI_MSG_DBG, "HAL: initializing hal_lib\n"); + char rtapi_name[RTAPI_NAME_LEN + 1]; + rtapi_snprintf(rtapi_name, RTAPI_NAME_LEN, "HAL_LIB_%d", (int)getpid()); + lib_module_id = rtapi_init(rtapi_name); + if (lib_module_id < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: could not initialize RTAPI\n"); + init_cnt--; + return lib_module_id; + } + + /* get HAL shared memory block from RTAPI */ + lib_mem_id = rtapi_shmem_new(HAL_KEY, lib_module_id, HAL_SIZE); + if (lib_mem_id < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: could not open shared memory\n"); + rtapi_exit(lib_module_id); + // Reset the 'lib_mem_id' because it is used as a key in the test to + // perform the memory mapping at the start of the function. + lib_mem_id = 0; + lib_module_id = -1; + init_cnt--; + return -EINVAL; + } + /* get address of shared memory area */ + void *mem; + int retval = rtapi_shmem_getptr(lib_mem_id, &mem); + if (retval < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: could not access shared memory\n"); + rtapi_shmem_delete(lib_mem_id, lib_module_id); + rtapi_exit(lib_module_id); + lib_mem_id = 0; + lib_module_id = -1; + init_cnt--; + return -EINVAL; + } + /* set up internal pointers to shared mem and data structure */ + hal_shmem_base = (char *)mem; + hal_data = (hal_data_t *)mem; + /* perform a global init if needed */ + retval = init_hal_data(); + if (0 != retval) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: could not init shared memory\n"); + rtapi_shmem_delete(lib_mem_id, lib_module_id); + rtapi_exit(lib_module_id); + hal_shmem_base = NULL; + hal_data = NULL; + lib_mem_id = 0; + lib_module_id = -1; + init_cnt--; + return -EINVAL; + } + return 0; +} + +static int dangling_comp_cb(hal_query_t *q, void *arg) +{ + (void)arg; + if(q->callerdata.sival == q->comp.pid) { + rtapi_print_msg(RTAPI_MSG_ERR, " dangling component: '%s' id=%d pid=%d ready=%d insmod='%s'\n", + q->name, q->comp.comp_id, q->comp.pid, (int)q->comp.ready, q->comp.insmod ? q->comp.insmod : "(null)"); + } + return 0; +} + +void hal_lib_exit(void) +{ + if(init_cnt <= 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: hal_lib_exit() called too often (init_cnt=%d)\n", init_cnt); + return; + } + + init_cnt--; // Decrease the ref count + + if(init_cnt > 0) { + return; // Not yet final exit. + } + + // We check the hal_init() refcount. We can't delete until hal_exit() was + // called on all of them. We alse check whether we actually have been + // initialized and have a valid shared memory ID. This ID is non-zero when + // we sucessfully initialized. + if(0 == ref_cnt) { + if(0 != lib_mem_id) { + rtapi_print_msg(RTAPI_MSG_DBG, "HAL: releasing RTAPI resources\n"); + /* release RTAPI resources */ + rtapi_shmem_delete(lib_mem_id, lib_module_id); + rtapi_exit(lib_module_id); + lib_mem_id = 0; + lib_module_id = -1; + hal_shmem_base = NULL; + hal_data = NULL; + } // else it is a no-op + } else { + int pid = (int)getpid(); + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: hal_lib_exit() called" + " while holding %d component references (pid=%d)\n", ref_cnt, pid); + hal_query_t q = {}; + q.callerdata.sival = pid; + hal_list_comp(&q, dangling_comp_cb, NULL); + } +} +#endif /* ULAPI */ + int hal_init(const char *name) { int comp_id; -#ifdef ULAPI - int retval; - void *mem; -#endif char rtapi_name[RTAPI_NAME_LEN + 1]; char hal_name[HAL_NAME_LEN + 1]; hal_comp_t *comp; @@ -187,43 +391,10 @@ int hal_init(const char *name) } #ifdef ULAPI - if(!lib_mem_id) { - rtapi_print_msg(RTAPI_MSG_DBG, "HAL: initializing hal_lib\n"); - rtapi_snprintf(rtapi_name, RTAPI_NAME_LEN, "HAL_LIB_%d", (int)getpid()); - lib_module_id = rtapi_init(rtapi_name); - if (lib_module_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: could not initialize RTAPI\n"); - return -EINVAL; - } - - /* get HAL shared memory block from RTAPI */ - lib_mem_id = rtapi_shmem_new(HAL_KEY, lib_module_id, HAL_SIZE); - if (lib_mem_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: could not open shared memory\n"); - rtapi_exit(lib_module_id); - return -EINVAL; - } - /* get address of shared memory area */ - retval = rtapi_shmem_getptr(lib_mem_id, &mem); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: could not access shared memory\n"); - rtapi_exit(lib_module_id); - return -EINVAL; - } - /* set up internal pointers to shared mem and data structure */ - hal_shmem_base = (char *) mem; - hal_data = (hal_data_t *) mem; - /* perform a global init if needed */ - retval = init_hal_data(); - if ( retval ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: could not init shared memory\n"); - rtapi_exit(lib_module_id); - return -EINVAL; - } + if(ref_cnt == 0) { + int retval = hal_lib_init(); + if (0 != retval) + return retval; } #endif rtapi_print_msg(RTAPI_MSG_DBG, "HAL: initializing component '%s'\n", @@ -235,24 +406,24 @@ int hal_init(const char *name) comp_id = rtapi_init(rtapi_name); if (comp_id < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: rtapi init failed\n"); - return -EINVAL; + return comp_id; } /* get mutex before manipulating the shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* make sure name is unique in the system */ if (halpr_find_comp_by_name(hal_name) != NULL) { /* a component with this name already exists */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate component name '%s'\n", hal_name); rtapi_exit(comp_id); - return -EINVAL; + return -EEXIST; } /* allocate a new component structure */ comp = halpr_alloc_comp_struct(); if (comp == NULL) { /* couldn't allocate structure */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for component '%s'\n", hal_name); rtapi_exit(comp_id); @@ -261,10 +432,10 @@ int hal_init(const char *name) /* initialize the structure */ comp->comp_id = comp_id; #ifdef RTAPI - comp->type = COMPONENT_TYPE_REALTIME; + comp->type = HAL_COMP_TYPE_REALTIME; comp->pid = 0; #else /* ULAPI */ - comp->type = COMPONENT_TYPE_USER; + comp->type = HAL_COMP_TYPE_USER; comp->pid = getpid(); #endif comp->ready = 0; @@ -275,7 +446,7 @@ int hal_init(const char *name) comp->next_ptr = hal_data->comp_list_ptr; hal_data->comp_list_ptr = SHMOFF(comp); /* done with list, release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); /* done */ rtapi_print_msg(RTAPI_MSG_DBG, "HAL: component '%s' initialized, ID = %02d\n", hal_name, comp_id); @@ -283,6 +454,25 @@ int hal_init(const char *name) return comp_id; } +int hal_is_init(void) +{ + return hal_shmem_base != NULL; +} + +rtapi_intptr_t hal_reference_unmap(const void *ref) +{ + if(!hal_shmem_base || !ref || !SHMCHK(ref)) + return 0; + return (rtapi_intptr_t)SHMOFF(ref); +} + +void *hal_reference_map(rtapi_intptr_t ref) +{ + if(!hal_shmem_base || ref <= 0 || ref >= HAL_SIZE) + return NULL; + return SHMPTR(ref); +} + int hal_exit(int comp_id) { rtapi_intptr_t *prev, next; @@ -292,20 +482,20 @@ int hal_exit(int comp_id) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: exit called before init\n"); - return -EINVAL; + return -EFAULT; } rtapi_print_msg(RTAPI_MSG_DBG, "HAL: removing component %02d\n", comp_id); /* grab mutex before manipulating list */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search component list for 'comp_id' */ prev = &(hal_data->comp_list_ptr); next = *prev; if (next == 0) { /* list is empty - should never happen, but... */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); - return -EINVAL; + return -ENOENT; } comp = SHMPTR(next); while (comp->comp_id != comp_id) { @@ -314,10 +504,10 @@ int hal_exit(int comp_id) next = *prev; if (next == 0) { /* reached end of list without finding component */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); - return -EINVAL; + return -ENOENT; } comp = SHMPTR(next); } @@ -345,18 +535,13 @@ int hal_exit(int comp_id) } #endif /* release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); --ref_cnt; #ifdef ULAPI - if(ref_cnt == 0) { - rtapi_print_msg(RTAPI_MSG_DBG, "HAL: releasing RTAPI resources\n"); - /* release RTAPI resources */ - rtapi_shmem_delete(lib_mem_id, lib_module_id); - rtapi_exit(lib_module_id); - lib_mem_id = 0; - lib_module_id = -1; - hal_shmem_base = NULL; - hal_data = NULL; + if (0 == ref_cnt) { + hal_lib_exit(); + } else if(ref_cnt < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: hal_exit() made reference count negative\n"); } #endif rtapi_exit(comp_id); @@ -383,11 +568,11 @@ void *hal_malloc(long int size) } /* get the mutex */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* allocate memory */ retval = shmalloc_up(size); /* release the mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); /* check return value */ if (retval == NULL) { rtapi_print_msg(RTAPI_MSG_DBG, @@ -401,13 +586,13 @@ int hal_set_constructor(int comp_id, constructor make) { int next; hal_comp_t *comp; - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search component list for 'comp_id' */ next = hal_data->comp_list_ptr; if (next == 0) { /* list is empty - should never happen, but... */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -419,7 +604,7 @@ int hal_set_constructor(int comp_id, constructor make) { next = comp->next_ptr; if (next == 0) { /* reached end of list without finding component */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -429,17 +614,17 @@ int hal_set_constructor(int comp_id, constructor make) { comp->make = make; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } #endif int hal_set_unready(int comp_id) { hal_comp_t *comp; - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); comp = halpr_find_comp_by_id(comp_id); if (comp) { comp->ready = 0; } - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); if (comp) {return 0;} rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: hal_set_unready(): component %d not found\n", comp_id); @@ -450,13 +635,13 @@ int hal_ready(int comp_id) { int next; hal_comp_t *comp; - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search component list for 'comp_id' */ next = hal_data->comp_list_ptr; if (next == 0) { /* list is empty - should never happen, but... */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -468,7 +653,7 @@ int hal_ready(int comp_id) { next = comp->next_ptr; if (next == 0) { /* reached end of list without finding component */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -478,11 +663,11 @@ int hal_ready(int comp_id) { if(comp->ready > 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: Component '%s' already ready\n", comp->name); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return -EINVAL; } comp->ready = 1; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -490,13 +675,13 @@ int hal_unready(int comp_id) { int next; hal_comp_t *comp; - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search component list for 'comp_id' */ next = hal_data->comp_list_ptr; if (next == 0) { /* list is empty - should never happen, but... */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -508,7 +693,7 @@ int hal_unready(int comp_id) { next = comp->next_ptr; if (next == 0) { /* reached end of list without finding component */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -518,30 +703,57 @@ int hal_unready(int comp_id) { if(comp->ready < 1) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: Component '%s' already unready\n", comp->name); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return -EINVAL; } comp->ready = 0; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } -char *hal_comp_name(int comp_id) + +// +// Return an appropriate error string for HAL error values +// +// The error value should be a negative errno value returned by +// a HAL function. +// +const char *hal_strerror(int err) +{ + switch(err) { + case -EINVAL: return "invalid argument"; + case -ENOENT: return "not found"; + case -EACCES: return "not writable"; + case -EIO: return "missing target storage"; + case -EBADF: return "invalid type"; + case -ERANGE: return "value out of range"; + case -ENOMEM: return "out of memory"; + case -EISCONN: return "queue already allocated"; + case -EEXIST: return "name exists"; // also when pin/param/sig matched with different type + case -EFAULT: return "shared memory not mapped"; + case -EMFILE: return "too many modules"; + case -EPROTO: return "hal data version mismatch"; + case -EPERM: return "hal is locked"; + case -ENOEXEC: return "missing constructor"; + default: return "unknown error"; + } +} +const char *hal_comp_name(int comp_id) { hal_comp_t *comp; - char *result = NULL; - rtapi_mutex_get(&(hal_data->mutex)); + const char *result = NULL; + halpr_mutex_acquire(); comp = halpr_find_comp_by_id(comp_id); if(comp) result = comp->name; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return result; } hal_realtime_type_t hal_get_realtime_type() { - if (hal_data == 0) { + if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: hal_get_realtime_type called before init\n"); - return -EINVAL; + return -EFAULT; } return hal_data->realtime_type; } @@ -556,7 +768,7 @@ int hal_set_lock(unsigned char lock_type) { if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: set_lock called before init\n"); - return -EINVAL; + return -EFAULT; } hal_data->lock = lock_type; return 0; @@ -568,9 +780,12 @@ int hal_set_lock(unsigned char lock_type) { unsigned char hal_get_lock() { if (hal_data == NULL) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: get_lock called before init\n"); - return -EINVAL; + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: get_lock called before init\n"); + // There is no point in returning a negative error value. The return + // type wont allow it. We just pretend that everything is locked tight + // and nothing can change, which would adequately describe the + // unavailability of shared memory. + return HAL_LOCK_ALL; } return hal_data->lock; } @@ -780,7 +995,7 @@ int hal_pin_new_uint(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_u64 def, return 0; } -int hal_pin_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, real_t def, const char *fmt, ...) +int hal_pin_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, rtapi_real def, const char *fmt, ...) { va_list ap; va_start(ap, fmt); @@ -792,10 +1007,8 @@ int hal_pin_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, real_t def, co return 0; } -#if 0 -// Must wait until switch -// Note: port has no initial default as it is an 'internal' reference -int hal_pin_new_port(int compid, hal_pdir_t dir, hal_port_t *ref, const char *fmt, ...) +// FIXME: This needs to change into hal_port_t argument when we break the API +int hal_pin_new_port(int compid, hal_pdir_t dir, hal_sint_t *ref, const char *fmt, ...) { va_list ap; va_start(ap, fmt); @@ -803,7 +1016,6 @@ int hal_pin_new_port(int compid, hal_pdir_t dir, hal_port_t *ref, const char *fm va_end(ap); return ret; } -#endif /* this is a generic function that does the majority of the work. */ @@ -818,7 +1030,7 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin_new called before init\n"); - return -EINVAL; + return -EFAULT; } if(*data_ptr_addr) @@ -856,12 +1068,12 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, rtapi_print_msg(RTAPI_MSG_DBG, "HAL: creating pin '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* validate comp_id */ comp = halpr_find_comp_by_id(comp_id); if (comp == NULL) { /* bad comp_id */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -869,7 +1081,7 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, // Already check duplicate before allocating if(halpr_find_pin_by_name(name)) { // Duplicate pin name - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate pin '%s'\n", name); return -EINVAL; } @@ -883,13 +1095,13 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, /* validate passed in pointer - must point to HAL shmem */ if (! SHMCHK(data_ptr_addr)) { /* bad pointer */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: data_ptr_addr not in shared memory\n"); return -EINVAL; } if(comp->ready) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin_new called after hal_ready\n"); return -EINVAL; @@ -898,7 +1110,7 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, new = alloc_pin_struct(); if (new == NULL) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for pin '%s'\n", name); return -ENOMEM; @@ -921,7 +1133,7 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, /* reached end of list, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } ptr = SHMPTR(next); @@ -930,13 +1142,13 @@ int hal_pin_new(const char *name, hal_type_t type, hal_pin_dir_t dir, /* found the right place for it, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } if (cmp == 0) { /* name already in list, can't insert */ free_pin_struct(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate variable '%s'\n", name); return -EINVAL; @@ -957,7 +1169,7 @@ int hal_pin_alias(const char *pin_name, const char *alias) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin_alias called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -972,11 +1184,11 @@ int hal_pin_alias(const char *pin_name, const char *alias) } } /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); if (alias != NULL ) { pin = halpr_find_pin_by_name(alias); if ( pin != NULL ) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate pin/alias name '%s'\n", alias); return -EINVAL; @@ -990,7 +1202,7 @@ int hal_pin_alias(const char *pin_name, const char *alias) to succeed since at least one struct is on the free list. */ oldname = halpr_alloc_oldname_struct(); if ( oldname == NULL ) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for pin_alias\n"); return -EINVAL; @@ -1002,7 +1214,7 @@ int hal_pin_alias(const char *pin_name, const char *alias) while (1) { if (next == 0) { /* reached end of list, not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin '%s' not found\n", pin_name); return -EINVAL; @@ -1053,7 +1265,7 @@ int hal_pin_alias(const char *pin_name, const char *alias) /* reached end of list, insert here */ pin->next_ptr = next; *prev = SHMOFF(pin); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } ptr = SHMPTR(next); @@ -1062,7 +1274,7 @@ int hal_pin_alias(const char *pin_name, const char *alias) /* found the right place for it, insert here */ pin->next_ptr = next; *prev = SHMOFF(pin); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* didn't find it yet, look at next one */ @@ -1086,7 +1298,7 @@ int hal_signal_new(const char *name, hal_type_t type) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal_new called before init\n"); - return -EINVAL; + return -EFAULT; } if (strlen(name) > HAL_NAME_LEN) { @@ -1102,10 +1314,10 @@ int hal_signal_new(const char *name, hal_type_t type) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: creating signal '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* check for an existing signal with the same name */ if (halpr_find_sig_by_name(name) != NULL) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate signal '%s'\n", name); return -EINVAL; @@ -1117,19 +1329,19 @@ int hal_signal_new(const char *name, hal_type_t type) * See: #421 and https://github.com/machinekit/machinekit/issues/524 */ switch (type) { - case HAL_BIT: + case HAL_BOOL: case HAL_S32: case HAL_U32: - case HAL_S64: - case HAL_U64: - case HAL_FLOAT: + case HAL_SINT: + case HAL_UINT: + case HAL_REAL: case HAL_PORT: data_addr = shmalloc_up(sizeof(hal_data_u)); // Initialize the signal value memset(data_addr, 0, sizeof(hal_data_u)); break; default: - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: illegal signal type %d'\n", type); return -EINVAL; @@ -1138,7 +1350,7 @@ int hal_signal_new(const char *name, hal_type_t type) new = alloc_sig_struct(); if ((new == NULL) || (data_addr == NULL)) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for signal '%s'\n", name); return -ENOMEM; @@ -1158,7 +1370,7 @@ int hal_signal_new(const char *name, hal_type_t type) /* reached end of list, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } ptr = SHMPTR(next); @@ -1167,7 +1379,7 @@ int hal_signal_new(const char *name, hal_type_t type) /* found the right place for it, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* didn't find it yet, look at next one */ @@ -1184,7 +1396,7 @@ int hal_signal_delete(const char *name) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal_delete called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -1195,7 +1407,7 @@ int hal_signal_delete(const char *name) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: deleting signal '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search for the signal */ prev = &(hal_data->sig_list_ptr); next = *prev; @@ -1207,7 +1419,7 @@ int hal_signal_delete(const char *name) /* and delete it */ free_sig_struct(sig); /* done */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* no match, try the next one */ @@ -1215,7 +1427,7 @@ int hal_signal_delete(const char *name) next = *prev; } /* if we get here, we didn't find a match */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' not found\n", name); return -EINVAL; @@ -1231,7 +1443,7 @@ int hal_link(const char *pin_name, const char *sig_name) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: link called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -1252,12 +1464,12 @@ int hal_link(const char *pin_name, const char *sig_name) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: linking pin '%s' to '%s'\n", pin_name, sig_name); /* get mutex before accessing data structures */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* locate the pin */ pin = halpr_find_pin_by_name(pin_name); if (pin == NULL) { /* not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin '%s' not found\n", pin_name); return -EINVAL; @@ -1266,21 +1478,21 @@ int hal_link(const char *pin_name, const char *sig_name) sig = halpr_find_sig_by_name(sig_name); if (sig == NULL) { /* not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' not found\n", sig_name); return -EINVAL; } /* found both pin and signal, are they already connected? */ if (SHMPTR(pin->signal) == sig) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_WARN, "HAL: Warning: pin '%s' already linked to '%s'\n", pin_name, sig_name); return 0; } /* is the pin connected to something else? */ if(pin->signal) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); sig = SHMPTR(pin->signal); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin '%s' is linked to '%s', cannot link to '%s'\n", @@ -1289,7 +1501,7 @@ int hal_link(const char *pin_name, const char *sig_name) } /* check types */ if (pin->type != sig->type) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: type mismatch '%s' <- '%s'\n", pin_name, sig_name); return -EINVAL; @@ -1297,14 +1509,14 @@ int hal_link(const char *pin_name, const char *sig_name) /* linking output pin to sig that already has output or I/O pins? */ if ((pin->dir == HAL_OUT) && ((sig->writers > 0) || (sig->bidirs > 0 ))) { /* yes, can't do that */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' already has output or I/O pin(s)\n", sig_name); return -EINVAL; } /* linking bidir pin to sig that is a port?*/ if ((pin->dir == HAL_IO) && (pin->type == HAL_PORT)) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' is a port and cannot have I/O pin(s)\n", sig_name); return -EINVAL; @@ -1312,7 +1524,7 @@ int hal_link(const char *pin_name, const char *sig_name) /* linking bidir pin to sig that already has output pin? */ if ((pin->dir == HAL_IO) && (sig->writers > 0)) { /* yes, can't do that */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' already has output pin\n", sig_name); return -EINVAL; @@ -1321,7 +1533,7 @@ int hal_link(const char *pin_name, const char *sig_name) /* linking input pin to port sig that already has an input port? */ if ((pin->type == HAL_PORT) && (pin->dir == HAL_IN) && (sig->readers > 0)) { /* ports can only have one reader */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: signal '%s' can only have one input pin\n", sig_name); return -EINVAL; @@ -1350,7 +1562,7 @@ int hal_link(const char *pin_name, const char *sig_name) //*((hal_data_u *)data_addr) = pin->dummysig; switch (pin->type) { - case HAL_BIT: + case HAL_BOOL: *((hal_bit_t *) data_addr) = pin->dummysig.b; break; case HAL_S32: @@ -1359,13 +1571,13 @@ int hal_link(const char *pin_name, const char *sig_name) case HAL_U32: *((hal_u32_t *) data_addr) = pin->dummysig.u; break; - case HAL_S64: + case HAL_SINT: *((hal_s64_t *) data_addr) = pin->dummysig.s; break; - case HAL_U64: + case HAL_UINT: *((hal_u64_t *) data_addr) = pin->dummysig.u; break; - case HAL_FLOAT: + case HAL_REAL: *((hal_float_t *) data_addr) = pin->dummysig.f; break; default: @@ -1388,7 +1600,7 @@ int hal_link(const char *pin_name, const char *sig_name) /* and update the pin */ pin->signal = SHMOFF(sig); /* done, release the mutex and return */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -1399,7 +1611,7 @@ int hal_unlink(const char *pin_name) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: unlink called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -1415,12 +1627,12 @@ int hal_unlink(const char *pin_name) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: unlinking pin '%s'\n", pin_name); /* get mutex before accessing data structures */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* locate the pin */ pin = halpr_find_pin_by_name(pin_name); if (pin == NULL) { /* not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: pin '%s' not found\n", pin_name); return -EINVAL; @@ -1428,7 +1640,7 @@ int hal_unlink(const char *pin_name) /* found pin, unlink it */ unlink_pin(pin); /* done, release the mutex and return */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -1570,7 +1782,7 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param_new called before init\n"); - return -EINVAL; + return -EFAULT; } if (type != HAL_BIT && type != HAL_FLOAT && type != HAL_S32 && type != HAL_U32 && type != HAL_S64 && type != HAL_U64) { @@ -1598,12 +1810,12 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di rtapi_print_msg(RTAPI_MSG_DBG, "HAL: creating parameter '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* validate comp_id */ comp = halpr_find_comp_by_id(comp_id); if (comp == NULL) { /* bad comp_id */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; @@ -1611,7 +1823,7 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di // Already check duplicate before allocating if(halpr_find_param_by_name(name)) { // Duplicate parameter name - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate parameter '%s'\n", name); return -EINVAL; } @@ -1625,13 +1837,13 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di /* validate passed in pointer - must point to HAL shmem */ if (! SHMCHK(data_addr)) { /* bad pointer */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: data_addr not in shared memory\n"); return -EINVAL; } if(comp->ready) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param_new called after hal_ready\n"); return -EINVAL; @@ -1640,7 +1852,7 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di new = alloc_param_struct(); if (new == NULL) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for parameter '%s'\n", name); return -ENOMEM; @@ -1666,7 +1878,7 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di /* reached end of list, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } ptr = SHMPTR(next); @@ -1675,13 +1887,13 @@ static int hal_param_new_anyapi(const char *name, hal_type_t type, hal_pdir_t di /* found the right place for it, insert here */ new->next_ptr = next; *prev = SHMOFF(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } if (cmp == 0) { /* name already in list, can't insert */ free_param_struct(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate parameter '%s'\n", name); return -EINVAL; @@ -1732,7 +1944,7 @@ int hal_param_new_si32(int compid, hal_pdir_t dir, hal_sint_t *ref, rtapi_s32 de { va_list ap; va_start(ap, fmt); - int ret = hal_param_new_newapi(HAL_S32, dir, (void**)ref, compid, fmt, ap); + int ret = hal_param_new_newapi(HAL_S32, dir, ref, compid, fmt, ap); va_end(ap); if(ret) return ret; @@ -1744,7 +1956,7 @@ int hal_param_new_ui32(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_u32 de { va_list ap; va_start(ap, fmt); - int ret = hal_param_new_newapi(HAL_U32, dir, (void**)ref, compid, fmt, ap); + int ret = hal_param_new_newapi(HAL_U32, dir, ref, compid, fmt, ap); va_end(ap); if(ret) return ret; @@ -1756,7 +1968,7 @@ int hal_param_new_sint(int compid, hal_pdir_t dir, hal_sint_t *ref, rtapi_s64 de { va_list ap; va_start(ap, fmt); - int ret = hal_param_new_newapi(HAL_S64, dir, (void**)ref, compid, fmt, ap); + int ret = hal_param_new_newapi(HAL_S64, dir, ref, compid, fmt, ap); va_end(ap); if(ret) return ret; @@ -1768,7 +1980,7 @@ int hal_param_new_uint(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_u64 de { va_list ap; va_start(ap, fmt); - int ret = hal_param_new_newapi(HAL_U64, dir, (void**)ref, compid, fmt, ap); + int ret = hal_param_new_newapi(HAL_U64, dir, ref, compid, fmt, ap); va_end(ap); if(ret) return ret; @@ -1776,11 +1988,11 @@ int hal_param_new_uint(int compid, hal_pdir_t dir, hal_uint_t *ref, rtapi_u64 de return 0; } -int hal_param_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, real_t def, const char *fmt, ...) +int hal_param_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, rtapi_real def, const char *fmt, ...) { va_list ap; va_start(ap, fmt); - int ret = hal_param_new_newapi(HAL_FLOAT, dir, (void**)ref, compid, fmt, ap); + int ret = hal_param_new_newapi(HAL_FLOAT, dir, ref, compid, fmt, ap); va_end(ap); if(ret) return ret; @@ -1788,8 +2000,29 @@ int hal_param_new_real(int compid, hal_pdir_t dir, hal_real_t *ref, real_t def, return 0; } +// This is a special case for parameters, where you want them available, but +// not exposed. This is used in the stepgen component. +// We ensure a valid target for the pointer destination but do not have a name +// attached. The code can then use whatever type read/write and run. +int hal_param_new_fake(int compid, hal_refs_u *ref) +{ + (void)compid; + if(!ref) + return -EINVAL; + __hal_private_vals_u *ptr = hal_malloc(sizeof(*ptr)); + if(!ptr) + return -ENOMEM; + memset(ptr, 0, sizeof(*ptr)); + *(void **)ref = ptr; + return 0; +} + /* wrapper functs for typed params - these call the generic funct below */ +// We don't want our library to emit the deprecation warning. +// We already know it and need to provide them until removed. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" int hal_param_bit_set(const char *name, int value) { return hal_param_set(name, HAL_BIT, &value); @@ -1819,6 +2052,7 @@ int hal_param_s64_set(const char *name, signed long value) { return hal_param_set(name, HAL_S64, &value); } +#pragma GCC diagnostic pop /* this is a generic function that does the majority of the work */ @@ -1830,7 +2064,7 @@ int hal_param_set(const char *name, hal_type_t type, void *value_addr) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param_set called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_PARAMS) { @@ -1841,27 +2075,27 @@ int hal_param_set(const char *name, hal_type_t type, void *value_addr) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: setting parameter '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search param list for name */ param = halpr_find_param_by_name(name); if (param == NULL) { /* parameter not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: parameter '%s' not found\n", name); return -EINVAL; } /* found it, is type compatible? */ if (param->type != type) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: type mismatch setting param '%s'\n", name); return -EINVAL; } /* is it read only? */ if (param->dir == HAL_RO) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param '%s' is not writable\n", name); return -EINVAL; @@ -1893,12 +2127,12 @@ int hal_param_set(const char *name, hal_type_t type, void *value_addr) break; default: /* Shouldn't get here, but just in case... */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: bad type %d setting param\n", param->type); return -EINVAL; } - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -1912,7 +2146,7 @@ int hal_param_alias(const char *param_name, const char *alias) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param_alias called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -1927,11 +2161,11 @@ int hal_param_alias(const char *param_name, const char *alias) } } /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); if (alias != NULL ) { param = halpr_find_param_by_name(alias); if ( param != NULL ) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate pin/alias name '%s'\n", alias); return -EINVAL; @@ -1945,7 +2179,7 @@ int hal_param_alias(const char *param_name, const char *alias) to succeed since at least one struct is on the free list. */ oldname = halpr_alloc_oldname_struct(); if ( oldname == NULL ) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for param_alias\n"); return -EINVAL; @@ -1957,7 +2191,7 @@ int hal_param_alias(const char *param_name, const char *alias) while (1) { if (next == 0) { /* reached end of list, not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: param '%s' not found\n", param_name); return -EINVAL; @@ -2008,7 +2242,7 @@ int hal_param_alias(const char *param_name, const char *alias) /* reached end of list, insert here */ param->next_ptr = next; *prev = SHMOFF(param); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } ptr = SHMPTR(next); @@ -2017,7 +2251,7 @@ int hal_param_alias(const char *param_name, const char *alias) /* found the right place for it, insert here */ param->next_ptr = next; *prev = SHMOFF(param); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* didn't find it yet, look at next one */ @@ -2117,7 +2351,6 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), int cmp; hal_funct_t *new, *fptr; hal_comp_t *comp; - char buf[HAL_NAME_LEN + 1]; if (hal_data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -2138,25 +2371,25 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), rtapi_print_msg(RTAPI_MSG_DBG, "HAL: exporting function '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* validate comp_id */ comp = halpr_find_comp_by_id(comp_id); if (comp == 0) { /* bad comp_id */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d not found\n", comp_id); return -EINVAL; } - if (comp->type == COMPONENT_TYPE_USER) { + if (comp->type == HAL_COMP_TYPE_USER) { /* not a realtime component */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: component %d is not realtime\n", comp_id); return -EINVAL; } if(comp->ready) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: export_funct called after hal_ready\n"); return -EINVAL; @@ -2165,7 +2398,7 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), new = alloc_funct_struct(); if (new == 0) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for function '%s'\n", name); return -ENOMEM; @@ -2202,7 +2435,7 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), if (cmp == 0) { /* name already in list, can't insert */ free_funct_struct(new); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate function '%s'\n", name); return -EINVAL; @@ -2212,28 +2445,28 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), next = *prev; } /* at this point we have a new function and can yield the mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); /* create a pin with the function's runtime in it */ - if (hal_pin_s32_newf(HAL_OUT, &(new->runtime), comp_id,"%s.time",name)) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL: ERROR: fail to create pin '%s.time'\n", name); + if (hal_pin_new_si32(comp_id, HAL_OUT, &(new->runtime), 0, "%s.time", name) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create pin '%s.time'\n", name); return -EINVAL; } - *(new->runtime) = 0; /* note that failure to successfully create the following params does not cause the "export_funct()" call to fail - they are for debugging and testing use only */ /* create a parameter with the function's maximum runtime in it */ - rtapi_snprintf(buf, sizeof(buf), "%s.tmax", name); - new->maxtime = 0; - hal_param_s32_new(buf, HAL_RW, &(new->maxtime), comp_id); + if(hal_param_new_si32(comp_id, HAL_RW, &(new->maxtime), 0, "%s.tmax", name) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create param '%s.tmax'\n", name); + return -EINVAL; + } /* create a parameter with the function's maximum runtime in it */ - rtapi_snprintf(buf, sizeof(buf), "%s.tmax-increased", name); - new->maxtime_increased = 0; - hal_param_bit_new(buf, HAL_RO, &(new->maxtime_increased), comp_id); + if(hal_param_new_bool(comp_id, HAL_RO, &(new->maxtime_increased), 0, "%s.tmax-increased", name) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create param '%s.tmax-increased'\n", name); + return -EINVAL; + } return 0; } @@ -2252,7 +2485,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) if (hal_data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: create_thread called before init\n"); - return -EINVAL; + return -EFAULT; } if (period_nsec == 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -2272,7 +2505,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) } /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* make sure name is unique on thread list */ next = hal_data->thread_list_ptr; while (next != 0) { @@ -2280,10 +2513,10 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) cmp = strcmp(tptr->name, name); if (cmp == 0) { /* name already in list, can't insert */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: duplicate thread name %s\n", name); - return -EINVAL; + return -EEXIST; } /* didn't find it yet, look at next one */ next = tptr->next_ptr; @@ -2292,7 +2525,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) new = alloc_thread_struct(); if (new == 0) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory to create thread\n"); return -ENOMEM; @@ -2310,7 +2543,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) /* not running, start it */ curr_period = rtapi_clock_set_period(period_nsec); if (curr_period < 0) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: ERROR: clock_set_period returned %ld\n", curr_period); @@ -2319,7 +2552,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) } /* make sure period <= desired period (allow 1% roundoff error) */ if (curr_period > (long)(period_nsec + (period_nsec / 100))) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: ERROR: clock period too long: %ld\n", curr_period); return -EINVAL; @@ -2341,7 +2574,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) prev_priority = tptr->priority; } if ( (long)period_nsec < hal_data->base_period) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: ERROR: new thread period %ld is less than clock period %ld\n", period_nsec, hal_data->base_period); @@ -2351,7 +2584,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) n = (period_nsec + hal_data->base_period / 2) / hal_data->base_period; new->period = hal_data->base_period * n; if ( new->period < prev_period ) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: ERROR: new thread period %ld is less than existing thread period %ld\n", period_nsec, prev_period); @@ -2364,7 +2597,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) retval = rtapi_task_new(thread_task, new, new->priority, lib_module_id, HAL_STACKSIZE, 1); if (retval < 0) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: could not create task for thread %s\n", name); return -EINVAL; @@ -2373,7 +2606,7 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) /* start task */ retval = rtapi_task_start(new->task_id, new->period); if (retval < 0) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL_LIB: could not start task for thread %s: %d\n", name, retval); return -EINVAL; @@ -2381,31 +2614,44 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) /* insert new structure at head of list */ new->next_ptr = hal_data->thread_list_ptr; hal_data->thread_list_ptr = SHMOFF(new); + + // The counter that increases monotonically once every thread loop cycle. + // This is a 'fast' counter with normal access semantics. Separated from + // the param 'threadbeat' so it only needs to write _once_ to volatile + // memory instead of a very expensive read-modify-write cycle. + new->beatcnt = 0; + /* done, release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_snprintf(buf,sizeof(buf), HAL_PSEUDO_COMP_PREFIX"%s",new->name); // pseudo prefix new->comp_id = hal_init(buf); if (new->comp_id < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create pseudo comp for thread: '%s'\n", new->name); - return -EINVAL; + return new->comp_id; } - rtapi_snprintf(buf, sizeof(buf), "%s.tmax", new->name); - new->maxtime = 0; - if (hal_param_s32_new(buf, HAL_RW, &(new->maxtime), new->comp_id)) { + if ((retval = hal_param_new_si32(new->comp_id, HAL_RW, &(new->maxtime), 0, "%s.tmax", new->name)) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create param '%s.tmax'\n", new->name); - return -EINVAL; + return retval; } - if (hal_pin_s32_newf(HAL_OUT, &(new->runtime), new->comp_id,"%s.time",new->name)) { + if ((retval = hal_pin_new_si32(new->comp_id, HAL_OUT, &(new->runtime), 0, "%s.time", new->name)) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create pin '%s.time'\n", new->name); - return -EINVAL; + return retval; + } + + // A parameter that increases monotonically once every thread loop cycle. + // This way we can detect when a RT-cycle was completed from non-RT and + // prevent racy indeterministic sleep() constructs. + if((retval = hal_param_new_sint(new->comp_id, HAL_RO, &(new->threadbeat), 0, "%s.threadbeat", name)) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: fail to create param '%s.threadbeat'\n", name); + return retval; } - *(new->runtime) = 0; + hal_ready(new->comp_id); rtapi_print_msg(RTAPI_MSG_DBG, "HAL: thread created\n"); @@ -2420,7 +2666,7 @@ extern int hal_thread_delete(const char *name) if (hal_data == 0) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread_delete called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -2431,7 +2677,7 @@ extern int hal_thread_delete(const char *name) rtapi_print_msg(RTAPI_MSG_DBG, "HAL: deleting thread '%s'\n", name); /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* search for the signal */ prev = &(hal_data->thread_list_ptr); next = *prev; @@ -2447,7 +2693,7 @@ extern int hal_thread_delete(const char *name) /* and delete it */ free_thread_struct(thread); /* done */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* no match, try the next one */ @@ -2455,10 +2701,10 @@ extern int hal_thread_delete(const char *name) next = *prev; } /* if we get here, we didn't find a match */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread '%s' not found\n", name); - return -EINVAL; + return -ENOENT; } #endif /* RTAPI */ @@ -2474,7 +2720,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: add_funct called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -2487,25 +2733,25 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int "HAL: adding function '%s' to thread '%s'\n", funct_name, thread_name); /* get mutex before accessing data structures */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* make sure position is valid */ if (position == 0) { /* zero is not allowed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: bad position: 0\n"); return -EINVAL; } /* make sure we were given a function name */ if (funct_name == NULL) { /* no name supplied */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: missing function name\n"); return -EINVAL; } /* make sure we were given a thread name */ if (thread_name == NULL) { /* no name supplied */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: missing thread name\n"); return -EINVAL; } @@ -2513,14 +2759,14 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int funct = halpr_find_funct_by_name(funct_name); if (funct == NULL) { /* function not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: function '%s' not found\n", funct_name); return -EINVAL; } /* found the function, is it available? */ if ((funct->users > 0) && (funct->reentrant == 0)) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: function '%s' may only be added to one thread\n", funct_name); return -EINVAL; @@ -2529,7 +2775,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int thread = halpr_find_thread_by_name(thread_name); if (thread == NULL) { /* thread not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread '%s' not found\n", thread_name); return -EINVAL; @@ -2548,7 +2794,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int list_entry = list_next(list_entry); if (list_entry == list_root) { /* reached end of list */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: position '%d' is too high\n", position); return -EINVAL; @@ -2561,7 +2807,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int list_entry = list_prev(list_entry); if (list_entry == list_root) { /* reached end of list */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: position '%d' is too low\n", position); return -EINVAL; @@ -2574,7 +2820,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int funct_entry = alloc_funct_entry_struct(); if (funct_entry == NULL) { /* alloc failed */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for thread->function link\n"); return -ENOMEM; @@ -2587,7 +2833,7 @@ int hal_add_funct_to_thread(const char *funct_name, const char *thread_name, int list_add_after((hal_list_t *) funct_entry, list_entry); /* update the function usage count */ funct->users++; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -2602,7 +2848,7 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: init_funct called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -2626,29 +2872,29 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in "HAL: adding init function '%s' to thread '%s'\n", funct_name, thread_name); - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); funct = halpr_find_funct_by_name(funct_name); if (funct == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: function '%s' not found\n", funct_name); - return -EINVAL; + return -ENOENT; } thread = halpr_find_thread_by_name(thread_name); if (thread == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread '%s' not found\n", thread_name); - return -EINVAL; + return -ENOENT; } /* once the special init cycle has executed, further initf calls are a no-op so config order doesn't depend on whether start_threads has been issued. Surface this with -EALREADY so halcmd can warn loudly. */ if (thread->init_done) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_WARN, "HAL: WARNING: thread '%s' init cycle already ran; '%s' will not be invoked\n", thread_name, funct_name); @@ -2664,7 +2910,7 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in while (++n < position) { list_entry = list_next(list_entry); if (list_entry == list_root) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: position '%d' is too high\n", position); return -EINVAL; @@ -2674,7 +2920,7 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in while (--n > position) { list_entry = list_prev(list_entry); if (list_entry == list_root) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: position '%d' is too low\n", position); return -EINVAL; @@ -2687,7 +2933,7 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in referenced multiple times in the init list itself (no users-cap check) */ funct_entry = alloc_funct_entry_struct(); if (funct_entry == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: insufficient memory for thread->init function link\n"); return -ENOMEM; @@ -2700,7 +2946,7 @@ int hal_init_funct_to_thread(const char *funct_name, const char *thread_name, in funct->users++; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -2714,7 +2960,7 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: del_funct called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_CONFIG) { @@ -2727,18 +2973,18 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) "HAL: removing function '%s' from thread '%s'\n", funct_name, thread_name); /* get mutex before accessing data structures */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* make sure we were given a function name */ if (funct_name == NULL) { /* no name supplied */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: missing function name\n"); return -EINVAL; } /* make sure we were given a thread name */ if (thread_name == NULL) { /* no name supplied */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: missing thread name\n"); return -EINVAL; } @@ -2746,14 +2992,14 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) funct = halpr_find_funct_by_name(funct_name); if (funct == NULL) { /* function not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: function '%s' not found\n", funct_name); return -EINVAL; } /* found the function, is it in use? */ if (funct->users == 0) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: function '%s' is not in use\n", funct_name); return -EINVAL; @@ -2762,7 +3008,7 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) thread = halpr_find_thread_by_name(thread_name); if (thread == NULL) { /* thread not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread '%s' not found\n", thread_name); return -EINVAL; @@ -2773,7 +3019,7 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) while (1) { if (list_entry == list_root) { /* reached end of list, funct not found */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: thread '%s' doesn't use %s\n", thread_name, funct_name); @@ -2786,7 +3032,7 @@ int hal_del_funct_from_thread(const char *funct_name, const char *thread_name) /* and delete it */ free_funct_entry_struct(funct_entry); /* done */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } /* try next one */ @@ -2800,7 +3046,7 @@ int hal_start_threads(void) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: start_threads called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_RUN) { @@ -2821,7 +3067,7 @@ int hal_stop_threads(void) if (hal_data == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: stop_threads called before init\n"); - return -EINVAL; + return -EFAULT; } if (hal_data->lock & HAL_LOCK_RUN) { @@ -3298,7 +3544,7 @@ void rtapi_app_exit(void) rtapi_print_msg(RTAPI_MSG_DBG, "HAL_LIB: removing kernel lib\n"); hal_proc_clean(); /* grab mutex before manipulating list */ - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); /* must remove all threads before unloading this module */ while (hal_data->thread_list_ptr != 0) { /* point to a thread */ @@ -3309,7 +3555,7 @@ void rtapi_app_exit(void) free_thread_struct(thread); } /* release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); /* release RTAPI resources */ rtapi_shmem_delete(lib_mem_id, lib_module_id); rtapi_exit(lib_module_id); @@ -3376,12 +3622,12 @@ static void thread_task(void *arg) /* point to function structure */ funct = SHMPTR(funct_entry->funct_ptr); /* update execution time data */ - *(funct->runtime) = (hal_s32_t)(end_time - start_time); - if ( *(funct->runtime) > funct->maxtime) { - funct->maxtime = *(funct->runtime); - funct->maxtime_increased = 1; + rtapi_s32 runtime = hal_set_si32(funct->runtime, end_time - start_time); + if ( runtime > hal_get_si32(funct->maxtime)) { + hal_set_si32(funct->maxtime, runtime); + hal_set_bool(funct->maxtime_increased, 1); } else { - funct->maxtime_increased = 0; + hal_set_bool(funct->maxtime_increased, 0); } /* point to next next entry in list */ funct_entry = SHMPTR(funct_entry->links.next); @@ -3389,10 +3635,11 @@ static void thread_task(void *arg) start_time = end_time; } /* update thread execution time */ - *(thread->runtime) = (hal_s32_t)(end_time - thread_start_time); - if ( *(thread->runtime) > thread->maxtime) { - thread->maxtime = *(thread->runtime); + rtapi_s32 runtime = hal_set_si32(thread->runtime, end_time - thread_start_time); + if ( runtime > hal_get_si32(thread->maxtime)) { + hal_set_si32(thread->maxtime, runtime); } + hal_set_sint(thread->threadbeat, ++thread->beatcnt); } /* wait until next period */ rtapi_wait(); @@ -3408,23 +3655,25 @@ static int init_hal_data(void) { /* has the hal_data block already been initialized? */ - /* Lock hal_data by taking the mutex, so that two processes - don't both try to initialize hal_data at the same time. NOTE: - The first time through, the hal_data memory buffer is fresh from - rtapi_shmem_new(), which means it's initialized to all zero bytes. - This means hal_data->mutex is valid and unlocked. */ - rtapi_mutex_get(&(hal_data->mutex)); - + // Lock hal_data by taking the mutex, so that two processes don't both try + // to initialize hal_data at the same time. + // NOTE: The first time through, the hal_data memory buffer is fresh from + // rtapi_shmem_new(), which means it's initialized to all zero bytes. + // The used mutex in halpr_mutex_acquire()/halpr_mutex_release() uses a + // reversed default mutex, where zero means it is locked and non-zero when + // unlocked. This is required for recursive mutex functionality where the + // default is locked at init. + halpr_mutex_acquire(); if (hal_data->version != 0) { /* hal_data has been initialized already, verify version code */ if (hal_data->version == HAL_VER) { - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } else { + halpr_mutex_release(); rtapi_print("HAL: version:%d expected:%d\n",hal_data->version,HAL_VER); rtapi_print_msg(RTAPI_MSG_ERR, "HAL: ERROR: version code mismatch\n"); - rtapi_mutex_give(&(hal_data->mutex)); - return -1; + return -EPROTO; } } @@ -3458,7 +3707,7 @@ static int init_hal_data(void) hal_data->shmem_top = HAL_SIZE; hal_data->lock = HAL_LOCK_NONE; /* done, release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return 0; } @@ -3561,7 +3810,7 @@ hal_comp_t *halpr_alloc_comp_struct(void) p->next_ptr = 0; p->comp_id = 0; p->mem_id = 0; - p->type = COMPONENT_TYPE_USER; + p->type = HAL_COMP_TYPE_USER; p->shmem_base = NULL; p->name[0] = '\0'; } @@ -3829,7 +4078,7 @@ static void free_comp_struct(hal_comp_t * comp) /* clear contents of struct */ comp->comp_id = 0; comp->mem_id = 0; - comp->type = COMPONENT_TYPE_USER; + comp->type = HAL_COMP_TYPE_USER; comp->shmem_base = NULL; comp->name[0] = '\0'; /* add it to free list */ @@ -3859,7 +4108,7 @@ static void unlink_pin(hal_pin_t * pin) dummy_addr = (hal_data_u *)(hal_shmem_base + SHMOFF(&(pin->dummysig))); switch (pin->type) { - case HAL_BIT: + case HAL_BOOL: dummy_addr->b = sig_data_addr->b; break; case HAL_S32: @@ -3868,13 +4117,13 @@ static void unlink_pin(hal_pin_t * pin) case HAL_U32: dummy_addr->u = sig_data_addr->u; break; - case HAL_S64: + case HAL_SINT: dummy_addr->s = sig_data_addr->s; break; - case HAL_U64: + case HAL_UINT: dummy_addr->u = sig_data_addr->u; break; - case HAL_FLOAT: + case HAL_REAL: dummy_addr->f = sig_data_addr->f; break; case HAL_PORT: @@ -4229,7 +4478,15 @@ static bool hal_port_compute_copy(unsigned read, } -int hal_port_alloc(unsigned size, hal_port_t *port) { +// hal_port_alloc() is DEPRECATED +// Access to port allocation is done by hal_set_s() on the signal that has the +// port pins connected. +int hal_port_alloc(unsigned size, hal_port_t *port) +{ + return halpr_port_alloc(size, port); +} + +int halpr_port_alloc(unsigned size, hal_port_t *port) { if(!port || size < 1 || size > HAL_PORT_SIZE_MAX) return -EINVAL; @@ -4860,12 +5117,17 @@ int hal_stream_num_underruns(hal_stream_t *stream) /* only export symbols when we're building a kernel module */ EXPORT_SYMBOL(hal_init); +EXPORT_SYMBOL(hal_is_init); EXPORT_SYMBOL(hal_ready); EXPORT_SYMBOL(hal_set_unready); EXPORT_SYMBOL(hal_exit); EXPORT_SYMBOL(hal_malloc); EXPORT_SYMBOL(hal_comp_name); EXPORT_SYMBOL(hal_get_realtime_type); +EXPORT_SYMBOL(hal_strerror); + +EXPORT_SYMBOL(hal_reference_map); +EXPORT_SYMBOL(hal_reference_unmap); EXPORT_SYMBOL(hal_pin_new_bool); EXPORT_SYMBOL(hal_pin_new_si32); @@ -4873,7 +5135,7 @@ EXPORT_SYMBOL(hal_pin_new_ui32); EXPORT_SYMBOL(hal_pin_new_sint); EXPORT_SYMBOL(hal_pin_new_uint); EXPORT_SYMBOL(hal_pin_new_real); -//EXPORT_SYMBOL(hal_pin_new_port); +EXPORT_SYMBOL(hal_pin_new_port); EXPORT_SYMBOL(hal_pin_bit_new); EXPORT_SYMBOL(hal_pin_float_new); @@ -4919,7 +5181,10 @@ EXPORT_SYMBOL(hal_param_new_ui32); EXPORT_SYMBOL(hal_param_new_sint); EXPORT_SYMBOL(hal_param_new_uint); EXPORT_SYMBOL(hal_param_new_real); +EXPORT_SYMBOL(hal_param_new_fake); +// Parameter set functions have been deprecated. +// Use the generic hal_set_p() instead. EXPORT_SYMBOL(hal_param_bit_set); EXPORT_SYMBOL(hal_param_float_set); EXPORT_SYMBOL(hal_param_u32_set); @@ -4942,6 +5207,8 @@ EXPORT_SYMBOL(hal_del_funct_from_thread); EXPORT_SYMBOL(hal_start_threads); EXPORT_SYMBOL(hal_stop_threads); +// All HAL lib internals' access has bee deprecated. All function prefixed with +// halpr_ are only for private internal use. EXPORT_SYMBOL(hal_shmem_base); EXPORT_SYMBOL(halpr_find_comp_by_name); EXPORT_SYMBOL(halpr_find_pin_by_name); @@ -4960,7 +5227,7 @@ EXPORT_SYMBOL(halpr_find_pin_by_sig); EXPORT_SYMBOL(hal_pin_alias); EXPORT_SYMBOL(hal_param_alias); -EXPORT_SYMBOL(hal_port_alloc); +EXPORT_SYMBOL(hal_port_alloc); // Deprecated EXPORT_SYMBOL(hal_port_read); EXPORT_SYMBOL(hal_port_peek); EXPORT_SYMBOL(hal_port_peek_commit); diff --git a/src/hal/hal_lib_extra.c b/src/hal/hal_lib_extra.c new file mode 100644 index 00000000000..655bb414629 --- /dev/null +++ b/src/hal/hal_lib_extra.c @@ -0,0 +1,154 @@ +// +// HAL non-RT support API +// +// Copyright 2026 B.Stultiens +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of version 2 of the GNU General +// Public License as published by the Free Software Foundation. +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +#include "hal.h" +#include "hal_priv.h" + +// +// Allow user-land to forcefully release the HAL mutex. +// +// WARNING: This may crash the rest of the LCNC application(s). +// +int hal_mutex_force_release(void) +{ + if(!hal_data) { + // The HAL shared memory segment was not mapped, do so now + int comp_id = rtapi_init("hal_unlocker"); + if(comp_id < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "error: hal_mutex_force_release: rtapi_init failed\n"); + return comp_id; + } + int mem_id = rtapi_shmem_new(HAL_KEY, comp_id, HAL_SIZE); + if(mem_id < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "error: hal_mutex_force_release: could not open shared memory\n"); + rtapi_exit(comp_id); + return mem_id; + } + int rv = rtapi_shmem_getptr(mem_id, (void **)&hal_shmem_base); + if (rv < 0) { + hal_shmem_base = NULL; + rtapi_print_msg(RTAPI_MSG_ERR, "error: hal_mutex_force_release: could not access shared memory\n"); + rtapi_shmem_delete(mem_id, comp_id); + rtapi_exit(comp_id); + return rv; + } + hal_data = (hal_data_t *)hal_shmem_base; + + halpr_mutex_force_release(); + + // We're done, cleanup our mapping + rtapi_shmem_delete(mem_id, comp_id); + rtapi_exit(comp_id); + hal_data = NULL; + hal_shmem_base = NULL; + } else { + // We already have a mapped segment, use it + halpr_mutex_force_release(); + } + return 0; +} + +// +// HAL will pretend that the exact base period requested is possible. +// This mode is not suitable for running real hardware. +// Returns zero (0) on success or a negative -EACCES error if already set. +// +int hal_enforce_exact_base_period(void) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_DBG, "hal_enforce_exact_base_period: HAL shared memory not mapped\n"); + return -EFAULT; + } + halpr_mutex_acquire(); + if(0 != hal_data->exact_base_period) { + halpr_mutex_release(); + return -EACCES; + } + hal_data->exact_base_period = 1; + halpr_mutex_release(); + return 0; +} + +// Invoke the constructor for a new instance +int hal_comp_invoke_make(const char *compname, const char *newname, const char *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_DBG, "hal_invoke_make: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!compname || !newname || !arg) { + rtapi_print_msg(RTAPI_MSG_DBG, "hal_invoke_make: Invalid arguments\n"); + return -EINVAL; + } + + halpr_mutex_acquire(); + hal_comp_t *comp = halpr_find_comp_by_name(compname); + if(!comp) { + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_DBG, "hal_invoke_make: Component '%s' not found\n", compname); + return -ENOENT; + } + + if(!comp->make) { + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_DBG, "hal_invoke_make: Component '%s' has no contructor\n", compname); + return -ENOEXEC; + } + halpr_mutex_release(); + // This is a race, but only if the module gets unloaded before we call its + // constructor. Luckily, this is rather unlikely. However, the original in + // uspace_rtapi_main.cc:so_newinst_cmd() also had this race. It is unclear + // how it can be prevented. Unless we want to hold the mutex while the + // module calls hal_init() and creates pins and the like, which is not + // necessarily a good idea. But with the recursive mutex, it could be made + // working. + // The code assumes that the constructor is called from the rtapi_app + // context (which houses all uspace RT modules). If not, then the function + // pointer will point into the wrong context and a crash is expected. + return comp->make(newname, arg); +} + +// +// Set the insmod arguments in a named component +// This call is used when loading is (nearly) done +// +int hal_comp_insmod_args(const char *compname, const char *args) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_DBG, "hal_comp_insmod_args: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!compname || !args) { + rtapi_print_msg(RTAPI_MSG_DBG, "hal_comp_insmod_args: Invalid arguments\n"); + return -EINVAL; + } + if(!SHMCHK(args)) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_comp_insmod_args: 'args' not in HAL memory\n"); + return -EINVAL; + } + + halpr_mutex_acquire(); + hal_comp_t *comp = halpr_find_comp_by_name(compname); + if(!comp) { + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_DBG, "hal_comp_insmod_args: Component '%s' not found\n", compname); + return -ENOENT; + } + comp->insmod_args = SHMOFF(args); + halpr_mutex_release(); + return 0; +} diff --git a/src/hal/hal_lib_query.c b/src/hal/hal_lib_query.c new file mode 100644 index 00000000000..d1c24e6fdb6 --- /dev/null +++ b/src/hal/hal_lib_query.c @@ -0,0 +1,1097 @@ +// +// HAL non-RT query API +// +// Copyright 2026 B.Stultiens +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of version 2 of the GNU General +// Public License as published by the Free Software Foundation. +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +#include "hal.h" +#include "hal_priv.h" + +//===================================================== +// +// HAL query API implementation of gets/sets and getp/setp +// +// Additionally adds retrieving the pin/param/signal +// reference for reading and writing using hal_getref_[ps]. +// +// Replaces all (re-)implementations in other programs as +// one standard and unified API. +// +// NOTE: This API is not exported in the kernel. +// It is a user-land thing and should only +// be called from non-RT applications. +// +// Additional hal_list_* code implements iteration of all HAL +// structures with a callback provided for user code to do +// extract any data how it seems fit. +// +//===================================================== + +static int set_common(hal_type_t type, const hal_query_value_u *v, hal_refs_u u, bool setport, bool isparam) +{ + // This is a special case because compatibility requires us to write to the + // smaller field when addressing paramaters. A param has a user-defined + // storage that may be not large enough for many types and would overwrite + // other memory. + // This code must be retired when we do the API break. + if(isparam) { + switch(type) { + case HAL_BOOL: ((hal_data_u *)u.b)->b = v->b; break; + case HAL_S32: ((hal_data_u *)u.s)->s = v->s; break; + case HAL_U32: ((hal_data_u *)u.u)->u = v->u; break; + case HAL_SINT: ((hal_data_u *)u.s)->ls = v->s; break; + case HAL_UINT: ((hal_data_u *)u.u)->lu = v->u; break; + case HAL_REAL: ((hal_data_u *)u.r)->f = v->r; break; + default: + case HAL_PORT: return -EBADF; + } + return 0; + } + switch(type) { + case HAL_BOOL: hal_set_bool(u.b, v->b); break; + case HAL_S32: hal_set_si32(u.s, v->s); break; + case HAL_U32: hal_set_ui32(u.u, v->u); break; + case HAL_SINT: hal_set_sint(u.s, v->s); break; + case HAL_UINT: hal_set_uint(u.u, v->u); break; + case HAL_REAL: hal_set_real(u.r, v->r); break; + case HAL_PORT: { + if(!setport) + return -EBADF; + // FIXME: This needs to be changed when the old API is removed + rtapi_port port = hal_get_sint(u.s); + if(0 != port && hal_port_buffer_size((hal_port_t *)u.s) > 0) { + return -EISCONN; + } + int rv = halpr_port_alloc(v->u, (hal_port_t *)u.s); + if(rv) + return rv; + } break; + default: + return -EBADF; + } + return 0; +} + +// +// hal_set_s() - Set the value of a signal +// +// Query inputs: +// q->name - Signal to set +// q->sig.type - Optional: must match specific HAL_X type +// The q->sig.value must be set to the proper value, +// which will be used, if there is no callback set. +// q->sig.value - Mandatory if no callback is specified. +// +int hal_set_s(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_s: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_s: Invalid query arguments\n"); + return -EINVAL; + } + if(0 == q->sig.type && !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_s: Must have callback if type is not specified\n"); + return -EINVAL; + } + + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_type_t qtp = q->sig.type; // Save original request signal type + hal_sig_t *sig = halpr_find_sig_by_name(q->name); + if(!sig) { + // Signal name not found + halpr_mutex_release(); + return -ENOENT; + } + if(!sig->data_ptr) { + // Signal's data pointer is invalid + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_s: Signal '%s' has no data target\n", q->name); + return -EIO; + } + if(HAL_PORT != sig->type && sig->writers > 0) { + // Signal is not a port and has writers + halpr_mutex_release(); + return -EACCES; + } + + // Setup callback data + q->qtype = HAL_QTYPE_SIGNAL; // Handling a signal + q->name = sig->name; + q->sig.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + q->sig.type = sig->type; // of this type + q->sig.writers = sig->writers; // Signals have no direction + q->sig.readers = sig->readers; // Signals have no alias + q->sig.bidirs = sig->bidirs; // Only relevant for pins + + if(0 != qtp && qtp != sig->type) { + // Specific type requested and it didn't match + halpr_mutex_release(); + return -EEXIST; + } + + int rv = cb ? cb(q, arg) : 0; // Callback to get the value + + if(!rv) { + // Success, data to write must be in the value union + hal_refs_u u = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + if((rv = set_common(sig->type, &q->sig.value, u, 1, 0)) < 0) { + halpr_mutex_release(); + if(-EBADF == rv) + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_s: Signal '%s' has bad type %d\n", q->name, sig->type); + return rv; + } + } // else something went wrong in the callback + + halpr_mutex_release(); + return rv; +} + +// +// hal_set_p() - Set the value of a pin/param +// +// Returns an error if it matches a pin and it is connected. +// +// Query inputs: +// q->name - Pin/param to set +// q->qtype - Optional: HAL_QTYPE_PIN or HAL_QTYPE_PARAM to limit type +// q->pp.type - Optional: must match specific HAL_X type +// The q->pp.value must be set to the proper value, +// which will be used, if there is no callback set. +// q->pp.value - Mandatory if no callback is specified. +// +int hal_set_p(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_p: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_p: Invalid query arguments\n"); + return -EINVAL; + } + if(0 == q->pp.type && !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_p: Must have callback if type is not specified\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_type_t qtp = q->pp.type; // Save original request pin/param type + hal_type_t t; + hal_pin_t *pin = NULL; + hal_refs_u u; + bool isparam; + // If only parameters requested, don't look for pins + if(HAL_QTYPE_PARAM != q->qtype) + pin = halpr_find_pin_by_name(q->name); + if(!pin) { + if(HAL_QTYPE_PIN == q->qtype) { + // Only pin search requested and it was not found + halpr_mutex_release(); + return -ENOENT; + } + // Not a pin, try param + hal_param_t *param = halpr_find_param_by_name(q->name); + if(!param) { + // Neither pin nor param name found + halpr_mutex_release(); + return -ENOENT; + } + // We have the param, copy the data, but we still can fail + q->qtype = HAL_QTYPE_PARAM; + q->name = param->name; + q->pp.type = t = param->type; + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(param->data_ptr); + q->pp.dir = param->dir; + q->pp.alias = param->oldname ? ((hal_oldname_t *)SHMPTR(param->oldname))->name : NULL; + q->pp.signal = NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(param->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + + if(0 != qtp && qtp != param->type) { + // Specific type requested and it didn't match + halpr_mutex_release(); + return -EEXIST; + } + if(HAL_RO == param->dir) { + // Param not writable + halpr_mutex_release(); + return -EACCES; + } + if(!param->data_ptr) { + // Param's data pointer is invalid + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_p: Param '%s' has no data target\n", q->name); + return -EIO; + } + // FIXME: This can be targeted to param's data when the old API is retired + u = (hal_refs_u)(hal_sint_t)SHMPTR(param->data_ptr); + isparam = 1; + } else { + // We have a pin, copy the data, but we still can fail + q->qtype = HAL_QTYPE_PIN; + q->name = pin->name; + q->pp.type = t = pin->type; + q->pp.ref = (hal_refs_u)(hal_sint_t)&pin->dummysig; + q->pp.dir = pin->dir; + q->pp.alias = pin->oldname ? ((hal_oldname_t *)SHMPTR(pin->oldname))->name : NULL; + q->pp.signal = NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(pin->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + + // We still record the signal, even if we fail to write + if(0 != pin->signal) { + hal_sig_t *sig = (hal_sig_t *)SHMPTR(pin->signal); + q->pp.signal = sig->name; + } + if(0 != qtp && qtp != pin->type) { + // Specific type requested and it didn't match + halpr_mutex_release(); + return -EEXIST; + } + if(HAL_OUT == pin->dir || 0 != pin->signal) { + // Pin not writable + halpr_mutex_release(); + return -EACCES; + } + u = (hal_refs_u)(hal_sint_t)&pin->dummysig; + isparam = 0; + } + + // Note: the callback is called while holding the mutex + int rv = cb ? cb(q, arg) : 0; // Callback to get the value + + if(!rv) { + // Success, data to write must be in the value union + if((rv = set_common(t, &q->pp.value, u, 0, isparam)) < 0) { + halpr_mutex_release(); + if(-EBADF == rv) + rtapi_print_msg(RTAPI_MSG_ERR, "hal_set_p: %s '%s' has bad type %d\n", pin ? "Pin" : "Param", q->name, t); + return rv; + } + } // else something went wrong in the callback + + halpr_mutex_release(); + return rv; +} + +static int get_common(hal_type_t type, hal_query_value_u *v, hal_refs_u u, bool getport) +{ + switch(type) { + case HAL_BOOL: v->b = hal_get_bool(u.b); break; + case HAL_S32: v->s = hal_get_si32(u.s); break; + case HAL_U32: v->u = hal_get_ui32(u.u); break; + case HAL_SINT: v->s = hal_get_sint(u.s); break; + case HAL_UINT: v->u = hal_get_uint(u.u); break; + case HAL_REAL: v->r = hal_get_real(u.r); break; + case HAL_PORT: + if(!getport) { + v->u = 0; + } else { + // FIXME: This needs to be changed when the old API is removed + v->u = hal_port_buffer_size((hal_port_t *)u.s); + } + break; + default: + return -EBADF; + } + return 0; +} + +// +// hal_get_s() - Retrieve the value of a signal +// +// Query inputs: +// q->name - Signal to get +// q->sig.type - Optional: must match specific HAL_X type +// +int hal_get_s(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_get_s: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_get_s: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_type_t qtp = q->sig.type; // Save original request signal type + hal_sig_t *sig = halpr_find_sig_by_name(q->name); + if(!sig) { + // No signal by that name found + halpr_mutex_release(); + return -ENOENT; + } + if(!sig->data_ptr) { + // Signal's data pointer is invalid + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_ERR, "hal_get_s: Signal '%s' has no data target\n", q->name); + return -EIO; + } + q->qtype = HAL_QTYPE_SIGNAL; + q->name = sig->name; + q->sig.type = sig->type; + q->sig.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + q->sig.writers = sig->writers; + q->sig.readers = sig->readers; + q->sig.bidirs = sig->bidirs; + + // We have the primary data copied, but fail if there is a type mismatch. + if(0 != qtp && qtp != sig->type) { + // A specific signal type was requested and it didn't match + halpr_mutex_release(); + return -EEXIST; + } + int rv = get_common(sig->type, &q->sig.value, q->sig.ref, 1); + if(!rv && cb) + rv = cb(q, arg); + halpr_mutex_release(); + return rv; +} + +// +// hal_get_p() - Retrieve the value of a pin/param +// +// Returns the signal's value if a pin matches and it is connected. +// +// Query inputs: +// q->name - Pin/param to get +// q->qtype - Optional: HAL_QTYPE_PIN or HAL_QTYPE_PARAM to limit type +// q->pp.type - Optional: must match specific HAL_X type +// +int hal_get_p(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_get_p: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_get_p: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_type_t qtp = q->pp.type; // Save original request pin/param type + hal_type_t t; + hal_refs_u u; + hal_pin_t *pin = NULL; + // Only search for pins when requested + if(HAL_QTYPE_PARAM != q->qtype) + pin = halpr_find_pin_by_name(q->name); + if(!pin) { + if(HAL_QTYPE_PIN == q->qtype) { + // Only pin search requested and it was not found + halpr_mutex_release(); + return -ENOENT; + } + // Not a pin, try param + hal_param_t *param = halpr_find_param_by_name(q->name); + if(!param) { + // Neither pin nor param name found + halpr_mutex_release(); + return -ENOENT; + } + // We have the param, copy the data + q->qtype = HAL_QTYPE_PARAM; + q->name = param->name; + q->pp.type = t = param->type; + // FIXME: This can be targeted to param's data when the old API is retired + q->pp.ref = u = (hal_refs_u)(hal_sint_t)SHMPTR(param->data_ptr); + q->pp.dir = param->dir; + q->pp.alias = param->oldname ? ((hal_oldname_t *)SHMPTR(param->oldname))->name : NULL; + q->pp.signal = NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(param->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + } else { + // We have the pin, copy the data + q->qtype = HAL_QTYPE_PIN; + q->name = pin->name; + q->pp.type = t = pin->type; + q->pp.dir = pin->dir; + q->pp.alias = pin->oldname ? ((hal_oldname_t *)SHMPTR(pin->oldname))->name : NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(pin->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + if(0 != pin->signal) { + // Pin is connected, use the signal value + hal_sig_t *sig = (hal_sig_t *)SHMPTR(pin->signal); + q->pp.ref = u = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + q->pp.signal = sig->name; + } else { + // Unconnected, use the dummy value + q->pp.ref = u = (hal_refs_u)(hal_sint_t)&pin->dummysig; + q->pp.signal = NULL; + } + } + + // We have the primary data copied, but fail if there is a type mismatch. + if(0 != qtp && qtp != t) { + // Specific type requested and it didn't match + halpr_mutex_release(); + return -EEXIST; + } + + int rv = get_common(t, &q->pp.value, u, 0); + if(!rv && cb) + rv = cb(q, arg); + halpr_mutex_release(); + return rv; +} + +// +// hal_getref_s() - Retrieve the pin reference to read/write the signal +// +// Query inputs: +// q->name - Signal to get +// +int hal_getref_s(hal_query_t *q) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_s: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_s: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_sig_t *sig = halpr_find_sig_by_name(q->name); + if(!sig) { + // Signal name not found + halpr_mutex_release(); + return -ENOENT; + } + if(!sig->data_ptr) { + // Signal's data pointer is invalid + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_s: Signal '%s' has no data target\n", q->name); + return -EIO; + } + // We have a signal. We don't really care whether it is writable or + // readable. That is the caller's responsibility. This API is rather + // low-level and only hides the HAL private stuff. The data access is + // public as long as you use the hal_[gs]et_xxxx() interface. + // Setup return data + q->qtype = HAL_QTYPE_SIGNAL; // Handling a signal + q->name = sig->name; + q->sig.type = sig->type; // of this type + q->sig.writers = sig->writers; + q->sig.readers = sig->readers; + q->sig.bidirs = sig->bidirs; + q->sig.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + halpr_mutex_release(); + return 0; +} + +// +// hal_getref_p() - Retrieve the pin reference to read/write the pin/param +// +// It will return the signal reference if the pin is connected. +// +// Query inputs: +// q->name - Pin/param to get +// +int hal_getref_p(hal_query_t *q) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_p: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_p: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_pin_t *pin = NULL; + // If only parameters requested, don't look for pins + if(q->qtype != HAL_QTYPE_PARAM) + pin = halpr_find_pin_by_name(q->name); + if(!pin) { + if(q->qtype == HAL_QTYPE_PIN) { + // Only pin search requested and it was not found + halpr_mutex_release(); + return -ENOENT; + } + // Not a pin, try param + hal_param_t *param = halpr_find_param_by_name(q->name); + if(!param) { + // Neither pin nor param name found + halpr_mutex_release(); + return -ENOENT; + } + // We have the param, copy the data, but we still can fail + q->qtype = HAL_QTYPE_PARAM; + q->name = param->name; + q->pp.type = param->type; + q->pp.dir = param->dir; + q->pp.alias = param->oldname ? ((hal_oldname_t *)SHMPTR(param->oldname))->name : NULL; + q->pp.signal = NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(param->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + + if(!param->data_ptr) { + // Param's data pointer is invalid + halpr_mutex_release(); + rtapi_print_msg(RTAPI_MSG_ERR, "hal_getref_p: Param '%s' has no data target\n", q->name); + return -EIO; + } + // FIXME: This can be targeted to param's data when the old API is retired + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(param->data_ptr); + } else { + // We have a pin, copy the data + q->qtype = HAL_QTYPE_PIN; + q->name = pin->name; + q->pp.type = pin->type; + q->pp.dir = pin->dir; + q->pp.alias = pin->oldname ? ((hal_oldname_t *)SHMPTR(pin->oldname))->name : NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(pin->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + + if(0 != pin->signal) { + // The pin is connected, return the signal ref + hal_sig_t *sig = (hal_sig_t *)SHMPTR(pin->signal); + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + q->pp.signal = sig->name; + } else { + // Just the dummy value + q->pp.ref = (hal_refs_u)(hal_sint_t)&pin->dummysig; + q->pp.signal = NULL; + } + } + + halpr_mutex_release(); + return 0; +} + +// +// Iterate all pins/params with a callback +// +// Query inputs: +// q->qtype - Optional: HAL_QTYPE_PIN or HAL_QTYPE_PARAM to limit type +// +int hal_list_p(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_p: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !cb || (0 != q->qtype && !(HAL_QTYPE_PIN == q->qtype || HAL_QTYPE_PARAM == q->qtype))) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_p: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_qtype_t qtype = q->qtype; // Need to cache because field is reused + + // FIXME: this can be mostly merged once we merge pin/param structures + if(!qtype || HAL_QTYPE_PIN == qtype) { + rtapi_intptr_t pinref = hal_data->pin_list_ptr; + while(pinref) { + hal_pin_t *pin = (hal_pin_t *)SHMPTR(pinref); + q->name = pin->name; + q->qtype = HAL_QTYPE_PIN; + q->pp.type = pin->type; + q->pp.dir = pin->dir; + q->pp.alias = pin->oldname ? ((hal_oldname_t *)SHMPTR(pin->oldname))->name : NULL; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(pin->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + if(pin->signal) { + hal_sig_t *sig = (hal_sig_t *)SHMPTR(pin->signal); + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + q->pp.signal = sig->name; + } else { + q->pp.ref = (hal_refs_u)(hal_sint_t)&pin->dummysig; + q->pp.signal = NULL; + } + int rv = get_common(q->pp.type, &q->pp.value, q->pp.ref, 0); + if(0 != rv) { + // Non-zero return from get_common means inconsistent pin + halpr_mutex_release(); + return rv; + } + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + halpr_mutex_release(); + return rv; + } + pinref = pin->next_ptr; + } + } + if(!qtype || HAL_QTYPE_PARAM == qtype) { + rtapi_intptr_t paramref = hal_data->param_list_ptr; + while(paramref) { + hal_param_t *param = (hal_param_t *)SHMPTR(paramref); + q->name = param->name; + q->qtype = HAL_QTYPE_PARAM; + q->pp.type = param->type; + q->pp.dir = param->dir; + q->pp.alias = param->oldname ? ((hal_oldname_t *)SHMPTR(param->oldname))->name : NULL; + q->pp.signal = NULL; + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(param->data_ptr); + hal_comp_t *comp = (hal_comp_t *)SHMPTR(param->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + int rv = get_common(q->pp.type, &q->pp.value, q->pp.ref, 0); + if(0 != rv) { + // Non-zero return from get_common means inconsistent param + halpr_mutex_release(); + return rv; + } + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + halpr_mutex_release(); + return rv; + } + paramref = param->next_ptr; + } + } + + halpr_mutex_release(); + return 0; +} + +// +// Iterate all pins and find those connected to the signal specified +// +// Query inputs: +// q->name - Signal to search for +// +int hal_list_p_s(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_p_s: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !q->name || !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_p_s: Invalid query arguments\n"); + return -EINVAL; + } + + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + hal_sig_t *sig = halpr_find_sig_by_name(q->name); + if(!sig) { + halpr_mutex_release(); + return -ENOENT; // Signal not found + } + + int rv = 0; + hal_pin_t *pin = halpr_find_pin_by_sig(sig, NULL); // Find first + while(NULL != pin) { + q->name = pin->name; + q->qtype = HAL_QTYPE_PIN; + q->pp.type = pin->type; + q->pp.dir = pin->dir; + q->pp.alias = pin->oldname ? ((hal_oldname_t *)SHMPTR(pin->oldname))->name : NULL; + q->pp.signal = sig->name; + q->pp.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + hal_comp_t *comp = (hal_comp_t *)SHMPTR(pin->owner_ptr); + q->pp.comp = comp->name; + q->pp.comp_id = comp->comp_id; + + rv = get_common(q->pp.type, &q->pp.value, q->pp.ref, 0); + if(0 != rv) { + // Non-zero return from get_common means inconsistent pin + break; + } + if(0 != (rv = cb(q, arg))) { + // Callback requested exit + break; + } + pin = halpr_find_pin_by_sig(sig, pin); // Find next + } + + halpr_mutex_release(); + return rv; +} + +// +// Iterate all signals with a callback +// +// Query inputs: None +// +int hal_list_s(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_s: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_s: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + int rv = 0; + rtapi_intptr_t sigref = hal_data->sig_list_ptr; + while(sigref) { + hal_sig_t *sig = (hal_sig_t *)SHMPTR(sigref); + q->name = sig->name; + q->qtype = HAL_QTYPE_SIGNAL; + q->sig.type = sig->type; + q->sig.writers = sig->writers; + q->sig.readers = sig->readers; + q->sig.bidirs = sig->bidirs; + // If someone wants to find the connected pins, then call + // hal_list_p_s() to get the full list. + q->sig.ref = (hal_refs_u)(hal_sint_t)SHMPTR(sig->data_ptr); + rv = get_common(q->sig.type, &q->sig.value, q->sig.ref, 1); + if(0 != rv) { + // Non-zero return from get_common means inconsistent signal + break; + } + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + break; + } + sigref = sig->next_ptr; + } + + halpr_mutex_release(); + return rv; +} + +// +// Iterate all components with a callback +// +// Query inputs: None +// +int hal_list_comp(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_comp: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_comp: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + int rv = 0; + rtapi_intptr_t compref = hal_data->comp_list_ptr; + while(compref) { + hal_comp_t *comp = (hal_comp_t *)SHMPTR(compref); + q->name = comp->name; + q->qtype = HAL_QTYPE_COMP; + q->comp.type = comp->type; + q->comp.comp_id = comp->comp_id; + q->comp.pid = comp->pid; + q->comp.ready = !!comp->ready; + q->comp.insmod = comp->insmod_args ? (const char *)SHMPTR(comp->insmod_args) : NULL; + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + break; + } + compref = comp->next_ptr; + } + + halpr_mutex_release(); + return rv; +} + +// +// Iterate all functions with a callback +// +// Query inputs: None +// +int hal_list_funct(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_funct: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_funct: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + int rv = 0; + rtapi_intptr_t functref = hal_data->funct_list_ptr; + while(functref) { + hal_funct_t *funct = (hal_funct_t *)SHMPTR(functref); + q->name = funct->name; + q->qtype = HAL_QTYPE_FUNCT; + hal_comp_t *comp = (hal_comp_t *)SHMPTR(funct->owner_ptr); + q->funct.comp_id = comp->comp_id; + q->funct.comp = comp->name; + q->funct.users = funct->users; + q->funct.arg = (rtapi_intptr_t)funct->arg; // Purely informational + q->funct.funct = (rtapi_intptr_t)funct->funct; // Purely informational + q->funct.reentrant = !!funct->reentrant; + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + break; + } + functref = funct->next_ptr; + } + + halpr_mutex_release(); + return rv; +} + +// +// Iterate all threads with a callback +// +// Query inputs: +// q->qtype - Optional: HAL_QTYPE_THREAD to only iterate threads or +// HAL_QTYPE_THREAD_FUNCT to iterate threads *and* the functions +// attached to the thread. +// +// Iteration of threads and its functions will call the callback with the +// thread's name first and the q->qtype set to HAL_QTYPE_THREAD. Then it will +// call the callback with q->qtype set to HAL_QTYPE_THREAD_FUNCT for each +// function attached to the thread. +// +int hal_list_thread(hal_query_t *q, hal_query_cb cb, void *arg) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_thread: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!q || !cb) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_list_thread: Invalid query arguments\n"); + return -EINVAL; + } + bool dofuncts = q->qtype == HAL_QTYPE_THREAD_FUNCT; + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + + int rv = 0; + rtapi_intptr_t threadref = hal_data->thread_list_ptr; + while(threadref) { + hal_thread_t *thread = (hal_thread_t *)SHMPTR(threadref); + q->name = thread->name; + q->thread.comp_id = thread->comp_id; + hal_comp_t *comp = halpr_find_comp_by_id(thread->comp_id); + const char *compname = comp ? comp->name : "?"; + q->thread.comp = compname; + q->thread.priority = thread->priority; + q->thread.period = thread->period; + q->thread.functidx = 0; + q->thread.funct = NULL; + q->thread.is_init = 0; + q->qtype = HAL_QTYPE_THREAD; + // Callback on the thread + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback breaks the loop and we're done + break; + } + if(dofuncts) { + // Callback on the thread's normal functions + hal_funct_entry_t *froot = (hal_funct_entry_t *)&thread->funct_list; + hal_funct_entry_t *entry = (hal_funct_entry_t *)SHMPTR(froot->links.next); + for(int cnt = 0; entry != froot; cnt++) { + hal_funct_t *funct = (hal_funct_t *)SHMPTR(entry->funct_ptr); + // Make sure all data is set + q->name = thread->name; + q->thread.comp_id = thread->comp_id; + q->thread.comp = compname; + q->thread.priority = thread->priority; + q->thread.period = thread->period; + // Function level data + q->qtype = HAL_QTYPE_THREAD_FUNCT; + q->thread.functidx = cnt; + q->thread.funct = funct->name; + q->thread.is_init = 0; + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback quits and we're done + halpr_mutex_release(); + return rv; + } + entry = (hal_funct_entry_t *)SHMPTR(entry->links.next); + } + // Callback on the thread's init functions + froot = (hal_funct_entry_t *)&thread->init_funct_list; + entry = (hal_funct_entry_t *)SHMPTR(froot->links.next); + for(int cnt = 0; entry != froot; cnt++) { + hal_funct_t *funct = (hal_funct_t *)SHMPTR(entry->funct_ptr); + // Make sure all data is set + q->name = thread->name; + q->thread.comp_id = thread->comp_id; + q->thread.comp = compname; + q->thread.priority = thread->priority; + q->thread.period = thread->period; + // Function level data + q->qtype = HAL_QTYPE_THREAD_FUNCT; + q->thread.functidx = cnt; + q->thread.funct = funct->name; + q->thread.is_init = 1; + if(0 != (rv = cb(q, arg))) { + // Non-zero return from the callback quits and we're done + halpr_mutex_release(); + return rv; + } + entry = (hal_funct_entry_t *)SHMPTR(entry->links.next); + } + } + threadref = thread->next_ptr; + } + + halpr_mutex_release(); + return rv; +} + +// +// Return HAL statistics +// +static int count_list(rtapi_intptr_t ptr) +{ + int n = 0; + while(0 != ptr) { + n++; + // The first field in the structure is the 'next_ptr' field + ptr = *((rtapi_intptr_t *)SHMPTR(ptr)); + } + return n; +} + +int hal_statistics(hal_statistics_t *sts) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_statistics: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!sts) { + return -EINVAL; + } + // Grab the mutex to keep the data stable + // (list access and iteration may otherwise fail) + halpr_mutex_acquire(); + + sts->mem_total = HAL_SIZE; + sts->mem_free = hal_data->shmem_avail; + + sts->ncomps = count_list(hal_data->comp_list_ptr); + sts->ncomps_free = count_list(hal_data->comp_free_ptr); + sts->nsignals = count_list(hal_data->sig_list_ptr); + sts->nsignals_free = count_list(hal_data->sig_free_ptr); + sts->nfuncts = count_list(hal_data->funct_list_ptr); + sts->nfuncts_free = count_list(hal_data->funct_free_ptr); + sts->nthreads = count_list(hal_data->thread_list_ptr); + sts->nthreads_free = count_list(hal_data->thread_free_ptr); + + // Count pins, params and aliases in use + int nalias = 0; + int npin = 0; + int nparam = 0; + rtapi_intptr_t ptr = hal_data->pin_list_ptr; + while(0 != ptr) { + npin++; + hal_pin_t *pin = (hal_pin_t *)SHMPTR(ptr); + if(0 != pin->oldname) + nalias++; + ptr = pin->next_ptr; + } + ptr = hal_data->param_list_ptr; + while(0 != ptr) { + nparam++; + hal_param_t *param = (hal_param_t *)SHMPTR(ptr); + if(0 != param->oldname) + nalias++; + ptr = param->next_ptr; + } + sts->naliases = nalias; + sts->naliases_free = count_list(hal_data->oldname_free_ptr); + sts->npins = npin; + sts->npins_free = count_list(hal_data->pin_free_ptr); + sts->nparams = nparam; + sts->nparams_free = count_list(hal_data->param_free_ptr); + + halpr_mutex_release(); + return 0; +} + +// +// Return the status of a component by ID +// +int hal_comp_by_id(int comp_id, hal_query_t *q) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_comp_by_id: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(comp_id <= 0) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_comp_by_id: Invalid query arguments\n"); + return -EINVAL; + } + // Grab the mutex to keep the data stable + halpr_mutex_acquire(); + hal_comp_t *comp = halpr_find_comp_by_id(comp_id); + + if(NULL != comp && NULL != q) { + q->name = comp->name; + q->qtype = HAL_QTYPE_COMP; + q->comp.type = comp->type; + q->comp.comp_id = comp->comp_id; + q->comp.pid = comp->pid; + q->comp.ready = !!comp->ready; + q->comp.insmod = comp->insmod_args ? (const char *)SHMPTR(comp->insmod_args) : NULL; + } + halpr_mutex_release(); + return NULL != comp ? 0 : -ENOENT; +} + +// +// Return the status of a named component +// +int hal_comp_by_name(const char *name, hal_query_t *q) +{ + if(NULL == hal_data) { + rtapi_print_msg(RTAPI_MSG_ERR, "hal_comp_by_name: HAL shared memory not mapped\n"); + return -EFAULT; + } + if(!name) { + return -EINVAL; + } + halpr_mutex_acquire(); + hal_comp_t *comp = halpr_find_comp_by_name(name); + + if(NULL != comp && NULL != q) { + q->name = comp->name; + q->qtype = HAL_QTYPE_COMP; + q->comp.type = comp->type; + q->comp.comp_id = comp->comp_id; + q->comp.pid = comp->pid; + q->comp.ready = !!comp->ready; + q->comp.insmod = comp->insmod_args ? (const char *)SHMPTR(comp->insmod_args) : NULL; + } + halpr_mutex_release(); + return NULL != comp ? 0 : -ENOENT; +} diff --git a/src/hal/hal_priv.h b/src/hal/hal_priv.h index 0b0b94509a9..41f165d9361 100644 --- a/src/hal/hal_priv.h +++ b/src/hal/hal_priv.h @@ -118,9 +118,8 @@ */ #define HAL_KEY 0x48414C32 /* key used to open HAL shared memory */ -#define HAL_VER 0x00000011 /* version code */ +#define HAL_VER 0x00000012 /* version code */ #define HAL_SIZE (2*256*4096) -#define HAL_PSEUDO_COMP_PREFIX "__" /* prefix to identify a pseudo component */ /* These pointers are set by hal_init() to point to the shmem block and to the master data structure. All access should use these @@ -204,6 +203,16 @@ static_assert(sizeof(hal_shmfield) == sizeof(rtapi_intptr_t), "hal_shmfiel * PRIVATE HAL DATA STRUCTURES AND DECLARATIONS * ************************************************************************/ +// The underlying HAL pin/param data storage unit. Not normally exposed because +// we need everything to go through the getter/setter interface. However, there +// is a reason to have it for sizeof() queries. +typedef union { + rtapi_bool _b; + rtapi_sint _s; + rtapi_uint _u; + rtapi_real _r; +} __hal_private_vals_u; + /** HAL "list element" data structure. This structure is used to implement generic double linked circular lists. Such lists have the following characteristics: @@ -247,8 +256,18 @@ typedef struct hal_thread_t hal_thread_t; */ typedef struct hal_data_t { int version; /* version code for structs, etc */ - rtapi_mutex_t mutex; /* protection for linked lists, etc. */ - hal_s32_t shmem_avail; /* amount of shmem left free */ + + // WARNING: Do not touch these mutex lock fields. Only use the proper + // functions halpr_mutex_acquire() and halpr_mutex_release(). See comment + // above hal_lib.c:halpr_mutex_acquire() for functional explanation. + rtapi_mutex_t priv_rdmutex; // Private mutex for recursive lock + // Important: the mutex uses reverse default + // which means: 0==locked, 1==unlocked + int lockcnt; // Lock counter (using interlocked inc/dec) + int locklvl; // Lock recursion level + int locktid; // Lock owner thread ID + + rtapi_s32 shmem_avail; /* amount of shmem left free */ constructor pending_constructor; /* pointer to the pending constructor function */ char constructor_prefix[HAL_NAME_LEN+1]; @@ -279,15 +298,7 @@ typedef struct hal_data_t { unsigned char lock; /* hal locking, can be one of the HAL_LOCK_* types */ } hal_data_t; -/** HAL 'component' type. - Assigned according to RTAPI and ULAPI definitions. - */ -typedef enum { - COMPONENT_TYPE_UNKNOWN = -1, - COMPONENT_TYPE_USER, - COMPONENT_TYPE_REALTIME, - COMPONENT_TYPE_OTHER -} component_type_t; +typedef hal_comp_type_t component_type_t; /** HAL 'component' data structure. This structure contains information that is unique to a HAL component. @@ -378,9 +389,12 @@ struct hal_funct_t { int users; /* number of threads using function */ void *arg; /* argument for function */ void (*funct) (void *, long); /* ptr to function code */ - hal_s32_t* runtime; /* (pin) duration of last run, in CPU cycles */ - hal_s32_t maxtime; /* (param) duration of longest run, in CPU cycles */ - hal_bit_t maxtime_increased; /* (param) on last call, maxtime increased */ + // IMPORTANT: The pins and params are valid as seen from the context that + // created them. For uspace that is rtapi_app and in the kernel it is the + // kernel's module context. + hal_sint_t runtime; /* (pin) duration of last run, in CPU cycles */ + hal_sint_t maxtime; /* (param) duration of longest run, in CPU cycles */ + hal_bool_t maxtime_increased; /* (param) on last call, maxtime increased */ char name[HAL_NAME_LEN + 1]; /* function name */ }; @@ -399,8 +413,13 @@ struct hal_thread_t { long int period; /* period of the thread, in nsec */ int priority; /* priority of the thread */ int task_id; /* ID of the task that runs this thread */ - hal_s32_t* runtime; /* (pin) duration of last run, in ns */ - hal_s32_t maxtime; /* (param) duration of longest run, in ns */ + // IMPORTANT: The pins and params are valid as seen from the context that + // created them. For uspace that is rtapi_app and in the kernel it is the + // kernel's module context. + hal_sint_t runtime; /* (pin) duration of last run, in ns */ + hal_sint_t maxtime; /* (param) duration of longest run, in ns */ + hal_sint_t threadbeat; /* (param) visible monotonic loop beat counter */ + rtapi_sint beatcnt; /* Thread monotonic increasing loop beat counter (so we don't need to read/write volatile) */ hal_list_t funct_list; /* list of functions to run */ hal_list_t init_funct_list; /* list of init functions, run once before first cyclic cycle */ int init_done; /* 0 = init pending, 1 = init cycle has executed */ @@ -497,8 +516,17 @@ extern hal_pin_t *halpr_find_pin_by_sig(hal_sig_t * sig, hal_pin_t * start); Returns a negative value on failure. On success zero (0) is returned and the newly allocated hal_port_t is returned in the port argument and can be used with all other hal_port functions. + This is supposed to be private. The public function is deprecated and you + should use hal_set_s() to allocate the port once the pins are connected to + the signal. */ -extern int hal_port_alloc(unsigned size, hal_port_t *port); +int hal_port_alloc(unsigned size, hal_port_t *port) __attribute__((deprecated("Use hal_set_s()"))); +int halpr_port_alloc(unsigned size, hal_port_t *port); + +// Recursive HAL mutex (replaces old mutex) +int halpr_mutex_acquire(void); +int halpr_mutex_release(void); +void halpr_mutex_force_release(void); RTAPI_END_DECLS #endif /* HAL_PRIV_H */ diff --git a/src/hal/halmodule.cc b/src/hal/halmodule.cc index b0a132fd0c2..c0734aa21be 100644 --- a/src/hal/halmodule.cc +++ b/src/hal/halmodule.cc @@ -25,8 +25,8 @@ #include #include -#include "hal.h" -#include "hal_priv.h" +#include +#include "utils/setps_util.h" #define EXCEPTION_IF_NOT_LIVE(retval) do { \ if(self->hal_id <= 0) { \ @@ -35,13 +35,6 @@ } \ } while(0) -#define TEST_HAL_SHMEM_BASE(fname) do { \ - if(!hal_shmem_base) { \ - PyErr_Format(PyExc_RuntimeError, "%s: Cannot call before creating component", fname); \ - return NULL; \ - } \ - } while(0) - // Use stdint interfaces when we have them #if PY_VERSION_HEX >= 0x030e00f0 // 3.14 #define PyLong_FromRtapiS32 PyLong_FromInt32 @@ -85,23 +78,6 @@ struct scoped_lc_numeric_c { locale_t newlc; }; -// -// Acquire the HAL mutex for operations. -// ***** -// NOTE: the HAL mutex is _not_ recursive safe! -// ***** -// The mutex is automatically released when the instance is destructed. -// -struct scoped_hal_mutex { - scoped_hal_mutex() { - rtapi_mutex_get(&(hal_data->mutex)); - } - ~scoped_hal_mutex() { - rtapi_mutex_give(&(hal_data->mutex)); - } -}; - - PyObject *to_python(bool b) { return PyBool_FromLong(b); } @@ -114,15 +90,15 @@ PyObject *to_python(rtapi_s32 i) { return PyLong_FromRtapiS32(i); } -PyObject *to_python(rtapi_u64 u) { +PyObject *to_python(rtapi_uint u) { return PyLong_FromRtapiU64(u); } -PyObject *to_python(rtapi_s64 i) { +PyObject *to_python(rtapi_sint i) { return PyLong_FromRtapiS64(i); } -PyObject *to_python(double d) { +PyObject *to_python(rtapi_real d) { return PyFloat_FromDouble(d); } @@ -193,7 +169,7 @@ bool from_python(PyObject *o, bool *b) return false; } -bool from_python(PyObject *o, double *d) { +bool from_python(PyObject *o, rtapi_real *d) { if(PyFloat_Check(o)) { *d = PyFloat_AsDouble(o); return true; @@ -258,7 +234,7 @@ bool from_python(PyObject *o, rtapi_s32 *i) { return false; } -bool from_python(PyObject *o, rtapi_u64 *u) { +bool from_python(PyObject *o, rtapi_uint *u) { PyObject *tmp = NULL; unsigned long long l; tmp = PyLong_Check(o) ? o : PyNumber_Long(o); @@ -276,7 +252,7 @@ bool from_python(PyObject *o, rtapi_u64 *u) { return false; } -bool from_python(PyObject *o, rtapi_s64 *i) { +bool from_python(PyObject *o, rtapi_sint *i) { PyObject *tmp = NULL; long long l; tmp = PyLong_Check(o) ? o : PyNumber_Long(o); @@ -294,41 +270,11 @@ bool from_python(PyObject *o, rtapi_s64 *i) { return false; } -union paramunion { - hal_bit_t b; - hal_u32_t u32; - hal_s32_t s32; - hal_u64_t u64; - hal_s64_t s64; - hal_float_t f; -}; - -union pinunion { - void *v; - hal_bit_t *b; - hal_u32_t *u32; - hal_s32_t *s32; - hal_u64_t *u64; - hal_s64_t *s64; - hal_float_t *f; - hal_port_t *p; -}; - -union halunion { - union pinunion pin; - union paramunion param; -}; - -union haldirunion { - hal_pin_dir_t pindir; - hal_param_dir_t paramdir; -}; - struct halitem { bool is_pin; hal_type_t type; - union haldirunion dir; - union halunion *u; + hal_pdir_t dir; + hal_refs_u *u; }; struct pyhalitem { @@ -342,7 +288,7 @@ static PyObject * pyhal_pin_new(halitem * pin, const char *name); typedef std::map itemmap; typedef struct halobject { - PyObject_HEAD + PyObject_HEAD int hal_id; char *name; char *prefix; @@ -415,117 +361,65 @@ static void pyhal_delete(PyObject *_self) { static int pyhal_write_common(halitem *pin, PyObject *value) { if(!pin) return -1; - if(pin->is_pin) { - switch(pin->type) { - case HAL_BIT: { - bool tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.b = tmp; - break; - } - case HAL_FLOAT: { - double tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.f = tmp; - break; - } - case HAL_U32: { - rtapi_u32 tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.u32 = tmp; - break; - } - case HAL_S32: { - rtapi_s32 tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.s32 = tmp; - break; - } - case HAL_U64: { - rtapi_u64 tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.u64 = tmp; - break; - } - case HAL_S64: { - rtapi_s64 tmp; - if(!from_python(value, &tmp)) return -1; - *pin->u->pin.s64 = tmp; - break; - } - default: - PyErr_Format(pyhal_error_type, "Invalid pin type %d", pin->type); - } - } else { - switch(pin->type) { - case HAL_BIT: { - bool tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.b = tmp; - break; - } - case HAL_FLOAT: { - double tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.f = tmp; - break; - } - case HAL_U32: { - rtapi_u32 tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.u32 = tmp; - break; - } - case HAL_S32: - rtapi_s32 tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.s32 = tmp; - break; - case HAL_U64: { - rtapi_u64 tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.u64 = tmp; - break; - } - case HAL_S64: { - rtapi_s64 tmp; - if(!from_python(value, &tmp)) return -1; - pin->u->param.s64 = tmp; - break; - } - default: - PyErr_Format(pyhal_error_type, "Invalid pin type %d", pin->type); - } + switch(pin->type) { + case HAL_BOOL: { + bool tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_bool(pin->u->b, tmp); + break; + } + case HAL_REAL: { + rtapi_real tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_real(pin->u->r, tmp); + break; + } + case HAL_U32: { + rtapi_u32 tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_ui32(pin->u->u, tmp); + break; + } + case HAL_S32: { + rtapi_s32 tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_si32(pin->u->s, tmp); + break; + } + case HAL_UINT: { + rtapi_uint tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_uint(pin->u->u, tmp); + break; + } + case HAL_SINT: { + rtapi_sint tmp; + if(!from_python(value, &tmp)) return -1; + hal_set_sint(pin->u->s, tmp); + break; + } + default: + PyErr_Format(pyhal_error_type, "Invalid pin type %d", pin->type); } return 0; } static PyObject *pyhal_read_common(halitem *item) { if(!item) return NULL; - if(item->is_pin) { - switch(item->type) { - case HAL_BIT: return to_python(*(item->u->pin.b)); - case HAL_U32: return to_python(*(item->u->pin.u32)); - case HAL_S32: return to_python(*(item->u->pin.s32)); - case HAL_U64: return to_python(*(item->u->pin.u64)); - case HAL_S64: return to_python(*(item->u->pin.s64)); - case HAL_FLOAT: return to_python(*(item->u->pin.f)); - case HAL_PORT: return to_python(hal_port_buffer_size(item->u->pin.p)); - default: - break; - } - } else { - switch(item->type) { - case HAL_BIT: return to_python(item->u->param.b); - case HAL_U32: return to_python(item->u->param.u32); - case HAL_S32: return to_python(item->u->param.s32); - case HAL_U64: return to_python(item->u->param.u64); - case HAL_S64: return to_python(item->u->param.s64); - case HAL_FLOAT: return to_python(item->u->param.f); - case HAL_PORT: return to_python((unsigned)0); // HAL_PORT cannot be a parameter - default: - break; - } + switch(item->type) { + case HAL_BOOL: return to_python(hal_get_bool(item->u->b)); + case HAL_U32: return to_python(hal_get_ui32(item->u->u)); + case HAL_S32: return to_python(hal_get_si32(item->u->s)); + case HAL_UINT: return to_python(hal_get_uint(item->u->u)); + case HAL_SINT: return to_python(hal_get_sint(item->u->s)); + case HAL_REAL: return to_python(hal_get_real(item->u->r)); + case HAL_PORT: + if(item->is_pin) + return to_python(hal_port_buffer_size(reinterpret_cast(item->u->u))); + else + return to_python((unsigned)0); // HAL_PORT cannot be a parameter + default: + break; } PyErr_Format(pyhal_error_type, "Invalid item type %d", item->type); return NULL; @@ -544,29 +438,50 @@ static halitem *find_item(halobject *self, const char *name) { return &(i->second); } +static bool is_valid_hal_type(hal_type_t t, bool allowport) +{ + switch(t) { + case HAL_BOOL: + case HAL_S32: + case HAL_U32: + case HAL_SINT: + case HAL_UINT: + case HAL_REAL: + return true; + case HAL_PORT: + return allowport; + default: + return false; + } +} + static PyObject * pyhal_create_param(halobject *self, const char *name, hal_type_t type, hal_param_dir_t dir) { - char param_name[HAL_NAME_LEN+1]; int res; halitem param; param.is_pin = 0; - /* FIXME consider type < HAL_TYPE_UNSPECIFIED || HAL_TYPE_MAX <= type */ - if(type < HAL_BIT || type > HAL_U64) { + if(!is_valid_hal_type(type, false)) { PyErr_Format(pyhal_error_type, "Invalid param type %d", type); return NULL; } param.type = type; - param.dir.paramdir = dir; - param.u = (halunion*)hal_malloc(sizeof(halunion)); + param.dir = dir; + param.u = (hal_refs_u *)hal_malloc(sizeof(*param.u)); if(!param.u) { PyErr_SetString(PyExc_MemoryError, "hal_malloc failed"); return NULL; } - res = snprintf(param_name, sizeof(param_name), "%s.%s", self->prefix, name); - if(res > HAL_NAME_LEN || res < 0) { return pyhal_error(-EINVAL); } - res = hal_param_new(param_name, type, dir, (void*)param.u, self->hal_id); + switch(type) { + case HAL_BOOL: res = hal_param_new_bool(self->hal_id, dir, ¶m.u->b, 0, "%s.%s", self->prefix, name); break; + case HAL_S32: res = hal_param_new_si32(self->hal_id, dir, ¶m.u->s, 0, "%s.%s", self->prefix, name); break; + case HAL_U32: res = hal_param_new_ui32(self->hal_id, dir, ¶m.u->u, 0, "%s.%s", self->prefix, name); break; + case HAL_SINT: res = hal_param_new_sint(self->hal_id, dir, ¶m.u->s, 0, "%s.%s", self->prefix, name); break; + case HAL_UINT: res = hal_param_new_uint(self->hal_id, dir, ¶m.u->u, 0, "%s.%s", self->prefix, name); break; + case HAL_REAL: res = hal_param_new_real(self->hal_id, dir, ¶m.u->r, 0.0, "%s.%s", self->prefix, name); break; + default: res = -EINVAL; break; + } if(res) return pyhal_error(res); (*self->items)[name] = param; @@ -581,14 +496,14 @@ static PyObject * pyhal_create_pin(halobject *self, const char *name, hal_type_t halitem pin; pin.is_pin = 1; - if(type < HAL_BIT || type > HAL_U64) { + if(!is_valid_hal_type(type, true)) { PyErr_Format(pyhal_error_type, "Invalid pin type %d", type); return NULL; } pin.type = type; - pin.dir.pindir = dir; - pin.u = (halunion*)hal_malloc(sizeof(halunion)); + pin.dir = dir; + pin.u = (hal_refs_u *)hal_malloc(sizeof(*pin.u)); if(!pin.u) { PyErr_SetString(PyExc_MemoryError, "hal_malloc failed"); return NULL; @@ -601,7 +516,16 @@ static PyObject * pyhal_create_pin(halobject *self, const char *name, hal_type_t self->prefix, name, HAL_NAME_LEN); return NULL; } - res = hal_pin_new(pin_name, type, dir, (void**)pin.u, self->hal_id); + switch(type) { + case HAL_BOOL: res = hal_pin_new_bool(self->hal_id, dir, &pin.u->b, 0, "%s.%s", self->prefix, name); break; + case HAL_S32: res = hal_pin_new_si32(self->hal_id, dir, &pin.u->s, 0, "%s.%s", self->prefix, name); break; + case HAL_U32: res = hal_pin_new_ui32(self->hal_id, dir, &pin.u->u, 0, "%s.%s", self->prefix, name); break; + case HAL_SINT: res = hal_pin_new_sint(self->hal_id, dir, &pin.u->s, 0, "%s.%s", self->prefix, name); break; + case HAL_UINT: res = hal_pin_new_uint(self->hal_id, dir, &pin.u->u, 0, "%s.%s", self->prefix, name); break; + case HAL_REAL: res = hal_pin_new_real(self->hal_id, dir, &pin.u->r, 0.0, "%s.%s", self->prefix, name); break; + case HAL_PORT: res = hal_pin_new_port(self->hal_id, dir, &pin.u->s, "%s.%s", self->prefix, name); break; + default: res = -EINVAL; break; + } if(res) return pyhal_error(res); (*self->items)[name] = pin; @@ -686,7 +610,20 @@ static PyObject *pyhal_get_pins(PyObject *_self, PyObject * /*o*/) { PyObject *d = PyDict_New(); for(itemmap::iterator i = self->items->begin(); i != self->items->end(); ++i) { halitem * pin = &(i->second); - PyDict_SetItem(d, PyUnicode_FromString(i->first.c_str()), pyhal_read_common(pin)); + PyObject *key = PyUnicode_FromString(i->first.c_str()); + if(!key) { + Py_DECREF(d); + return NULL; + } + PyObject *val = pyhal_read_common(pin); + if(!val) { + Py_DECREF(key); + Py_DECREF(d); + return NULL; + } + PyDict_SetItem(d, key, val); + Py_DECREF(val); + Py_DECREF(key); } return d; } @@ -882,28 +819,22 @@ PyTypeObject halobject_type = { static const char * pin_type2name(hal_type_t type) { switch (type) { - case HAL_BIT: return "BIT"; - case HAL_S32: return "S32"; - case HAL_U32: return "U32"; - case HAL_S64: return "S64"; - case HAL_U64: return "U64"; - case HAL_FLOAT: return "FLOAT"; - case HAL_PORT: return "PORT"; + case HAL_BOOL: return "BIT"; + case HAL_S32: return "S32"; + case HAL_U32: return "U32"; + case HAL_SINT: return "S64"; + case HAL_UINT: return "U64"; + case HAL_REAL: return "FLOAT"; + case HAL_PORT: return "PORT"; default: return "unknown"; } } -static const char * pin_dir2name(hal_pin_dir_t type) { +static const char * pin_dir2name(hal_pdir_t type) { switch (type) { case HAL_IN: return "IN"; case HAL_IO: return "IO"; case HAL_OUT: return "OUT"; - default: return "unknown"; - } -} - -static const char * param_dir2name(hal_param_dir_t type) { - switch (type) { case HAL_RO: return "RO"; case HAL_RW: return "RW"; default: return "unknown"; @@ -917,11 +848,9 @@ static PyObject *pyhalpin_repr(PyObject *_self) { const char * name = "(null)"; if (pyself->name) name = pyself->name; - if (!self->is_pin) - return PyUnicode_FromFormat("", name, - pin_type2name(self->type), param_dir2name(self->dir.paramdir)); - return PyUnicode_FromFormat("", name, - pin_type2name(self->type), pin_dir2name(self->dir.pindir)); + const char *pp = self->is_pin ? "pin" : "param"; + return PyUnicode_FromFormat("", pp, name, + pin_type2name(self->type), pin_dir2name(self->dir)); } static int pyhalpin_init(PyObject * /*_self*/, PyObject *, PyObject *) { @@ -957,10 +886,7 @@ static PyObject * pyhal_pin_get_type(PyObject * _self, PyObject *) { static PyObject * pyhal_pin_get_dir(PyObject * _self, PyObject *) { pyhalitem * self = reinterpret_cast(_self); - if (self->pin.is_pin) - return PyLong_FromLong(self->pin.dir.pindir); - else - return PyLong_FromLong(self->pin.dir.paramdir); + return PyLong_FromLong(self->pin.dir); } static PyObject * pyhal_pin_is_pin(PyObject * _self, PyObject *) { @@ -997,7 +923,7 @@ static PyObject *pyhal_port_write(PyObject *self, PyObject *o) pyhalitem *item = reinterpret_cast(self); if(!check_port(item, "write")) return NULL; - if(item->pin.dir.pindir != HAL_OUT) { + if(item->pin.dir != HAL_OUT) { PyErr_Format(PyExc_RuntimeError, "write: %s: Pin not output", item->name); return NULL; } @@ -1022,12 +948,12 @@ static PyObject *pyhal_port_write(PyObject *self, PyObject *o) Py_INCREF(Py_False); return Py_False; } - if(len > (Py_ssize_t)hal_port_writable(item->pin.u->pin.p)) { + if(len > (Py_ssize_t)hal_port_writable((hal_port_t *)item->pin.u->u)) { Py_INCREF(Py_False); return Py_False; } - return PyBool_FromLong(hal_port_write(item->pin.u->pin.p, cptr, (unsigned)len)); + return PyBool_FromLong(hal_port_write((hal_port_t *)item->pin.u->u, cptr, (unsigned)len)); } static PyObject *pyhal_port_read_peek(pyhalitem *item, PyObject *o, bool isread) @@ -1035,7 +961,7 @@ static PyObject *pyhal_port_read_peek(pyhalitem *item, PyObject *o, bool isread) const char *pfx = isread ? "read" : "peek"; if(!check_port(item, pfx)) return NULL; - if(item->pin.dir.pindir != HAL_IN) { + if(item->pin.dir != HAL_IN) { PyErr_Format(PyExc_RuntimeError, "%s: %s: Pin not input", pfx, item->name); return NULL; } @@ -1051,7 +977,7 @@ static PyObject *pyhal_port_read_peek(pyhalitem *item, PyObject *o, bool isread) Py_INCREF(Py_False); return Py_False; } - if(l > (unsigned long)hal_port_readable(item->pin.u->pin.p)) { + if(l > (unsigned long)hal_port_readable((hal_port_t *)item->pin.u->u)) { Py_INCREF(Py_False); return Py_False; } @@ -1063,9 +989,9 @@ static PyObject *pyhal_port_read_peek(pyhalitem *item, PyObject *o, bool isread) } bool b; if(isread) - b = hal_port_read(item->pin.u->pin.p, PyBytes_AsString(bts), (unsigned)l); + b = hal_port_read((hal_port_t *)item->pin.u->u, PyBytes_AsString(bts), (unsigned)l); else - b = hal_port_peek(item->pin.u->pin.p, PyBytes_AsString(bts), (unsigned)l); + b = hal_port_peek((hal_port_t *)item->pin.u->u, PyBytes_AsString(bts), (unsigned)l); if(b) { Py_DECREF(bts); Py_INCREF(Py_False); @@ -1103,7 +1029,7 @@ static PyObject *pyhal_port_peek_commit(PyObject *self, PyObject *o) Py_INCREF(Py_False); return Py_False; } - return PyBool_FromLong(hal_port_peek_commit(item->pin.u->pin.p, (unsigned)l)); + return PyBool_FromLong(hal_port_peek_commit((hal_port_t *)item->pin.u->u, (unsigned)l)); } static PyObject *pyhal_port_writable(PyObject *self, PyObject *) @@ -1111,11 +1037,11 @@ static PyObject *pyhal_port_writable(PyObject *self, PyObject *) pyhalitem *item = reinterpret_cast(self); if(!check_port(item, "writable")) return NULL; - if(item->pin.dir.pindir != HAL_OUT) { + if(item->pin.dir != HAL_OUT) { PyErr_Format(PyExc_RuntimeError, "writable: %s: Pin not output", item->name); return NULL; } - return PyLong_FromUnsignedLong(hal_port_writable(item->pin.u->pin.p)); + return PyLong_FromUnsignedLong(hal_port_writable((hal_port_t *)item->pin.u->u)); } static PyObject *pyhal_port_readable(PyObject *self, PyObject *) @@ -1123,11 +1049,11 @@ static PyObject *pyhal_port_readable(PyObject *self, PyObject *) pyhalitem *item = reinterpret_cast(self); if(!check_port(item, "readable")) return NULL; - if(item->pin.dir.pindir != HAL_IN) { + if(item->pin.dir != HAL_IN) { PyErr_Format(PyExc_RuntimeError, "readable: %s: Pin not input", item->name); return NULL; } - return PyLong_FromUnsignedLong(hal_port_readable(item->pin.u->pin.p)); + return PyLong_FromUnsignedLong(hal_port_readable((hal_port_t *)item->pin.u->u)); } static PyObject *pyhal_port_clear(PyObject *self, PyObject *) @@ -1135,7 +1061,7 @@ static PyObject *pyhal_port_clear(PyObject *self, PyObject *) pyhalitem *item = reinterpret_cast(self); if(!check_port(item, "clear")) return NULL; - hal_port_clear(item->pin.u->pin.p); + hal_port_clear((hal_port_t *)item->pin.u->u); Py_INCREF(Py_None); return Py_None; } @@ -1145,7 +1071,7 @@ static PyObject *pyhal_port_size(PyObject *self, PyObject *) pyhalitem *item = reinterpret_cast(self); if(!check_port(item, "size")) return NULL; - return PyLong_FromUnsignedLong(hal_port_buffer_size(item->pin.u->pin.p)); + return PyLong_FromUnsignedLong(hal_port_buffer_size((hal_port_t *)item->pin.u->u)); } static PyMethodDef halpin_methods[] = { @@ -1245,24 +1171,31 @@ static PyObject * pyhal_pin_new(halitem * pin, const char * name) { } PyObject *pin_has_writer(PyObject * /*self*/, PyObject *args) { - const char *name; - if(!PyArg_ParseTuple(args, "s", &name)) return NULL; - - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; // get mutex before accessing shared data - hal_pin_t *pin = halpr_find_pin_by_name(name); - if(!pin) { - PyErr_Format(PyExc_NameError, "Pin `%s' does not exist", name); + hal_query_t q = {}; + if(!PyArg_ParseTuple(args, "s", &q.name)) return NULL; + + q.qtype = HAL_QTYPE_PIN; // Only query a pin + int rv = hal_get_p(&q, NULL, NULL); + if(0 == rv) { + // Success reading. See if it has a driver. + if(!q.pp.signal) { + // No signal, it may be its own writer? + return PyBool_FromLong(q.pp.dir == HAL_OUT); + } + hal_query_t qs = {}; + qs.name = q.pp.signal; + if(0 != (rv = hal_getref_s(&qs))) { + PyErr_Format(PyExc_NameError, "Signal '%s' of pin '%s' gave unexpected error=%d", q.pp.signal, q.name, rv); + return NULL; + } + return PyBool_FromLong(qs.sig.writers > 0); + } else if(-ENOENT == rv) { + // Pin not found + PyErr_Format(PyExc_NameError, "Pin `%s' does not exist", q.name); return NULL; } - - if(pin->signal) { - hal_sig_t *signal = (hal_sig_t*)SHMPTR(pin->signal); - return PyBool_FromLong(signal->writers > 0); - } - Py_INCREF(Py_False); - return Py_False; + PyErr_Format(PyExc_RuntimeError, "pin_has_writer: %s: returned error: %s", q.name, hal_strerror(rv)); + return NULL; } @@ -1270,21 +1203,25 @@ PyObject *component_exists(PyObject * /*self*/, PyObject *args) { const char *name; if(!PyArg_ParseTuple(args, "s", &name)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; // get mutex before accessing shared data - return PyBool_FromLong(halpr_find_comp_by_name(name) != NULL); + int rv = hal_comp_by_name(name, NULL); + if(0 == rv) { + Py_INCREF(Py_True); + return Py_True; + } else if(-ENOENT == rv) { + Py_INCREF(Py_False); + return Py_False; + } + PyErr_Format(PyExc_RuntimeError, "component_exists: hal_comp_by_name '%s' returned %d", name, rv); + return NULL; } PyObject *component_is_ready(PyObject * /*self*/, PyObject *args) { const char *name; if(!PyArg_ParseTuple(args, "s", &name)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; // get mutex before accessing shared data - hal_comp_t *thecomp = halpr_find_comp_by_name(name); - return PyBool_FromLong((thecomp) && (thecomp->ready != 0)); + hal_query_t q = {}; + int rv = hal_comp_by_name(name, &q); + return PyBool_FromLong(0 == rv && q.comp.ready); } PyObject *new_sig(PyObject * /*self*/, PyObject *args) { @@ -1292,16 +1229,14 @@ PyObject *new_sig(PyObject * /*self*/, PyObject *args) { int type,retval; if(!PyArg_ParseTuple(args, "si", &name,&type)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - //printf("INFO HALMODULE -- make signal -> %s type %d\n",name,(hal_type_t) type); switch (type) { - case HAL_BIT: + case HAL_BOOL: case HAL_S32: case HAL_U32: - case HAL_S64: - case HAL_U64: - case HAL_FLOAT: + case HAL_SINT: + case HAL_UINT: + case HAL_REAL: case HAL_PORT: retval = hal_signal_new(name, (hal_type_t)type); break; @@ -1317,8 +1252,6 @@ PyObject *connect(PyObject * /*self*/, PyObject *args) { const char *signame,*pinname; if(!PyArg_ParseTuple(args, "ss", &pinname,&signame)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - //printf("INFO HALMODULE -- link sig %s to pin %s\n",signame,pinname); return PyBool_FromLong(hal_link(pinname, signame) != 0); } @@ -1327,522 +1260,359 @@ PyObject *disconnect(PyObject * /*self*/, PyObject *args) { const char *pinname; if(!PyArg_ParseTuple(args, "s", &pinname)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - //printf("INFO HALMODULE -- unlink pin %s\n",pinname); return PyBool_FromLong(hal_unlink(pinname) != 0); } -static int set_common(hal_type_t type, hal_data_u *d_ptr, PyObject *obj) +static int set_common_cb(hal_query_t *q, void *arg) { - // This function assumes that the mutex is held + PyObject *obj = static_cast(arg); + hal_type_t type = HAL_QTYPE_SIGNAL == q->qtype ? q->sig.type : q->pp.type; + hal_query_value_u *qvp = HAL_QTYPE_SIGNAL == q->qtype ? &q->sig.value : &q->pp.value; switch(type) { - case HAL_BIT: { + case HAL_BOOL: { bool tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->b = tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->b = tmp; break; } - case HAL_FLOAT: { - double tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->f = tmp; + case HAL_REAL: { + rtapi_real tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->r = tmp; break; } case HAL_S32: { rtapi_s32 tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->s = tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->s = tmp; break; } case HAL_U32: { rtapi_u32 tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->u = tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->u = tmp; break; } - case HAL_S64: { - rtapi_s64 tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->ls = tmp; + case HAL_SINT: { + rtapi_sint tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->s = tmp; break; } - case HAL_U64: { - rtapi_u64 tmp; - if(!from_python(obj, &tmp)) return -1; - d_ptr->lu = tmp; + case HAL_UINT: { + rtapi_uint tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->u = tmp; break; } - case HAL_PORT: - if((d_ptr->p != 0) && (hal_port_buffer_size(&d_ptr->p) > 0)) { - // port is already allocated - PyErr_Format(PyExc_RuntimeError, "port has already memory allocated"); - return -1; - } else { - unsigned tmp; - if(!from_python(obj, &tmp)) - return -1; - int err = hal_port_alloc(tmp, &d_ptr->p); - if(err < 0) { - PyErr_Format(PyExc_RuntimeError, "port memory allocation failed"); - } - } + case HAL_PORT: { + unsigned tmp; + if(!from_python(obj, &tmp)) return -EINVAL; + qvp->u = tmp; break; + } default: // Shouldn't get here, but just in case... - return -1; + return -EBADF; } return 0; } PyObject *set_p(PyObject * /*self*/, PyObject *args) { - const char *name; + hal_query_t q = {}; PyObject *obj; - int retval; - hal_type_t type; - hal_data_u *d_ptr; - if(!PyArg_ParseTuple(args, "sO", &name, &obj)) return NULL; + if(!PyArg_ParseTuple(args, "sO", &q.name, &obj)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; // get mutex before accessing shared data - - // Search pin and then param - // We are more likely to set a pin than a param - hal_pin_t *pin = halpr_find_pin_by_name(name); - if(pin == NULL) { - hal_param_t *param = halpr_find_param_by_name(name); - if (param == NULL) { - // Found neither pin nor param - PyErr_Format(PyExc_RuntimeError, "pin or param not found"); - return NULL; - } - // Found a param - type = param->type; - /* is it read only? */ - if (param->dir == HAL_RO) { - PyErr_Format(PyExc_RuntimeError, "param not writable"); - return NULL; - } - d_ptr = reinterpret_cast(SHMPTR(param->data_ptr)); - } else { - // Found a pin - type = pin->type; - if(pin->dir == HAL_OUT) { - PyErr_Format(PyExc_RuntimeError, "pin not writable"); - return NULL; - } - if(pin->type == HAL_PORT) { - PyErr_Format(PyExc_RuntimeError, "ports are not writable"); - return NULL; - } - if(pin->signal != 0) { - PyErr_Format(PyExc_RuntimeError, "pin connected to signal"); - return NULL; - } - d_ptr = &pin->dummysig; + int rv = hal_set_p(&q, set_common_cb, obj); + if(rv < 0) { + PyErr_Format(PyExc_RuntimeError, "set_p: %s: %s", q.name, hal_strerror(rv)); + return NULL; } - - retval = set_common(type, d_ptr, obj); - if(retval != 0) - return NULL; // set_common has set an exception return PyBool_FromLong(1); } PyObject *set_s(PyObject * /*self*/, PyObject *args) { - const char *name; + hal_query_t q = {}; PyObject *obj; - int retval; - hal_sig_t *sig; - hal_type_t type; - hal_data_u *d_ptr; - - if(!PyArg_ParseTuple(args, "sO", &name, &obj)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); + if(!PyArg_ParseTuple(args, "sO", &q.name, &obj)) return NULL; - scoped_hal_mutex _hallock; // get mutex before accessing shared data - - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { - PyErr_Format(PyExc_RuntimeError, - "signal not found"); + int rv = hal_set_s(&q, set_common_cb, obj); + if(rv < 0) { + PyErr_Format(PyExc_RuntimeError, "set_s: %s: %s", q.name, hal_strerror(rv)); return NULL; - } else { - if ((sig->type != HAL_PORT) && (sig->writers > 0)) { - PyErr_Format(PyExc_RuntimeError, - "signal '%s' already has writer(s)\n", name); - return NULL; - } - /* no writer, so we can safely set it */ - type = sig->type; - d_ptr = reinterpret_cast(SHMPTR(sig->data_ptr)); - retval = set_common(type, d_ptr, obj); - if(retval != 0) - return NULL; // set_common has set an exception - return PyBool_FromLong(1); } + return PyBool_FromLong(1); } /*######################################*/ /* Get a Pin, Param or signal value */ /* Search order: pin, param, signal */ -static PyObject *halref_to_object(hal_data_u *d_ptr, hal_type_t type) +static PyObject *halref_to_object(hal_type_t type, const hal_query_value_u *v) { switch(type) { - case HAL_BIT: return to_python(d_ptr->b); - case HAL_U32: return to_python(d_ptr->u); - case HAL_S32: return to_python(d_ptr->s); - case HAL_U64: return to_python(d_ptr->lu); - case HAL_S64: return to_python(d_ptr->ls); - case HAL_FLOAT: return to_python(d_ptr->f); - case HAL_PORT: return to_python(d_ptr->p); + case HAL_BOOL: return to_python(v->b); + case HAL_U32: return to_python((rtapi_u32)v->u); + case HAL_S32: return to_python((rtapi_s32)v->s); + case HAL_UINT: return to_python(v->u); + case HAL_SINT: return to_python(v->s); + case HAL_REAL: return to_python(v->r); + case HAL_PORT: return to_python(v->s); default: PyErr_Format(PyExc_RuntimeError, "halref_to_object: unknown hal type '%d'", (int)type); return NULL; } } -PyObject *get_value(PyObject * /*self*/, PyObject *args) { - const char *name; +// +// get_p() tries to get the value of a named pin or parameter. +// +PyObject *get_p(PyObject * /*self*/, PyObject *args) +{ + hal_query_t q = {}; - if(!PyArg_ParseTuple(args, "s", &name)) return NULL; + if(!PyArg_ParseTuple(args, "s", &q.name)) return NULL; - TEST_HAL_SHMEM_BASE(__FUNCTION__); + // A connected pin will return the signal's value + int rv = hal_get_p(&q, NULL, NULL); + if(0 == rv) + return halref_to_object(q.pp.type, &q.pp.value); + // Get here: most likely no pin/param with that name + PyErr_Format(PyExc_RuntimeError, "get_p: %s: %s", q.name, hal_strerror(rv)); + return NULL; +} + +// +// get_s() tries to get the value of a named signal. +// +PyObject *get_s(PyObject * /*self*/, PyObject *args) +{ + hal_query_t q = {}; - scoped_hal_mutex _hallock; /* get mutex before accessing shared data */ + if(!PyArg_ParseTuple(args, "s", &q.name)) return NULL; - /* search pin list for name */ - hal_pin_t *pin = halpr_find_pin_by_name(name); - if(pin) { - hal_data_u *d_ptr; - if (pin->signal != 0) { - hal_sig_t *sig = (hal_sig_t*)SHMPTR(pin->signal); - d_ptr = reinterpret_cast(SHMPTR(sig->data_ptr)); - } else { - d_ptr = &(pin->dummysig); - } - return halref_to_object(d_ptr, pin->type); /* convert to python value */ - } - /* search param list for name */ - hal_param_t *param = halpr_find_param_by_name(name); - if (param) { - hal_data_u *d_ptr = reinterpret_cast(SHMPTR(param->data_ptr)); - return halref_to_object(d_ptr, param->type); /* convert to python value */ - } - /* search signal list for name */ - hal_sig_t *sig = halpr_find_sig_by_name(name); - if (sig) { - hal_data_u *d_ptr = reinterpret_cast(SHMPTR(sig->data_ptr)); - return halref_to_object(d_ptr, sig->type); /* convert to python value */ - } - /* error if here */ - PyErr_Format(PyExc_RuntimeError, "Can't get value: pin / param %s not found", name); + int rv = hal_get_s(&q, NULL, NULL); + if(0 == rv) + return halref_to_object(q.sig.type, &q.sig.value); + // Get here: most likely no signal with that name + PyErr_Format(PyExc_RuntimeError, "get_s: %s: %s", q.name, hal_strerror(rv)); return NULL; +} +// +// get_value() first tries pins/params and then signals if no pin/param with +// that name. +// +PyObject *get_value(PyObject * /*self*/, PyObject *args) +{ + hal_query_t q = {}; + + if(!PyArg_ParseTuple(args, "s", &q.name)) return NULL; + + // Try a pin/param + // A connected pin will return the signal's value + int rv = hal_get_p(&q, NULL, NULL); + if(0 == rv) + return halref_to_object(q.pp.type, &q.pp.value); + // No pin/param with that name, try a signal + if(-ENOENT == rv) { + rv = hal_get_s(&q, NULL, NULL); + if(0 == rv) + return halref_to_object(q.sig.type, &q.sig.value); + } + PyErr_Format(PyExc_RuntimeError, "get_value: %s: %s", q.name, hal_strerror(rv)); + return NULL; } /*######################################*/ /* Get a dict of pin info for all pins in system */ -PyObject *get_info_pins(PyObject * /*self*/, PyObject * /*args*/) { - SHMFIELD(hal_pin_t) next; - int type; +static int pinparaminfo_cb(hal_query_t *q, void *arg) +{ + PyObject *lst = static_cast(arg); + PyObject *obj; static const char str_n[] = "NAME"; static const char str_v[] = "VALUE"; static const char str_t[] = "TYPE"; static const char str_d[] = "DIRECTION"; - hal_data_u *d_ptr; - hal_pin_t *pin; - hal_sig_t *sig; + switch(q->pp.type) { + case HAL_BOOL: + obj = Py_BuildValue("{s:s,s:N,s:N,s:N}", + str_n, q->name, str_v, PyBool_FromLong(hal_get_bool(q->pp.ref.b)), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_BOOL)); + break; + case HAL_U32: + obj = Py_BuildValue("{s:s,s:k,s:N,s:N}", + str_n, q->name, str_v, hal_get_ui32(q->pp.ref.u), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_U32)); + break; + case HAL_S32: + obj = Py_BuildValue("{s:s,s:l,s:N,s:N}", + str_n, q->name, str_v, hal_get_si32(q->pp.ref.s), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_S32)); + break; + case HAL_UINT: + obj = Py_BuildValue("{s:s,s:K,s:N,s:N}", + str_n, q->name, str_v, hal_get_uint(q->pp.ref.u), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_UINT)); + break; + case HAL_SINT: + obj = Py_BuildValue("{s:s,s:L,s:N,s:N}", + str_n, q->name, str_v, hal_get_sint(q->pp.ref.s), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_SINT)); + break; + case HAL_REAL: + obj = Py_BuildValue("{s:s,s:d,s:N,s:N}", + str_n, q->name, str_v, hal_get_real(q->pp.ref.r), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_REAL)); + break; + case HAL_PORT: + obj = Py_BuildValue("{s:s,s:l,s:N,s:N}", + str_n, q->name, str_v, hal_get_sint(q->pp.ref.s), + str_d, PyLong_FromLong(q->pp.dir), str_t, PyLong_FromLong(HAL_PORT)); + break; + default: + obj = Py_BuildValue("{s:s,s:s,s:N,s:s}", + str_n, q->name, str_v, NULL, + str_d, PyLong_FromLong(q->pp.dir), str_t, NULL); + break; + } + PyList_Append(lst, obj); + Py_DECREF(obj); + return 0; +} +PyObject *get_info_pins(PyObject * /*self*/, PyObject * /*args*/) +{ PyObject* python_list = PyList_New(0); - PyObject *obj; - - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; /* get mutex before accessing shared data */ - - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - type = pin->type; - if (pin->signal != 0) { - sig = (hal_sig_t*)SHMPTR(pin->signal); - d_ptr = reinterpret_cast(SHMPTR(sig->data_ptr)); - } else { - sig = NULL; - d_ptr = &(pin->dummysig); - } - - /* convert to dict of python values */ - switch(type) { - case HAL_BIT: - obj = Py_BuildValue("{s:s,s:N,s:N,s:N}", - str_n, pin->name, - str_v, PyBool_FromLong((long)d_ptr->b), - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_BIT)); - break; - case HAL_U32: - obj = Py_BuildValue("{s:s,s:k,s:N,s:N}", - str_n, pin->name, - str_v, (unsigned long)d_ptr->u, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_U32)); - break; - case HAL_S32: - obj = Py_BuildValue("{s:s,s:l,s:N,s:N}", - str_n, pin->name, - str_v, (long)d_ptr->s, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_S32)); - break; - case HAL_U64: - obj = Py_BuildValue("{s:s,s:K,s:N,s:N}", - str_n, pin->name, - str_v, (unsigned long long)d_ptr->lu, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_S64)); - break; - case HAL_S64: - obj = Py_BuildValue("{s:s,s:L,s:N,s:N}", - str_n, pin->name, - str_v, (long long)d_ptr->ls, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_S64)); - break; - case HAL_FLOAT: - obj = Py_BuildValue("{s:s,s:d,s:N,s:N}", - str_n, pin->name, - str_v, (double)d_ptr->f, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_FLOAT)); - break; - case HAL_PORT: - obj = Py_BuildValue("{s:s,s:l,s:N,s:N}", - str_n, pin->name, - str_v, (long)d_ptr->p, - str_d, PyLong_FromLong(pin->dir), - str_t, PyLong_FromLong(HAL_PORT)); - break; - case HAL_TYPE_UNSPECIFIED: /* fallthrough */ ; - case HAL_TYPE_UNINITIALIZED: /* fallthrough */ ; - default: - obj = Py_BuildValue("{s:s,s:s,s:N,s:s}", - str_n, pin->name, - str_v, NULL, - str_d, PyLong_FromLong(pin->dir), - str_t, NULL); - break; - } - - // add to list - PyList_Append( python_list, obj); - next = pin->next_ptr; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; // Only handle pins + int rv = hal_list_p(&q, pinparaminfo_cb, python_list); + if(0 != rv) { + Py_DECREF(python_list); + PyErr_Format(PyExc_RuntimeError, "hal_list_p: returned '%s' (%d)", hal_strerror(rv), rv); + return NULL; } - return python_list; } /*######################################*/ /* Get a dict of signal info for all signals in system */ -PyObject *get_info_signals(PyObject * /*self*/, PyObject * /*args*/) { - SHMFIELD(hal_sig_t) next; - int type; + +static int siginfo_writer_cb(hal_query_t *q, void *arg) +{ + if(HAL_OUT == q->pp.dir) { + // Found the writer, record and quit the loop + *((const char **)arg) = q->name; + return 1; + } + return 0; +} + +static int siginfo_cb(hal_query_t *q, void *arg) +{ + PyObject *lst = static_cast(arg); + PyObject *obj; static const char str_n[] = "NAME"; static const char str_v[] = "VALUE"; static const char str_t[] = "TYPE"; static const char str_d[] = "DRIVER"; - hal_data_u *d_ptr; - hal_sig_t *sig; - hal_pin_t *pin; - PyObject* python_list = PyList_New(0); - PyObject *obj; - - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; /* get mutex before accessing shared data */ - - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - type = sig->type; - d_ptr = reinterpret_cast(SHMPTR(sig->data_ptr)); - /* it have a writer? */ - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - if (pin->dir == HAL_OUT){break;} - pin = halpr_find_pin_by_sig(sig, pin); - } - /* convert to dict of python values */ - switch(type) { - case HAL_BIT: - obj = Py_BuildValue("{s:s,s:N,s:s,s:N}", - str_n, sig->name, - str_v, PyBool_FromLong((long)d_ptr->b), - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_BIT)); - break; - case HAL_U32: - obj = Py_BuildValue("{s:s,s:k,s:s,s:N}", - str_n, sig->name, - str_v, (unsigned long)d_ptr->u, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_U32)); - break; - case HAL_S32: - obj = Py_BuildValue("{s:s,s:l,s:s,s:N}", - str_n, sig->name, - str_v, (long)d_ptr->s, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_S32)); - break; - case HAL_U64: - obj = Py_BuildValue("{s:s,s:K,s:s,s:N}", - str_n, sig->name, - str_v, (unsigned long long)d_ptr->lu, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_U64)); - break; - case HAL_S64: - obj = Py_BuildValue("{s:s,s:L,s:s,s:N}", - str_n, sig->name, - str_v, (long long)d_ptr->ls, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_S64)); - break; - case HAL_FLOAT: - obj = Py_BuildValue("{s:s,s:d,s:s,s:N}", - str_n, sig->name, - str_v, (double)d_ptr->f, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_FLOAT)); - break; - case HAL_PORT: - obj = Py_BuildValue("{s:s,s:l,s:s,s:N}", - str_n, sig->name, - str_v, (long)d_ptr->p, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, PyLong_FromLong(HAL_PORT)); - break; - case HAL_TYPE_UNSPECIFIED: /* fallthrough */ ; - case HAL_TYPE_UNINITIALIZED: /* fallthrough */ ; - default: - obj = Py_BuildValue("{s:s,s:s,s:s,s:s}", - str_n, sig->name, - str_v, NULL, - str_d, (pin != NULL) ? pin->name : NULL, - str_t, NULL); - break; - } + const char *writer = NULL; + if(q->sig.writers > 0) { + // Retrieve the writer pin name + hal_query_t qd = {}; + qd.name = q->name; + hal_list_p_s(&qd, siginfo_writer_cb, (void *)&writer); + } - PyList_Append( python_list, obj); - next = sig->next_ptr; + switch(q->sig.type) { + case HAL_BOOL: + obj = Py_BuildValue("{s:s,s:N,s:s,s:N}", + str_n, q->name, str_v, PyBool_FromLong(hal_get_bool(q->sig.ref.b)), + str_d, writer, str_t, PyLong_FromLong(HAL_BOOL)); + break; + case HAL_U32: + obj = Py_BuildValue("{s:s,s:k,s:s,s:N}", + str_n, q->name, str_v, hal_get_ui32(q->sig.ref.u), + str_d, writer, str_t, PyLong_FromLong(HAL_U32)); + break; + case HAL_S32: + obj = Py_BuildValue("{s:s,s:l,s:s,s:N}", + str_n, q->name, str_v, hal_get_si32(q->sig.ref.s), + str_d, writer, str_t, PyLong_FromLong(HAL_S32)); + break; + case HAL_UINT: + obj = Py_BuildValue("{s:s,s:K,s:s,s:N}", + str_n, q->name, str_v, hal_get_uint(q->sig.ref.u), + str_d, writer, str_t, PyLong_FromLong(HAL_UINT)); + break; + case HAL_SINT: + obj = Py_BuildValue("{s:s,s:L,s:s,s:N}", + str_n, q->name, str_v, hal_get_sint(q->sig.ref.s), + str_d, writer, str_t, PyLong_FromLong(HAL_SINT)); + break; + case HAL_REAL: + obj = Py_BuildValue("{s:s,s:d,s:s,s:N}", + str_n, q->name, str_v, hal_get_real(q->sig.ref.r), + str_d, writer, str_t, PyLong_FromLong(HAL_REAL)); + break; + case HAL_PORT: + obj = Py_BuildValue("{s:s,s:l,s:s,s:N}", + str_n, q->name, str_v, hal_get_sint(q->sig.ref.s), + str_d, writer, str_t, PyLong_FromLong(HAL_PORT)); + break; + default: + obj = Py_BuildValue("{s:s,s:s,s:s,s:s}", + str_n, q->name, str_v, NULL, + str_d, writer, str_t, NULL); + break; } + PyList_Append(lst, obj); + Py_DECREF(obj); + return 0; +} +PyObject *get_info_signals(PyObject * /*self*/, PyObject * /*args*/) +{ + PyObject* python_list = PyList_New(0); + hal_query_t q = {}; + int rv = hal_list_s(&q, siginfo_cb, python_list); + if(0 != rv) { + Py_DECREF(python_list); + PyErr_Format(PyExc_RuntimeError, "hal_list_s: returned '%s' (%d)", hal_strerror(rv), rv); + return NULL; + } return python_list; } /*######################################*/ /* Get a dict of parameter info for all parameters in system */ -PyObject *get_info_params(PyObject * /*self*/, PyObject * /*args*/) { - SHMFIELD(hal_param_t) next; - int type; - static const char str_n[] = "NAME"; - static const char str_v[] = "VALUE"; - static const char str_t[] = "TYPE"; - static const char str_d[] = "DIRECTION"; - hal_data_u *d_ptr; - hal_param_t *param; +PyObject *get_info_params(PyObject * /*self*/, PyObject * /*args*/) +{ PyObject* python_list = PyList_New(0); - PyObject *obj; - - TEST_HAL_SHMEM_BASE(__FUNCTION__); - - scoped_hal_mutex _hallock; /* get mutex before accessing shared data */ - - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - type = param->type; - d_ptr = reinterpret_cast(SHMPTR(param->data_ptr)); - - /* convert to dict of python values */ - switch(type) { - case HAL_BIT: - obj = Py_BuildValue("{s:s,s:N,s:N,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, PyBool_FromLong((long)d_ptr->b), - str_t, PyLong_FromLong(HAL_BIT)); - break; - case HAL_U32: - obj = Py_BuildValue("{s:s,s:N,s:k,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, (unsigned long)d_ptr->u, - str_t, PyLong_FromLong(HAL_U32)); - break; - case HAL_S32: - obj = Py_BuildValue("{s:s,s:N,s:l,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, (long)d_ptr->s, - str_t, PyLong_FromLong(HAL_S32)); - break; - case HAL_U64: - obj = Py_BuildValue("{s:s,s:N,s:K,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, (unsigned long long)d_ptr->lu, - str_t, PyLong_FromLong(HAL_U64)); - break; - case HAL_S64: - obj = Py_BuildValue("{s:s,s:N,s:L,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, (long long)d_ptr->ls, - str_t, PyLong_FromLong(HAL_S64)); - break; - case HAL_FLOAT: - obj = Py_BuildValue("{s:s,s:N,s:d,s:N}", - str_n, param->name, - str_d, PyLong_FromLong(param->dir), - str_v, (double)d_ptr->f, - str_t, PyLong_FromLong(HAL_FLOAT)); - break; - case HAL_PORT: // HAL_PORT cannot be a parameter - case HAL_TYPE_UNSPECIFIED: /* fallthrough */ ; - case HAL_TYPE_UNINITIALIZED: /* fallthrough */ ; - default: - obj = Py_BuildValue("{s:s,s:s,s:s,s:s}", - str_n, param->name, - str_d, NULL, - str_v, NULL, - str_t, NULL); - break; - } - - PyList_Append( python_list, obj); - next = param->next_ptr; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; // Only handle parameters + int rv = hal_list_p(&q, pinparaminfo_cb, python_list); + if(0 != rv) { + Py_DECREF(python_list); + PyErr_Format(PyExc_RuntimeError, "hal_list_p: returned '%s' (%d)", hal_strerror(rv), rv); + return NULL; } - return python_list; } static PyObject *pyhal_get_realtime_type(PyObject * /*self*/, PyObject * /*o*/) { - TEST_HAL_SHMEM_BASE(__FUNCTION__); int res = hal_get_realtime_type(); return PyLong_FromLong(res); } static PyObject *pyhal_is_initialized(PyObject * /*self*/, PyObject * /*o*/) { - return PyBool_FromLong(hal_shmem_base != NULL); + return PyBool_FromLong(hal_is_init()); } struct shmobject { @@ -2061,12 +1831,12 @@ static int pystream_init(PyObject *_self, PyObject *args, PyObject * /*kw*/) { for(int i=0; istream, i)) { - case HAL_BIT: tbuf[i] = 'b'; break; - case HAL_FLOAT: tbuf[i] = 'f'; break; - case HAL_S32: tbuf[i] = 's'; break; - case HAL_U32: tbuf[i] = 'u'; break; - case HAL_S64: tbuf[i] = 'l'; break; - case HAL_U64: tbuf[i] = 'k'; break; + case HAL_BOOL: tbuf[i] = 'b'; break; + case HAL_REAL: tbuf[i] = 'f'; break; + case HAL_S32: tbuf[i] = 's'; break; + case HAL_U32: tbuf[i] = 'u'; break; + case HAL_SINT: tbuf[i] = 'l'; break; + case HAL_UINT: tbuf[i] = 'k'; break; default: tbuf[i] = '?'; break; } } @@ -2312,6 +2082,11 @@ static PyMethodDef module_methods[] = { ".set_p('name', 'value'): Set the pin or param value"}, {"set_s", set_s, METH_VARARGS, ".set_s('name', 'value'): Set the signal value"}, + {"get_p", get_p, METH_VARARGS, + ".get_p('name', 'value'): Get the pin or param value. Will return the signal value if it is a pin and connected"}, + {"get_s", get_s, METH_VARARGS, + ".get_s('name', 'value'): Get the signal value"}, + {"get_value", get_value, METH_VARARGS, ".get_value('name'): Gets the pin, param or signal value"}, @@ -2358,7 +2133,7 @@ static struct PyModuleDef hal_moduledef = { PyModuleDef_HEAD_INIT, /* m_base */ "_hal", /* m_name */ module_doc, /* m_doc */ - -1, /* m_size */ + 0, /* m_size */ module_methods, /* m_methods */ NULL, /* m_slots */ NULL, /* m_traverse */ @@ -2366,10 +2141,117 @@ static struct PyModuleDef hal_moduledef = { NULL, /* m_free */ }; +static void addToDict(PyObject *dict, const char *key, int val) +{ + PyObject *k = PyUnicode_FromString(key); + PyObject *v = PyLong_FromLong(val); + PyDict_SetItem(dict, k, v); + Py_DECREF(v); + Py_DECREF(k); +} + +static PyObject *dictEnumType(void) +{ + PyObject *dict = PyDict_New(); + if(!dict) { + return NULL; + } + addToDict(dict, "BOOL", HAL_BOOL); + addToDict(dict, "SINT", HAL_SINT); + addToDict(dict, "UINT", HAL_UINT); + addToDict(dict, "REAL", HAL_REAL); + addToDict(dict, "PORT", HAL_PORT); + // These are here for compatibility + addToDict(dict, "BIT", HAL_BIT); + addToDict(dict, "S32", HAL_S32); + addToDict(dict, "U32", HAL_U32); + addToDict(dict, "FLOAT", HAL_FLOAT); + addToDict(dict, "S64", HAL_S64); + addToDict(dict, "U64", HAL_U64); + return dict; +} + +static PyObject *dictEnumDir(void) +{ + PyObject *dict = PyDict_New(); + if(!dict) { + return NULL; + } + addToDict(dict, "IN", HAL_IN); + addToDict(dict, "OUT", HAL_OUT); + addToDict(dict, "IO", HAL_IO); + addToDict(dict, "RO", HAL_RO); + addToDict(dict, "WO", HAL_WO); + addToDict(dict, "RW", HAL_RW); + return dict; +} + +// +// This effectively does: +// import enum +// myenum = enum.IntEnum('MyEnumName', dict(key1=val1, key2=val2, ...)) +// del enum +// return myenum +// +static PyObject *addModuleEnum(PyObject *mod, PyObject *dict, const char *enumname) +{ + // Import enum + PyObject *enum_module = PyImport_ImportModule("enum"); + if(!enum_module) { + PyErr_SetString(PyExc_ImportError, "Failed to import 'enum'"); + return NULL; + } + + // Get enum.Enum, the class we need + PyObject *enum_class = PyObject_GetAttrString(enum_module, "IntEnum"); + if(!enum_class) { + PyErr_SetString(PyExc_ImportError, "Failed to retrieve 'enum.IntEnum'"); + Py_DECREF(enum_module); + return NULL; + } + Py_INCREF(enum_class); // Take ownership, tp_base references it + + PyObject *name = PyUnicode_FromString(enumname); + PyObject *args = PyTuple_Pack(2, name, dict); + Py_DECREF(dict); + Py_DECREF(name); + + PyObject *kwargs = PyDict_New(); + PyObject *modarg = PyUnicode_FromString("module"); + PyObject *modname = PyModule_GetNameObject(mod); + PyDict_SetItem(kwargs, modarg, modname); + Py_DECREF(modname); + Py_DECREF(modarg); + + // This calls: result = enum.Enum(, dict(key=val,...)) + PyObject *enum_type = PyObject_Call(enum_class, args, kwargs); + Py_DECREF(kwargs); + Py_DECREF(args); + Py_DECREF(enum_class); + Py_DECREF(enum_module); + + if(!enum_type) { + PyErr_Format(PyExc_ImportError, "Failed to create 'hal.%s'", enumname); + return NULL; + } + return enum_type; +} + PyMODINIT_FUNC PyInit__hal(void); PyMODINIT_FUNC PyInit__hal(void) { PyObject *m = PyModule_Create(&hal_moduledef); + if(!m) + return NULL; + + int rv; + if(0 != (rv = hal_lib_init())) { + PyErr_Format(PyExc_ImportError, "Initializing hal_lib returned error=%d", rv); + Py_DECREF(m); + return NULL; + } + + Py_AtExit(hal_lib_exit); pyhal_error_type = PyErr_NewException("hal.error", NULL, NULL); PyModule_AddObject(m, "error", pyhal_error_type); @@ -2383,6 +2265,23 @@ PyMODINIT_FUNC PyInit__hal(void) PyModule_AddObject(m, "item", (PyObject*)&halpin_type); PyModule_AddObject(m, "stream", (PyObject*)&stream_type); + // hal.Type.BOOL, REAL,... + PyObject *et = addModuleEnum(m, dictEnumType(), "Type"); + if(et) { + PyModule_AddObject(m, "Type", et); + } else { + Py_DECREF(m); + return NULL; + } + // hal.Dir.IN, OUT,... + PyObject *ed = addModuleEnum(m, dictEnumDir(), "Dir"); + if(ed) { + PyModule_AddObject(m, "Dir", ed); + } else { + Py_DECREF(m); + return NULL; + } + PyModule_AddIntConstant(m, "MSG_NONE", RTAPI_MSG_NONE); PyModule_AddIntConstant(m, "MSG_ERR", RTAPI_MSG_ERR); PyModule_AddIntConstant(m, "MSG_WARN", RTAPI_MSG_WARN); @@ -2390,6 +2289,10 @@ PyMODINIT_FUNC PyInit__hal(void) PyModule_AddIntConstant(m, "MSG_DBG", RTAPI_MSG_DBG); PyModule_AddIntConstant(m, "MSG_ALL", RTAPI_MSG_ALL); + PyModule_AddIntConstant(m, "HAL_BOOL", HAL_BOOL); + PyModule_AddIntConstant(m, "HAL_REAL", HAL_REAL); + PyModule_AddIntConstant(m, "HAL_SINT", HAL_SINT); + PyModule_AddIntConstant(m, "HAL_UINT", HAL_UINT); PyModule_AddIntConstant(m, "HAL_BIT", HAL_BIT); PyModule_AddIntConstant(m, "HAL_FLOAT", HAL_FLOAT); PyModule_AddIntConstant(m, "HAL_S32", HAL_S32); diff --git a/src/hal/halquery.c b/src/hal/halquery.c new file mode 100644 index 00000000000..d95c83dc5b2 --- /dev/null +++ b/src/hal/halquery.c @@ -0,0 +1,619 @@ +// +// HAL Python query API +// +// Copyright (c) 2026 B.Stultiens +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +#include +#include + +#include "utils/setps_util.h" + +static PyObject *value_object(hal_type_t type, hal_refs_u u) +{ + switch(type) { + case HAL_BOOL: return PyBool_FromLong(hal_get_bool(u.b)); + case HAL_S32: return PyLong_FromLong(hal_get_si32(u.s)); + case HAL_SINT: return PyLong_FromLongLong(hal_get_sint(u.s)); + case HAL_U32: return PyLong_FromUnsignedLong(hal_get_ui32(u.u)); + case HAL_UINT: return PyLong_FromUnsignedLongLong(hal_get_uint(u.u)); + case HAL_REAL: return PyFloat_FromDouble(hal_get_real(u.r)); + case HAL_PORT: return PyLong_FromLong(0); // FIXME + default: Py_INCREF(Py_None); return Py_None; + } +} + +static PyObject *build_dict_comp(const hal_query_t *q) +{ + return Py_BuildValue("{s:s,s:s,s:i,s:i,s:i,s:p,s:s}", + "haltype", "component", + "name", q->name, + "type", q->comp.type, + "id", q->comp.comp_id, + "pid", q->comp.pid, + "ready", (int)q->comp.ready, + "insmod", q->comp.insmod); +} + +static PyObject *build_dict_pin_param(const hal_query_t *q, int ispin) +{ + return Py_BuildValue("{s:s,s:s,s:i,s:i,s:N,s:s,s:s,s:s,s:i}", + "haltype", ispin ? "pin" : "param", + "name", q->name, + "type", (int)q->pp.type, + "dir", (int)q->pp.dir, + "value", value_object(q->pp.type, q->pp.ref), + "alias", q->pp.alias, + "signal", q->pp.signal, + "comp", q->pp.comp, + "comp_id", q->pp.comp_id); +} + +static PyObject *build_dict_signal(const hal_query_t *q) +{ + return Py_BuildValue("{s:s,s:s,s:i,s:N,s:i,s:i,s:i}", + "haltype", "signal", + "name", q->name, + "type", (int)q->sig.type, + "value", value_object(q->sig.type, q->sig.ref), + "writers", q->sig.writers, + "readers", q->sig.readers, + "bidirs", q->sig.bidirs); +} + +static PyObject *build_dict_funct(const hal_query_t *q) +{ + return Py_BuildValue("{s:s,s:s,s:s,s:i,s:i,s:p}", + "haltype", "function", + "name", q->name, + "comp", q->funct.comp, + "comp_id", q->funct.comp_id, + "users", q->funct.users, + "reentrant", q->funct.reentrant); +} + +static PyObject *build_dict_threadfunct(const hal_query_t *q) +{ + return Py_BuildValue("{s:s,s:s,s:i,s:p}", + "haltype", "threadfunction", + "name", q->thread.funct, + "index", q->thread.functidx, + "is_init", (int)q->thread.is_init); +} + +static PyObject *build_dict_thread(const hal_query_t *q, PyObject *functs) +{ + return Py_BuildValue("{s:s,s:s,s:s,s:i,s:i,s:l,s:N}", + "haltype", "thread", + "name", q->name, + "comp", q->thread.comp, + "comp_id", q->thread.comp_id, + "priority", q->thread.priority, + "period", q->thread.period, + "functions", functs); +} + +// +// *** Get named component *** +// +static PyObject *get_comp(PyObject *self, PyObject *args) +{ + (void)self; + PyObject *obj = NULL; + if(!PyArg_ParseTuple(args, "O", &obj)) + return NULL; + + hal_query_t q = {}; + int rv; + if(PyUnicode_Check(obj)) { + rv = hal_comp_by_name(PyUnicode_AsUTF8(obj), &q); + } else if(PyLong_Check(obj)) { + rv = hal_comp_by_id((int)PyLong_AsLong(obj), &q); + } else { + PyErr_SetString(PyExc_TypeError, "component() expects a string or an integer as argument"); + return NULL; + } + switch(rv) { + case -ENOENT: Py_INCREF(Py_None); return Py_None; + case 0: return build_dict_comp(&q); + default: + PyErr_Format(PyExc_RuntimeError, "hal_comp_by_*: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; + } +} + +// +// *** Get named pin/param *** +// +static PyObject *get_pin_param(PyObject *args, int ispin) +{ + hal_query_t q = {}; + q.qtype = ispin ? HAL_QTYPE_PIN : HAL_QTYPE_PARAM; + + if(!PyArg_ParseTuple(args, "s", &q.name)) + return NULL; + + int rv = hal_getref_p(&q); + switch(rv) { + case -ENOENT: Py_INCREF(Py_None); return Py_None; + case 0: return build_dict_pin_param(&q, ispin); + default: + PyErr_Format(PyExc_RuntimeError, "hal_get_p: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; + } +} + +static PyObject *get_pin(PyObject *self, PyObject *args) +{ + (void)self; + return get_pin_param(args, 1); +} + +static PyObject *get_param(PyObject *self, PyObject *args) +{ + (void)self; + return get_pin_param(args, 0); +} + +// +// *** Get named signal *** +// +static PyObject *get_signal(PyObject *self, PyObject *args) +{ + (void)self; + hal_query_t q = {}; + + if(!PyArg_ParseTuple(args, "s", &q.name)) + return NULL; + + int rv = hal_getref_s(&q); + switch(rv) { + case -ENOENT: Py_INCREF(Py_None); return Py_None; + case 0: return build_dict_signal(&q); + default: + PyErr_Format(PyExc_RuntimeError, "hal_get_s: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; + } +} + +// +// *** Get named function *** +// +static int get_funct_cb(hal_query_t *q, void *arg) +{ + if(!strcmp(q->name, (const char *)arg)) + return 1; // Found it,break the loop without error + return 0; +} + +static PyObject *get_funct(PyObject *self, PyObject *args) +{ + (void)self; + const char *name; + if(!PyArg_ParseTuple(args, "s", &name)) + return NULL; + + hal_query_t q = {}; + int rv = hal_list_funct(&q, get_funct_cb, (void *)name); + switch(rv) { + case 0: Py_INCREF(Py_None); return Py_None; + case 1: return build_dict_funct(&q); + default: + PyErr_Format(PyExc_RuntimeError, "hal_list_funct: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; + } +} + +// +// *** Get named thread *** +// +typedef struct { + const char *name; + PyObject *dict; + PyObject *functs; + hal_query_t qt; +} threadlist_t; + +static int get_thread_cb(hal_query_t *q, void *arg) +{ + threadlist_t *tlp = (threadlist_t *)arg; + if(!strcmp(tlp->name, q->name)) { + if(q->qtype == HAL_QTYPE_THREAD) { + // Thread construct + tlp->qt = *q; + tlp->functs = PyList_New(0); + if(!tlp->functs) + return -ENOMEM; + } else if(q->qtype == HAL_QTYPE_THREAD_FUNCT) { + // Attached function to thread + PyObject *obj = build_dict_threadfunct(q); + PyList_Append(tlp->functs, obj); + Py_DECREF(obj); + } else { + return -EINVAL; + } + } else if(tlp->dict) { + // We moved to the next thread name and caught the one we want + tlp->dict = build_dict_thread(&tlp->qt, tlp->functs); + tlp->functs = NULL; + return 1; + } + return 0; +} + +static PyObject *get_thread(PyObject *self, PyObject *args) +{ + (void)self; + const char *name; + if(!PyArg_ParseTuple(args, "s", &name)) + return NULL; + + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; + threadlist_t tl = { .name = name, .dict = NULL, .functs = NULL, .qt = {} }; + int rv = hal_list_thread(&q, get_thread_cb, &tl); + if(rv >= 0) { + // Return value can be zero if the last in the list was the one we + // wanted. Iteration stops by end-of-list and not by a name change. + if(tl.functs) { + // List created, but callback terminated without seeing a new + // thread object. This happens when the found thread is the last in + // the list. We need to create the thread dict here. + tl.dict = build_dict_thread(&tl.qt, tl.functs); + } + if(!tl.dict) { + // List not created means name not found + Py_INCREF(Py_None); + return Py_None; + } + return tl.dict; + } + PyErr_Format(PyExc_RuntimeError, "hal_list_thread: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all pins connected to a named signal *** +// +static int get_signalpins_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_pin_param(q, 1); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_signalpins(PyObject *self, PyObject *args) +{ + (void)self; + hal_query_t q = {}; + if(!PyArg_ParseTuple(args, "s", &q.name)) + return NULL; + + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_SetString(PyExc_RuntimeError, "get_signalpins: PyDict_New failed"); + return NULL; + } + int rv = hal_list_p_s(&q, get_signalpins_cb, (void *)dict); + if(!rv) + return dict; + if(-ENOENT == rv) { + Py_INCREF(Py_None); + return Py_None; + } + PyErr_Format(PyExc_RuntimeError, "hal_list_p_s: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all pins *** +// +static int get_pins_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_pin_param(q, 1); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_pins(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_SetString(PyExc_RuntimeError, "get_pins: PyDict_New failed"); + return NULL; + } + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + int rv = hal_list_p(&q, get_pins_cb, (void *)dict); + if(!rv) + return dict; + PyErr_Format(PyExc_RuntimeError, "hal_list_p: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all params *** +// +static int get_params_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_pin_param(q, 0); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_params(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_SetString(PyExc_RuntimeError, "get_params: PyDict_New failed"); + return NULL; + } + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; + int rv = hal_list_p(&q, get_params_cb, (void *)dict); + if(!rv) + return dict; + PyErr_Format(PyExc_RuntimeError, "hal_list_p: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all signals *** +// +static int get_signals_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_signal(q); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_signals(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_Format(PyExc_RuntimeError, "get_signals: PyDict_New failed"); + return NULL; + } + hal_query_t q = {}; + int rv = hal_list_s(&q, get_signals_cb, (void *)dict); + if(!rv) + return dict; + PyErr_Format(PyExc_RuntimeError, "hal_list_s: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all components *** +// +static int get_comps_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_comp(q); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_comps(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_Format(PyExc_RuntimeError, "get_comps: PyDict_New failed"); + return NULL; + } + hal_query_t q = {}; + int rv = hal_list_comp(&q, get_comps_cb, (void *)dict); + if(!rv) + return dict; + PyErr_Format(PyExc_RuntimeError, "hal_list_comp: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all functions *** +// +static int get_functs_cb(hal_query_t *q, void *arg) +{ + PyObject *obj = build_dict_funct(q); + PyObject *str = PyUnicode_FromString(q->name); + PyDict_SetItem((PyObject *)arg, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + return 0; +} + +static PyObject *get_functs(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + PyObject *dict = PyDict_New(); + if(!dict) { + PyErr_Format(PyExc_RuntimeError, "get_functs: PyDict_New failed"); + return NULL; + } + hal_query_t q = {}; + int rv = hal_list_funct(&q, get_functs_cb, (void *)dict); + if(!rv) + return dict; + PyErr_Format(PyExc_RuntimeError, "hal_list_funct: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +// +// *** Get all threads *** +// +typedef struct { + hal_query_t qt; + PyObject *threads; + PyObject *functs; +} threadscb_t; +static int get_threads_cb(hal_query_t *q, void *arg) +{ + threadscb_t *tcb = (threadscb_t *)arg; + + if(HAL_QTYPE_THREAD == q->qtype) { + if(tcb->functs) { + // Seen functions from previous thread + PyObject *obj = build_dict_thread(&tcb->qt, tcb->functs); + PyObject *str = PyUnicode_FromString(tcb->qt.name); + PyDict_SetItem(tcb->threads, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + tcb->functs = NULL; + } + tcb->qt = *q; // Save the current thread info + // Create a function dictionary + if(!(tcb->functs = PyList_New(0))) + return -ENOMEM; + } else if(HAL_QTYPE_THREAD_FUNCT == q->qtype) { + PyObject *obj = build_dict_threadfunct(q); + PyList_Append(tcb->functs, obj); + Py_DECREF(obj); + } else { + return -EINVAL; + } + return 0; +} + +static PyObject *get_threads(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + threadscb_t tc = {}; + tc.threads = PyDict_New(); + if(!tc.threads) { + PyErr_Format(PyExc_RuntimeError, "get_threads: PyDict_New failed"); + return NULL; + } + + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; + int rv = hal_list_thread(&q, get_threads_cb, &tc); + if(rv >= 0) { + // Return value can be zero if the last in the list was the one we + // wanted. Iteration stops by end-of-list and not by a name change. + if(tc.functs) { + PyObject *obj = build_dict_thread(&tc.qt, tc.functs); + PyObject *str = PyUnicode_FromString(tc.qt.name); + PyDict_SetItem(tc.threads, str, obj); + Py_DECREF(str); + Py_DECREF(obj); + } + return tc.threads; + } + PyErr_Format(PyExc_RuntimeError, "hal_list_thread: error=%d (%s)", rv, hal_strerror(rv)); + return NULL; +} + +static PyMethodDef halquery_module_methods[] = { + {"pin", get_pin, METH_VARARGS, "pin(name:string)"}, + {"param", get_param, METH_VARARGS, "param(name:string)"}, + {"signal", get_signal, METH_VARARGS, "signal(name:string)"}, + {"comp", get_comp, METH_VARARGS, "comp(name:string|id:int)"}, + {"funct", get_funct, METH_VARARGS, "funct(name:string)"}, + {"thread", get_thread, METH_VARARGS, "thread(name:string)"}, + + {"signalpins", get_signalpins, METH_VARARGS, "signalpins(name:string)"}, + + {"pins", get_pins, METH_NOARGS, "pins()"}, + {"params", get_params, METH_NOARGS, "params()"}, + {"signals", get_signals, METH_NOARGS, "signals()"}, + {"comps", get_comps, METH_NOARGS, "comps()"}, + {"functs", get_functs, METH_NOARGS, "functs()"}, + {"threads", get_threads, METH_NOARGS, "threads()"}, + {}, +}; + +static const char halquery_module_doc[] = + "Query interface to LinuxCNC's HAL internals\n" + "\n" + "This module allows you to retrieve information about all HAL\n" + "internal constructs, such as:\n" + " - pins\n" + " - parameters\n" + " - signals\n" + " - components\n" + " - functions\n" + " - threads\n" + "\n" + "Typical usage:\n" + " import halquery\n" + " # print info on one component\n" + " print(\"Component xyz:\", halquery.component(\"xyz\"))\n" + "\n" + " # print info on all signals\n" + " print(\"Signals:\")\n" + " print(halquery.signals())\n" + ; + + +static int halquery_module_exec(PyObject *m) +{ + (void)m; + static int hq_init = 0; + if(hq_init) { + PyErr_SetString(PyExc_ImportError, "Cannot initialize halquery module more than once"); + return -1; + } + hq_init = 1; + + int rv; + if(0 != (rv = hal_lib_init())) { + PyErr_Format(PyExc_ImportError, "Initializing hal_lib returned error=%d", rv); + return -1; + } + return 0; +} + +static PyModuleDef_Slot halquery_module_slots[] = { + {Py_mod_exec, (void *)halquery_module_exec}, + {0, NULL} +}; + +static struct PyModuleDef halquery_moduledef = { + .m_base = PyModuleDef_HEAD_INIT, + .m_name = "halquery", + .m_doc = halquery_module_doc, + .m_methods = halquery_module_methods, + .m_slots = halquery_module_slots, +}; + +PyMODINIT_FUNC PyInit_halquery(void) +{ + return PyModuleDef_Init(&halquery_moduledef); +} +// vim: ts=4 sw=4 et diff --git a/src/hal/user_comps/gs2_vfd.c b/src/hal/user_comps/gs2_vfd.c index 0516af37a5d..5215f0b1679 100644 --- a/src/hal/user_comps/gs2_vfd.c +++ b/src/hal/user_comps/gs2_vfd.c @@ -89,38 +89,39 @@ typedef struct { /* HAL data struct */ typedef struct { - hal_s32_t *stat1; // status words from the VFD. Maybe split these out sometime - hal_s32_t *stat2; - hal_float_t *freq_cmd; // frequency command - hal_float_t *freq_out; // actual output frequency - hal_float_t *curr_out; // output current - hal_float_t *DCBusV; // - hal_float_t *outV; - hal_float_t *RPM; - hal_float_t *scale_freq; - hal_float_t *power_factor; - hal_float_t *load_pct; - hal_s32_t *FW_Rev; - hal_s32_t errorcount; - hal_float_t looptime; - hal_float_t speed_tolerance; - hal_s32_t retval; - hal_bit_t *at_speed; // when drive freq_cmd == freq_out and running - hal_bit_t *is_stopped; // when drive freq out is 0 - hal_float_t *speed_command; // speed command input - hal_float_t motor_hz; // speeds are scaled in Hz, not RPM - hal_float_t motor_RPM; // nameplate RPM at default Hz - hal_bit_t *spindle_on; // spindle 1=on, 0=off - hal_bit_t *spindle_fwd; // direction, 0=fwd, 1=rev - hal_bit_t *spindle_rev; // on when in rev and running - hal_bit_t *err_reset; // reset errors when 1 - hal_s32_t ack_delay; // number of read/writes before checking at-speed - - hal_bit_t old_run; // so we can detect changes in the run state - hal_bit_t old_dir; - hal_bit_t old_err_reset; - hal_bit_t *ena_gs2comp; // gs2 component enable pin - hal_bit_t *isInitialized; // initialized status pin + hal_sint_t stat1; // (pin) status words from the VFD. Maybe split these out sometime + hal_sint_t stat2; // (pin) + hal_real_t freq_cmd; // (pin) frequency command + hal_real_t freq_out; // (pin) actual output frequency + hal_real_t curr_out; // (pin) output current + hal_real_t DCBusV; // (pin) + hal_real_t outV; // (pin) + hal_real_t RPM; // (pin) + hal_real_t scale_freq; // (pin) + hal_real_t power_factor; // (pin) + hal_real_t load_pct; // (pin) + hal_sint_t FW_Rev; // (pin) + hal_sint_t errorcount; // (param) + hal_real_t looptime; // (param) + hal_real_t speed_tolerance; // (param) + hal_sint_t retval; // (param) + hal_bool_t at_speed; // (pin) when drive freq_cmd == freq_out and running + hal_bool_t is_stopped; // (pin) when drive freq out is 0 + hal_real_t speed_command; // (pin) speed command input + hal_real_t motor_hz; // (param) speeds are scaled in Hz, not RPM + hal_real_t motor_RPM; // (param) nameplate RPM at default Hz + hal_bool_t spindle_on; // (pin) spindle 1=on, 0=off + hal_bool_t spindle_fwd; // (pin) direction, 0=fwd, 1=rev + hal_bool_t spindle_rev; // (pin) on when in rev and running + hal_bool_t err_reset; // (pin) reset errors when 1 + hal_sint_t ack_delay; // (param) number of read/writes before checking at-speed + + hal_bool_t ena_gs2comp; // (pin) gs2 component enable pin + hal_bool_t isInitialized; // (pin) initialized status pin + + rtapi_bool old_run; // so we can detect changes in the run state + rtapi_bool old_dir; + rtapi_bool old_err_reset; } haldata_t; static int done; @@ -347,58 +348,63 @@ void gs2_show_config(modbus_t *mb_ctx) { int write_data(modbus_t *mb_ctx, slavedata_t *slavedata, haldata_t *haldata) { // int write_data[MAX_WRITE_REGS]; int retval; - hal_float_t hzcalc; + rtapi_real hzcalc; - if (haldata->motor_hz<10) - haldata->motor_hz = 60; - if ((haldata->motor_RPM < 600) || (haldata->motor_RPM > 5000)) - haldata->motor_RPM = 1800; - hzcalc = haldata->motor_hz/haldata->motor_RPM; + rtapi_real motor_hz = hal_get_real(haldata->motor_hz); + rtapi_real motor_RPM = hal_get_real(haldata->motor_RPM); + if (motor_hz < 10) + motor_hz = hal_set_real(haldata->motor_hz, 60); + if (motor_RPM < 600 || motor_RPM > 5000) + motor_RPM = hal_set_real(haldata->motor_RPM, 1800); + hzcalc = motor_hz / motor_RPM; retval = modbus_write_register( mb_ctx, slavedata->write_reg_start, - abs((int)(*(haldata->speed_command)*hzcalc*10)) + abs((int)(hal_get_real(haldata->speed_command)*hzcalc*10)) ); - if (*(haldata->spindle_on) != haldata->old_run) { - if (*haldata->spindle_on){ + rtapi_bool spindle_on = hal_get_bool(haldata->spindle_on); + if (spindle_on != haldata->old_run) { + if (spindle_on){ modbus_write_register(mb_ctx, slavedata->write_reg_start+1, 1); comm_delay=0; } else modbus_write_register(mb_ctx, slavedata->write_reg_start+1, 0); - haldata->old_run = *(haldata->spindle_on); + haldata->old_run = spindle_on; } - if (*(haldata->spindle_fwd) != haldata->old_dir) { - if (*haldata->spindle_fwd) + rtapi_bool spindle_fwd = hal_get_bool(haldata->spindle_fwd); + if (spindle_fwd != haldata->old_dir) { + if (spindle_fwd) modbus_write_register(mb_ctx, slavedata->write_reg_start+2, 0); else modbus_write_register(mb_ctx, slavedata->write_reg_start+2, 1); - haldata->old_dir = *(haldata->spindle_fwd); + haldata->old_dir = spindle_fwd; } - if (*(haldata->spindle_fwd) || !(*(haldata->spindle_on))) // JET turn on and off rev based on the status of fwd - *(haldata->spindle_rev) = 0; - if (!(*haldata->spindle_fwd) && *(haldata->spindle_on)) - *(haldata->spindle_rev) = 1; - if (*(haldata->err_reset) != haldata->old_err_reset) { - if (*(haldata->err_reset)) + if (spindle_fwd || !spindle_on) // JET turn on and off rev based on the status of fwd + hal_set_bool(haldata->spindle_rev, 0); + if (!spindle_fwd && spindle_on) + hal_set_bool(haldata->spindle_rev, 1); + rtapi_bool err_reset = hal_get_bool(haldata->err_reset); + if (err_reset != haldata->old_err_reset) { + if (err_reset) modbus_write_register(mb_ctx, slavedata->write_reg_start+4, 1); else modbus_write_register(mb_ctx, slavedata->write_reg_start+4, 0); - haldata->old_err_reset = *(haldata->err_reset); + haldata->old_err_reset = err_reset; } - if (comm_delay < haldata->ack_delay){ // JET allow time for communications between drive and EMC + if (comm_delay < hal_get_si32(haldata->ack_delay)){ // JET allow time for communications between drive and EMC comm_delay++; } - if ((*haldata->spindle_on) && comm_delay == haldata->ack_delay){ // JET test for up to speed - if ((*(haldata->freq_cmd))==(*(haldata->freq_out))) - *(haldata->at_speed) = 1; + if (spindle_on && comm_delay == hal_get_si32(haldata->ack_delay)){ // JET test for up to speed + if (hal_get_real(haldata->freq_cmd) == hal_get_real(haldata->freq_out)) + hal_set_bool(haldata->at_speed, 1); } - if (*(haldata->spindle_on)==0){ // JET reset at-speed - *(haldata->at_speed) = 0; + if (!spindle_on){ // JET reset at-speed + hal_set_bool(haldata->at_speed, 0); } - haldata->retval = retval; + hal_set_si32(haldata->retval, retval); return retval; } @@ -458,34 +464,34 @@ int read_data(modbus_t *mb_ctx, slavedata_t *slavedata, haldata_t *hal_data_bloc return -1; /* but we can signal an error if the other params are null */ if ((mb_ctx==NULL) || (slavedata == NULL)) { - hal_data_block->errorcount++; + hal_set_si32(hal_data_block->errorcount, hal_get_si32(hal_data_block->errorcount) + 1); return -1; } retval = modbus_read_registers(mb_ctx, slavedata->read_reg_start, slavedata->read_reg_count, receive_data); if (retval==slavedata->read_reg_count) { retval = 0; - hal_data_block->retval = retval; - *(hal_data_block->stat1) = receive_data[0]; - *(hal_data_block->stat2) = receive_data[1]; - *(hal_data_block->freq_cmd) = receive_data[2] * 0.1; - *(hal_data_block->freq_out) = receive_data[3] * 0.1; + hal_set_si32(hal_data_block->retval, retval); + hal_set_si32(hal_data_block->stat1, receive_data[0]); + hal_set_si32(hal_data_block->stat2, receive_data[1]); + hal_set_real(hal_data_block->freq_cmd, receive_data[2] * 0.1); + hal_set_real(hal_data_block->freq_out, receive_data[3] * 0.1); if (receive_data[3]==0) { // JET if freq out is 0 then the drive is stopped - *(hal_data_block->is_stopped) = 1; + hal_set_bool(hal_data_block->is_stopped, 1); } else { - *(hal_data_block->is_stopped) = 0; + hal_set_bool(hal_data_block->is_stopped, 0); } - *(hal_data_block->curr_out) = receive_data[4] * 0.1; - *(hal_data_block->DCBusV) = receive_data[5] * 0.1; - *(hal_data_block->outV) = receive_data[6] * 0.1; - *(hal_data_block->RPM) = receive_data[7]; - *(hal_data_block->scale_freq) = (receive_data[8] | (receive_data[9] << 16)) * 0.1; - *(hal_data_block->power_factor) = receive_data[10]; - *(hal_data_block->load_pct) = receive_data[11] * 0.1; - *(hal_data_block->FW_Rev) = receive_data[12]; + hal_set_real(hal_data_block->curr_out, receive_data[4] * 0.1); + hal_set_real(hal_data_block->DCBusV, receive_data[5] * 0.1); + hal_set_real(hal_data_block->outV, receive_data[6] * 0.1); + hal_set_real(hal_data_block->RPM, receive_data[7]); + hal_set_real(hal_data_block->scale_freq, (receive_data[8] | (receive_data[9] << 16)) * 0.1); + hal_set_real(hal_data_block->power_factor, receive_data[10]); + hal_set_real(hal_data_block->load_pct, receive_data[11] * 0.1); + hal_set_si32(hal_data_block->FW_Rev, receive_data[12]); } else { - hal_data_block->retval = retval; - hal_data_block->errorcount++; + hal_set_si32(hal_data_block->retval, retval); + hal_set_si32(hal_data_block->errorcount, hal_get_si32(hal_data_block->errorcount) + 1); retval = -1; } return retval; @@ -680,93 +686,64 @@ int main(int argc, char **argv) goto out_close; } - retval = hal_pin_s32_newf(HAL_OUT, &(haldata->stat1), hal_comp_id, "%s.status-1", modname); + retval = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(haldata->stat1), 0, "%s.status-1", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_s32_newf(HAL_OUT, &(haldata->stat2), hal_comp_id, "%s.status-2", modname); + retval = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(haldata->stat2), 0, "%s.status-2", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_cmd), hal_comp_id, "%s.frequency-command", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_cmd), 0.0, "%s.frequency-command", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_out), hal_comp_id, "%s.frequency-out", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_out), 0.0, "%s.frequency-out", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->curr_out), hal_comp_id, "%s.output-current", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->curr_out), 0.0, "%s.output-current", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->DCBusV), hal_comp_id, "%s.DC-bus-volts", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->DCBusV), 0.0, "%s.DC-bus-volts", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->outV), hal_comp_id, "%s.output-voltage", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->outV), 0.0, "%s.output-voltage", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->RPM), hal_comp_id, "%s.motor-RPM", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->RPM), 0.0, "%s.motor-RPM", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->scale_freq), hal_comp_id, "%s.scale-frequency", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->scale_freq), 0.0, "%s.scale-frequency", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->power_factor), hal_comp_id, "%s.power-factor", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->power_factor), 0.0, "%s.power-factor", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->load_pct), hal_comp_id, "%s.load-percentage", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->load_pct), 0.0, "%s.load-percentage", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_s32_newf(HAL_OUT, &(haldata->FW_Rev), hal_comp_id, "%s.firmware-revision", modname); + retval = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(haldata->FW_Rev), 0, "%s.firmware-revision", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_s32_newf(HAL_RW, &(haldata->errorcount), hal_comp_id, "%s.error-count", modname); + retval = hal_param_new_si32(hal_comp_id, HAL_RW, &(haldata->errorcount), 0, "%s.error-count", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_float_newf(HAL_RW, &(haldata->looptime), hal_comp_id, "%s.loop-time", modname); + retval = hal_param_new_real(hal_comp_id, HAL_RW, &(haldata->looptime), 0.1, "%s.loop-time", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_s32_newf(HAL_RW, &(haldata->retval), hal_comp_id, "%s.retval", modname); + retval = hal_param_new_si32(hal_comp_id, HAL_RW, &(haldata->retval), 0, "%s.retval", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->at_speed), hal_comp_id, "%s.at-speed", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->at_speed), 0, "%s.at-speed", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->is_stopped), hal_comp_id, "%s.is-stopped", modname); // JET + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->is_stopped), 0, "%s.is-stopped", modname); // JET if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_IN, &(haldata->speed_command), hal_comp_id, "%s.speed-command", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->speed_command), 0.0, "%s.speed-command", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_on), hal_comp_id, "%s.spindle-on", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_on), 0, "%s.spindle-on", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_fwd), hal_comp_id, "%s.spindle-fwd", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_fwd), 1, "%s.spindle-fwd", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_rev), hal_comp_id, "%s.spindle-rev", modname); //JET + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_rev), 0, "%s.spindle-rev", modname); //JET if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->err_reset), hal_comp_id, "%s.err-reset", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->err_reset), 0, "%s.err-reset", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_float_newf(HAL_RW, &(haldata->speed_tolerance), hal_comp_id, "%s.tolerance", modname); + retval = hal_param_new_real(hal_comp_id, HAL_RW, &(haldata->speed_tolerance), 0.01, "%s.tolerance", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_float_newf(HAL_RW, &(haldata->motor_hz), hal_comp_id, "%s.nameplate-HZ", modname); + retval = hal_param_new_real(hal_comp_id, HAL_RW, &(haldata->motor_hz), 60, "%s.nameplate-HZ", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_float_newf(HAL_RW, &(haldata->motor_RPM), hal_comp_id, "%s.nameplate-RPM", modname); + retval = hal_param_new_real(hal_comp_id, HAL_RW, &(haldata->motor_RPM), 1730, "%s.nameplate-RPM", modname); if (retval!=0) goto out_closeHAL; - retval = hal_param_s32_newf(HAL_RW, &(haldata->ack_delay), hal_comp_id, "%s.ack-delay", modname); + retval = hal_param_new_si32(hal_comp_id, HAL_RW, &(haldata->ack_delay), 2, "%s.ack-delay", modname); if (retval!=0) goto out_closeHAL; /* define run (enable) pin and isInitialized */ - retval = hal_pin_bit_newf(HAL_IN, &(haldata->ena_gs2comp), hal_comp_id, "%s.enable", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->ena_gs2comp), enabled, "%s.enable", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->isInitialized), hal_comp_id, "%s.initialized", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->isInitialized), 0, "%s.initialized", modname); if (retval!=0) goto out_closeHAL; - /* make default data match what we expect to use */ - *(haldata->stat1) = 0; - *(haldata->stat2) = 0; - *(haldata->freq_cmd) = 0; - *(haldata->freq_out) = 0; - *(haldata->curr_out) = 0; - *(haldata->DCBusV) = 0; - *(haldata->outV) = 0; - *(haldata->RPM) = 0; - *(haldata->scale_freq) = 0; - *(haldata->power_factor) = 0; - *(haldata->load_pct) = 0; - *(haldata->FW_Rev) = 0; - haldata->errorcount = 0; - haldata->looptime = 0.1; - haldata->motor_RPM = 1730; - haldata->motor_hz = 60; - haldata->speed_tolerance = 0.01; - haldata->ack_delay = 2; - *(haldata->err_reset) = 0; - *(haldata->spindle_on) = 0; - *(haldata->spindle_fwd) = 1; - *(haldata->spindle_rev) = 0; - haldata->old_run = -1; // make sure the initial value gets output - haldata->old_dir = -1; - haldata->old_err_reset = -1; - *(haldata->ena_gs2comp) = enabled; // command line override, defaults to "enabled" for compatibility - *(haldata->isInitialized) = 0; - // Activate HAL component hal_ready(hal_comp_id); @@ -774,23 +751,24 @@ int main(int argc, char **argv) while (done==0) { /* don't want to scan too fast, and shouldn't delay more than a few seconds */ - if (haldata->looptime < 0.001) haldata->looptime = 0.001; - if (haldata->looptime > 2.0) haldata->looptime = 2.0; - loop_timespec.tv_sec = (time_t)(haldata->looptime); - loop_timespec.tv_nsec = (long)((haldata->looptime - loop_timespec.tv_sec) * 1000000000l); + rtapi_real looptime = hal_get_real(haldata->looptime); + if (looptime < 0.001) looptime = hal_set_real(haldata->looptime, 0.001); + if (looptime > 2.0) looptime = hal_set_real(haldata->looptime, 2.0); + loop_timespec.tv_sec = (time_t)looptime; + loop_timespec.tv_nsec = (long)((looptime - loop_timespec.tv_sec) * 1000000000l); nanosleep(&loop_timespec, &remaining); - if(*(haldata->ena_gs2comp) == 0) { + if(!hal_get_bool(haldata->ena_gs2comp)) { // Component not enabled, so do nothing and force uninitialized state - if (*(haldata->isInitialized)) { - *(haldata->spindle_on) = 0; + if (hal_get_bool(haldata->isInitialized)) { + hal_set_bool(haldata->spindle_on, 0); // need to write to vfd in case we are here when it is being disabled write_data(mb_ctx, &slavedata, haldata); // debug printf below // printf("GS2: Disabling\n"); } - *(haldata->isInitialized) = 0; - } else if (!*(haldata->isInitialized)) { + hal_set_bool(haldata->isInitialized, 0); + } else if (!hal_get_bool(haldata->isInitialized)) { // Initialize: configure the gs2 vfd based on command-line arguments if (gs2_set_accel_time(mb_ctx, accel_time) != 0) { continue; @@ -803,13 +781,18 @@ int main(int argc, char **argv) } // debug printf below // printf("GS2: Initialized\n"); - *(haldata->isInitialized) = 1; + hal_set_bool(haldata->isInitialized, 1); } else { // Enabled and initialized, so do read/write of Modbus read_data(mb_ctx, &slavedata, haldata); write_data(mb_ctx, &slavedata, haldata); } } + // Set stored 'previous' to inverse of initialized to + // make sure the initial value gets output + haldata->old_run = !hal_get_bool(haldata->spindle_on); + haldata->old_dir = !hal_get_bool(haldata->spindle_fwd); + haldata->old_err_reset = !hal_get_bool(haldata->err_reset); retval = 0; /* if we get here, then everything is fine, so just clean up and exit */ out_closeHAL: diff --git a/src/hal/user_comps/huanyang-vfd/hy_vfd.c b/src/hal/user_comps/huanyang-vfd/hy_vfd.c index 630a6d48543..b42736c54a2 100644 --- a/src/hal/user_comps/huanyang-vfd/hy_vfd.c +++ b/src/hal/user_comps/huanyang-vfd/hy_vfd.c @@ -77,68 +77,56 @@ typedef struct { // The HAL comp name will be set to , and all pin and parameter // names will begin with . - hal_bit_t *enable; // bit to enable this component - - hal_float_t *Set_F; // frequency command - hal_float_t *Out_F; // actual output frequency - hal_float_t *Out_A; // actual output amps - hal_float_t *RoTT; // actual motor rmp (based on VFD parameters) - hal_float_t *DCV; // DC Volts (to be confirmed) - hal_float_t *ACV; // AC Volts (to be confirmed) - hal_float_t *Cont; - hal_float_t *Tmp; // Temperature (to be confirmed) - - hal_bit_t *spindle_forward; // spindle forward input - hal_bit_t *spindle_reverse; // spindle reverse input - hal_bit_t *spindle_on; // spinlde on input - hal_float_t *CNTR; // stores the status of the control request - hal_float_t *CNST; // stores the response of the control request - - hal_bit_t *CNST_Run; // CNST Run bit - hal_bit_t *CNST_Jog; // CNST Jog bit - hal_bit_t *CNST_Command_rf; // CNST Run reverse / forward bit - hal_bit_t *CNST_Running; // CNST Running bit - hal_bit_t *CNST_Jogging; // CNST Jogging bit - hal_bit_t *CNST_Running_rf; // CNST Jog reverse / forward bit - hal_bit_t *CNST_Bracking; // CNST bracking bit - hal_bit_t *CNST_Track_Start; // CNST track start bit - - hal_float_t *speed_command; // spindle speed command from EMC - hal_float_t *freq_cmd; // calculated frequency command - - hal_float_t *max_freq; // PD005 Max Operating Frequency - hal_float_t *base_freq; // PD004 Base Frequency - hal_float_t *freq_lower_limit; // PD011 Frequency Lower Limit - hal_float_t *rated_motor_voltage; // PD141 Rated Motor Voltage - as per motor name plate - hal_float_t *rated_motor_current; // PD142 Rated Motor Current - as per motor name plate - hal_u32_t *motor_poles; // PD143 Number of motor poles - from motor name plate - hal_float_t *rated_motor_rev; // max motor speed (at max_freq). PD144 gets set to value corresponding to RPM at 50Hz - - hal_bit_t *hycomm_ok; // the last HYCOMM_OK transactions returned successfully - - hal_float_t *max_rpm; // calculated based on VFD max frequency setup parameter - - hal_float_t *spindle_speed_fb; // (out) reports current spindle speed (rpm) - hal_float_t *spindle_speed_fb_rps; // (out) reports current spindle speed (rps) - hal_bit_t *spindle_at_speed; // (out) True when spindle is on and at commanded speed - hal_float_t *spindle_at_speed_tolerance; // (in) - - hal_u32_t *retval; - hal_s32_t *errorcount; - hal_float_t looptime; - - //hal_float_t motor_nameplate_hz; // speeds are scaled in Hz, not RPM - //hal_float_t motor_nameplate_RPM; // nameplate RPM at default Hz - //hal_float_t rpm_limit; // do-not-exceed output frequency - //hal_bit_t *acc_dec_pattern; // if set: choose ramp times as defined in F500+F501 - // if zero (default): choose ramp times as defined in ACC and DEC - //hal_float_t upper_limit_hz; // VFD setup parameter - maximum output frequency in HZ - - //hal_bit_t old_run; // so we can detect changes in the run state - //hal_bit_t old_dir; - //hal_bit_t old_err_reset; - //hal_u32_t old_cmd1_reg; // copy of last write to FA00 - //hal_u32_t failed_reg; // remember register for failed hycomm transaction - aids debugging + hal_bool_t enable; // bit to enable this component + + hal_real_t Set_F; // frequency command + hal_real_t Out_F; // actual output frequency + hal_real_t Out_A; // actual output amps + hal_real_t RoTT; // actual motor rmp (based on VFD parameters) + hal_real_t DCV; // DC Volts (to be confirmed) + hal_real_t ACV; // AC Volts (to be confirmed) + hal_real_t Cont; + hal_real_t Tmp; // Temperature (to be confirmed) + + hal_bool_t spindle_forward; // spindle forward input + hal_bool_t spindle_reverse; // spindle reverse input + hal_bool_t spindle_on; // spinlde on input + hal_real_t CNTR; // stores the status of the control request + hal_real_t CNST; // stores the response of the control request + + hal_bool_t CNST_Run; // CNST Run bit + hal_bool_t CNST_Jog; // CNST Jog bit + hal_bool_t CNST_Command_rf; // CNST Run reverse / forward bit + hal_bool_t CNST_Running; // CNST Running bit + hal_bool_t CNST_Jogging; // CNST Jogging bit + hal_bool_t CNST_Running_rf; // CNST Jog reverse / forward bit + hal_bool_t CNST_Bracking; // CNST bracking bit + hal_bool_t CNST_Track_Start; // CNST track start bit + + hal_real_t speed_command; // spindle speed command from EMC + hal_real_t freq_cmd; // calculated frequency command + + hal_real_t max_freq; // PD005 Max Operating Frequency + hal_real_t base_freq; // PD004 Base Frequency + hal_real_t freq_lower_limit; // PD011 Frequency Lower Limit + hal_real_t rated_motor_voltage; // PD141 Rated Motor Voltage - as per motor name plate + hal_real_t rated_motor_current; // PD142 Rated Motor Current - as per motor name plate + hal_uint_t motor_poles; // PD143 Number of motor poles - from motor name plate + hal_real_t rated_motor_rev; // max motor speed (at max_freq). PD144 gets set to value corresponding to RPM at 50Hz + + hal_bool_t hycomm_ok; // the last HYCOMM_OK transactions returned successfully + + hal_real_t max_rpm; // calculated based on VFD max frequency setup parameter + + hal_real_t spindle_speed_fb; // (out) reports current spindle speed (rpm) + hal_real_t spindle_speed_fb_rps; // (out) reports current spindle speed (rps) + hal_bool_t spindle_at_speed; // (out) True when spindle is on and at commanded speed + hal_real_t spindle_at_speed_tolerance; // (in) + + hal_uint_t retval; + hal_sint_t errorcount; + + rtapi_real looptime; } haldata_t; static int done; @@ -259,7 +247,7 @@ int write_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald int retval; int CNTR, old_CNTR; int CNST; - hal_float_t hz_per_rpm; + rtapi_real hz_per_rpm; int freq_comp; int freq, old_freq; @@ -267,31 +255,31 @@ int write_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald hc_data->function = WRITE_FREQ_DATA; hc_data->parameter = 0x00; - if ((*(haldata->spindle_forward) && !*(haldata->spindle_reverse)) && *(haldata->spindle_on)) { + if ((hal_get_bool(haldata->spindle_forward) && !hal_get_bool(haldata->spindle_reverse)) && hal_get_bool(haldata->spindle_on)) { freq_comp = 1; - } else if ((*(haldata->spindle_reverse) && !*(haldata->spindle_forward)) && *(haldata->spindle_on)) { + } else if ((hal_get_bool(haldata->spindle_reverse) && !hal_get_bool(haldata->spindle_forward)) && hal_get_bool(haldata->spindle_on)) { freq_comp = -1; } else { freq_comp = 0; } - hz_per_rpm = *haldata->max_freq / *(haldata->rated_motor_rev); - freq = abs((int)((*(haldata->speed_command)+freq_comp)*hz_per_rpm*100)); + hz_per_rpm = hal_get_real(haldata->max_freq) / hal_get_real(haldata->rated_motor_rev); + freq = abs((int)((hal_get_real(haldata->speed_command)+freq_comp)*hz_per_rpm*100)); // limit the frequency to the max and min as setup in the VFD - if (freq > *(haldata->max_freq)*100) - freq = *(haldata->max_freq)*100; - if (freq < *(haldata->freq_lower_limit)*100) - freq = *(haldata->freq_lower_limit)*100; + if (freq > hal_get_real(haldata->max_freq)*100) + freq = hal_get_real(haldata->max_freq)*100; + if (freq < hal_get_real(haldata->freq_lower_limit)*100) + freq = hal_get_real(haldata->freq_lower_limit)*100; - old_freq = *(haldata->freq_cmd); + old_freq = hal_get_real(haldata->freq_cmd); if (freq != old_freq) { // commanded frequency has changed hc_data->data = freq; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->freq_cmd) = freq; + hal_set_real(haldata->freq_cmd, freq); } @@ -300,87 +288,47 @@ int write_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald hc_data->function = WRITE_CONTROL_DATA; hc_data->parameter = 0x00; - if ((*(haldata->spindle_forward) && !*(haldata->spindle_reverse)) && *(haldata->spindle_on)) { + if ((hal_get_bool(haldata->spindle_forward) && !hal_get_bool(haldata->spindle_reverse)) && hal_get_bool(haldata->spindle_on)) { CNTR = CONTROL_Run_Fwd; - } else if ((*(haldata->spindle_reverse) && !*(haldata->spindle_forward)) && (*haldata->spindle_on)) { + } else if ((hal_get_bool(haldata->spindle_reverse) && !hal_get_bool(haldata->spindle_forward)) && hal_get_bool(haldata->spindle_on)) { CNTR = CONTROL_Run_Rev; } else { CNTR = CONTROL_Stop; } - old_CNTR = *(haldata->CNTR); + old_CNTR = hal_get_real(haldata->CNTR); hc_data->data = old_CNTR; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; if (CNTR != old_CNTR) { // CNTR register needs to be updated hc_data->data = CNTR; - *(haldata->CNTR) = CNTR; + hal_set_real(haldata->CNTR, CNTR); } CNST = hc_data->ret_data; - *(haldata->CNST) = CNST; - - if ((CNST & CONTROL_Run) != 0) { - *(haldata->CNST_Run) = TRUE; - } else { - *(haldata->CNST_Run) = FALSE; - } - - if ((CNST & CONTROL_Jog) != 0) { - *(haldata->CNST_Jog) = TRUE; - } else { - *(haldata->CNST_Jog) = FALSE; - } - - if ((CNST & CONTROL_Command_rf) != 0) { - *(haldata->CNST_Command_rf) = TRUE; - } else { - *(haldata->CNST_Command_rf) = FALSE; - } - - if ((CNST & CONTROL_Running) != 0) { - *(haldata->CNST_Running) = TRUE; - } else { - *(haldata->CNST_Running) = FALSE; - } - - if ((CNST & CONTROL_Jogging) != 0) { - *(haldata->CNST_Jogging) = TRUE; - } else { - *(haldata->CNST_Jogging) = FALSE; - } + hal_set_real(haldata->CNST, CNST); - if ((CNST & CONTROL_Running_rf) != 0) { - *(haldata->CNST_Running_rf) = TRUE; - } else { - *(haldata->CNST_Running_rf) = FALSE; - } - - - if ((CNST & CONTROL_Bracking) != 0) { - *(haldata->CNST_Bracking) = TRUE; - } else { - *(haldata->CNST_Bracking) = FALSE; - } - - if ((CNST & CONTROL_Track_Start) != 0) { - *(haldata->CNST_Track_Start) = TRUE; - } else { - *(haldata->CNST_Track_Start) = FALSE; - } + hal_set_bool(haldata->CNST_Run, (CNST & CONTROL_Run) != 0); + hal_set_bool(haldata->CNST_Jog, (CNST & CONTROL_Jog) != 0); + hal_set_bool(haldata->CNST_Command_rf, (CNST & CONTROL_Command_rf) != 0); + hal_set_bool(haldata->CNST_Running, (CNST & CONTROL_Running) != 0); + hal_set_bool(haldata->CNST_Jogging, (CNST & CONTROL_Jogging) != 0); + hal_set_bool(haldata->CNST_Running_rf, (CNST & CONTROL_Running_rf) != 0); + hal_set_bool(haldata->CNST_Bracking, (CNST & CONTROL_Bracking) != 0); + hal_set_bool(haldata->CNST_Track_Start, (CNST & CONTROL_Track_Start) != 0); retval = 0; - *(haldata->retval) = retval; + hal_set_ui32(haldata->retval, retval); return retval; failed: if (hc_param->debug) { printf("write_data: FAILED\n"); } - *(haldata->retval) = retval; - (*(haldata->errorcount))++; + hal_set_ui32(haldata->retval, retval); + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); retval = -1; return retval; @@ -396,7 +344,7 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald return -1; /* but we can signal an error if the other params are null */ if (hc_param==NULL) { - (*(haldata->errorcount))++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); return -1; } @@ -423,10 +371,10 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald hc_data->data = 0x0000; hc_data->parameter = 5; // PD005 Max Operating Frequency - if (*haldata->max_freq != 0) { + if (hal_get_real(haldata->max_freq) != 0) { // user passed in motor max freq, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->max_freq * 100); + hc_data->data = (uint16_t)(hal_get_real(haldata->max_freq) * 100); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -434,13 +382,13 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->max_freq) = hc_data->ret_data * 0.01; + hal_set_real(haldata->max_freq, hc_data->ret_data * 0.01); hc_data->parameter = 4; // PD004 Base Frequency - if (*haldata->base_freq != 0) { + if (hal_get_real(haldata->base_freq) != 0) { // user passed in base freq, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->base_freq * 100); + hc_data->data = (uint16_t)(hal_get_real(haldata->base_freq) * 100); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -448,13 +396,13 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->base_freq) = hc_data->ret_data * 0.01; + hal_set_real(haldata->base_freq, hc_data->ret_data * 0.01); hc_data->parameter = 11; // PD011 Frequency Lower Limit - if (*haldata->freq_lower_limit != 0) { + if (hal_get_real(haldata->freq_lower_limit) != 0) { // user passed in motor min freq, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->freq_lower_limit * 100); + hc_data->data = (uint16_t)(hal_get_real(haldata->freq_lower_limit) * 100); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -462,13 +410,13 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->freq_lower_limit) = hc_data->ret_data * 0.01; + hal_set_real(haldata->freq_lower_limit, hc_data->ret_data * 0.01); hc_data->parameter = 141; // PD141 Rated Motor Voltage - if (*haldata->rated_motor_voltage != 0) { + if (hal_get_real(haldata->rated_motor_voltage) != 0) { // user passed in motor max voltage, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->rated_motor_voltage * 10); + hc_data->data = (uint16_t)(hal_get_real(haldata->rated_motor_voltage) * 10); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -476,13 +424,13 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->rated_motor_voltage) = hc_data->ret_data * 0.1; + hal_set_real(haldata->rated_motor_voltage, hc_data->ret_data * 0.1); hc_data->parameter = 142; // PD142 Rated Motor Current - if (*haldata->rated_motor_current != 0) { + if (hal_get_real(haldata->rated_motor_current) != 0) { // user passed in motor max current, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->rated_motor_current * 10); + hc_data->data = (uint16_t)(hal_get_real(haldata->rated_motor_current) * 10); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -490,13 +438,13 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->rated_motor_current) = hc_data->ret_data * 0.1; + hal_set_real(haldata->rated_motor_current, hc_data->ret_data * 0.1); hc_data->parameter = 143; // PD143 Number of Motor Poles - if (*haldata->motor_poles != 0) { + if (hal_get_ui32(haldata->motor_poles) != 0) { // user passed in motor poles, send to VFD hc_data->function = FUNCTION_WRITE; - hc_data->data = (uint16_t)(*haldata->motor_poles); + hc_data->data = (uint16_t)hal_get_ui32(haldata->motor_poles); if ((retval = hy_comm(hc_param, hc_data)) != 0) { goto failed; } @@ -504,14 +452,14 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald } if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *haldata->motor_poles = hc_data->ret_data; + hal_set_ui32(haldata->motor_poles, hc_data->ret_data); hc_data->parameter = 144; // PD144 Rated Motor Rev (at 50 Hz) - if (*haldata->rated_motor_rev != 0) { + if (hal_get_real(haldata->rated_motor_rev) != 0) { // user passed in motor max speed // we know motor max freq // write the VFD's P144 with "motor speed at 50 Hz" - rpm_at_50hz = (*haldata->rated_motor_rev / *haldata->max_freq) * 50.0; + rpm_at_50hz = (hal_get_real(haldata->rated_motor_rev) / hal_get_real(haldata->max_freq)) * 50.0; hc_data->function = FUNCTION_WRITE; hc_data->data = (uint16_t)rpm_at_50hz; if ((retval = hy_comm(hc_param, hc_data)) != 0) { @@ -523,7 +471,7 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; rpm_at_50hz = hc_data->ret_data; - *(haldata->rated_motor_rev) = (rpm_at_50hz / 50.0) * *haldata->max_freq; + hal_set_real(haldata->rated_motor_rev, (rpm_at_50hz / 50.0) * hal_get_real(haldata->max_freq)); // Handle explicitly set registers for (int i = 0;hc_param->extra_reg[i] != 0; i++){ @@ -547,15 +495,15 @@ int read_setup(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *hald fflush(NULL); retval = 0; - *(haldata->retval) = retval; + hal_set_ui32(haldata->retval, retval); return retval; failed: if (hc_param->debug) { printf("read_setup: FAILED\n"); } - *(haldata->retval) = retval; - (*(haldata->errorcount))++; + hal_set_ui32(haldata->retval, retval); + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); retval = -1; return retval; @@ -574,7 +522,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_SetF; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->Set_F) = hc_data->ret_data * 0.01; + hal_set_real(haldata->Set_F, hc_data->ret_data * 0.01); if (hc_param->debug) { printf("Set_F = [%.2X]", hc_data->ret_data); printf("\n"); @@ -583,33 +531,33 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_OutF; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->Out_F) = hc_data->ret_data * 0.01; + hal_set_real(haldata->Out_F, hc_data->ret_data * 0.01); if (hc_param->debug) { printf("Out_F = [%.2X]", hc_data->ret_data); printf("\n"); } if ( - *haldata->spindle_on - && (fabs(*haldata->speed_command) > 0.0) - && (*haldata->Set_F > 0.0) + hal_get_bool(haldata->spindle_on) + && (fabs(hal_get_real(haldata->speed_command)) > 0.0) + && (hal_get_real(haldata->Set_F) > 0.0) ) { - *haldata->spindle_speed_fb = (*haldata->Out_F / *haldata->max_freq) * *haldata->rated_motor_rev; - *haldata->spindle_speed_fb_rps = *haldata->spindle_speed_fb / 60.0; - if (fabs(1 - (*haldata->spindle_speed_fb / fabs(*haldata->speed_command))) < *haldata->spindle_at_speed_tolerance) { - *haldata->spindle_at_speed = 1; + hal_set_real(haldata->spindle_speed_fb, (hal_get_real(haldata->Out_F) / hal_get_real(haldata->max_freq)) * hal_get_real(haldata->rated_motor_rev)); + hal_set_real(haldata->spindle_speed_fb_rps, hal_get_real(haldata->spindle_speed_fb) / 60.0); + if (fabs(1 - (hal_get_real(haldata->spindle_speed_fb) / fabs(hal_get_real(haldata->speed_command)))) < hal_get_real(haldata->spindle_at_speed_tolerance)) { + hal_set_bool(haldata->spindle_at_speed, 1); } else { - *haldata->spindle_at_speed = 0; + hal_set_bool(haldata->spindle_at_speed, 0); } } else { - *haldata->spindle_speed_fb = 0.0; - *haldata->spindle_at_speed = 0; + hal_set_real(haldata->spindle_speed_fb, 0.0); + hal_set_bool(haldata->spindle_at_speed, 0); } hc_data->data = STATUS_OutA; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->Out_A) = hc_data->ret_data * 0.1; + hal_set_real(haldata->Out_A, hc_data->ret_data * 0.1); if (hc_param->debug) { printf("Out_A = [%.2X]", hc_data->ret_data); printf("\n"); @@ -618,7 +566,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_RoTT; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->RoTT) = hc_data->ret_data; + hal_set_real(haldata->RoTT, hc_data->ret_data); if (hc_param->debug) { printf("RoTT = [%.2X]", hc_data->ret_data); printf("\n"); @@ -627,7 +575,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_DCV; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->DCV) = hc_data->ret_data; + hal_set_real(haldata->DCV, hc_data->ret_data); if (hc_param->debug) { printf("DCV = [%.2X]", hc_data->ret_data); printf("\n"); @@ -636,7 +584,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_ACV; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->ACV) = hc_data->ret_data; + hal_set_real(haldata->ACV, hc_data->ret_data); if (hc_param->debug) { printf("ACV = [%.2X]", hc_data->ret_data); printf("\n"); @@ -645,7 +593,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_Cont; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->Cont) = hc_data->ret_data; + hal_set_real(haldata->Cont, hc_data->ret_data); if (hc_param->debug) { printf("Cont = [%.2X]", hc_data->ret_data); printf("\n"); @@ -654,7 +602,7 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda hc_data->data = STATUS_Tmp; if ((retval = hy_comm(hc_param, hc_data)) != 0) goto failed; - *(haldata->Tmp) = hc_data->ret_data; + hal_set_real(haldata->Tmp, hc_data->ret_data); if (hc_param->debug) { printf("Tmp = [%.2X]", hc_data->ret_data); printf("\n"); @@ -662,15 +610,15 @@ int read_data(hycomm_param_t *hc_param, hycomm_data_t *hc_data, haldata_t *halda retval = 0; - *(haldata->retval) = retval; + hal_set_ui32(haldata->retval, retval); return retval; failed: if (hc_param->debug) { printf("read_data: FAILED\n"); } - *(haldata->retval) = retval; - (*(haldata->errorcount))++; + hal_set_ui32(haldata->retval, retval); + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); retval = -1; return retval; @@ -697,7 +645,7 @@ int main(int argc, char **argv) float motor_v = 0; float motor_i = 0; float motor_speed = 0; - hal_u32_t motor_poles = 0; + rtapi_u32 motor_poles = 0; done = 0; @@ -902,150 +850,106 @@ int main(int argc, char **argv) goto out_close; } - retval = hal_pin_bit_newf(HAL_IN, &(haldata->enable), hal_comp_id, "%s.enable", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->enable), 0, "%s.enable", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->Set_F), hal_comp_id, "%s.SetF", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->Set_F), 0.0, "%s.SetF", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->Out_F), hal_comp_id, "%s.OutF", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->Out_F), 0.0, "%s.OutF", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->Out_A), hal_comp_id, "%s.OutA", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->Out_A), 0.0, "%s.OutA", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->RoTT), hal_comp_id, "%s.Rott", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->RoTT), 0.0, "%s.Rott", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->DCV), hal_comp_id, "%s.DCV", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->DCV), 0.0, "%s.DCV", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->ACV), hal_comp_id, "%s.ACV", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->ACV), 0.0, "%s.ACV", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->Cont), hal_comp_id, "%s.Cont", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->Cont), 0.0, "%s.Cont", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->Tmp), hal_comp_id, "%s.Tmp", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->Tmp), 0.0, "%s.Tmp", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_forward), hal_comp_id, "%s.spindle-forward", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_forward), 0, "%s.spindle-forward", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_reverse), hal_comp_id, "%s.spindle-reverse", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_reverse), 0, "%s.spindle-reverse", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_on), hal_comp_id, "%s.spindle-on", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_on), 0, "%s.spindle-on", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->CNTR), hal_comp_id, "%s.CNTR", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->CNTR), 0.0, "%s.CNTR", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->CNST), hal_comp_id, "%s.CNST", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->CNST), 0.0, "%s.CNST", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Run), hal_comp_id, "%s.CNST-run", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Run), 0, "%s.CNST-run", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Jog), hal_comp_id, "%s.CNST-jog", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Jog), 0, "%s.CNST-jog", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Command_rf), hal_comp_id, "%s.CNST-command-rf", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Command_rf), 0, "%s.CNST-command-rf", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Running), hal_comp_id, "%s.CNST-running", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Running), 0, "%s.CNST-running", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Jogging), hal_comp_id, "%s.CNST-jogging", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Jogging), 0, "%s.CNST-jogging", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Running_rf), hal_comp_id, "%s.CNST-running-rf", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Running_rf), 0, "%s.CNST-running-rf", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Bracking), hal_comp_id, "%s.CNST-bracking", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Bracking), 0, "%s.CNST-bracking", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->CNST_Track_Start), hal_comp_id, "%s.CNST-track-start", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->CNST_Track_Start), 0, "%s.CNST-track-start", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_IN, &(haldata->speed_command), hal_comp_id, "%s.speed-command", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->speed_command), 0.0, "%s.speed-command", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_cmd), hal_comp_id, "%s.frequency-command", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_cmd), 0.0, "%s.frequency-command", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->max_freq), hal_comp_id, "%s.max-freq", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->max_freq), max_freq, "%s.max-freq", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->base_freq), hal_comp_id, "%s.base-freq", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->base_freq), base_freq, "%s.base-freq", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_lower_limit), hal_comp_id, "%s.freq-lower-limit", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_lower_limit), min_freq, "%s.freq-lower-limit", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->rated_motor_voltage), hal_comp_id, "%s.rated-motor-voltage", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->rated_motor_voltage), motor_v, "%s.rated-motor-voltage", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->rated_motor_current), hal_comp_id, "%s.rated-motor-current", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->rated_motor_current), motor_i, "%s.rated-motor-current", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->rated_motor_rev), hal_comp_id, "%s.rated-motor-rev", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->rated_motor_rev), motor_speed, "%s.rated-motor-rev", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_u32_newf(HAL_OUT, &(haldata->motor_poles), hal_comp_id, "%s.motor-poles", modname); + retval = hal_pin_new_ui32(hal_comp_id, HAL_OUT, &(haldata->motor_poles), motor_poles, "%s.motor-poles", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->hycomm_ok), hal_comp_id, "%s.hycomm-ok", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->hycomm_ok), 0, "%s.hycomm-ok", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_s32_newf(HAL_OUT, &(haldata->errorcount), hal_comp_id, "%s.error-count", modname); + retval = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(haldata->errorcount), 0, "%s.error-count", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_u32_newf(HAL_OUT, &(haldata->retval), hal_comp_id, "%s.retval", modname); + retval = hal_pin_new_ui32(hal_comp_id, HAL_OUT, &(haldata->retval), 0, "%s.retval", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->spindle_speed_fb), hal_comp_id, "%s.spindle-speed-fb", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->spindle_speed_fb), 0.0, "%s.spindle-speed-fb", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->spindle_at_speed), hal_comp_id, "%s.spindle-at-speed", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->spindle_at_speed), 0, "%s.spindle-at-speed", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_IN, &(haldata->spindle_at_speed_tolerance), hal_comp_id, "%s.spindle-at-speed-tolerance", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->spindle_at_speed_tolerance), 0.02, "%s.spindle-at-speed-tolerance", modname); if (retval!=0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->spindle_speed_fb_rps), hal_comp_id, "%s.spindle-speed-fb-rps", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->spindle_speed_fb_rps), 0.0, "%s.spindle-speed-fb-rps", modname); if (retval!=0) goto out_closeHAL; /* make default data match what we expect to use */ - *(haldata->enable) = 0; - - *(haldata->Set_F) = 0; - *(haldata->Out_F) = 0; - *(haldata->Out_A) = 0; - *(haldata->RoTT) = 0; - *(haldata->DCV) = 0; - *(haldata->ACV) = 0; - *(haldata->Cont) = 0; - *(haldata->Tmp) = 0; - - *(haldata->spindle_forward) = 0; - *(haldata->spindle_reverse) = 0; - *(haldata->spindle_on) = 0; - *(haldata->freq_cmd) = 0; - *(haldata->CNTR) = 0; - *(haldata->CNST) = 0; - - *(haldata->max_freq) = max_freq; - *(haldata->base_freq) = base_freq; - *(haldata->freq_lower_limit) = min_freq; - *(haldata->rated_motor_voltage) = motor_v; - *(haldata->rated_motor_current) = motor_i; - *(haldata->rated_motor_rev) = motor_speed; - *(haldata->motor_poles) = motor_poles; - - *(haldata->hycomm_ok) = 0; - - *haldata->spindle_speed_fb = 0.0; - *haldata->spindle_at_speed = 0; - *haldata->spindle_at_speed_tolerance = 0.02; - hc_data.slave = slave; - *(haldata->errorcount) = 0; haldata->looptime = 0.1; - - //haldata->motor_nameplate_hz = 50; // folks in The Colonies typically would use 60Hz and 1730 rpm - //haldata->motor_nameplate_RPM = 1410; - //haldata->rpm_limit = MAX_RPM; - //haldata->acc_dec_pattern = 0; - - //haldata->old_run = -1; // make sure the initial value gets output - //haldata->old_dir = -1; - //haldata->old_err_reset = -1; - //haldata->failed_reg = 0; - hal_ready(hal_comp_id); hc_data.slave = slave; // wait until EMC and AXIS is ready, ie enable bit is set - while (!*(haldata->enable)){ + while (!hal_get_bool(haldata->enable)){ // do nothing until enabled usleep(10*1000); if (done) { @@ -1074,7 +978,7 @@ int main(int argc, char **argv) // here's the meat of the program. loop until done (which may be never) while (done==0) { - if (*(haldata->enable)) { + if (hal_get_bool(haldata->enable)) { // Read inputs if (read_data(&hc_param, &hc_data, haldata) < 0) { hycomm_ok = 0; @@ -1090,14 +994,7 @@ int main(int argc, char **argv) } } - - - if (hycomm_ok > HYCOMM_MIN_OK) { - *(haldata->hycomm_ok) = 1; - } else { - *(haldata->hycomm_ok) = 0; - } - + hal_set_bool(haldata->hycomm_ok, hycomm_ok > HYCOMM_MIN_OK); // don't want to scan too fast, and shouldn't delay more than a few seconds if (haldata->looptime < 0.001) haldata->looptime = 0.001; diff --git a/src/hal/user_comps/hy_gt_vfd.c b/src/hal/user_comps/hy_gt_vfd.c index 3d91bd15287..0c532204f78 100644 --- a/src/hal/user_comps/hy_gt_vfd.c +++ b/src/hal/user_comps/hy_gt_vfd.c @@ -41,15 +41,15 @@ typedef struct { - hal_float_t *period; + hal_real_t period; - hal_float_t *speed_cmd; - hal_float_t *freq_cmd; - hal_bit_t *at_speed; + hal_real_t speed_cmd; + hal_real_t freq_cmd; + hal_bool_t at_speed; - hal_bit_t *spindle_on; + hal_bool_t spindle_on; - hal_u32_t *modbus_errors; + hal_uint_t modbus_errors; } haldata_t; haldata_t *haldata; @@ -66,8 +66,8 @@ typedef struct { float multiplier; int type; union { - hal_float_t *hal_pin_float; - hal_u32_t *hal_pin_u32; + hal_real_t hal_pin_float; + hal_uint_t hal_pin_u32; }; } modbus_register_t; @@ -207,7 +207,7 @@ int set_motor_on_forward(modbus_t *mb) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -225,7 +225,7 @@ int set_motor_off(modbus_t *mb) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -244,7 +244,7 @@ int set_motor_frequency(modbus_t *mb, float freq) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -260,16 +260,16 @@ int read_modbus_register(modbus_t *mb, modbus_register_t *reg) { if (r == 1) { switch (reg->type) { case REGISTER_FLOAT: - *reg->hal_pin_float = data * reg->multiplier; + hal_set_real(reg->hal_pin_float, data * reg->multiplier); break; case REGISTER_U32: - *reg->hal_pin_u32 = data; + hal_set_ui32(reg->hal_pin_u32, data); break; } return 0; } fprintf(stderr, "%s: error reading %s (register 0x%04x): %s\n", __func__, reg->name, reg->address, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -289,7 +289,7 @@ modbus_register_t *add_modbus_register_float(modbus_t *mb, int address, const ch reg = &modbus_register[num_modbus_registers]; reg->type = REGISTER_FLOAT; - r = hal_pin_float_newf(HAL_OUT, ®->hal_pin_float, hal_comp_id, "%s.%s", modname, pin_name); + r = hal_pin_new_real(hal_comp_id, HAL_OUT, ®->hal_pin_float, 0.0, "%s.%s", modname, pin_name); if (r != 0) { return NULL; } @@ -314,7 +314,7 @@ modbus_register_t *add_modbus_register_u32(modbus_t *mb, int address, const char reg = &modbus_register[num_modbus_registers]; reg->type = REGISTER_U32; - r = hal_pin_u32_newf(HAL_OUT, ®->hal_pin_u32, hal_comp_id, "%s.%s", modname, pin_name); + r = hal_pin_new_ui32(hal_comp_id, HAL_OUT, ®->hal_pin_u32, 0, "%s.%s", modname, pin_name); if (r != 0) { return NULL; } @@ -564,39 +564,32 @@ int main(int argc, char **argv) { goto out_close; } - haldata = (haldata_t *)hal_malloc(sizeof(haldata_t)); + haldata = (haldata_t *)hal_malloc(sizeof(*haldata)); if (haldata == NULL) { printf("%s: ERROR: unable to allocate shared memory\n", modname); retval = -1; goto out_closeHAL; } - retval = hal_pin_float_newf(HAL_IN, &(haldata->period), hal_comp_id, "%s.period-seconds", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->period), 0.1, "%s.period-seconds", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_IN, &(haldata->speed_cmd), hal_comp_id, "%s.speed-cmd", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->speed_cmd), 0.0, "%s.speed-cmd", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_cmd), hal_comp_id, "%s.freq-cmd", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_cmd), 0.0, "%s.freq-cmd", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->at_speed), hal_comp_id, "%s.at-speed", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->at_speed), 0, "%s.at-speed", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_on), hal_comp_id, "%s.spindle-on", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_on), 0, "%s.spindle-on", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_u32_newf(HAL_OUT, &(haldata->modbus_errors), hal_comp_id, "%s.modbus-errors", modname); + retval = hal_pin_new_ui32(hal_comp_id, HAL_OUT, &(haldata->modbus_errors), 0, "%s.modbus-errors", modname); if (retval != 0) goto out_closeHAL; - *haldata->period = 0.1; - - *haldata->freq_cmd = 0.0; - *haldata->at_speed = 0; - - *haldata->modbus_errors = 0; - - modbus_register = (modbus_register_t *)hal_malloc(20 * sizeof(modbus_register_t)); + modbus_register = (modbus_register_t *)hal_malloc(20 * sizeof(*modbus_register)); if (modbus_register == NULL) { printf("%s: ERROR: unable to allocate memory\n", modname); retval = -1; @@ -664,28 +657,26 @@ int main(int argc, char **argv) { hal_ready(hal_comp_id); while (done == 0) { - if (*haldata->period < 0.001) *haldata->period = 0.001; - if (*haldata->period > 2.0) *haldata->period = 2.0; - period_timespec.tv_sec = (time_t)(*haldata->period); - period_timespec.tv_nsec = (long)((*haldata->period - period_timespec.tv_sec) * 1000000000l); + rtapi_real hdpr = hal_get_real(haldata->period); + if (hdpr < 0.001) hdpr = hal_set_real(haldata->period, 0.001); + if (hdpr > 2.0) hdpr = hal_set_real(haldata->period, 2.0); + period_timespec.tv_sec = (time_t)hdpr; + period_timespec.tv_nsec = (long)((hdpr - period_timespec.tv_sec) * 1000000000l); nanosleep(&period_timespec, NULL); read_modbus_registers(mb); - if (*haldata->spindle_on) { + if (hal_get_bool(haldata->spindle_on)) { set_motor_on_forward(mb); - *haldata->freq_cmd = (*haldata->speed_cmd / motor_max_speed) * max_freq; - set_motor_frequency(mb, *haldata->freq_cmd); + rtapi_real hdsc = hal_get_real(haldata->speed_cmd); + hal_set_real(haldata->freq_cmd, (hdsc / motor_max_speed) * max_freq); + set_motor_frequency(mb, hal_get_real(haldata->freq_cmd)); - if ((fabs(*haldata->speed_cmd - *speed_fb_reg->hal_pin_float) / *haldata->speed_cmd) < 0.02) { - *haldata->at_speed = 1; - } else { - *haldata->at_speed = 0; - } + hal_set_bool(haldata->at_speed, (fabs(hdsc - hal_get_real(speed_fb_reg->hal_pin_float)) / hdsc) < 0.02); } else { set_motor_off(mb); - *haldata->at_speed = 0; - *haldata->freq_cmd = 0.0; + hal_set_bool(haldata->at_speed, 0); + hal_set_real(haldata->freq_cmd, 0.0); } } diff --git a/src/hal/user_comps/mb2hal/mb2hal.c b/src/hal/user_comps/mb2hal/mb2hal.c index ae5f6f1b2d2..0509a459711 100644 --- a/src/hal/user_comps/mb2hal/mb2hal.c +++ b/src/hal/user_comps/mb2hal/mb2hal.c @@ -224,15 +224,15 @@ void *link_loop_and_logic(void *thrd_link_num) } if (ret != retOK && modbus_get_socket(this_mb_link->modbus) < 0) { //link failure - (**this_mb_tx->num_errors)++; + hal_set_ui32(*this_mb_tx->num_errors, hal_get_ui32(*this_mb_tx->num_errors) + 1); ERR(this_mb_tx->cfg_debug, "mb_tx_num[%d] mb_links[%d] thread[%d] fd[%d] link failure, going to close link", this_mb_tx_num, this_mb_tx->mb_link_num, this_mb_link_num, modbus_get_socket(this_mb_link->modbus)); modbus_close(this_mb_link->modbus); } else if (ret != retOK) { //transaction failure but link OK - (**this_mb_tx->num_errors)++; + hal_set_ui32(*this_mb_tx->num_errors, hal_get_ui32(*this_mb_tx->num_errors) + 1); ERR(this_mb_tx->cfg_debug, "mb_tx_num[%d] mb_links[%d] thread[%d] fd[%d] transaction failure, num_errors[%u]", - this_mb_tx_num, this_mb_tx->mb_link_num, this_mb_link_num, modbus_get_socket(this_mb_link->modbus), **this_mb_tx->num_errors); + this_mb_tx_num, this_mb_tx->mb_link_num, this_mb_link_num, modbus_get_socket(this_mb_link->modbus), hal_get_ui32(*this_mb_tx->num_errors)); // Clear any unread data. Otherwise the link might get out of sync modbus_flush(this_mb_link->modbus); } @@ -241,7 +241,7 @@ void *link_loop_and_logic(void *thrd_link_num) this_mb_tx_num, this_mb_tx->mb_link_num, this_mb_link_num, modbus_get_socket(this_mb_link->modbus), 1.0/(get_time()-this_mb_tx->last_time_ok)); this_mb_tx->last_time_ok = get_time(); - (**this_mb_tx->num_errors) = 0; + hal_set_ui32(*this_mb_tx->num_errors, 0); } //set the next (waiting) time for update rate @@ -348,7 +348,7 @@ retCode get_tx_connection(const int this_mb_tx_num, int *ret_connected) ret = modbus_connect(this_mb_link->modbus); if (ret != 0 || modbus_get_socket(this_mb_link->modbus) < 0) { modbus_set_socket(this_mb_link->modbus, -1); //some times ret was < 0 and fd > 0 - (**this_mb_tx->num_errors)++; + hal_set_ui32(*this_mb_tx->num_errors, hal_get_ui32(*this_mb_tx->num_errors) + 1); ERR(this_mb_tx->cfg_debug, "mb_tx_num[%d] mb_links[%d] cannot connect to link, ret[%d] fd[%d]", this_mb_tx_num, this_mb_tx->mb_link_num, ret, modbus_get_socket(this_mb_link->modbus)); return retOK; //not connected diff --git a/src/hal/user_comps/mb2hal/mb2hal.h b/src/hal/user_comps/mb2hal/mb2hal.h index 409c9562005..2a9b1e1f292 100644 --- a/src/hal/user_comps/mb2hal/mb2hal.h +++ b/src/hal/user_comps/mb2hal/mb2hal.h @@ -102,13 +102,13 @@ typedef struct { double last_time_ok; //last OK tx time //HAL related params char hal_tx_name[HAL_NAME_LEN + 1]; - hal_float_t **float_value; - hal_s32_t **int_value; - //hal_float_t *scale; //not yet implemented - //hal_float_t *offset; //not yet implemented - hal_bit_t **bit; - hal_bit_t **bit_inv; - hal_u32_t **num_errors; //num of acummulated errors (0=last tx OK) + hal_real_t *float_value; + hal_sint_t *int_value; + //hal_real_t scale; //not yet implemented + //hal_real_t offset; //not yet implemented + hal_bool_t *bit; + hal_bool_t *bit_inv; + hal_uint_t *num_errors; //num of acummulated errors (0=last tx OK) } mb_tx_t; //Modbus link structure (mb_link_t) diff --git a/src/hal/user_comps/mb2hal/mb2hal_hal.c b/src/hal/user_comps/mb2hal/mb2hal_hal.c index a9637c42600..7a9e102ea7b 100644 --- a/src/hal/user_comps/mb2hal/mb2hal_hal.c +++ b/src/hal/user_comps/mb2hal/mb2hal_hal.c @@ -29,19 +29,18 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) } //num_errors hal pin - mb_tx->num_errors = hal_malloc(sizeof(hal_u32_t *)); + mb_tx->num_errors = hal_malloc(sizeof(*mb_tx->num_errors)); if (mb_tx->num_errors == NULL) { ERR(gbl.init_dbg, "[%d] [%s] NULL hal_malloc num_errors", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name); return retERR; } - memset(mb_tx->num_errors, 0, sizeof(hal_u32_t *)); + memset(mb_tx->num_errors, 0, sizeof(*mb_tx->num_errors)); ret = snprintf(hal_pin_name, HAL_NAME_LEN, "%s.%s.num_errors", gbl.hal_mod_name, mb_tx->hal_tx_name); - if (ret >= HAL_NAME_LEN || ret < 0 || 0 != hal_pin_u32_newf(HAL_OUT, mb_tx->num_errors, gbl.hal_mod_id, "%s", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_u32_newf failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); + if (ret >= HAL_NAME_LEN || ret < 0 || 0 != (ret = hal_pin_new_ui32(gbl.hal_mod_id, HAL_OUT, mb_tx->num_errors, 0, "%s", hal_pin_name))) { + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_ui32 failed (ret=%d)", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name, ret); return retERR; } - **(mb_tx->num_errors) = 0; DBG(gbl.init_dbg, "mb_tx_num [%d] pin_name [%s]", mb_tx->mb_tx_num, hal_pin_name); switch (mb_tx->mb_tx_fnct) { @@ -50,26 +49,26 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) case mbtx_02_READ_DISCRETE_INPUTS: case mbtx_05_WRITE_SINGLE_COIL: case mbtx_15_WRITE_MULTIPLE_COILS: - mb_tx->bit = hal_malloc(sizeof(hal_bit_t *) * mb_tx->mb_tx_nelem); - mb_tx->bit_inv = hal_malloc(sizeof(hal_bit_t *) * mb_tx->mb_tx_nelem); + mb_tx->bit = hal_malloc(sizeof(*mb_tx->bit) * mb_tx->mb_tx_nelem); + mb_tx->bit_inv = hal_malloc(sizeof(*mb_tx->bit_inv) * mb_tx->mb_tx_nelem); if (mb_tx->bit == NULL || mb_tx->bit_inv == NULL) { ERR(gbl.init_dbg, "[%d] [%s] NULL hal_malloc [%d] elements", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, mb_tx->mb_tx_nelem); return retERR; } - memset(mb_tx->bit, 0, sizeof(hal_bit_t *) * mb_tx->mb_tx_nelem); - memset(mb_tx->bit_inv, 0, sizeof(hal_bit_t *) * mb_tx->mb_tx_nelem); + memset(mb_tx->bit, 0, sizeof(*mb_tx->bit) * mb_tx->mb_tx_nelem); + memset(mb_tx->bit_inv, 0, sizeof(*mb_tx->bit_inv) * mb_tx->mb_tx_nelem); break; case mbtx_03_READ_HOLDING_REGISTERS: case mbtx_04_READ_INPUT_REGISTERS: case mbtx_06_WRITE_SINGLE_REGISTER: case mbtx_16_WRITE_MULTIPLE_REGISTERS: - mb_tx->float_value= hal_malloc(sizeof(hal_float_t *) * mb_tx->mb_tx_nelem); - mb_tx->int_value = hal_malloc(sizeof(hal_s32_t *) * mb_tx->mb_tx_nelem); - //mb_tx->scale = hal_malloc(sizeof(hal_float_t) * mb_tx->mb_tx_nelem); - //mb_tx->offset = hal_malloc(sizeof(hal_float_t) * mb_tx->mb_tx_nelem); + mb_tx->float_value= hal_malloc(sizeof(*mb_tx->float_value) * mb_tx->mb_tx_nelem); + mb_tx->int_value = hal_malloc(sizeof(*mb_tx->int_value) * mb_tx->mb_tx_nelem); + //mb_tx->scale = hal_malloc(sizeof(*mb_tx->scale ) * mb_tx->mb_tx_nelem); + //mb_tx->offset = hal_malloc(sizeof(*mb_tx->offset) * mb_tx->mb_tx_nelem); //if (mb_tx->float_value == NULL || mb_tx->int_value == NULL // || mb_tx->scale == NULL || mb_tx->offset == NULL) { if (mb_tx->float_value == NULL || mb_tx->int_value == NULL) { @@ -77,10 +76,10 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, mb_tx->mb_tx_nelem); return retERR; } - memset(mb_tx->float_value, 0, sizeof(hal_float_t *) * mb_tx->mb_tx_nelem); - memset(mb_tx->int_value, 0, sizeof(hal_s32_t *) * mb_tx->mb_tx_nelem); - //memset((void *) mb_tx->scale, 0, sizeof(hal_float_t) * mb_tx->mb_tx_nelem); - //memset((void *) mb_tx->offset, 0, sizeof(hal_float_t) * mb_tx->mb_tx_nelem); + memset(mb_tx->float_value, 0, sizeof(*mb_tx->float_value) * mb_tx->mb_tx_nelem); + memset(mb_tx->int_value, 0, sizeof(*mb_tx->int_value) * mb_tx->mb_tx_nelem); + //memset((void *) mb_tx->scale, 0, sizeof(*mb_tx->scale ) * mb_tx->mb_tx_nelem); + //memset((void *) mb_tx->offset, 0, sizeof(*mb_tx->offset) * mb_tx->mb_tx_nelem); break; default: @@ -102,60 +101,56 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) case mbtx_05_WRITE_SINGLE_COIL: case mbtx_15_WRITE_MULTIPLE_COILS: if(gbl.version < 1001){ - if (0 != hal_pin_bit_newf(HAL_IN, mb_tx->bit + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_bool(gbl.hal_mod_id, HAL_IN, mb_tx->bit + pin_counter, 0, "%s", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_bit_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_bool failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } } else { - if (0 != hal_pin_bit_newf(HAL_IN, mb_tx->bit + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_bool(gbl.hal_mod_id, HAL_IN, mb_tx->bit + pin_counter, 0, "%s.bit", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_bit_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_bool failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } } - *mb_tx->bit[pin_counter] = 0; break; case mbtx_01_READ_COILS: case mbtx_02_READ_DISCRETE_INPUTS: if (gbl.version < 1001) { - if (0 != hal_pin_bit_newf(HAL_OUT, mb_tx->bit + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_bool(gbl.hal_mod_id, HAL_OUT, mb_tx->bit + pin_counter, 0, "%s", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_bit_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_bool failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - *mb_tx->bit[pin_counter] = 0; } else { - if (0 != hal_pin_bit_newf(HAL_OUT, mb_tx->bit + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_bool(gbl.hal_mod_id, HAL_OUT, mb_tx->bit + pin_counter, 0, "%s.bit", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_bit_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_bool failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - if (0 != hal_pin_bit_newf(HAL_OUT, mb_tx->bit_inv + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_bool(gbl.hal_mod_id, HAL_OUT, mb_tx->bit_inv + pin_counter, 1, "%s.bit-inv", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_bit_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_bool failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - *mb_tx->bit[pin_counter] = 0; - *mb_tx->bit_inv[pin_counter] = 1; } break; case mbtx_04_READ_INPUT_REGISTERS: case mbtx_03_READ_HOLDING_REGISTERS: - if (0 != hal_pin_float_newf(HAL_OUT, mb_tx->float_value + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_real(gbl.hal_mod_id, HAL_OUT, mb_tx->float_value + pin_counter, 0.0, "%s.float", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_float_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_real failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - if (0 != hal_pin_s32_newf(HAL_OUT, mb_tx->int_value + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_si32(gbl.hal_mod_id, HAL_OUT, mb_tx->int_value + pin_counter, 0, "%s.int", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_s32_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_si32 failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } @@ -169,31 +164,28 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) // ERR(gbl.init_dbg, "[%d] [%s] [%s]", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); // return retERR; //} - *mb_tx->float_value[pin_counter] = 0; - *mb_tx->int_value[pin_counter] = 0; //mb_tx->scale[pin_counter] = 1; //mb_tx->offset[pin_counter] = 0; break; case mbtx_06_WRITE_SINGLE_REGISTER: case mbtx_16_WRITE_MULTIPLE_REGISTERS: if (gbl.version < 1001) { - if (0 != hal_pin_float_newf(HAL_IN, mb_tx->float_value + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_real(gbl.hal_mod_id, HAL_IN, mb_tx->float_value + pin_counter, 0.0, "%s", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_float_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_real failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - *mb_tx->float_value[pin_counter] = 0; } else { - if (0 != hal_pin_float_newf(HAL_IN, mb_tx->float_value + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_real(gbl.hal_mod_id, HAL_IN, mb_tx->float_value + pin_counter, 0.0, "%s.float", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_float_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_real failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } - if (0 != hal_pin_s32_newf(HAL_IN, mb_tx->int_value + pin_counter, gbl.hal_mod_id, + if (0 != hal_pin_new_si32(gbl.hal_mod_id, HAL_IN, mb_tx->int_value + pin_counter, 0, "%s.int", hal_pin_name)) { - ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_s32_newf failed", + ERR(gbl.init_dbg, "[%d] [%s] [%s] hal_pin_new_si32 failed", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name, hal_pin_name); return retERR; } @@ -207,8 +199,6 @@ retCode create_each_mb_tx_hal_pins(mb_tx_t *mb_tx) // ERR(gbl.init_dbg, "[%d] [%s]", mb_tx->mb_tx_fnct, mb_tx->mb_tx_fnct_name); // return retERR; //} - *mb_tx->float_value[pin_counter] = 0; - *mb_tx->int_value[pin_counter] = 0; //mb_tx->scale[pin_counter] = 1; //mb_tx->offset[pin_counter] = 0; } diff --git a/src/hal/user_comps/mb2hal/mb2hal_modbus.c b/src/hal/user_comps/mb2hal/mb2hal_modbus.c index 40817812a29..86260e4cff7 100644 --- a/src/hal/user_comps/mb2hal/mb2hal_modbus.c +++ b/src/hal/user_comps/mb2hal/mb2hal_modbus.c @@ -30,8 +30,8 @@ retCode fnct_01_read_coils(mb_tx_t *this_mb_tx, mb_link_t *this_mb_link) } for (counter = 0; counter < this_mb_tx->mb_tx_nelem; counter++) { - *(this_mb_tx->bit[counter]) = bits[counter]; - *(this_mb_tx->bit_inv[counter]) = !bits[counter]; + hal_set_bool(this_mb_tx->bit[counter], bits[counter]); + hal_set_bool(this_mb_tx->bit_inv[counter], !bits[counter]); } return retOK; @@ -66,9 +66,9 @@ retCode fnct_02_read_discrete_inputs(mb_tx_t *this_mb_tx, mb_link_t *this_mb_lin } for (counter = 0; counter < this_mb_tx->mb_tx_nelem; counter++) { - *(this_mb_tx->bit[counter]) = bits[counter]; + hal_set_bool(this_mb_tx->bit[counter], bits[counter]); if (gbl.version > 1000) - *(this_mb_tx->bit_inv[counter]) = !bits[counter]; + hal_set_bool(this_mb_tx->bit_inv[counter], !bits[counter]); } return retOK; @@ -106,8 +106,8 @@ retCode fnct_03_read_holding_registers(mb_tx_t *this_mb_tx, mb_link_t *this_mb_l float val = data[counter]; //val *= this_mb_tx->scale[counter]; //val += this_mb_tx->offset[counter]; - *(this_mb_tx->float_value[counter]) = val; - *(this_mb_tx->int_value[counter]) = data[counter]; + hal_set_real(this_mb_tx->float_value[counter], val); + hal_set_si32(this_mb_tx->int_value[counter], data[counter]); } return retOK; @@ -145,8 +145,8 @@ retCode fnct_04_read_input_registers(mb_tx_t *this_mb_tx, mb_link_t *this_mb_lin float val = data[counter]; //val += this_mb_tx->offset[counter]; //val *= this_mb_tx->scale[counter]; - *(this_mb_tx->float_value[counter]) = val; - *(this_mb_tx->int_value[counter]) = data[counter]; + hal_set_real(this_mb_tx->float_value[counter], val); + hal_set_si32(this_mb_tx->int_value[counter], data[counter]); } return retOK; @@ -164,7 +164,7 @@ retCode fnct_05_write_single_coil(mb_tx_t *this_mb_tx, mb_link_t *this_mb_link) return retERR; } - bit = *(this_mb_tx->bit[0]); + bit = hal_get_bool(this_mb_tx->bit[0]); DBG(this_mb_tx->cfg_debug, "mb_tx[%d] mb_links[%d] slave[%d] fd[%d] 1st_addr[%d] nelem[%d]", this_mb_tx->mb_tx_num, this_mb_tx->mb_link_num, this_mb_tx->mb_tx_slave_id, @@ -196,9 +196,9 @@ retCode fnct_06_write_single_register(mb_tx_t *this_mb_tx, mb_link_t *this_mb_li return retERR; } - data = *(this_mb_tx->float_value[0]); + data = hal_get_real(this_mb_tx->float_value[0]); if (gbl.version > 1000) - data += *(this_mb_tx->int_value[0]); + data += hal_get_si32(this_mb_tx->int_value[0]); if(data > UINT16_MAX) { // prevent wrap on overflow data = UINT16_MAX; } @@ -235,7 +235,7 @@ retCode fnct_15_write_multiple_coils(mb_tx_t *this_mb_tx, mb_link_t *this_mb_lin } for (counter = 0; counter < this_mb_tx->mb_tx_nelem; counter++) { - bits[counter] = *(this_mb_tx->bit[counter]); + bits[counter] = hal_get_bool(this_mb_tx->bit[counter]); } DBG(this_mb_tx->cfg_debug, "mb_tx[%d] mb_links[%d] slave[%d] fd[%d] 1st_addr[%d] nelem[%d]", @@ -272,9 +272,9 @@ retCode fnct_16_write_multiple_registers(mb_tx_t *this_mb_tx, mb_link_t *this_mb for (counter = 0; counter < this_mb_tx->mb_tx_nelem; counter++) { //float val = *(this_mb_tx->float_value[counter]) / this_mb_tx->scale[counter]; //val -= this_mb_tx->offset[counter]; - int data32 = (uint16_t) *(this_mb_tx->float_value[counter]); + int data32 = (uint16_t) hal_get_real(this_mb_tx->float_value[counter]); if (gbl.version > 1000) - data32 += *(this_mb_tx->int_value[counter]); + data32 += hal_get_si32(this_mb_tx->int_value[counter]); if(data32 > UINT16_MAX) { // prevent wrap on overflow data[counter] = UINT16_MAX; } diff --git a/src/hal/user_comps/pi500_vfd/pi500_vfd.comp b/src/hal/user_comps/pi500_vfd/pi500_vfd.comp index 3a791438bdb..792852b1ab4 100644 --- a/src/hal/user_comps/pi500_vfd/pi500_vfd.comp +++ b/src/hal/user_comps/pi500_vfd/pi500_vfd.comp @@ -1,15 +1,15 @@ component pi500_vfd "Powtran PI500 Modbus driver"; -param rw unsigned mbslaveaddr "Modbus slave address"; -pin in float commanded_frequency "Frequency of vfd"; -pin in bit run "run the vfd"; -pin in bit enable "1 to enable the vfd. 0 will remote trip the vfd, thereby disabling it."; -pin out bit is_running "1 when running"; -pin out bit is_at_speed "1 when running at assigned frequency"; -pin out bit is_ready "1 when vfd is ready to run"; -pin out bit is_alarm "1 when vfd alarm is set"; -pin out float motor_current "Output current in amps"; -pin out float heatsink_temp "Temperature of drive heatsink"; -pin out bit watchdog_out "Alternates between 1 and 0 after every update cycle. Feed into a watchdog component to ensure vfd driver is communicating with the vfd properly."; +param rw ui32 mbslaveaddr "Modbus slave address"; +pin in real commanded_frequency "Frequency of vfd"; +pin in bool run "run the vfd"; +pin in bool enable "1 to enable the vfd. 0 will remote trip the vfd, thereby disabling it."; +pin out bool is_running "1 when running"; +pin out bool is_at_speed "1 when running at assigned frequency"; +pin out bool is_ready "1 when vfd is ready to run"; +pin out bool is_alarm "1 when vfd alarm is set"; +pin out real motor_current "Output current in amps"; +pin out real heatsink_temp "Temperature of drive heatsink"; +pin out bool watchdog_out "Alternates between 1 and 0 after every update cycle. Feed into a watchdog component to ensure vfd driver is communicating with the vfd properly."; option userspace yes; option userinit yes; license "GPLv2 or greater"; @@ -289,9 +289,9 @@ void user_mainloop(void) { continue; } - is_running = status.running; - is_ready = status.ready; - is_alarm = status.alarm; + is_running_set(status.running); + is_ready_set(status.ready); + is_alarm_set(status.alarm); if(!status.alarm && !enable) { // && !pi500_trip(ctx) print_modbus_error(__comp_inst, "failed to trip"); @@ -304,7 +304,7 @@ void user_mainloop(void) { else { calculated_frequency = (uint16_t)(fabs(commanded_frequency) * 10 * (status.freq_two_digits ? 10 : 1)); - is_at_speed = (commanded_frequency > 0 && calculated_frequency == status.frequency ? 1 : 0); + is_at_speed_set(commanded_frequency > 0 && calculated_frequency == status.frequency ? 1 : 0); if(commanded_frequency > 0 && calculated_frequency != status.frequency @@ -319,9 +319,9 @@ void user_mainloop(void) { continue; } - watchdog_out = !watchdog_out; - motor_current = status.output_current / 100; - heatsink_temp = status.sink_temp / 10; + watchdog_out_set(!watchdog_out); + motor_current_set(status.output_current / 100); + heatsink_temp_set(status.sink_temp / 10); } } } diff --git a/src/hal/user_comps/sendkeys.c b/src/hal/user_comps/sendkeys.c index afa5d637ad7..d8919f367e0 100644 --- a/src/hal/user_comps/sendkeys.c +++ b/src/hal/user_comps/sendkeys.c @@ -30,11 +30,11 @@ static int comp_id; typedef struct{ - hal_u32_t *keycode; - hal_s32_t *current_event; - hal_bit_t *init; - hal_bit_t **trigger; - hal_u32_t *event; + hal_uint_t keycode; + hal_sint_t current_event; + hal_bool_t init; + hal_bool_t *trigger; + hal_uint_t *event; } sendkeys_hal; typedef struct { @@ -44,7 +44,7 @@ typedef struct { bool inited; int fd; bool *prev; - hal_u32_t oldcode; + rtapi_u32 oldcode; } sendkeys_param; typedef struct { @@ -85,9 +85,9 @@ int init(int argc, char* argv[]){ return -1; } - me = hal_malloc(sizeof(sendkeys)); - codes = malloc(sizeof(int)); - pins = malloc(sizeof(int)); + me = hal_malloc(sizeof(*me)); + codes = malloc(sizeof(*codes)); + pins = malloc(sizeof(*pins)); // This is all because RTAPI_MP_ARRAY_** macros do not appear to work in userspace for (i = 1; i < argc; i++){ static int index = -1; @@ -105,8 +105,8 @@ int init(int argc, char* argv[]){ case ' ': case ',': index++; - v1 = realloc(codes, (index + 1) * sizeof(int)); - v2 = realloc(pins, (index + 1) * sizeof(int)); + v1 = realloc(codes, (index + 1) * sizeof(*codes)); + v2 = realloc(pins, (index + 1) * sizeof(*codes)); if (!v1 || !v2) { free(v1 ? v1 : codes); free(v2 ? v2 : pins); @@ -156,24 +156,24 @@ int init(int argc, char* argv[]){ break; } } - me->hal = (sendkeys_hal*)hal_malloc(me->num_insts * sizeof(sendkeys_hal)); - me->param = malloc(me->num_insts * sizeof(sendkeys_param)); + me->hal = (sendkeys_hal*)hal_malloc(me->num_insts * sizeof(*me->hal)); + me->param = malloc(me->num_insts * sizeof(*me->param)); for (i = 0; i < me->num_insts; i++){ sendkeys_hal* hal = &(me->hal[i]); sendkeys_param* param = &(me->param[i]); - if (hal_pin_u32_newf(HAL_IN, &(hal->keycode), comp_id, + if (hal_pin_new_ui32(comp_id, HAL_IN, &(hal->keycode), 0, "sendkeys.%i.keycode", i) < 0) { free(codes); free(pins); rtapi_print_msg(RTAPI_MSG_ERR, "sendkeys.N.keycode error\n"); return -ENOMEM;} - if (hal_pin_s32_newf(HAL_OUT, &(hal->current_event), comp_id, + if (hal_pin_new_si32(comp_id, HAL_OUT, &(hal->current_event), 0, "sendkeys.%i.current-event", i) < 0) { free(codes); free(pins); rtapi_print_msg(RTAPI_MSG_ERR, "sendkeys.N.current-event error\n"); return -ENOMEM;} - if (hal_pin_bit_newf(HAL_IN, &(hal->init), comp_id, + if (hal_pin_new_bool(comp_id, HAL_IN, &(hal->init), 0, "sendkeys.%i.init", i) < 0) { free(codes); free(pins); @@ -184,9 +184,9 @@ int init(int argc, char* argv[]){ param->num_triggers = pins[i]; param->num_codes = codes[i]; param->num_events = codes[i] + pins[i]; - hal->event = hal_malloc(param->num_events * sizeof(hal_u32_t*)); + hal->event = hal_malloc(param->num_events * sizeof(*hal->event)); for (j = 0; j < param->num_codes; j++){ - if (hal_param_u32_newf(HAL_RW, &(hal->event[j]), comp_id, + if (hal_param_new_ui32(comp_id, HAL_RW, &(hal->event[j]), 0, "sendkeys.%i.scan-event-%02i", i, j) < 0) { free(codes); free(pins); @@ -194,7 +194,7 @@ int init(int argc, char* argv[]){ return -ENOMEM;} } for (j = 0; j < param->num_triggers; j++){ - if (hal_param_u32_newf(HAL_RW, &(hal->event[j + param->num_codes]), comp_id, + if (hal_param_new_ui32(comp_id, HAL_RW, &(hal->event[j + param->num_codes]), 0, "sendkeys.%i.pin-event-%02i", i, j) < 0) { free(codes); free(pins); @@ -202,10 +202,10 @@ int init(int argc, char* argv[]){ return -ENOMEM;} } // trigger pins - hal->trigger = hal_malloc(param->num_triggers * sizeof(hal_bit_t*)); - param->prev = malloc(param->num_triggers * sizeof(hal_bit_t)); + hal->trigger = hal_malloc(param->num_triggers * sizeof(*hal->trigger)); + param->prev = malloc(param->num_triggers * sizeof(*param->prev)); for (j = 0; j < param->num_triggers; j++){ - if (hal_pin_bit_newf(HAL_IN, &(hal->trigger[j]), comp_id, + if (hal_pin_new_bool(comp_id, HAL_IN, &(hal->trigger[j]), 0, "sendkeys.%i.trigger-%02i", i, j) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "sendkeys.N.trigger-%02i error\n",j); free(codes); @@ -234,17 +234,18 @@ int main(int argc, char* argv[]) { for (i = 0; i < me->num_insts; i++){ sendkeys_hal* hal = &(me->hal[i]); sendkeys_param* param = &(me->param[i]); - if ((*hal->keycode & 0xC0) == 0x80){ - *hal->current_event = (*hal->keycode & 0x3f); + rtapi_u32 kk = hal_get_ui32(hal->keycode); + if ((kk & 0xC0) == 0x80){ + hal_set_si32(hal->current_event, (kk & 0x3f)); } else { - *hal->current_event = -1; + hal_set_si32(hal->current_event, -1); } // The event codes are written to pins in HAL after the // component is loaded. // We need to set up the keyboard based on the events selected // so there is a secondary init here. - if (! *hal->init) continue; - if (*hal->init && ! param->inited) { + if (!hal_get_bool(hal->init)) continue; + if (hal_get_bool(hal->init) && ! param->inited) { param->fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); if (param->fd < 0) { rtapi_print_msg(RTAPI_MSG_ERR, @@ -253,9 +254,10 @@ int main(int argc, char* argv[]) { } ioctl(param->fd, UI_SET_EVBIT, EV_KEY); for (j = 0; j < param->num_events; j++){ - if (hal->event[j] > 0 && hal->event[j] < KEY_MAX){ - ioctl(param->fd, UI_SET_KEYBIT, hal->event[j]); - rtapi_print("SET_EVBIT %i\n", hal->event[j]); + rtapi_u32 evj = hal_get_ui32(hal->event[j]); + if (evj > 0 && evj < KEY_MAX){ + ioctl(param->fd, UI_SET_KEYBIT, evj); + rtapi_print("SET_EVBIT %i\n", evj); } } struct uinput_user_dev uidev; @@ -270,29 +272,31 @@ int main(int argc, char* argv[]) { if (ioctl(param->fd, UI_DEV_CREATE) < 0) { perror("ioctl(UI_DEV_CREATE)"); abort(); } param->inited = 1; } - if (*hal->keycode != param->oldcode) { + rtapi_u32 kc = hal_get_ui32(hal->keycode); + if (kc != param->oldcode) { /* Key press, report the event, send key release, and report again*/ - if ((int)(*hal->keycode & 0x3F) > param->num_events) continue; - if (hal->event[*hal->keycode & 0x3F] == 0) continue; - if ((*hal->keycode & 0xC0) == 0xC0){ // keydown - emit(param->fd, EV_KEY, hal->event[*hal->keycode & 0x3F], 1); + if ((int)(kc & 0x3F) > param->num_events) continue; + if (hal_get_ui32(hal->event[kc & 0x3F]) == 0) continue; + if ((kc & 0xC0) == 0xC0){ // keydown + emit(param->fd, EV_KEY, hal_get_ui32(hal->event[kc & 0x3F]), 1); emit(param->fd, EV_SYN, SYN_REPORT, 0); - } else if ((*hal->keycode & 0xC0) == 0x80){ // keyup - emit(param->fd, EV_KEY, hal->event[*hal->keycode & 0x3F], 0); + } else if ((kc & 0xC0) == 0x80){ // keyup + emit(param->fd, EV_KEY, hal_get_ui32(hal->event[kc & 0x3F]), 0); emit(param->fd, EV_SYN, SYN_REPORT, 0); } - param->oldcode = *hal->keycode; + param->oldcode = kc; } for (j = 0; j < param->num_triggers; j++){ - if (param->prev[j] != *hal->trigger[j]){ - if (*hal->trigger[j]){ // keydown - emit(param->fd, EV_KEY, hal->event[param->num_codes + j], 1); + rtapi_bool trj = hal->trigger[j]; + if (param->prev[j] != trj){ + if (trj){ // keydown + emit(param->fd, EV_KEY, hal_get_ui32(hal->event[param->num_codes + j]), 1); emit(param->fd, EV_SYN, SYN_REPORT, 0); } else { // keyup - emit(param->fd, EV_KEY, hal->event[param->num_codes + j], 0); + emit(param->fd, EV_KEY, hal_get_ui32(hal->event[param->num_codes + j]), 0); emit(param->fd, EV_SYN, SYN_REPORT, 0); } - param->prev[j] = *hal->trigger[j]; + param->prev[j] = trj; } } } diff --git a/src/hal/user_comps/shuttle.c b/src/hal/user_comps/shuttle.c index f9556e24a05..179653fab76 100644 --- a/src/hal/user_comps/shuttle.c +++ b/src/hal/user_comps/shuttle.c @@ -100,11 +100,11 @@ int hal_comp_id; // each Shuttle* device presents this interface to HAL struct shuttle_hal { - hal_bit_t *button[MAX_BUTTONS]; - hal_bit_t *button_not[MAX_BUTTONS]; - hal_s32_t *counts; // accumulated counts from the jog wheel - hal_float_t *spring_wheel_f; // current position of the springy outer wheel, as a float from -1 to +1 inclusive - hal_s32_t *spring_wheel_s32; // current position of the springy outer wheel, as a s32 from -7 to +7 inclusive + hal_bool_t button[MAX_BUTTONS]; + hal_bool_t button_not[MAX_BUTTONS]; + hal_sint_t counts; // accumulated counts from the jog wheel + hal_real_t spring_wheel_f; // current position of the springy outer wheel, as a float from -1 to +1 inclusive + hal_sint_t spring_wheel_s32; // current position of the springy outer wheel, as a s32 from -7 to +7 inclusive }; @@ -155,32 +155,29 @@ int read_update(struct shuttle *s) { button = ((uint8_t)packet[4] << 8) | (uint8_t)packet[3]; for (int i = 0; i < s->contour_type->num_buttons; i ++) { - if (button & s->contour_type->button_mask[i]) { - *s->hal->button[i] = 1; - } else { - *s->hal->button[i] = 0; - } - *s->hal->button_not[i] = !*s->hal->button[i]; + bool b = !!(button & s->contour_type->button_mask[i]); + hal_set_bool(s->hal->button[i], b); + hal_set_bool(s->hal->button_not[i], !b); } { int curr_count = packet[1]; if (s->read_first_event == 0) { - *s->hal->counts = 0; + hal_set_si32(s->hal->counts, 0); s->prev_count = curr_count; s->read_first_event = 1; } else { int diff_count = curr_count - s->prev_count; if (diff_count > 128) diff_count -= 256; if (diff_count < -128) diff_count += 256; - *s->hal->counts += diff_count; + hal_set_si32(s->hal->counts, hal_get_si32(s->hal->counts) + diff_count); s->prev_count = curr_count; } } - *s->hal->spring_wheel_s32 = packet[0]; - *s->hal->spring_wheel_f = packet[0] / 7.0; + hal_set_si32(s->hal->spring_wheel_s32, packet[0]); + hal_set_real(s->hal->spring_wheel_f, packet[0] / 7.0); return 0; } @@ -251,28 +248,22 @@ struct shuttle *check_for_shuttle(char *dev_filename) { } for (int i = 0; i < s->contour_type->num_buttons; i ++) { - r = hal_pin_bit_newf(HAL_OUT, &(s->hal->button[i]), hal_comp_id, "%s.%d.button-%d", modname, num_devices, i); + r = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(s->hal->button[i]), 0, "%s.%d.button-%d", modname, num_devices, i); if (r != 0) goto fail1; - *s->hal->button[i] = 0; - r = hal_pin_bit_newf(HAL_OUT, &(s->hal->button_not[i]), hal_comp_id, "%s.%d.button-%d-not", modname, num_devices, i); + r = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(s->hal->button_not[i]), 1, "%s.%d.button-%d-not", modname, num_devices, i); if (r != 0) goto fail1; - *s->hal->button_not[i] = 1; } - r = hal_pin_s32_newf(HAL_OUT, &(s->hal->counts), hal_comp_id, "%s.%d.counts", modname, num_devices); + r = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(s->hal->counts), 0, "%s.%d.counts", modname, num_devices); if (r != 0) goto fail1; - r = hal_pin_float_newf(HAL_OUT, &(s->hal->spring_wheel_f), hal_comp_id, "%s.%d.spring-wheel-f", modname, num_devices); + r = hal_pin_new_real(hal_comp_id, HAL_OUT, &(s->hal->spring_wheel_f), 0.0, "%s.%d.spring-wheel-f", modname, num_devices); if (r != 0) goto fail1; - r = hal_pin_s32_newf(HAL_OUT, &(s->hal->spring_wheel_s32), hal_comp_id, "%s.%d.spring-wheel-s32", modname, num_devices); + r = hal_pin_new_si32(hal_comp_id, HAL_OUT, &(s->hal->spring_wheel_s32), 0, "%s.%d.spring-wheel-s32", modname, num_devices); if (r != 0) goto fail1; - *s->hal->counts = 0; - *s->hal->spring_wheel_f = 0.0; - *s->hal->spring_wheel_s32 = 0; - return s; diff --git a/src/hal/user_comps/svd-ps_vfd.c b/src/hal/user_comps/svd-ps_vfd.c index b8cc73d0857..43beebcf856 100644 --- a/src/hal/user_comps/svd-ps_vfd.c +++ b/src/hal/user_comps/svd-ps_vfd.c @@ -42,15 +42,15 @@ typedef struct { - hal_float_t *period; + hal_real_t period; - hal_float_t *speed_cmd; - hal_float_t *freq_cmd; - hal_bit_t *at_speed; + hal_real_t speed_cmd; + hal_real_t freq_cmd; + hal_bool_t at_speed; - hal_bit_t *spindle_on; + hal_bool_t spindle_on; - hal_u32_t *modbus_errors; + hal_uint_t modbus_errors; } haldata_t; haldata_t *haldata; @@ -66,7 +66,7 @@ typedef struct { // readable value. float multiplier; - hal_float_t *hal_pin; + hal_real_t hal_pin; } modbus_register_t; int num_modbus_registers = 0; @@ -190,7 +190,7 @@ int set_motor_on_forward(modbus_t *mb) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -207,7 +207,7 @@ int set_motor_off(modbus_t *mb) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -226,7 +226,7 @@ int set_motor_frequency(modbus_t *mb, float freq) { return 0; } fprintf(stderr, "%s: error writing %u to register 0x%04x: %s\n", __func__, val, addr, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -240,11 +240,11 @@ int read_modbus_register(modbus_t *mb, modbus_register_t *reg) { svd_modbus_sleep(); r = modbus_read_registers(mb, reg->address, 1, &data); if (r == 1) { - *reg->hal_pin = data * reg->multiplier; + hal_set_real(reg->hal_pin, data * reg->multiplier); return 0; } fprintf(stderr, "%s: error reading %s (register 0x%04x): %s\n", __func__, reg->name, reg->address, modbus_strerror(errno)); - *haldata->modbus_errors = *haldata->modbus_errors + 1; + hal_set_ui32(haldata->modbus_errors, hal_get_ui32(haldata->modbus_errors) + 1); } return -1; } @@ -263,7 +263,7 @@ modbus_register_t *add_modbus_register(modbus_t *mb, int address, const char *pi reg = &modbus_register[num_modbus_registers]; - r = hal_pin_float_newf(HAL_OUT, ®->hal_pin, hal_comp_id, "%s.%s", modname, pin_name); + r = hal_pin_new_real(hal_comp_id, HAL_OUT, ®->hal_pin, 0.0, "%s.%s", modname, pin_name); if (r != 0) { return NULL; } @@ -520,31 +520,24 @@ int main(int argc, char **argv) { goto out_closeHAL; } - retval = hal_pin_float_newf(HAL_IN, &(haldata->period), hal_comp_id, "%s.period-seconds", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->period), 0.1, "%s.period-seconds", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_IN, &(haldata->speed_cmd), hal_comp_id, "%s.speed-cmd", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_IN, &(haldata->speed_cmd), 0.0, "%s.speed-cmd", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_cmd), hal_comp_id, "%s.freq-cmd", modname); + retval = hal_pin_new_real(hal_comp_id, HAL_OUT, &(haldata->freq_cmd), 0.0, "%s.freq-cmd", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_OUT, &(haldata->at_speed), hal_comp_id, "%s.at-speed", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_OUT, &(haldata->at_speed), 0, "%s.at-speed", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_on), hal_comp_id, "%s.spindle-on", modname); + retval = hal_pin_new_bool(hal_comp_id, HAL_IN, &(haldata->spindle_on), 0, "%s.spindle-on", modname); if (retval != 0) goto out_closeHAL; - retval = hal_pin_u32_newf(HAL_OUT, &(haldata->modbus_errors), hal_comp_id, "%s.modbus-errors", modname); + retval = hal_pin_new_ui32(hal_comp_id, HAL_OUT, &(haldata->modbus_errors), 0, "%s.modbus-errors", modname); if (retval != 0) goto out_closeHAL; - *haldata->period = 0.1; - - *haldata->freq_cmd = 0.0; - *haldata->at_speed = 0; - - *haldata->modbus_errors = 0; - modbus_register = (modbus_register_t *)hal_malloc(20 * sizeof(modbus_register_t)); if (modbus_register == NULL) { printf("%s: ERROR: unable to allocate memory\n", modname); @@ -584,28 +577,29 @@ int main(int argc, char **argv) { hal_ready(hal_comp_id); while (done == 0) { - if (*haldata->period < 0.001) *haldata->period = 0.001; - if (*haldata->period > 2.0) *haldata->period = 2.0; - period_timespec.tv_sec = (time_t)(*haldata->period); - period_timespec.tv_nsec = (long)((*haldata->period - period_timespec.tv_sec) * 1000000000l); + rtapi_real period = hal_get_real(haldata->period); + if (period < 0.001) period = hal_set_real(haldata->period, 0.001); + if (period > 2.0) period = hal_set_real(haldata->period, 2.0); + period_timespec.tv_sec = (time_t)period; + period_timespec.tv_nsec = (long)((period - period_timespec.tv_sec) * 1000000000l); nanosleep(&period_timespec, NULL); read_modbus_registers(mb); - if (*haldata->spindle_on) { + if (hal_get_bool(haldata->spindle_on)) { set_motor_on_forward(mb); - *haldata->freq_cmd = (*haldata->speed_cmd / motor_max_speed) * max_freq; - set_motor_frequency(mb, *haldata->freq_cmd); + hal_set_real(haldata->freq_cmd, (hal_get_real(haldata->speed_cmd) / motor_max_speed) * max_freq); + set_motor_frequency(mb, hal_get_real(haldata->freq_cmd)); - if ((fabs(*haldata->speed_cmd - *speed_fb_reg->hal_pin) / *haldata->speed_cmd) < 0.02) { - *haldata->at_speed = 1; + if ((fabs(hal_get_real(haldata->speed_cmd) - hal_get_real(speed_fb_reg->hal_pin)) / hal_get_real(haldata->speed_cmd)) < 0.02) { + hal_set_bool(haldata->at_speed, 1); } else { - *haldata->at_speed = 0; + hal_set_bool(haldata->at_speed, 0); } } else { set_motor_off(mb); - *haldata->at_speed = 0; - *haldata->freq_cmd = 0.0; + hal_set_bool(haldata->at_speed, 0); + hal_set_real(haldata->freq_cmd, 0.0); } } diff --git a/src/hal/user_comps/thermistor.comp b/src/hal/user_comps/thermistor.comp index 8bf7f6b592d..a553eaa6bb3 100644 --- a/src/hal/user_comps/thermistor.comp +++ b/src/hal/user_comps/thermistor.comp @@ -32,33 +32,33 @@ variant of the Steinhart-Hart equation, described here: include ; include ; -pin in float t0_c """Reference temperature of the thermistor, in degrees +pin in real t0_c """Reference temperature of the thermistor, in degrees Celsius (typically 25 C). This must be set before the component can compute the thermistor temperature. The reference temperature information is supplied by the thermistor manufacturer."""; -pin in float r0 """Resistance of the thermistor at the reference +pin in real r0 """Resistance of the thermistor at the reference temperature. This must be set before the component can compute the thermistor temperature. The reference resistance information is supplied by the thermistor manufacturer."""; -pin in float beta """Beta parameter of the thermistor (sometimes +pin in real beta """Beta parameter of the thermistor (sometimes just called B). This must be set before the component can compute the thermistor temperature. The Beta parameter is supplied by the thermistor manufacturer."""; -pin in float r_other """Resistance of the other resistor in the +pin in real r_other """Resistance of the other resistor in the voltage-divider ladder. This must be set before the component can compute the thermistor temperature."""; -pin in float v_total "Supply voltage of the voltage-divider ladder."; -pin in float v_thermistor "Voltage drop across the termistor."; +pin in real v_total "Supply voltage of the voltage-divider ladder."; +pin in real v_thermistor "Voltage drop across the termistor."; -pin out float temperature_c "Temperature sensed by the thermistor, in degrees Celsius."; -pin out float temperature_k "Temperature sensed by the thermistor, in Kelvins."; -pin out float temperature_f "Temperature sensed by the thermistor, in degrees Fahrenheit."; +pin out real temperature_c "Temperature sensed by the thermistor, in degrees Celsius."; +pin out real temperature_k "Temperature sensed by the thermistor, in Kelvins."; +pin out real temperature_f "Temperature sensed by the thermistor, in degrees Fahrenheit."; -pin out float resistance "Computed resistance of the thermistor."; +pin out real resistance "Computed resistance of the thermistor."; ;; @@ -80,9 +80,9 @@ static void userinit(int argc, char **argv) { void user_mainloop(void) { while (!should_exit) { FOR_ALL_INSTS() { - hal_float_t t0_k = t0_c + 273.15; - hal_float_t r_inf; - hal_float_t current; + rtapi_real t0_k = t0_c + 273.15; + rtapi_real r_inf; + rtapi_real current; if (t0_k <= 0.0) { goto problem; @@ -102,12 +102,12 @@ void user_mainloop(void) { goto problem; } - resistance = v_thermistor / current; + resistance_set(v_thermistor / current); if (isnan(resistance) || isinf(resistance) || (resistance <= 0.0)) { goto problem; } - temperature_k = beta / log(resistance/r_inf); + temperature_k_set(beta / log(resistance/r_inf)); if (isnan(temperature_k) || isinf(temperature_k) || (temperature_k < 0.0)) { goto problem; } @@ -117,12 +117,12 @@ void user_mainloop(void) { problem: // override problematic output pins with bogus but not invalid values - resistance = 0; - temperature_k = 9999; + resistance_set(0); + temperature_k_set(9999); ok: - temperature_c = temperature_k - 273.15; - temperature_f = (temperature_c * 9.0 / 5.0) + 32.0; + temperature_c_set(temperature_k - 273.15); + temperature_f_set((temperature_c * 9.0 / 5.0) + 32.0); } usleep(100 * 1000); } diff --git a/src/hal/user_comps/vfdb_vfd/vfdb_vfd.c b/src/hal/user_comps/vfdb_vfd/vfdb_vfd.c index c4904fc0bb9..988e997eb22 100644 --- a/src/hal/user_comps/vfdb_vfd/vfdb_vfd.c +++ b/src/hal/user_comps/vfdb_vfd/vfdb_vfd.c @@ -112,37 +112,37 @@ /* HAL data struct */ typedef struct { - hal_s32_t *error_code; - hal_s32_t *status; - hal_float_t *freq_cmd; // frequency command - hal_float_t *freq_out; // actual output frequency - hal_float_t *output_volt; // output voltage - hal_float_t *RPM; - hal_float_t *RPS; - hal_float_t *torque_ratio; - hal_float_t *output_current; - hal_float_t *max_rpm; // calculated based on VFD max frequency setup parameter - hal_bit_t *at_speed; // when drive freq_cmd == freq_out and running - hal_bit_t *is_stopped; // when drive freq out is 0 - hal_bit_t *is_e_stopped; // true if emergency stop status set in 0xFD00 - hal_bit_t *modbus_ok; // the last MODBUS_OK transactions returned successfully - hal_float_t *speed_command; // speed command input - - hal_bit_t *spindle_on; // spindle 1=on, 0=off - // hal_bit_t *err_reset; // reset errors when 1 - set fault reset bit in 0xFA00 - hal_bit_t *jog_mode; // termed 'jog-run' in manual - might be useful for spindle positioning - hal_s32_t *errorcount; // number of failed Modbus transactions - hints at logical errors - - hal_float_t looptime; - hal_float_t speed_tolerance; - hal_float_t motor_nameplate_hz; // speeds are scaled in Hz, not RPM - hal_float_t motor_nameplate_RPM; // nameplate RPM at default Hz - hal_float_t rpm_limit; // do-not-exceed output frequency - hal_bit_t *enabled; // if set: control VFD via Modbus commands, panel control disabled + hal_sint_t error_code; + hal_sint_t status; + hal_real_t freq_cmd; // frequency command + hal_real_t freq_out; // actual output frequency + hal_real_t output_volt; // output voltage + hal_real_t RPM; + hal_real_t RPS; + hal_real_t torque_ratio; + hal_real_t output_current; + hal_real_t max_rpm; // calculated based on VFD max frequency setup parameter + hal_bool_t at_speed; // when drive freq_cmd == freq_out and running + hal_bool_t is_stopped; // when drive freq out is 0 + hal_bool_t is_e_stopped; // true if emergency stop status set in 0xFD00 + hal_bool_t modbus_ok; // the last MODBUS_OK transactions returned successfully + hal_real_t speed_command; // speed command input + + hal_bool_t spindle_on; // spindle 1=on, 0=off + // hal_bool_t err_reset; // reset errors when 1 - set fault reset bit in 0xFA00 + hal_bool_t jog_mode; // termed 'jog-run' in manual - might be useful for spindle positioning + hal_sint_t errorcount; // number of failed Modbus transactions - hints at logical errors + + hal_real_t looptime; // (param) + hal_real_t speed_tolerance; // (param) + hal_real_t motor_nameplate_hz; // (param) speeds are scaled in Hz, not RPM + hal_real_t motor_nameplate_RPM; // (param) nameplate RPM at default Hz + hal_real_t rpm_limit; // (param) do-not-exceed output frequency + hal_bool_t enabled; // if set: control VFD via Modbus commands, panel control disabled // if zero (default): manual control through panel enabled - hal_float_t *upper_limit_hz; // VFD setup parameter - maximum output frequency in HZ + hal_real_t upper_limit_hz; // VFD setup parameter - maximum output frequency in HZ - hal_bit_t *max_speed; // 1: run as fast as possible, ignore unimportant registers + hal_bool_t max_speed; // 1: run as fast as possible, ignore unimportant registers // link this to spindle.orient-enable for better orient PID loop behaviour } haldata_t; @@ -225,8 +225,8 @@ static struct option long_options[] = { void windup(param_pointer p) { - if (p->haldata && *(p->haldata->errorcount)) { - fprintf(stderr,"%s: %d modbus errors\n",p->progname, *(p->haldata->errorcount)); + if (p->haldata && hal_get_si32(p->haldata->errorcount)) { + fprintf(stderr,"%s: %d modbus errors\n",p->progname, hal_get_si32(p->haldata->errorcount)); fprintf(stderr,"%s: last command register: 0x%.4x\n",p->progname, p->failed_reg); fprintf(stderr,"%s: last error: %s\n",p->progname, modbus_strerror(p->last_errno)); } @@ -360,15 +360,15 @@ void usage(int argc, char **argv) { int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) { - hal_float_t hzcalc; + rtapi_real hzcalc; int cmd1_reg; int freq_reg, freq_cap; - if (!*(haldata->enabled)) { + if (!hal_get_bool(haldata->enabled)) { // send 0 to 0x2000 register - no bus control if (modbus_write_register(ctx, REG_COMMAND1, 0) < 0) { p->failed_reg = REG_COMMAND1; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } @@ -377,25 +377,25 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) retry: // set frequency register - hzcalc = haldata->motor_nameplate_hz / haldata->motor_nameplate_RPM; - freq_reg = (int)round(fabs((*(haldata->speed_command) * hzcalc * 100.0))); - freq_cap = (int)round(fabs((haldata->rpm_limit * hzcalc * 100))); + hzcalc = hal_get_real(haldata->motor_nameplate_hz) / hal_get_real(haldata->motor_nameplate_RPM); + freq_reg = (int)round(fabs((hal_get_real(haldata->speed_command) * hzcalc * 100.0))); + freq_cap = (int)round(fabs((hal_get_real(haldata->rpm_limit) * hzcalc * 100))); // limit frequency to frequency set via max-rpm if (freq_reg > freq_cap) freq_reg = freq_cap; - *(haldata->freq_cmd) = freq_reg / 100.0; + hal_set_real(haldata->freq_cmd, freq_reg / 100.0); // prepare command register cmd1_reg = 0; - if (*haldata->spindle_on){ - cmd1_reg |= (*haldata->jog_mode) ? CMD_JOG_RUN : CMD_RUN; + if (hal_get_bool(haldata->spindle_on)){ + cmd1_reg |= hal_get_bool(haldata->jog_mode) ? CMD_JOG_RUN : CMD_RUN; } else { cmd1_reg |= CMD_STOP; } - if (*(haldata->speed_command) >= 0) { + if (hal_get_real(haldata->speed_command) >= 0) { cmd1_reg |= CMD_FORWARD; } else { cmd1_reg |= CMD_REVERSE; @@ -425,7 +425,7 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) goto retry; } p->failed_reg = REG_COMMAND1; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } @@ -436,7 +436,7 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) if ((modbus_write_register(ctx, REG_FREQUENCY, freq_reg)) < 0) { p->failed_reg = REG_FREQUENCY; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } @@ -458,9 +458,9 @@ int read_initial(modbus_t *ctx, haldata_t *haldata, param_pointer p) voltage, model, eeprom, max_freq; GETREG(REG_UPPERLIMIT, &max_freq); - *(haldata->upper_limit_hz) = (float)max_freq/100.0; - *(haldata->max_rpm) = *(haldata->upper_limit_hz) * - haldata->motor_nameplate_RPM / haldata->motor_nameplate_hz; + hal_set_real(haldata->upper_limit_hz, (float)max_freq/100.0); + hal_set_real(haldata->max_rpm, hal_get_real(haldata->upper_limit_hz) * + hal_get_real(haldata->motor_nameplate_RPM) / hal_get_real(haldata->motor_nameplate_hz)); if (p->report_device) { GETREG(SR_RATED_CURRENT, ¤t); @@ -480,7 +480,7 @@ int read_initial(modbus_t *ctx, haldata_t *haldata, param_pointer p) failed: p->failed_reg = curr_reg; p->last_errno = errno; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); if (p->debug) fprintf(stderr, "%s: read_initial: modbus_read_registers(0x%4.4x): %s\n", p->progname, curr_reg, modbus_strerror(errno)); @@ -501,50 +501,41 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) } GETREG(SR_ERROR_CODE, &curr_reg); - *(haldata->error_code) = curr_reg; + hal_set_si32(haldata->error_code, curr_reg); // we always at least read the main status register SR_INV_OPSTATUS // and current operating frequency SR_OP_FREQUENCY GETREG(SR_INV_OPSTATUS, &status_reg); - *(haldata->status) = status_reg; + hal_set_si32(haldata->status, status_reg); GETREG(SR_OUTPUT_FREQ, &freq_reg); - *(haldata->freq_out) = freq_reg * 0.01; + hal_set_real(haldata->freq_out, freq_reg * 0.01); DBG("read_data: status_reg=%4.4x freq_reg=%4.4x\n", status_reg, freq_reg); // JET if freq out is 0 then the drive is stopped - *(haldata->is_stopped) = (freq_reg == 0); + hal_set_bool(haldata->is_stopped, (freq_reg == 0)); + hal_set_bool(haldata->is_e_stopped, status_reg == ST_EMERGENCY_STOPPED); - if (status_reg == ST_EMERGENCY_STOPPED) { // set e-stop status. - *(haldata->is_e_stopped) = 1; - } else { - *(haldata->is_e_stopped) = 0; - } - - if ((pollcount == 0) && !*(haldata->max_speed)) { + if ((pollcount == 0) && !hal_get_bool(haldata->max_speed)) { // less urgent registers GETREG(SR_MOTOR_SPEED, &val); - *(haldata->RPM) = val; - *(haldata->RPS) = val/60.0; + hal_set_real(haldata->RPM, val); + hal_set_real(haldata->RPS, val/60.0); GETREG(SR_TORQUE_RATIO, &val); - *(haldata->torque_ratio) = val; + hal_set_real(haldata->torque_ratio, val); GETREG(SR_OUTPUT_CURRENT, &val); - *(haldata->output_current) = val * 0.1; + hal_set_real(haldata->output_current, val * 0.1); GETREG(SR_OUTPUT_VOLTAGE, &val); - *(haldata->output_volt) = val * 0.1; + hal_set_real(haldata->output_volt, val * 0.1); { - float speed_error; - speed_error = (*haldata->RPM / *haldata->speed_command) - 1.0; - if (fabs(speed_error) > haldata->speed_tolerance) { - *haldata->at_speed = 0; - } else { - *haldata->at_speed = 1; - } + rtapi_real speed_error; + speed_error = (hal_get_real(haldata->RPM) / hal_get_real(haldata->speed_command)) - 1.0; + hal_set_bool(haldata->at_speed, fabs(speed_error) <= hal_get_real(haldata->speed_tolerance)); } } else { pollcount++; @@ -559,7 +550,7 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) failed: p->failed_reg = curr_reg; p->last_errno = errno; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); if (p->debug) fprintf(stderr, "%s: read_data: modbus_read_registers(0x%4.4x): %s\n", p->progname, curr_reg, modbus_strerror(errno)); @@ -578,34 +569,34 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) int hal_setup(int id, haldata_t *h, const char *name) { int status; - PIN(hal_pin_bit_newf(HAL_OUT, &(h->at_speed), id, "%s.at-speed", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->output_current), id, "%s.output-current", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->enabled), id, "%s.enable", name)); - // PIN(hal_pin_bit_newf(HAL_IN, &(h->err_reset), id, "%s.err-reset", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->jog_mode), id, "%s.jog-mode", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->freq_cmd), id, "%s.frequency-command", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->freq_out), id, "%s.frequency-out", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->torque_ratio), id, "%s.inverter-load-percentage", name)); - PIN(hal_pin_bit_newf(HAL_OUT, &(h->is_e_stopped), id, "%s.is-e-stopped", name)); // JET - PIN(hal_pin_bit_newf(HAL_OUT, &(h->is_stopped), id, "%s.is-stopped", name)); // JET - PIN(hal_pin_float_newf(HAL_OUT, &(h->max_rpm), id, "%s.max-rpm", name)); - PIN(hal_pin_bit_newf(HAL_OUT, &(h->modbus_ok), id, "%s.modbus-ok", name)); // JET - PIN(hal_pin_float_newf(HAL_OUT, &(h->RPM), id, "%s.motor-RPM", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->RPS), id, "%s.motor-RPS", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->output_volt), id, "%s.output-voltage", name)); - PIN(hal_pin_float_newf(HAL_IN, &(h->speed_command), id, "%s.speed-command", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->spindle_on), id, "%s.spindle-on", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->error_code), id, "%s.error-code", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->status), id, "%s.status", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->max_speed), id, "%s.max-speed", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->errorcount), id, "%s.error-count", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->upper_limit_hz), id, "%s.frequency-limit", name)); - - PIN(hal_param_float_newf(HAL_RW, &(h->looptime), id, "%s.loop-time", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->motor_nameplate_hz), id, "%s.nameplate-HZ", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->motor_nameplate_RPM), id, "%s.nameplate-RPM", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->rpm_limit), id, "%s.rpm-limit", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->speed_tolerance), id, "%s.tolerance", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->at_speed), 0, "%s.at-speed", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->output_current), 0.0, "%s.output-current", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->enabled), 0, "%s.enable", name)); + // PIN(hal_pin_new_bool(id, HAL_IN, &(h->err_reset), 0, "%s.err-reset", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->jog_mode), 0, "%s.jog-mode", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->freq_cmd), 0.0, "%s.frequency-command", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->freq_out), 0.0, "%s.frequency-out", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->torque_ratio), 0.0, "%s.inverter-load-percentage", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->is_e_stopped), 0, "%s.is-e-stopped", name)); // JET + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->is_stopped), 0, "%s.is-stopped", name)); // JET + PIN(hal_pin_new_real(id, HAL_OUT, &(h->max_rpm), 0.0, "%s.max-rpm", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->modbus_ok), 0, "%s.modbus-ok", name)); // JET + PIN(hal_pin_new_real(id, HAL_OUT, &(h->RPM), 0.0, "%s.motor-RPM", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->RPS), 0.0, "%s.motor-RPS", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->output_volt), 0.0, "%s.output-voltage", name)); + PIN(hal_pin_new_real(id, HAL_IN, &(h->speed_command), 0.0, "%s.speed-command", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->spindle_on), 0, "%s.spindle-on", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->error_code), 0, "%s.error-code", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->status), 0, "%s.status", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->max_speed), 0, "%s.max-speed", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->errorcount), 0, "%s.error-count", name)); + PIN(hal_pin_new_real(id,HAL_OUT, &(h->upper_limit_hz), 0.0, "%s.frequency-limit", name)); + + PIN(hal_param_new_real(id, HAL_RW, &(h->looptime), 0.1, "%s.loop-time", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->motor_nameplate_hz), 0.0, "%s.nameplate-HZ", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->motor_nameplate_RPM), 0.0, "%s.nameplate-RPM", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->rpm_limit), 0.0, "%s.rpm-limit", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->speed_tolerance), 0.01, "%s.tolerance", name)); return 0; } @@ -615,32 +606,32 @@ int set_defaults(param_pointer p) { haldata_t *h = p->haldata; - *(h->status) = 0; - *(h->freq_cmd) = 0; - *(h->freq_out) = 0; - *(h->output_volt) = 0; - *(h->RPM) = 0; - *(h->torque_ratio) = 0; - *(h->output_current) = 0; - *(h->upper_limit_hz) = 0; - *(h->at_speed) = 0; - *(h->is_stopped) = 0; - *(h->is_e_stopped) = 0; - *(h->speed_command) = 0; - *(h->modbus_ok) = 0; - - *(h->spindle_on) = 0; + hal_set_si32(h->status, 0); + hal_set_real(h->freq_cmd, 0); + hal_set_real(h->freq_out, 0); + hal_set_real(h->output_volt, 0); + hal_set_real(h->RPM, 0); + hal_set_real(h->torque_ratio, 0); + hal_set_real(h->output_current, 0); + hal_set_real(h->upper_limit_hz, 0); + hal_set_bool(h->at_speed, 0); + hal_set_bool(h->is_stopped, 0); + hal_set_bool(h->is_e_stopped, 0); + hal_set_real(h->speed_command, 0); + hal_set_bool(h->modbus_ok, 0); + + hal_set_bool(h->spindle_on, 0); // *(h->err_reset) = 0; - *(h->jog_mode) = 0; - *(h->enabled) = 0; - *(h->errorcount) = 0; - *(h->max_speed) = 0; + hal_set_bool(h->jog_mode, 0); + hal_set_bool(h->enabled, 0); + hal_set_si32(h->errorcount, 0); + hal_set_bool(h->max_speed, 0); - h->looptime = 0.1; - h->speed_tolerance = 0.01; // output frequency within 1% of target frequency - h->motor_nameplate_hz = p->motor_hz; - h->motor_nameplate_RPM = p->motor_rpm; - h->rpm_limit = p->motor_rpm; + hal_set_real(h->looptime, 0.1); + hal_set_real(h->speed_tolerance, 0.01); // output frequency within 1% of target frequency + hal_set_real(h->motor_nameplate_hz, p->motor_hz); + hal_set_real(h->motor_nameplate_RPM, p->motor_rpm); + hal_set_real(h->rpm_limit, p->motor_rpm); p->failed_reg = 0; return 0; @@ -755,11 +746,7 @@ int main(int argc, char **argv) } else { p->modbus_ok++; } - if (p->modbus_ok > MODBUS_MIN_OK) { - *(p->haldata->modbus_ok) = 1; - } else { - *(p->haldata->modbus_ok) = 0; - } + hal_set_bool(p->haldata->modbus_ok, p->modbus_ok > MODBUS_MIN_OK); if ((retval = write_data(p->ctx, p->haldata, p))) { p->modbus_ok = 0; if ((retval == EBADF || retval == ECONNRESET || retval == EPIPE)) { @@ -768,16 +755,13 @@ int main(int argc, char **argv) } else { p->modbus_ok++; } - if (p->modbus_ok > MODBUS_MIN_OK) { - *(p->haldata->modbus_ok) = 1; - } else { - *(p->haldata->modbus_ok) = 0; - } + hal_set_bool(p->haldata->modbus_ok, p->modbus_ok > MODBUS_MIN_OK); /* don't want to scan too fast, and shouldn't delay more than a few seconds */ - if (p->haldata->looptime < 0.001) p->haldata->looptime = 0.001; - if (p->haldata->looptime > 2.0) p->haldata->looptime = 2.0; - loop_timespec.tv_sec = (time_t)(p->haldata->looptime); - loop_timespec.tv_nsec = (long)((p->haldata->looptime - loop_timespec.tv_sec) * 1000000000l); + rtapi_real looptime = hal_get_real(p->haldata->looptime); + if (looptime < 0.001) looptime = hal_set_real(p->haldata->looptime, 0.001); + if (looptime > 2.0) looptime = hal_set_real(p->haldata->looptime, 2.0); + loop_timespec.tv_sec = (time_t)looptime; + loop_timespec.tv_nsec = (long)((looptime - loop_timespec.tv_sec) * 1000000000l); if (!p->haldata->max_speed) nanosleep(&loop_timespec, &remaining); } diff --git a/src/hal/user_comps/vfs11_vfd/vfs11_vfd.c b/src/hal/user_comps/vfs11_vfd/vfs11_vfd.c index ba17e6c2d05..b2a04c863c5 100644 --- a/src/hal/user_comps/vfs11_vfd/vfs11_vfd.c +++ b/src/hal/user_comps/vfs11_vfd/vfs11_vfd.c @@ -211,44 +211,44 @@ /* HAL data struct */ typedef struct { - hal_s32_t *status; - hal_float_t *freq_cmd; // frequency command - hal_float_t *freq_out; // actual output frequency - hal_float_t *curr_out_pct; // output current percentage (base unclear) - hal_float_t *outV_pct; // output voltage percent - hal_float_t *RPM; - hal_float_t *inv_load_pct; - hal_float_t *load_current_pct; - hal_float_t *max_rpm; // calculated based on VFD max frequency setup parameter - hal_s32_t *trip_code; - hal_s32_t *alarm_code; - hal_bit_t *at_speed; // when drive freq_cmd == freq_out and running - hal_bit_t *is_stopped; // when drive freq out is 0 - hal_bit_t *estop; // set estop bit in 0xFA00 - causes 'E trip' - hal_bit_t *is_e_stopped; // true if emergency stop status set in 0xFD00 - hal_bit_t *modbus_ok; // the last MODBUS_OK transactions returned successfully - hal_float_t *speed_command; // speed command input - - hal_bit_t *spindle_on; // spindle 1=on, 0=off - hal_bit_t *DC_brake; // setting this will turn off the spindle and engage the DC brake - hal_bit_t *spindle_fwd; // direction, 0=fwd, 1=rev - hal_bit_t *spindle_rev; // on when in rev and running - hal_bit_t *err_reset; // reset errors when 1 - set fault reset bit in 0xFA00 - hal_bit_t *jog_mode; // termed 'jog-run' in manual - might be useful for spindle positioning - hal_s32_t *errorcount; // number of failed Modbus transactions - hints at logical errors - - hal_float_t looptime; - hal_float_t speed_tolerance; - hal_float_t motor_nameplate_hz; // speeds are scaled in Hz, not RPM - hal_float_t motor_nameplate_RPM; // nameplate RPM at default Hz - hal_float_t rpm_limit; // do-not-exceed output frequency - hal_bit_t *acc_dec_pattern; // if set: choose ramp times as defined in F500+F501 + hal_sint_t status; + hal_real_t freq_cmd; // frequency command + hal_real_t freq_out; // actual output frequency + hal_real_t curr_out_pct; // output current percentage (base unclear) + hal_real_t outV_pct; // output voltage percent + hal_real_t RPM; + hal_real_t inv_load_pct; + hal_real_t load_current_pct; + hal_real_t max_rpm; // calculated based on VFD max frequency setup parameter + hal_sint_t trip_code; + hal_sint_t alarm_code; + hal_bool_t at_speed; // when drive freq_cmd == freq_out and running + hal_bool_t is_stopped; // when drive freq out is 0 + hal_bool_t estop; // set estop bit in 0xFA00 - causes 'E trip' + hal_bool_t is_e_stopped; // true if emergency stop status set in 0xFD00 + hal_bool_t modbus_ok; // the last MODBUS_OK transactions returned successfully + hal_real_t speed_command; // speed command input + + hal_bool_t spindle_on; // spindle 1=on, 0=off + hal_bool_t DC_brake; // setting this will turn off the spindle and engage the DC brake + hal_bool_t spindle_fwd; // direction, 0=fwd, 1=rev + hal_bool_t spindle_rev; // on when in rev and running + hal_bool_t err_reset; // reset errors when 1 - set fault reset bit in 0xFA00 + hal_bool_t jog_mode; // termed 'jog-run' in manual - might be useful for spindle positioning + hal_sint_t errorcount; // number of failed Modbus transactions - hints at logical errors + + hal_real_t looptime; // (param) + hal_real_t speed_tolerance; // (param) + hal_real_t motor_nameplate_hz; // (param) speeds are scaled in Hz, not RPM + hal_real_t motor_nameplate_RPM; // (param) nameplate RPM at default Hz + hal_real_t rpm_limit; // (param) do-not-exceed output frequency + hal_bool_t acc_dec_pattern; // if set: choose ramp times as defined in F500+F501 // if zero (default): choose ramp times as defined in ACC and DEC - hal_bit_t *enabled; // if set: control VFD via Modbus commands, panel control disabled + hal_bool_t enabled; // if set: control VFD via Modbus commands, panel control disabled // if zero (default): manual control through panel enabled - hal_float_t *upper_limit_hz; // VFD setup parameter - maximum output frequency in HZ + hal_real_t upper_limit_hz; // VFD setup parameter - maximum output frequency in HZ - hal_bit_t *max_speed; // 1: run as fast as possible, ignore unimportant registers + hal_bool_t max_speed; // 1: run as fast as possible, ignore unimportant registers // link this to spindle.orient-enable for better orient PID loop behaviour } haldata_t; @@ -345,8 +345,8 @@ static struct option long_options[] = { void windup(param_pointer p) { - if (p->haldata && *(p->haldata->errorcount)) { - fprintf(stderr,"%s: %d modbus errors\n",p->progname, *(p->haldata->errorcount)); + if (p->haldata && hal_get_si32(p->haldata->errorcount)) { + fprintf(stderr,"%s: %d modbus errors\n",p->progname, hal_get_si32(p->haldata->errorcount)); fprintf(stderr,"%s: last command register: 0x%.4x\n",p->progname, p->failed_reg); fprintf(stderr,"%s: last error: %s\n",p->progname, modbus_strerror(p->last_errno)); } @@ -521,15 +521,15 @@ void usage(int argc, char **argv) { int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) { - hal_float_t hzcalc; + rtapi_real hzcalc; int cmd1_reg; int freq_reg, freq_cap; - if (!*(haldata->enabled)) { + if (!hal_get_bool(haldata->enabled)) { // send 0 to FA00 register - no bus control if (modbus_write_register(ctx, REG_COMMAND1, 0) < 0) { p->failed_reg = REG_COMMAND1; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } @@ -537,26 +537,26 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) } retry: // set frequency register - if (haldata->motor_nameplate_hz < 10) - haldata->motor_nameplate_hz = 50; - if ((haldata->motor_nameplate_RPM < 600) || (haldata->motor_nameplate_RPM > 5000)) - haldata->motor_nameplate_RPM = 1410; - hzcalc = haldata->motor_nameplate_hz/haldata->motor_nameplate_RPM; + if (hal_get_real(haldata->motor_nameplate_hz) < 10) + hal_set_real(haldata->motor_nameplate_hz, 50); + if ((hal_get_real(haldata->motor_nameplate_RPM) < 600) || (hal_get_real(haldata->motor_nameplate_RPM) > 5000)) + hal_set_real(haldata->motor_nameplate_RPM, 1410); + hzcalc = hal_get_real(haldata->motor_nameplate_hz) / hal_get_real(haldata->motor_nameplate_RPM); - freq_reg = abs((int)(*(haldata->speed_command) * hzcalc * 100)); - freq_cap = abs((int)(haldata->rpm_limit * hzcalc * 100)); + freq_reg = abs((int)(hal_get_real(haldata->speed_command) * hzcalc * 100)); + freq_cap = abs((int)(hal_get_real(haldata->rpm_limit) * hzcalc * 100)); // limit frequency to frequency set via max-rpm if (freq_reg > freq_cap) freq_reg = freq_cap; - *(haldata->freq_cmd) = freq_reg / 100.0; + hal_set_real(haldata->freq_cmd, freq_reg / 100.0); // prepare command register // force Modbus control - this disables the panel cmd1_reg = (CMD_COMMAND_PRIORITY|CMD_FREQUENCY_PRIORITY); - if (*haldata->spindle_on){ - cmd1_reg|= (*haldata->jog_mode) ? CMD_JOG_RUN : CMD_RUN; + if (hal_get_bool(haldata->spindle_on)){ + cmd1_reg|= hal_get_bool(haldata->jog_mode) ? CMD_JOG_RUN : CMD_RUN; } // if 1, choose ramp times as per F500/F501 @@ -567,39 +567,39 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) // rev follows fwd // two bits for one direction is a mess in the first place - *(haldata->spindle_rev) = *(haldata->spindle_fwd) ? 0 : 1; - *(haldata->spindle_fwd) = *(haldata->spindle_rev) ? 0 : 1; + hal_set_bool(haldata->spindle_rev, !hal_get_bool(haldata->spindle_fwd)); + hal_set_bool(haldata->spindle_fwd, !hal_get_bool(haldata->spindle_rev)); - if (*haldata->spindle_rev) { + if (hal_get_bool(haldata->spindle_rev)) { cmd1_reg |= CMD_REVERSE; } else { cmd1_reg &= (~CMD_REVERSE); // direction bit = 0 -> forward } // DC brake - turn spindle_on off as well - if (*(haldata->DC_brake)) { + if (hal_get_bool(haldata->DC_brake)) { cmd1_reg |= CMD_DC_BRAKE; // set DC brake bit cmd1_reg &= ~(CMD_RUN | CMD_JOG_RUN); - *(haldata->spindle_on) = 0; - *(haldata->at_speed) = 0; + hal_set_bool(haldata->spindle_on, 0); + hal_set_bool(haldata->at_speed, 0); } else { cmd1_reg &= ~CMD_DC_BRAKE; } // send CMD_FAULT_RESET and CMD_EMERGENCY_STOP only once so the poor thing comes back // out of reset/estop status eventually - if (*(haldata->err_reset) && !(p->old_cmd1_reg & CMD_FAULT_RESET )) { // not sent yet + if (hal_get_bool(haldata->err_reset) && !(p->old_cmd1_reg & CMD_FAULT_RESET )) { // not sent yet cmd1_reg |= CMD_FAULT_RESET; // fault reset bit = 1 -> clear fault - *(haldata->err_reset) = 0; + hal_set_bool(haldata->err_reset, 0); } else { cmd1_reg &= ~CMD_FAULT_RESET; } - if (*(haldata->estop) && !(p->old_cmd1_reg & CMD_EMERGENCY_STOP )) { // not sent yet) + if (hal_get_bool(haldata->estop) && !(p->old_cmd1_reg & CMD_EMERGENCY_STOP )) { // not sent yet) cmd1_reg |= CMD_EMERGENCY_STOP; // estop bit -> trip VFD into estop mode - *(haldata->estop) = 0; - *(haldata->spindle_on) = 0; - *(haldata->at_speed) = 0; + hal_set_bool(haldata->estop, 0); + hal_set_bool(haldata->spindle_on, 0); + hal_set_bool(haldata->at_speed, 0); } else { cmd1_reg &= ~CMD_EMERGENCY_STOP; } @@ -618,7 +618,7 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) goto retry; } p->failed_reg = REG_COMMAND1; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } @@ -629,19 +629,19 @@ int write_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) if ((modbus_write_register(ctx, REG_FREQUENCY, freq_reg)) < 0) { p->failed_reg = REG_FREQUENCY; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); p->last_errno = errno; return errno; } - if ((*(haldata->freq_cmd) > 0.01) && ((1.0 - *(haldata->freq_out) / *(haldata->freq_cmd)) < haldata->speed_tolerance)){ - *(haldata->at_speed) = 1; + if ((hal_get_real(haldata->freq_cmd) > 0.01) && ((1.0 - hal_get_real(haldata->freq_out) / hal_get_real(haldata->freq_cmd)) < hal_get_real(haldata->speed_tolerance))){ + hal_set_bool(haldata->at_speed, 1); } else { - *(haldata->at_speed) = 0; + hal_set_bool(haldata->at_speed, 0); } - if (*(haldata->spindle_on) == 0){ // JET reset at-speed - *(haldata->at_speed) = 0; + if (hal_get_bool(haldata->spindle_on) == 0){ // JET reset at-speed + hal_set_bool(haldata->at_speed, 0); } return 0; } @@ -660,10 +660,10 @@ int read_initial(modbus_t *ctx, haldata_t *haldata, param_pointer p) voltage, model, cpu1, cpu2, eeprom, max_freq; GETREG(REG_UPPERLIMIT, &max_freq); - *(haldata->upper_limit_hz) = max_freq/100.0; - *(haldata->max_rpm) = *(haldata->upper_limit_hz) * - haldata->motor_nameplate_RPM / - haldata->motor_nameplate_hz; + hal_set_real(haldata->upper_limit_hz, max_freq/100.0); + hal_set_real(haldata->max_rpm, hal_get_real(haldata->upper_limit_hz) * + hal_get_real(haldata->motor_nameplate_RPM) / + hal_get_real(haldata->motor_nameplate_hz)); if (p->report_device) { GETREG(SR_RATED_CURRENT, ¤t); @@ -685,7 +685,7 @@ int read_initial(modbus_t *ctx, haldata_t *haldata, param_pointer p) failed: p->failed_reg = curr_reg; p->last_errno = errno; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); if (p->debug) fprintf(stderr, "%s: read_initial: modbus_read_registers(0x%4.4x): %s\n", p->progname, curr_reg, modbus_strerror(errno)); @@ -708,54 +708,54 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) // we always at least read the main status register SR_INV_OPSTATUS // and current operating frequency SR_OP_FREQUENCY GETREG(SR_INV_OPSTATUS, &status_reg); - *(haldata->status) = status_reg; + hal_set_si32(haldata->status, status_reg); GETREG(SR_OP_FREQUENCY, &freq_reg); - *(haldata->freq_out) = freq_reg * 0.01; + hal_set_real(haldata->freq_out, freq_reg * 0.01); DBG("read_data: status_reg=%4.4x freq_reg=%4.4x\n", status_reg, freq_reg); // JET if freq out is 0 then the drive is stopped - *(haldata->is_stopped) = (freq_reg == 0); + hal_set_bool(haldata->is_stopped, freq_reg == 0); // determine what to do next. if (status_reg & ST_TRIPPED) { // read and set trip code. GETREG(SR_TRIPCODE, &val); - *(haldata->trip_code) = val; + hal_set_si32(haldata->trip_code, val); // a sensible addition would be to read and convey SR_INV_OPSTATUS_T, the status just before the trip } else { - *(haldata->trip_code) = 0; + hal_set_si32(haldata->trip_code, 0); } if (status_reg & ST_ALARMED) { // read and set alarm bit map. GETREG(SR_ALARM_MONITOR, &val); - *(haldata->alarm_code) = val; + hal_set_si32(haldata->alarm_code, val); } else { - *(haldata->alarm_code) = 0; + hal_set_si32(haldata->alarm_code, 0); } if (status_reg & ST_EMERGENCY_STOPPED) { // set e-stop status. - *(haldata->is_e_stopped) = 1; + hal_set_bool(haldata->is_e_stopped, 1); } else { - *(haldata->is_e_stopped) = 0; + hal_set_bool(haldata->is_e_stopped, 0); } // unsure what to do here with ST_FAILURE_FL bit - if ((pollcount == 0) && !(*haldata->max_speed)) { + if ((pollcount == 0) && !hal_get_bool(haldata->max_speed)) { // less urgent registers GETREG(SR_ESTIMATED_OPFREQ, &val); - *(haldata->RPM) = val * haldata->motor_nameplate_hz / 100.0; + hal_set_real(haldata->RPM, val * hal_get_real(haldata->motor_nameplate_hz) / 100.0); GETREG(SR_INV_LOADFACTOR, &val); - *(haldata->inv_load_pct) = val; + hal_set_real(haldata->inv_load_pct, val); GETREG(SR_LOADCURRENT, &val); - *(haldata->load_current_pct) = val * 0.01; + hal_set_real(haldata->load_current_pct, val * 0.01); GETREG(SR_OUTPUT_VOLTAGE, &val); - *(haldata->outV_pct) = val * 0.01; + hal_set_real(haldata->outV_pct, val * 0.01); } else pollcount++; if (pollcount >= p->pollcycles) @@ -766,7 +766,7 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) failed: p->failed_reg = curr_reg; p->last_errno = errno; - (*haldata->errorcount)++; + hal_set_si32(haldata->errorcount, hal_get_si32(haldata->errorcount) + 1); if (p->debug) fprintf(stderr, "%s: read_data: modbus_read_registers(0x%4.4x): %s\n", p->progname, curr_reg, modbus_strerror(errno)); @@ -785,41 +785,41 @@ int read_data(modbus_t *ctx, haldata_t *haldata, param_pointer p) int hal_setup(int id, haldata_t *h, const char *name) { int status; - PIN(hal_pin_bit_newf(HAL_IN, &(h->acc_dec_pattern), id, "%s.acceleration-pattern", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->alarm_code), id, "%s.alarm-code", name)); - PIN(hal_pin_bit_newf(HAL_OUT, &(h->at_speed), id, "%s.at-speed", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->load_current_pct), id, "%s.current-load-percentage", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->DC_brake), id, "%s.dc-brake", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->enabled), id, "%s.enable", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->err_reset), id, "%s.err-reset", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->jog_mode), id, "%s.jog-mode", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->estop), id, "%s.estop", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->freq_cmd), id, "%s.frequency-command", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->freq_out), id, "%s.frequency-out", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->inv_load_pct), id, "%s.inverter-load-percentage", name)); - PIN(hal_pin_bit_newf(HAL_OUT, &(h->is_e_stopped), id, "%s.is-e-stopped", name)); // JET - PIN(hal_pin_bit_newf(HAL_OUT, &(h->is_stopped), id, "%s.is-stopped", name)); // JET - PIN(hal_pin_float_newf(HAL_OUT, &(h->max_rpm), id, "%s.max-rpm", name)); - PIN(hal_pin_bit_newf(HAL_OUT, &(h->modbus_ok), id, "%s.modbus-ok", name)); // JET - PIN(hal_pin_float_newf(HAL_OUT, &(h->RPM), id, "%s.motor-RPM", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->curr_out_pct), id, "%s.output-current-percentage", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->outV_pct), id, "%s.output-voltage-percentage", name)); - PIN(hal_pin_float_newf(HAL_IN, &(h->speed_command), id, "%s.speed-command", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->spindle_fwd), id, "%s.spindle-fwd", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->spindle_on), id, "%s.spindle-on", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->spindle_rev), id, "%s.spindle-rev", name)); //JET - PIN(hal_pin_s32_newf(HAL_OUT, &(h->status), id, "%s.status", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->trip_code), id, "%s.trip-code", name)); - PIN(hal_pin_bit_newf(HAL_IN, &(h->max_speed), id, "%s.max-speed", name)); - PIN(hal_pin_s32_newf(HAL_OUT, &(h->errorcount), id, "%s.error-count", name)); - PIN(hal_pin_float_newf(HAL_OUT, &(h->upper_limit_hz), id, "%s.frequency-limit", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->acc_dec_pattern), 0, "%s.acceleration-pattern", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->alarm_code), 0, "%s.alarm-code", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->at_speed), 0, "%s.at-speed", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->load_current_pct), 0.0, "%s.current-load-percentage", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->DC_brake), 0, "%s.dc-brake", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->enabled), 0, "%s.enable", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->err_reset), 0, "%s.err-reset", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->jog_mode), 0, "%s.jog-mode", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->estop), 0, "%s.estop", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->freq_cmd), 0.0, "%s.frequency-command", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->freq_out), 0.0, "%s.frequency-out", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->inv_load_pct), 0.0, "%s.inverter-load-percentage", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->is_e_stopped), 0, "%s.is-e-stopped", name)); // JET + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->is_stopped), 0, "%s.is-stopped", name)); // JET + PIN(hal_pin_new_real(id, HAL_OUT, &(h->max_rpm), 0.0, "%s.max-rpm", name)); + PIN(hal_pin_new_bool(id, HAL_OUT, &(h->modbus_ok), 0, "%s.modbus-ok", name)); // JET + PIN(hal_pin_new_real(id, HAL_OUT, &(h->RPM), 0.0, "%s.motor-RPM", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->curr_out_pct), 0.0, "%s.output-current-percentage", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->outV_pct), 0.0, "%s.output-voltage-percentage", name)); + PIN(hal_pin_new_real(id, HAL_IN, &(h->speed_command), 0.0, "%s.speed-command", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->spindle_fwd), 1, "%s.spindle-fwd", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->spindle_on), 0, "%s.spindle-on", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->spindle_rev), 0, "%s.spindle-rev", name)); //JET + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->status), 0, "%s.status", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->trip_code), 0, "%s.trip-code", name)); + PIN(hal_pin_new_bool(id, HAL_IN, &(h->max_speed), 0, "%s.max-speed", name)); + PIN(hal_pin_new_si32(id, HAL_OUT, &(h->errorcount), 0, "%s.error-count", name)); + PIN(hal_pin_new_real(id, HAL_OUT, &(h->upper_limit_hz), 0.0, "%s.frequency-limit", name)); // the following limit must be set manually from the panel since its in EEPROM - PIN(hal_param_float_newf(HAL_RW, &(h->looptime), id, "%s.loop-time", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->motor_nameplate_hz), id, "%s.nameplate-HZ", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->motor_nameplate_RPM), id, "%s.nameplate-RPM", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->rpm_limit), id, "%s.rpm-limit", name)); - PIN(hal_param_float_newf(HAL_RW, &(h->speed_tolerance), id, "%s.tolerance", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->looptime), 0.1, "%s.loop-time", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->motor_nameplate_hz), 50.0, "%s.nameplate-HZ", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->motor_nameplate_RPM), 1410.0, "%s.nameplate-RPM", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->rpm_limit), MAX_RPM, "%s.rpm-limit", name)); + PIN(hal_param_new_real(id, HAL_RW, &(h->speed_tolerance), 0.01, "%s.tolerance", name)); return 0; } @@ -829,40 +829,40 @@ int set_defaults(param_pointer p) { haldata_t *h = p->haldata; - *(h->status) = 0; - *(h->freq_cmd) = 0; - *(h->freq_out) = 0; - *(h->curr_out_pct) = 0; - *(h->outV_pct) = 0; - *(h->RPM) = 0; - *(h->inv_load_pct) = 0; - *(h->load_current_pct) = 0; - *(h->upper_limit_hz) = 0; - *(h->trip_code) = 0; - *(h->alarm_code) = 0; - *(h->at_speed) = 0; - *(h->is_stopped) = 0; - *(h->estop) = 0; - *(h->is_e_stopped) = 0; - *(h->speed_command) = 0; - *(h->modbus_ok) = 0; - - *(h->spindle_on) = 0; - *(h->DC_brake) = 0; - *(h->spindle_fwd) = 1; - *(h->spindle_rev) = 0; - *(h->err_reset) = 0; - *(h->jog_mode) = 0; - *(h->enabled) = 0; - *(h->acc_dec_pattern) = 0; - *(h->errorcount) = 0; - *(h->max_speed) = 0; - - h->looptime = 0.1; - h->speed_tolerance = 0.01; // output frequency within 1% of target frequency - h->motor_nameplate_hz = 50; // folks in The Colonies typically would use 60Hz and 1730 rpm - h->motor_nameplate_RPM = 1410; - h->rpm_limit = MAX_RPM; + hal_set_si32(h->status, 0); + hal_set_real(h->freq_cmd, 0); + hal_set_real(h->freq_out, 0); + hal_set_real(h->curr_out_pct, 0); + hal_set_real(h->outV_pct, 0); + hal_set_real(h->RPM, 0); + hal_set_real(h->inv_load_pct, 0); + hal_set_real(h->load_current_pct, 0); + hal_set_real(h->upper_limit_hz, 0); + hal_set_si32(h->trip_code, 0); + hal_set_si32(h->alarm_code, 0); + hal_set_bool(h->at_speed, 0); + hal_set_bool(h->is_stopped, 0); + hal_set_bool(h->estop, 0); + hal_set_bool(h->is_e_stopped, 0); + hal_set_real(h->speed_command, 0); + hal_set_bool(h->modbus_ok, 0); + + hal_set_bool(h->spindle_on, 0); + hal_set_bool(h->DC_brake, 0); + hal_set_bool(h->spindle_fwd, 1); + hal_set_bool(h->spindle_rev, 0); + hal_set_bool(h->err_reset, 0); + hal_set_bool(h->jog_mode, 0); + hal_set_bool(h->enabled, 0); + hal_set_bool(h->acc_dec_pattern, 0); + hal_set_si32(h->errorcount, 0); + hal_set_bool(h->max_speed, 0); + + hal_set_real(h->looptime, 0.1); + hal_set_real(h->speed_tolerance, 0.01); // output frequency within 1% of target frequency + hal_set_real(h->motor_nameplate_hz, 50); // folks in The Colonies typically would use 60Hz and 1730 rpm + hal_set_real(h->motor_nameplate_RPM, 1410); + hal_set_real(h->rpm_limit, MAX_RPM); p->failed_reg = 0; return 0; @@ -1034,11 +1034,7 @@ int main(int argc, char **argv) } else { p->modbus_ok++; } - if (p->modbus_ok > MODBUS_MIN_OK) { - *(p->haldata->modbus_ok) = 1; - } else { - *(p->haldata->modbus_ok) = 0; - } + hal_set_bool(p->haldata->modbus_ok, p->modbus_ok > MODBUS_MIN_OK); if ((retval = write_data(p->ctx, p->haldata, p))) { p->modbus_ok = 0; if ((retval == EBADF || retval == ECONNRESET || retval == EPIPE)) { @@ -1047,16 +1043,13 @@ int main(int argc, char **argv) } else { p->modbus_ok++; } - if (p->modbus_ok > MODBUS_MIN_OK) { - *(p->haldata->modbus_ok) = 1; - } else { - *(p->haldata->modbus_ok) = 0; - } + hal_set_bool(p->haldata->modbus_ok, p->modbus_ok > MODBUS_MIN_OK); /* don't want to scan too fast, and shouldn't delay more than a few seconds */ - if (p->haldata->looptime < 0.001) p->haldata->looptime = 0.001; - if (p->haldata->looptime > 2.0) p->haldata->looptime = 2.0; - loop_timespec.tv_sec = (time_t)(p->haldata->looptime); - loop_timespec.tv_nsec = (long)((p->haldata->looptime - loop_timespec.tv_sec) * 1000000000l); + rtapi_real looptime = hal_get_real(p->haldata->looptime); + if (looptime < 0.001) looptime = hal_set_real(p->haldata->looptime, 0.001); + if (looptime > 2.0) looptime = hal_set_real(p->haldata->looptime, 2.0); + loop_timespec.tv_sec = (time_t)looptime; + loop_timespec.tv_nsec = (long)((looptime - loop_timespec.tv_sec) * 1000000000l); if (!p->haldata->max_speed) nanosleep(&loop_timespec, &remaining); } diff --git a/src/hal/user_comps/wj200_vfd/wj200_vfd.comp b/src/hal/user_comps/wj200_vfd/wj200_vfd.comp index 76d76522f1e..71b1c9cf86b 100644 --- a/src/hal/user_comps/wj200_vfd/wj200_vfd.comp +++ b/src/hal/user_comps/wj200_vfd/wj200_vfd.comp @@ -1,20 +1,20 @@ component wj200_vfd "Hitachi wj200 modbus driver"; -param rw unsigned mbslaveaddr "Modbus slave address"; -param rw float frequency_scale = 1 "RPM / frequency, default 1"; -pin in float commanded_frequency "Frequency of vfd (scaled to RPM)"; -pin out float motor_frequency "Motor's actual frequency (scaled to RPM)"; -pin out bit motor_reverse "1 when actually turning in reverse"; -pin in bit reverse "1 when reverse 0 when forward"; -pin in bit run "run the vfd"; -pin in bit enable "1 to enable the vfd. 0 will remote trip the vfd, thereby disabling it."; -pin out bit is_running "1 when running"; -pin out bit is_at_speed "1 when running at assigned frequency"; -pin out bit is_stopped "1 when stopped"; -pin out bit is_ready "1 when vfd is ready to run"; -pin out bit is_alarm "1 when vfd alarm is set"; -pin out float motor_current "Output current in amps"; -pin out float heatsink_temp "Temperature of drive heatsink"; -pin out bit watchdog_out "Alternates between 1 and 0 after every update cycle. Feed into a watchdog component to ensure vfd driver is communicating with the vfd properly."; +param rw ui32 mbslaveaddr "Modbus slave address"; +param rw real frequency_scale = 1 "RPM / frequency, default 1"; +pin in real commanded_frequency "Frequency of vfd (scaled to RPM)"; +pin out real motor_frequency "Motor's actual frequency (scaled to RPM)"; +pin out bool motor_reverse "1 when actually turning in reverse"; +pin in bool reverse "1 when reverse 0 when forward"; +pin in bool run "run the vfd"; +pin in bool enable "1 to enable the vfd. 0 will remote trip the vfd, thereby disabling it."; +pin out bool is_running "1 when running"; +pin out bool is_at_speed "1 when running at assigned frequency"; +pin out bool is_stopped "1 when stopped"; +pin out bool is_ready "1 when vfd is ready to run"; +pin out bool is_alarm "1 when vfd alarm is set"; +pin out real motor_current "Output current in amps"; +pin out real heatsink_temp "Temperature of drive heatsink"; +pin out bool watchdog_out "Alternates between 1 and 0 after every update cycle. Feed into a watchdog component to ensure vfd driver is communicating with the vfd properly."; option userspace yes; option userinit yes; license "GPLv2 or greater"; @@ -339,21 +339,21 @@ void user_mainloop(void) { continue; } - is_running = status.running; - is_ready = status.ready; - is_alarm = status.alarm; - is_stopped = status.stopped; - motor_frequency = status.actual_frequency * frequency_scale; - motor_reverse = status.output_rotation == 2; + is_running_set(status.running); + is_ready_set(status.ready); + is_alarm_set(status.alarm); + is_stopped_set(status.stopped); + motor_frequency_set(status.actual_frequency * frequency_scale); + motor_reverse_set(status.output_rotation == 2); /* The WJ200 has a "bug" in that is_at_speed is set even if it's running in the wrong direction, which is not what we want. Check that here. */ if (reverse == motor_reverse) - is_at_speed = (status.frequency == 0 + is_at_speed_set(status.frequency == 0 ? status.stopped : status.at_speed); else - is_at_speed = 0; + is_at_speed_set(0); if(!status.alarm && !enable && !wj200_trip(ctx)) { print_modbus_error(__comp_inst, "failed to trip"); @@ -382,9 +382,9 @@ void user_mainloop(void) { continue; } - watchdog_out = !watchdog_out; - motor_current = status.output_current / 100; - heatsink_temp = status.sink_temp / 10; + watchdog_out_set(!watchdog_out); + motor_current_set(status.output_current / 100); + heatsink_temp_set(status.sink_temp / 10); } } } diff --git a/src/hal/user_comps/xhc-hb04.cc b/src/hal/user_comps/xhc-hb04.cc index 5c37a013052..e56d1cb7721 100644 --- a/src/hal/user_comps/xhc-hb04.cc +++ b/src/hal/user_comps/xhc-hb04.cc @@ -103,49 +103,50 @@ static int stepsize_last_idx = 0; //calculated` typedef struct { - hal_float_t *x_wc, *y_wc, *z_wc, *a_wc; - hal_float_t *x_mc, *y_mc, *z_mc, *a_mc; - - hal_float_t *feedrate_override, *feedrate; - hal_float_t *spindle_override, *spindle_rps; - - hal_bit_t *button_pin[NB_MAX_BUTTONS]; - - hal_bit_t *jog_enable_off; - hal_bit_t *jog_enable_x; - hal_bit_t *jog_enable_y; - hal_bit_t *jog_enable_z; - hal_bit_t *jog_enable_a; - hal_bit_t *jog_enable_feedrate; - hal_bit_t *jog_enable_spindle; - hal_float_t *jog_scale; - hal_s32_t *jog_counts, *jog_counts_neg; - - hal_float_t *jog_velocity; - hal_float_t *jog_max_velocity; - hal_float_t *jog_increment; - hal_bit_t *jog_plus_x, *jog_plus_y, *jog_plus_z, *jog_plus_a; - hal_bit_t *jog_minus_x, *jog_minus_y, *jog_minus_z, *jog_minus_a; - - hal_bit_t *stepsize_up; - hal_bit_t *stepsize_down; - hal_s32_t *stepsize; - hal_bit_t *sleeping; - hal_bit_t *connected; - hal_bit_t *require_pendant; - hal_bit_t *inch_icon; - hal_bit_t *zero_x; - hal_bit_t *zero_y; - hal_bit_t *zero_z; - hal_bit_t *zero_a; - hal_bit_t *gotozero_x; - hal_bit_t *gotozero_y; - hal_bit_t *gotozero_z; - hal_bit_t *gotozero_a; - hal_bit_t *half_x; - hal_bit_t *half_y; - hal_bit_t *half_z; - hal_bit_t *half_a; + hal_real_t x_wc, y_wc, z_wc, a_wc; + hal_real_t x_mc, y_mc, z_mc, a_mc; + + hal_real_t feedrate_override, feedrate; + hal_real_t spindle_override, spindle_rps; + + hal_bool_t button_pin[NB_MAX_BUTTONS]; + + hal_bool_t jog_enable_off; + hal_bool_t jog_enable_x; + hal_bool_t jog_enable_y; + hal_bool_t jog_enable_z; + hal_bool_t jog_enable_a; + hal_bool_t jog_enable_feedrate; + hal_bool_t jog_enable_spindle; + hal_real_t jog_scale; + hal_sint_t jog_counts; + hal_sint_t jog_counts_neg; + + hal_real_t jog_velocity; + hal_real_t jog_max_velocity; + hal_real_t jog_increment; + hal_bool_t jog_plus_x, jog_plus_y, jog_plus_z, jog_plus_a; + hal_bool_t jog_minus_x, jog_minus_y, jog_minus_z, jog_minus_a; + + hal_bool_t stepsize_up; + hal_bool_t stepsize_down; + hal_sint_t stepsize; + hal_bool_t sleeping; + hal_bool_t connected; + hal_bool_t require_pendant; + hal_bool_t inch_icon; + hal_bool_t zero_x; + hal_bool_t zero_y; + hal_bool_t zero_z; + hal_bool_t zero_a; + hal_bool_t gotozero_x; + hal_bool_t gotozero_y; + hal_bool_t gotozero_z; + hal_bool_t gotozero_a; + hal_bool_t half_x; + hal_bool_t half_y; + hal_bool_t half_z; + hal_bool_t half_a; } xhc_hal_t; #define STEP_UNDEFINED -1 @@ -163,7 +164,7 @@ typedef struct { unsigned char button_step; // Used in simulation mode to handle the STEP increment // Variables for velocity computation - hal_s32_t last_jog_counts; + rtapi_s32 last_jog_counts; struct timeval last_tv; struct timeval last_wakeup; @@ -219,20 +220,20 @@ void xhc_display_encode(xhc_t *xhc, unsigned char *data, int len) *p++ = 0xFD; *p++ = 0x0C; - if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * *(xhc->hal->a_wc)) / 1000, p); - else p += xhc_encode_float(round(1000 * *(xhc->hal->x_wc)) / 1000, p); - p += xhc_encode_float(round(1000 * *(xhc->hal->y_wc)) / 1000, p); - p += xhc_encode_float(round(1000 * *(xhc->hal->z_wc)) / 1000, p); - if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * *(xhc->hal->a_mc)) / 1000, p); - else p += xhc_encode_float(round(1000 * *(xhc->hal->x_mc)) / 1000, p); - p += xhc_encode_float(round(1000 * *(xhc->hal->y_mc)) / 1000, p); - p += xhc_encode_float(round(1000 * *(xhc->hal->z_mc)) / 1000, p); - p += xhc_encode_s16(round(100.0 * *(xhc->hal->feedrate_override)), p); - p += xhc_encode_s16(round(100.0 * *(xhc->hal->spindle_override)), p); - p += xhc_encode_s16(round(60.0 * *(xhc->hal->feedrate)), p); - p += xhc_encode_s16(round(60.0 * *(xhc->hal->spindle_rps)), p); - - switch (*(xhc->hal->stepsize)) { + if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->a_wc)) / 1000, p); + else p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->x_wc)) / 1000, p); + p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->y_wc)) / 1000, p); + p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->z_wc)) / 1000, p); + if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->a_mc)) / 1000, p); + else p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->x_mc)) / 1000, p); + p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->y_mc)) / 1000, p); + p += xhc_encode_float(round(1000 * hal_get_real(xhc->hal->z_mc)) / 1000, p); + p += xhc_encode_s16(round(100.0 * hal_get_real(xhc->hal->feedrate_override)), p); + p += xhc_encode_s16(round(100.0 * hal_get_real(xhc->hal->spindle_override)), p); + p += xhc_encode_s16(round(60.0 * hal_get_real(xhc->hal->feedrate)), p); + p += xhc_encode_s16(round(60.0 * hal_get_real(xhc->hal->spindle_rps)), p); + + switch (hal_get_si32(xhc->hal->stepsize)) { case 0: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_0; break; case 1: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_1; break; case 5: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_5; break; @@ -249,7 +250,7 @@ void xhc_display_encode(xhc_t *xhc, unsigned char *data, int len) } buf[FLAGS_BYTE] = 0; - if (*(xhc->hal->inch_icon)) { + if (hal_get_bool(xhc->hal->inch_icon)) { buf[FLAGS_BYTE] |= 0x80; } @@ -299,46 +300,46 @@ void linuxcnc_simu(xhc_t *xhc) xhc_hal_t *hal = xhc->hal; // for simu, always step up - *(hal->stepsize_up) = (xhc->button_step && xhc->button_code == xhc->button_step); - - if (*(hal->jog_counts) != last_jog_counts) { - int delta_int = *(hal->jog_counts) - last_jog_counts; - float delta = delta_int * *(hal->jog_scale); - if (*(hal->jog_enable_x)) { - *(hal->x_mc) = *(hal->x_mc) + delta; - *(hal->x_wc) = *(hal->x_wc) + delta; + hal_set_bool(hal->stepsize_up, (xhc->button_step && xhc->button_code == xhc->button_step)); + + if (hal_get_si32(hal->jog_counts) != last_jog_counts) { + int delta_int = hal_get_si32(hal->jog_counts) - last_jog_counts; + float delta = delta_int * hal_get_real(hal->jog_scale); + if (hal_get_bool(hal->jog_enable_x)) { + hal_set_real(hal->x_mc, hal_get_real(hal->x_mc) + delta); + hal_set_real(hal->x_wc, hal_get_real(hal->x_wc) + delta); } - if (*(hal->jog_enable_y)) { - *(hal->y_mc) = *(hal->y_mc) + delta; - *(hal->y_wc) = *(hal->y_wc) + delta; + if (hal_get_bool(hal->jog_enable_y)) { + hal_set_real(hal->y_mc, hal_get_real(hal->y_mc) + delta); + hal_set_real(hal->y_wc, hal_get_real(hal->y_wc) + delta); } - if (*(hal->jog_enable_z)) { - *(hal->z_mc) = *(hal->z_mc) + delta; - *(hal->z_wc) = *(hal->z_wc) + delta; + if (hal_get_bool(hal->jog_enable_z)) { + hal_set_real(hal->z_mc, hal_get_real(hal->z_mc) + delta); + hal_set_real(hal->z_wc, hal_get_real(hal->z_wc) + delta); } - if (*(hal->jog_enable_a)) { - *(hal->a_mc) = *(hal->a_mc) + delta; - *(hal->a_wc) = *(hal->a_wc) + delta; + if (hal_get_bool(hal->jog_enable_a)) { + hal_set_real(hal->a_mc, hal_get_real(hal->a_mc) + delta); + hal_set_real(hal->a_wc, hal_get_real(hal->a_wc) + delta); } - if (*(hal->jog_enable_spindle)) { - *(hal->spindle_override) = *(hal->spindle_override) + delta_int * 0.01; - if (*(hal->spindle_override) > 1) *(hal->spindle_override) = 1; - if (*(hal->spindle_override) < 0) *(hal->spindle_override) = 0; - *(hal->spindle_rps) = 25000.0/60.0 * *(hal->spindle_override); + if (hal_get_bool(hal->jog_enable_spindle)) { + hal_set_real(hal->spindle_override, hal_get_real(hal->spindle_override) + delta_int * 0.01); + if (hal_get_real(hal->spindle_override) > 1) hal_set_real(hal->spindle_override, 1); + if (hal_get_real(hal->spindle_override) < 0) hal_set_real(hal->spindle_override, 0); + hal_set_real(hal->spindle_rps, 25000.0/60.0 * hal_get_real(hal->spindle_override)); } - if (*(hal->jog_enable_feedrate)) { - *(hal->feedrate_override) = *(hal->feedrate_override) + delta_int * 0.01; - if (*(hal->feedrate_override) > 1) *(hal->feedrate_override) = 1; - if (*(hal->feedrate_override) < 0) *(hal->feedrate_override) = 0; - *(hal->feedrate) = 3000.0/60.0 * *(hal->feedrate_override); + if (hal_get_bool(hal->jog_enable_feedrate)) { + hal_set_real(hal->feedrate_override, hal_get_real(hal->feedrate_override) + delta_int * 0.01); + if (hal_get_real(hal->feedrate_override) > 1) hal_set_real(hal->feedrate_override, 1); + if (hal_get_real(hal->feedrate_override) < 0) hal_set_real(hal->feedrate_override, 0); + hal_set_real(hal->feedrate, 3000.0/60.0 * hal_get_real(hal->feedrate_override)); } - last_jog_counts = *(hal->jog_counts); + last_jog_counts = hal_get_si32(hal->jog_counts); } } @@ -352,36 +353,36 @@ void compute_velocity(xhc_t *xhc) float elapsed = delta_tv.tv_sec + 1e-6f*delta_tv.tv_usec; if (elapsed <= 0) return; - float delta_pos = (*(xhc->hal->jog_counts) - xhc->last_jog_counts) * *(xhc->hal->jog_scale); - float velocity = *(xhc->hal->jog_max_velocity) * 60.0f * *(xhc->hal->jog_scale); + float delta_pos = (hal_get_si32(xhc->hal->jog_counts) - xhc->last_jog_counts) * hal_get_real(xhc->hal->jog_scale); + float velocity = hal_get_real(xhc->hal->jog_max_velocity) * 60.0f * hal_get_real(xhc->hal->jog_scale); float k = 0.05f; if (delta_pos) { - *(xhc->hal->jog_velocity) = (1 - k) * *(xhc->hal->jog_velocity) + k * velocity; - *(xhc->hal->jog_increment) = fabs(delta_pos); - *(xhc->hal->jog_plus_x) = (delta_pos > 0) && *(xhc->hal->jog_enable_x); - *(xhc->hal->jog_minus_x) = (delta_pos < 0) && *(xhc->hal->jog_enable_x); - *(xhc->hal->jog_plus_y) = (delta_pos > 0) && *(xhc->hal->jog_enable_y); - *(xhc->hal->jog_minus_y) = (delta_pos < 0) && *(xhc->hal->jog_enable_y); - *(xhc->hal->jog_plus_z) = (delta_pos > 0) && *(xhc->hal->jog_enable_z); - *(xhc->hal->jog_minus_z) = (delta_pos < 0) && *(xhc->hal->jog_enable_z); - *(xhc->hal->jog_plus_a) = (delta_pos > 0) && *(xhc->hal->jog_enable_a); - *(xhc->hal->jog_minus_a) = (delta_pos < 0) && *(xhc->hal->jog_enable_a); - xhc->last_jog_counts = *(xhc->hal->jog_counts); + hal_set_real(xhc->hal->jog_velocity, (1 - k) * hal_get_real(xhc->hal->jog_velocity) + k * velocity); + hal_set_real(xhc->hal->jog_increment, fabs(delta_pos)); + hal_set_bool(xhc->hal->jog_plus_x, (delta_pos > 0) && hal_get_bool(xhc->hal->jog_enable_x)); + hal_set_bool(xhc->hal->jog_minus_x, (delta_pos < 0) && hal_get_bool(xhc->hal->jog_enable_x)); + hal_set_bool(xhc->hal->jog_plus_y, (delta_pos > 0) && hal_get_bool(xhc->hal->jog_enable_y)); + hal_set_bool(xhc->hal->jog_minus_y, (delta_pos < 0) && hal_get_bool(xhc->hal->jog_enable_y)); + hal_set_bool(xhc->hal->jog_plus_z, (delta_pos > 0) && hal_get_bool(xhc->hal->jog_enable_z)); + hal_set_bool(xhc->hal->jog_minus_z, (delta_pos < 0) && hal_get_bool(xhc->hal->jog_enable_z)); + hal_set_bool(xhc->hal->jog_plus_a, (delta_pos > 0) && hal_get_bool(xhc->hal->jog_enable_a)); + hal_set_bool(xhc->hal->jog_minus_a, (delta_pos < 0) && hal_get_bool(xhc->hal->jog_enable_a)); + xhc->last_jog_counts = hal_get_si32(xhc->hal->jog_counts); xhc->last_tv = now; } else { - *(xhc->hal->jog_velocity) = (1 - k) * *(xhc->hal->jog_velocity); + hal_set_real(xhc->hal->jog_velocity, (1 - k) * hal_get_real(xhc->hal->jog_velocity)); if (elapsed > 0.25) { - *(xhc->hal->jog_velocity) = 0; - *(xhc->hal->jog_plus_x) = 0; - *(xhc->hal->jog_minus_x) = 0; - *(xhc->hal->jog_plus_y) = 0; - *(xhc->hal->jog_minus_y) = 0; - *(xhc->hal->jog_plus_z) = 0; - *(xhc->hal->jog_minus_z) = 0; - *(xhc->hal->jog_plus_a) = 0; - *(xhc->hal->jog_minus_a) = 0; + hal_set_real(xhc->hal->jog_velocity, 0); + hal_set_bool(xhc->hal->jog_plus_x, 0); + hal_set_bool(xhc->hal->jog_minus_x, 0); + hal_set_bool(xhc->hal->jog_plus_y, 0); + hal_set_bool(xhc->hal->jog_minus_y, 0); + hal_set_bool(xhc->hal->jog_plus_z, 0); + hal_set_bool(xhc->hal->jog_minus_z, 0); + hal_set_bool(xhc->hal->jog_plus_a, 0); + hal_set_bool(xhc->hal->jog_minus_a, 0); } } } @@ -389,14 +390,14 @@ void compute_velocity(xhc_t *xhc) void handle_step(xhc_t *xhc) { int _inc_step_status = STEP_NONE; - int _stepsize = *(xhc->hal->stepsize); // Use a local variable to avoid STEP display as 0 on pendant during transitions + int _stepsize = hal_get_si32(xhc->hal->stepsize); // Use a local variable to avoid STEP display as 0 on pendant during transitions - if (*(xhc->hal->stepsize_up)) { + if (hal_get_bool(xhc->hal->stepsize_up)) { _inc_step_status = STEP_UP; - if (*(xhc->hal->stepsize_down)) { + if (hal_get_bool(xhc->hal->stepsize_down)) { _inc_step_status = STEP_NONE; // none if both pressed } - } else if (*(xhc->hal->stepsize_down)) { + } else if (hal_get_bool(xhc->hal->stepsize_down)) { _inc_step_status = STEP_DOWN; } else { _inc_step_status = STEP_NONE; @@ -418,14 +419,14 @@ void handle_step(xhc_t *xhc) xhc->old_inc_step_status = _inc_step_status; - *(xhc->hal->stepsize) = _stepsize; - *(xhc->hal->jog_scale) = *(xhc->hal->stepsize) * 0.001f; + hal_set_si32(xhc->hal->stepsize, _stepsize); + hal_set_real(xhc->hal->jog_scale, hal_get_si32(xhc->hal->stepsize) * 0.001f); } void cb_response_in(struct libusb_transfer *transfer) { int i; - if (!*(xhc.hal->connected)) return; + if (!hal_get_bool(xhc.hal->connected)) return; if (transfer->actual_length > 0) { if (simu_mode) hexdump(in_buf, transfer->actual_length); @@ -433,38 +434,38 @@ void cb_response_in(struct libusb_transfer *transfer) xhc.button_code = in_buf[1]; xhc.axis = (xhc_axis_t)in_buf[3]; - *(xhc.hal->jog_counts) = *(xhc.hal->jog_counts) + ((signed char)in_buf[4]); - *(xhc.hal->jog_counts_neg) = - *(xhc.hal->jog_counts); - *(xhc.hal->jog_enable_off) = (xhc.axis == axis_off); - *(xhc.hal->jog_enable_x) = (xhc.axis == axis_x); - *(xhc.hal->jog_enable_y) = (xhc.axis == axis_y); - *(xhc.hal->jog_enable_z) = (xhc.axis == axis_z); - *(xhc.hal->jog_enable_a) = (xhc.axis == axis_a); - *(xhc.hal->jog_enable_feedrate) = (xhc.axis == axis_feed); - *(xhc.hal->jog_enable_spindle) = (xhc.axis == axis_spindle); + hal_set_si32(xhc.hal->jog_counts, hal_get_si32(xhc.hal->jog_counts) + ((signed char)in_buf[4])); + hal_set_si32(xhc.hal->jog_counts_neg, - hal_get_si32(xhc.hal->jog_counts)); + hal_set_bool(xhc.hal->jog_enable_off, xhc.axis == axis_off); + hal_set_bool(xhc.hal->jog_enable_x, xhc.axis == axis_x); + hal_set_bool(xhc.hal->jog_enable_y, xhc.axis == axis_y); + hal_set_bool(xhc.hal->jog_enable_z, xhc.axis == axis_z); + hal_set_bool(xhc.hal->jog_enable_a, xhc.axis == axis_a); + hal_set_bool(xhc.hal->jog_enable_feedrate, xhc.axis == axis_feed); + hal_set_bool(xhc.hal->jog_enable_spindle, xhc.axis == axis_spindle); for (i=0; ibutton_pin[i]) continue; - *(xhc.hal->button_pin[i]) = (xhc.button_code == xhc.buttons[i].code); + hal_set_bool(xhc.hal->button_pin[i], xhc.button_code == xhc.buttons[i].code); if (strcmp("button-zero", xhc.buttons[i].pin_name) == 0) { - *(xhc.hal->zero_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); - *(xhc.hal->zero_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); - *(xhc.hal->zero_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); - *(xhc.hal->zero_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); + hal_set_bool(xhc.hal->zero_x, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x)); + hal_set_bool(xhc.hal->zero_y, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y)); + hal_set_bool(xhc.hal->zero_z, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z)); + hal_set_bool(xhc.hal->zero_a, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a)); } if (strcmp("button-goto-zero", xhc.buttons[i].pin_name) == 0) { - *(xhc.hal->gotozero_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); - *(xhc.hal->gotozero_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); - *(xhc.hal->gotozero_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); - *(xhc.hal->gotozero_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); + hal_set_bool(xhc.hal->gotozero_x, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x)); + hal_set_bool(xhc.hal->gotozero_y, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y)); + hal_set_bool(xhc.hal->gotozero_z, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z)); + hal_set_bool(xhc.hal->gotozero_a, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a)); } if (strcmp("button-half", xhc.buttons[i].pin_name) == 0) { - *(xhc.hal->half_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); - *(xhc.hal->half_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); - *(xhc.hal->half_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); - *(xhc.hal->half_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); + hal_set_bool(xhc.hal->half_x, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x)); + hal_set_bool(xhc.hal->half_y, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y)); + hal_set_bool(xhc.hal->half_z, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z)); + hal_set_bool(xhc.hal->half_a, (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a)); } - if (simu_mode && *(xhc.hal->button_pin[i])) { + if (simu_mode && hal_get_bool(xhc.hal->button_pin[i])) { printf("%s pressed", xhc.buttons[i].pin_name); } } @@ -480,7 +481,7 @@ void cb_response_in(struct libusb_transfer *transfer) && in_buf[3]==0 && in_buf[4]==0 && in_buf[5]==0) { - *(xhc.hal->sleeping) = 1; + hal_set_bool(xhc.hal->sleeping, 1); if (simu_mode) { struct timeval now; gettimeofday(&now, NULL); @@ -489,12 +490,12 @@ void cb_response_in(struct libusb_transfer *transfer) } } else { gettimeofday(&xhc.last_wakeup, NULL); - if (*(xhc.hal->sleeping)) { + if (hal_get_bool(xhc.hal->sleeping)) { if (simu_mode) { fprintf(stderr,"Wake\n"); } } - *(xhc.hal->sleeping) = 0; + hal_set_bool(xhc.hal->sleeping, 0); } } @@ -522,7 +523,7 @@ static int hal_pin_simu(char *pin_name, void **ptr, int s) return 0; } -int _hal_pin_float_newf(hal_pin_dir_t dir, hal_float_t ** data_ptr_addr, int comp_id, const char *fmt, ...) +int _hal_pin_float_newf(hal_pin_dir_t dir, hal_real_t *data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -531,14 +532,14 @@ int _hal_pin_float_newf(hal_pin_dir_t dir, hal_float_t ** data_ptr_addr, int com va_end(args); if (simu_mode) { - return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); + return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(hal_query_value_u)); } else { - return hal_pin_float_new(pin_name, dir, data_ptr_addr, comp_id); + return hal_pin_new_real(comp_id, dir, data_ptr_addr, 0.0, "%s", pin_name); } } -int _hal_pin_s32_newf(hal_pin_dir_t dir, hal_s32_t ** data_ptr_addr, int comp_id, const char *fmt, ...) +int _hal_pin_si32_newf(hal_pin_dir_t dir, hal_sint_t *data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -547,14 +548,14 @@ int _hal_pin_s32_newf(hal_pin_dir_t dir, hal_s32_t ** data_ptr_addr, int comp_id va_end(args); if (simu_mode) { - return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); + return hal_pin_simu(pin_name, (void**)data_ptr_addr, sizeof(hal_query_value_u)); } else { - return hal_pin_s32_new(pin_name, dir, data_ptr_addr, comp_id); + return hal_pin_new_si32(comp_id, dir, data_ptr_addr, 0, "%s", pin_name); } } -int _hal_pin_bit_newf(hal_pin_dir_t dir, hal_bit_t ** data_ptr_addr, int comp_id, const char *fmt, ...) +int _hal_pin_bit_newf(hal_pin_dir_t dir, hal_bool_t *data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -563,10 +564,10 @@ int _hal_pin_bit_newf(hal_pin_dir_t dir, hal_bit_t ** data_ptr_addr, int comp_id va_end(args); if (simu_mode) { - return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); + return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(hal_query_value_u)); } else { - return hal_pin_bit_new(pin_name, dir, data_ptr_addr, comp_id); + return hal_pin_new_bool(comp_id, dir, data_ptr_addr, 0, "%s", pin_name); } } @@ -636,7 +637,7 @@ static int hal_setup() r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->connected), hal_comp_id, "%s.connected", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->stepsize_up), hal_comp_id, "%s.stepsize-up", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->stepsize_down), hal_comp_id, "%s.stepsize-down", modname); - r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->stepsize), hal_comp_id, "%s.stepsize", modname); + r |= _hal_pin_si32_newf(HAL_OUT, &(xhc.hal->stepsize), hal_comp_id, "%s.stepsize", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->require_pendant), hal_comp_id, "%s.require_pendant", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->inch_icon), hal_comp_id, "%s.inch-icon", modname); @@ -649,8 +650,8 @@ static int hal_setup() r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_spindle), hal_comp_id, "%s.jog.enable-spindle-override", modname); r |= _hal_pin_float_newf(HAL_OUT, &(xhc.hal->jog_scale), hal_comp_id, "%s.jog.scale", modname); - r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->jog_counts), hal_comp_id, "%s.jog.counts", modname); - r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->jog_counts_neg), hal_comp_id, "%s.jog.counts-neg", modname); + r |= _hal_pin_si32_newf(HAL_OUT, &(xhc.hal->jog_counts), hal_comp_id, "%s.jog.counts", modname); + r |= _hal_pin_si32_newf(HAL_OUT, &(xhc.hal->jog_counts_neg), hal_comp_id, "%s.jog.counts-neg", modname); r |= _hal_pin_float_newf(HAL_OUT, &(xhc.hal->jog_velocity), hal_comp_id, "%s.jog.velocity", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->jog_max_velocity), hal_comp_id, "%s.jog.max-velocity", modname); @@ -805,10 +806,10 @@ int main (int argc,char **argv) // use environmental variable LIBUSB_DEBUG if needed printf("%s: waiting for XHC-HB04 device\n",modname); - *(xhc.hal->connected) = 0; + hal_set_bool(xhc.hal->connected, 0); wait_secs = 0; - *(xhc.hal->require_pendant) = wait_for_pendant_before_HAL; - *(xhc.hal->stepsize) = stepsize_sequence[0]; + hal_set_bool(xhc.hal->require_pendant, wait_for_pendant_before_HAL); + hal_set_si32(xhc.hal->stepsize, stepsize_sequence[0]); do { cnt = libusb_get_device_list(ctx, &devs); @@ -850,7 +851,7 @@ int main (int argc,char **argv) transfer_in = libusb_alloc_transfer(0); } - *(xhc.hal->connected) = 1; + hal_set_bool(xhc.hal->connected, 1); if (!hal_ready_done && !simu_mode) { hal_ready(hal_comp_id); @@ -873,9 +874,9 @@ int main (int argc,char **argv) handle_step(&xhc); xhc_set_display(dev_handle, &xhc); } - *(xhc.hal->connected) = 0; + hal_set_bool(xhc.hal->connected, 0); printf("%s: connection lost, cleaning up\n",modname); - if (*(xhc.hal->require_pendant)) { + if (hal_get_bool(xhc.hal->require_pendant)) { do_exit = 1; } libusb_cancel_transfer(transfer_in); // ignore result diff --git a/src/hal/user_comps/xhc-whb04b-6/hal.cc b/src/hal/user_comps/xhc-whb04b-6/hal.cc index 949057d12e1..985a86c7e4a 100644 --- a/src/hal/user_comps/xhc-whb04b-6/hal.cc +++ b/src/hal/user_comps/xhc-whb04b-6/hal.cc @@ -130,7 +130,7 @@ Hal::~Hal() freeSimulatedPin((void**)(&memory->in.isMachineOn)); - constexpr size_t pinsCount = sizeof(memory->out.button_pin) / sizeof(hal_bit_t * ); + constexpr size_t pinsCount = sizeof(memory->out.button_pin) / sizeof(hal_bool_t); for (size_t idx = 0; idx < pinsCount; idx++) { freeSimulatedPin((void**)(&memory->out.button_pin[idx])); @@ -223,13 +223,16 @@ Hal::~Hal() // ---------------------------------------------------------------------- int Hal::newSimulatedHalPin(char* /*pin_name*/, void** ptr, int s) { + if(s < (int)sizeof(hal_query_value_u)) + s = sizeof(hal_query_value_u); + *ptr = calloc(s, 1); assert(*ptr != nullptr); memset(*ptr, 0, s); return 0; } // ---------------------------------------------------------------------- -int Hal::newHalFloat(hal_pin_dir_t direction, hal_float_t** ptr, int componentId, const char* fmt, ...) +int Hal::newHalFloat(hal_pin_dir_t direction, hal_real_t *ptr, int componentId, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -255,17 +258,17 @@ int Hal::newHalFloat(hal_pin_dir_t direction, hal_float_t** ptr, int componentId if (mIsSimulationMode) { - return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_float_t)); + return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_query_value_u)); } else { - int r = hal_pin_float_new(pin_name, direction, ptr, componentId); + int r = hal_pin_new_real(componentId, direction, ptr, 0.0, "%s", pin_name); assert(r == 0); return r; } } // ---------------------------------------------------------------------- -int Hal::newHalSigned32(hal_pin_dir_t direction, hal_s32_t** ptr, int componentId, const char* fmt, ...) +int Hal::newHalSigned32(hal_pin_dir_t direction, hal_sint_t *ptr, int componentId, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -291,17 +294,17 @@ int Hal::newHalSigned32(hal_pin_dir_t direction, hal_s32_t** ptr, int componentI if (mIsSimulationMode) { - return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_s32_t)); + return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_query_value_u)); } else { - int r = hal_pin_s32_new(pin_name, direction, ptr, componentId); + int r = hal_pin_new_si32(componentId, direction, ptr, 0, "%s", pin_name); assert(r == 0); return r; } } // ---------------------------------------------------------------------- -int Hal::newHalUnsigned32(hal_pin_dir_t direction, hal_u32_t** ptr, int componentId, const char* fmt, ...) +int Hal::newHalUnsigned32(hal_pin_dir_t direction, hal_uint_t *ptr, int componentId, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -327,17 +330,17 @@ int Hal::newHalUnsigned32(hal_pin_dir_t direction, hal_u32_t** ptr, int componen if (mIsSimulationMode) { - return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_u32_t)); + return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_query_value_u)); } else { - int r = hal_pin_u32_new(pin_name, direction, ptr, componentId); + int r = hal_pin_new_ui32(componentId, direction, ptr, 0, "%s", pin_name); assert(r == 0); return r; } } // ---------------------------------------------------------------------- -int Hal::newHalBit(hal_pin_dir_t direction, hal_bit_t** ptr, int componentId, const char* fmt, ...) +int Hal::newHalBit(hal_pin_dir_t direction, hal_bool_t *ptr, int componentId, const char *fmt, ...) { char pin_name[256]; va_list args; @@ -363,11 +366,11 @@ int Hal::newHalBit(hal_pin_dir_t direction, hal_bit_t** ptr, int componentId, co if (mIsSimulationMode) { - return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_bit_t)); + return newSimulatedHalPin(pin_name, (void**)ptr, sizeof(hal_query_value_u)); } else { - int r = hal_pin_bit_new(pin_name, direction, ptr, componentId); + int r = hal_pin_new_bool(componentId, direction, ptr, 0, "%s", pin_name); assert(r == 0); return r; } @@ -575,58 +578,58 @@ void Hal::init(const MetaButtonCodes* metaButtons, const KeyCodes& keyCodes) mIsInitialized = true; } // ---------------------------------------------------------------------- -real_t Hal::getAxisXPosition(bool absolute) const +rtapi_real Hal::getAxisXPosition(bool absolute) const { if (absolute) { - return *memory->in.axisXPosition; + return hal_get_real(memory->in.axisXPosition); } - return *memory->in.axisXPositionRelative; + return hal_get_real(memory->in.axisXPositionRelative); } // ---------------------------------------------------------------------- -real_t Hal::getAxisYPosition(bool absolute) const +rtapi_real Hal::getAxisYPosition(bool absolute) const { if (absolute) { - return *memory->in.axisYPosition; + return hal_get_real(memory->in.axisYPosition); } - return *memory->in.axisYPositionRelative; + return hal_get_real(memory->in.axisYPositionRelative); } // ---------------------------------------------------------------------- -real_t Hal::getAxisZPosition(bool absolute) const +rtapi_real Hal::getAxisZPosition(bool absolute) const { if (absolute) { - return *memory->in.axisZPosition; + return hal_get_real(memory->in.axisZPosition); } - return *memory->in.axisZPositionRelative; + return hal_get_real(memory->in.axisZPositionRelative); } // ---------------------------------------------------------------------- -real_t Hal::getAxisAPosition(bool absolute) const +rtapi_real Hal::getAxisAPosition(bool absolute) const { if (absolute) { - return *memory->in.axisAPosition; + return hal_get_real(memory->in.axisAPosition); } - return *memory->in.axisAPositionRelative; + return hal_get_real(memory->in.axisAPositionRelative); } // ---------------------------------------------------------------------- -real_t Hal::getAxisBPosition(bool absolute) const +rtapi_real Hal::getAxisBPosition(bool absolute) const { if (absolute) { - return *memory->in.axisBPosition; + return hal_get_real(memory->in.axisBPosition); } - return *memory->in.axisBPositionRelative; + return hal_get_real(memory->in.axisBPositionRelative); } // ---------------------------------------------------------------------- -real_t Hal::getAxisCPosition(bool absolute) const +rtapi_real Hal::getAxisCPosition(bool absolute) const { if (absolute) { - return *memory->in.axisCPosition; + return hal_get_real(memory->in.axisCPosition); } - return *memory->in.axisCPositionRelative; + return hal_get_real(memory->in.axisCPositionRelative); } // ---------------------------------------------------------------------- void Hal::enableVerbose(bool enable) @@ -648,54 +651,54 @@ void Hal::setNoAxisActive(bool /*enabled*/) // ---------------------------------------------------------------------- void Hal::setAxisXActive(bool enabled) { - *memory->out.axisXSelect = enabled; - *memory->out.axisXJogEnable = enabled; + hal_set_bool(memory->out.axisXSelect, enabled); + hal_set_bool(memory->out.axisXJogEnable, enabled); *mHalCout << "hal X axis active" << endl; } // ---------------------------------------------------------------------- void Hal::setAxisYActive(bool enabled) { - *memory->out.axisYSelect = enabled; - *memory->out.axisYJogEnable = enabled; + hal_set_bool(memory->out.axisYSelect, enabled); + hal_set_bool(memory->out.axisYJogEnable, enabled); *mHalCout << "hal Y axis active" << endl; } // ---------------------------------------------------------------------- void Hal::setAxisZActive(bool enabled) { - *memory->out.axisZSelect = enabled; - *memory->out.axisZJogEnable = enabled; + hal_set_bool(memory->out.axisZSelect, enabled); + hal_set_bool(memory->out.axisZJogEnable, enabled); *mHalCout << "hal Z axis active" << endl; } // ---------------------------------------------------------------------- void Hal::setAxisAActive(bool enabled) { - *memory->out.axisASelect = enabled; - *memory->out.axisAJogEnable = enabled; + hal_set_bool(memory->out.axisASelect, enabled); + hal_set_bool(memory->out.axisAJogEnable, enabled); *mHalCout << "hal A axis active" << endl; } // ---------------------------------------------------------------------- void Hal::setAxisBActive(bool enabled) { - *memory->out.axisBSelect = enabled; - *memory->out.axisBJogEnable = enabled; + hal_set_bool(memory->out.axisBSelect, enabled); + hal_set_bool(memory->out.axisBJogEnable, enabled); *mHalCout << "hal B axis active" << endl; } // ---------------------------------------------------------------------- void Hal::setAxisCActive(bool enabled) { - *memory->out.axisCSelect = enabled; - *memory->out.axisCJogEnable = enabled; + hal_set_bool(memory->out.axisCSelect, enabled); + hal_set_bool(memory->out.axisCJogEnable, enabled); *mHalCout << "hal C axis active" << endl; } // ---------------------------------------------------------------------- -void Hal::setStepSize(const real_t stepSize) +void Hal::setStepSize(const rtapi_real stepSize) { - *memory->out.axisXJogScale = stepSize; - *memory->out.axisYJogScale = stepSize; - *memory->out.axisZJogScale = stepSize; - *memory->out.axisAJogScale = stepSize; - *memory->out.axisBJogScale = stepSize; - *memory->out.axisCJogScale = stepSize; + hal_set_real(memory->out.axisXJogScale, stepSize); + hal_set_real(memory->out.axisYJogScale, stepSize); + hal_set_real(memory->out.axisZJogScale, stepSize); + hal_set_real(memory->out.axisAJogScale, stepSize); + hal_set_real(memory->out.axisBJogScale, stepSize); + hal_set_real(memory->out.axisCJogScale, stepSize); *mHalCout << "hal step size " << stepSize << endl; } // ---------------------------------------------------------------------- @@ -709,20 +712,20 @@ void Hal::setLead() // ---------------------------------------------------------------------- void Hal::setReset(bool enabled) { - if (*memory->in.isMachineOn) + if (hal_get_bool(memory->in.isMachineOn)) { // disable machine clearStartResumeProgramStates(); - *memory->out.doMachineOff = true; + hal_set_bool(memory->out.doMachineOff, true); } else { // enable machine - *memory->out.doMachineOn = true; + hal_set_bool(memory->out.doMachineOn, true); } if (!enabled) { - *memory->out.doMachineOff = false; - *memory->out.doMachineOn = false; + hal_set_bool(memory->out.doMachineOff, false); + hal_set_bool(memory->out.doMachineOn, false); } setPin(enabled, KeyCodes::Buttons.reset.text); } @@ -730,7 +733,7 @@ void Hal::setReset(bool enabled) void Hal::setStop(bool enabled) { clearStartResumeProgramStates(); - *memory->out.doStopProgram = enabled; + hal_set_bool(memory->out.doStopProgram, enabled); setPin(enabled, KeyCodes::Buttons.stop.text); } // ---------------------------------------------------------------------- @@ -753,47 +756,47 @@ void Hal::setStart(bool enabled) // ---------------------------------------------------------------------- bool Hal::getIsMachineOn() const { - return *memory->in.isMachineOn; + return hal_get_bool(memory->in.isMachineOn); } // ---------------------------------------------------------------------- void Hal::setIsPendantSleeping(bool isSleeping) { - *memory->out.isPendantSleeping = isSleeping; + hal_set_bool(memory->out.isPendantSleeping, isSleeping); } // ---------------------------------------------------------------------- bool Hal::getIsPendantSleeping() const { - return *memory->out.isPendantSleeping; + return hal_get_bool(memory->out.isPendantSleeping); } // ---------------------------------------------------------------------- void Hal::setIsPendantConnected(bool isSleeping) { - *memory->out.isPendantConnected = isSleeping; + hal_set_bool(memory->out.isPendantConnected, isSleeping); } // ---------------------------------------------------------------------- bool Hal::getIsPendantConnected() const { - return *memory->out.isPendantConnected; + return hal_get_bool(memory->out.isPendantConnected); } // ---------------------------------------------------------------------- void Hal::clearStartResumeProgramStates() { - *memory->out.doModeTeleop = false; - *memory->out.doModeJoint = false; - *memory->out.doModeAuto = false; - *memory->out.doPauseProgram = false; - *memory->out.doRunProgram = false; - *memory->out.doResumeProgram = false; + hal_set_bool(memory->out.doModeTeleop, false); + hal_set_bool(memory->out.doModeJoint, false); + hal_set_bool(memory->out.doModeAuto, false); + hal_set_bool(memory->out.doPauseProgram, false); + hal_set_bool(memory->out.doRunProgram, false); + hal_set_bool(memory->out.doResumeProgram, false); } -void Hal::checkState(bool state, hal_bit_t *pin) +void Hal::checkState(bool state, hal_bool_t pin) { // 500 milliseconds timeout unsigned int timeouts=500; unsigned int timeoutMs=1; do { - if (state == *pin) + if (state == hal_get_bool(pin)) { usleep(timeoutMs * 1000); } @@ -801,129 +804,129 @@ void Hal::checkState(bool state, hal_bit_t *pin) { break; } - } while ((state == *pin) && (--timeouts) > 0); + } while ((state == hal_get_bool(pin)) && (--timeouts) > 0); } // ---------------------------------------------------------------------- void Hal::toggleStartResumeProgram() { - if (*memory->in.isProgramPaused) + if (hal_get_bool(memory->in.isProgramPaused)) { - *memory->out.doPauseProgram = false; - *memory->out.doRunProgram = false; - *memory->out.doResumeProgram = true; + hal_set_bool(memory->out.doPauseProgram, false); + hal_set_bool(memory->out.doRunProgram, false); + hal_set_bool(memory->out.doResumeProgram, true); checkState(true, memory->in.isProgramPaused); - *memory->out.doResumeProgram = false; - } else if (*memory->in.isProgramRunning) + hal_set_bool(memory->out.doResumeProgram, false); + } else if (hal_get_bool(memory->in.isProgramRunning)) { - *memory->out.doPauseProgram = true; + hal_set_bool(memory->out.doPauseProgram, true); checkState(false, memory->in.isProgramPaused); - *memory->out.doPauseProgram = false; - *memory->out.doRunProgram = false; - *memory->out.doResumeProgram = false; - } else if (*memory->in.isProgramIdle) + hal_set_bool(memory->out.doPauseProgram, false); + hal_set_bool(memory->out.doRunProgram, false); + hal_set_bool(memory->out.doResumeProgram, false); + } else if (hal_get_bool(memory->in.isProgramIdle)) { - *memory->out.doPauseProgram = false; - *memory->out.doRunProgram = true; + hal_set_bool(memory->out.doPauseProgram, false); + hal_set_bool(memory->out.doRunProgram, true); checkState(false, memory->in.isProgramRunning); - *memory->out.doRunProgram = false; - *memory->out.doResumeProgram = false; + hal_set_bool(memory->out.doRunProgram, false); + hal_set_bool(memory->out.doResumeProgram, false); } } // ---------------------------------------------------------------------- void Hal::setFeedPlus(bool enabled) { - *memory->out.feedOverrideScale = 0.05; - *memory->out.feedOverrideIncrease = enabled; + hal_set_real(memory->out.feedOverrideScale, 0.05); + hal_set_bool(memory->out.feedOverrideIncrease, enabled); setPin(enabled, KeyCodes::Buttons.feed_plus.text); } // ---------------------------------------------------------------------- void Hal::setFeedMinus(bool enabled) { - *memory->out.feedOverrideScale = 0.05; - *memory->out.feedOverrideDecrease = enabled; + hal_set_real(memory->out.feedOverrideScale, 0.05); + hal_set_bool(memory->out.feedOverrideDecrease, enabled); setPin(enabled, KeyCodes::Buttons.feed_minus.text); } // ---------------------------------------------------------------------- -real_t Hal::getspindleSpeedCmd() const +rtapi_real Hal::getspindleSpeedCmd() const { - return *memory->in.spindleSpeedCmd; + return hal_get_real(memory->in.spindleSpeedCmd); } // ---------------------------------------------------------------------- -real_t Hal::getspindleSpeedChangeIncrease() const +rtapi_real Hal::getspindleSpeedChangeIncrease() const { - return *memory->out.spindleDoIncrease; + return hal_get_bool(memory->out.spindleDoIncrease); } // ---------------------------------------------------------------------- -real_t Hal::getspindleSpeedChangeDecrease() const +rtapi_real Hal::getspindleSpeedChangeDecrease() const { - return *memory->out.spindleDoDecrease; + return hal_get_bool(memory->out.spindleDoDecrease); } // ---------------------------------------------------------------------- -real_t Hal::getSpindleOverrideValue() const +rtapi_real Hal::getSpindleOverrideValue() const { - return *memory->in.spindleOverrideValue; + return hal_get_real(memory->in.spindleOverrideValue); } // ---------------------------------------------------------------------- -real_t Hal::getFeedOverrideMaxVel() const +rtapi_real Hal::getFeedOverrideMaxVel() const { - return *memory->in.feedOverrideMaxVel; + return hal_get_real(memory->in.feedOverrideMaxVel); } // ---------------------------------------------------------------------- -real_t Hal::getFeedOverrideValue() const +rtapi_real Hal::getFeedOverrideValue() const { - return *memory->in.feedOverrideValue; + return hal_get_real(memory->in.feedOverrideValue); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected2(bool selected) { - *memory->out.feedValueSelected_2 = selected; + hal_set_bool(memory->out.feedValueSelected_2, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected5(bool selected) { - *memory->out.feedValueSelected_5 = selected; + hal_set_bool(memory->out.feedValueSelected_5, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected10(bool selected) { - *memory->out.feedValueSelected_10 = selected; + hal_set_bool(memory->out.feedValueSelected_10, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected30(bool selected) { - *memory->out.feedValueSelected_30 = selected; + hal_set_bool(memory->out.feedValueSelected_30, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected60(bool selected) { - *memory->out.feedValueSelected_60 = selected; + hal_set_bool(memory->out.feedValueSelected_60, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelected100(bool selected) { - *memory->out.feedValueSelected_100 = selected; + hal_set_bool(memory->out.feedValueSelected_100, selected); } // ---------------------------------------------------------------------- void Hal::setFeedValueSelectedLead(bool selected) { - *memory->out.feedValueSelected_lead = selected; + hal_set_bool(memory->out.feedValueSelected_lead, selected); } // ---------------------------------------------------------------------- -void Hal::setFeedOverrideScale(real_t scale) +void Hal::setFeedOverrideScale(rtapi_real scale) { - *memory->out.feedOverrideScale = scale; + hal_set_real(memory->out.feedOverrideScale, scale); } // ---------------------------------------------------------------------- void Hal::setSpindleOverridePlus(bool enabled) { if (enabled) { - *memory->out.spindleOverrideScale = 0.05; - *memory->out.spindleOverrideDoIncrease = true; + hal_set_real(memory->out.spindleOverrideScale, 0.05); + hal_set_bool(memory->out.spindleOverrideDoIncrease, true); } else { - *memory->out.spindleOverrideDoIncrease = false; + hal_set_bool(memory->out.spindleOverrideDoIncrease, false); } setPin(enabled, KeyCodes::Buttons.spindle_plus.text); } @@ -932,12 +935,12 @@ void Hal::setSpindleOverrideMinus(bool enabled) { if (enabled) { - *memory->out.spindleOverrideScale = 0.05; - *memory->out.spindleOverrideDoDecrease = true; + hal_set_real(memory->out.spindleOverrideScale, 0.05); + hal_set_bool(memory->out.spindleOverrideDoDecrease, true); } else { - *memory->out.spindleOverrideDoDecrease = false; + hal_set_bool(memory->out.spindleOverrideDoDecrease, false); } setPin(enabled, KeyCodes::Buttons.spindle_minus.text); } @@ -1008,26 +1011,26 @@ void Hal::toggleSpindleDirection(bool enabled) } // on running spindle update direction immediately - if (*memory->in.spindleIsOn) + if (hal_get_bool(memory->in.spindleIsOn)) { if (enabled) { if (mIsSpindleDirectionForward) { - *memory->out.spindleDoRunForward = true; - *memory->out.spindleDoIncrease = true; + hal_set_bool(memory->out.spindleDoRunForward, true); + hal_set_bool(memory->out.spindleDoIncrease, true); } else { - *memory->out.spindleDoRunReverse = true; - *memory->out.spindleDoIncrease = true; + hal_set_bool(memory->out.spindleDoRunReverse, true); + hal_set_bool(memory->out.spindleDoIncrease, true); } } else { - *memory->out.spindleDoRunForward = false; - *memory->out.spindleDoRunReverse = false; - *memory->out.spindleDoIncrease = false; + hal_set_bool(memory->out.spindleDoRunForward, false); + hal_set_bool(memory->out.spindleDoRunReverse, false); + hal_set_bool(memory->out.spindleDoIncrease, false); } } } @@ -1036,25 +1039,25 @@ void Hal::toggleSpindleOnOff(bool enabled) { if (enabled) { - if (*memory->in.spindleIsOn) + if (hal_get_bool(memory->in.spindleIsOn)) { // on spindle stop - *memory->out.spindleStop = true; + hal_set_bool(memory->out.spindleStop, true); } else { // on spindle start if (mIsSpindleDirectionForward) { - *memory->out.spindleDoRunForward = true; - *memory->out.spindleDoIncrease = true; - *memory->out.spindleStart = true; + hal_set_bool(memory->out.spindleDoRunForward, true); + hal_set_bool(memory->out.spindleDoIncrease, true); + hal_set_bool(memory->out.spindleStart, true); } else { - *memory->out.spindleDoRunReverse = true; - *memory->out.spindleDoIncrease = true; - *memory->out.spindleStart = true; + hal_set_bool(memory->out.spindleDoRunReverse, true); + hal_set_bool(memory->out.spindleDoIncrease, true); + hal_set_bool(memory->out.spindleStart, true); } } @@ -1062,11 +1065,11 @@ void Hal::toggleSpindleOnOff(bool enabled) else { // on button released - *memory->out.spindleStop = false; - *memory->out.spindleDoRunForward = false; - *memory->out.spindleDoRunReverse = false; - *memory->out.spindleDoIncrease = false; - *memory->out.spindleStart = false; + hal_set_bool(memory->out.spindleStop, false); + hal_set_bool(memory->out.spindleDoRunForward, false); + hal_set_bool(memory->out.spindleDoRunReverse, false); + hal_set_bool(memory->out.spindleDoIncrease, false); + hal_set_bool(memory->out.spindleStart, false); } setPin(enabled, KeyCodes::Buttons.spindle_on_off.text); } @@ -1075,22 +1078,22 @@ void Hal::toggleFloodOnOff(bool enabled) { if (enabled) { - if (*memory->in.floodIsOn) + if (hal_get_bool(memory->in.floodIsOn)) { // on flood stop - *memory->out.floodStop = true; + hal_set_bool(memory->out.floodStop, true); } else { // on flood start - *memory->out.floodStart = true; + hal_set_bool(memory->out.floodStart, true); } } else { // on button released - *memory->out.floodStop = false; - *memory->out.floodStart = false; + hal_set_bool(memory->out.floodStop, false); + hal_set_bool(memory->out.floodStart, false); } } // ---------------------------------------------------------------------- @@ -1098,22 +1101,22 @@ void Hal::toggleMistOnOff(bool enabled) { if (enabled) { - if (*memory->in.mistIsOn) + if (hal_get_bool(memory->in.mistIsOn)) { // on mist stop - *memory->out.mistStop = true; + hal_set_bool(memory->out.mistStop, true); } else { // on mist start - *memory->out.mistStart = true; + hal_set_bool(memory->out.mistStart, true); } } else { // on button released - *memory->out.mistStop = false; - *memory->out.mistStart = false; + hal_set_bool(memory->out.mistStop, false); + hal_set_bool(memory->out.mistStart, false); } } // ---------------------------------------------------------------------- @@ -1140,16 +1143,16 @@ void Hal::setConMode(bool enabled) { if (enabled) { - *memory->out.axisXSetVelocityMode = true; - *memory->out.axisYSetVelocityMode = true; - *memory->out.axisZSetVelocityMode = true; - *memory->out.axisASetVelocityMode = true; - *memory->out.axisBSetVelocityMode = true; - *memory->out.axisCSetVelocityMode = true; + hal_set_bool(memory->out.axisXSetVelocityMode, true); + hal_set_bool(memory->out.axisYSetVelocityMode, true); + hal_set_bool(memory->out.axisZSetVelocityMode, true); + hal_set_bool(memory->out.axisASetVelocityMode, true); + hal_set_bool(memory->out.axisBSetVelocityMode, true); + hal_set_bool(memory->out.axisCSetVelocityMode, true); *mHalCout << "hal step mode is con" << endl; - *memory->out.feedValueSelected_mpg_feed = false; - *memory->out.feedValueSelected_continuous = true; - *memory->out.feedValueSelected_step = false; + hal_set_bool(memory->out.feedValueSelected_mpg_feed, false); + hal_set_bool(memory->out.feedValueSelected_continuous, true); + hal_set_bool(memory->out.feedValueSelected_step, false); } setPin(enabled, KeyCodes::Buttons.continuous.text); } @@ -1158,16 +1161,16 @@ void Hal::setStepMode(bool enabled) { if (enabled) { - *memory->out.axisXSetVelocityMode = false; - *memory->out.axisYSetVelocityMode = false; - *memory->out.axisZSetVelocityMode = false; - *memory->out.axisASetVelocityMode = false; - *memory->out.axisBSetVelocityMode = false; - *memory->out.axisCSetVelocityMode = false; + hal_set_bool(memory->out.axisXSetVelocityMode, false); + hal_set_bool(memory->out.axisYSetVelocityMode, false); + hal_set_bool(memory->out.axisZSetVelocityMode, false); + hal_set_bool(memory->out.axisASetVelocityMode, false); + hal_set_bool(memory->out.axisBSetVelocityMode, false); + hal_set_bool(memory->out.axisCSetVelocityMode, false); *mHalCout << "hal step mode is step" << endl; - *memory->out.feedValueSelected_mpg_feed = false; - *memory->out.feedValueSelected_continuous = false; - *memory->out.feedValueSelected_step = true; + hal_set_bool(memory->out.feedValueSelected_mpg_feed, false); + hal_set_bool(memory->out.feedValueSelected_continuous, false); + hal_set_bool(memory->out.feedValueSelected_step, true); } setPin(enabled, KeyCodes::Buttons.step.text); } @@ -1176,16 +1179,16 @@ void Hal::setMpgMode(bool enabled) { if (enabled) { - *memory->out.axisXSetVelocityMode = false; - *memory->out.axisYSetVelocityMode = false; - *memory->out.axisZSetVelocityMode = false; - *memory->out.axisASetVelocityMode = false; - *memory->out.axisBSetVelocityMode = false; - *memory->out.axisCSetVelocityMode = false; + hal_set_bool(memory->out.axisXSetVelocityMode, false); + hal_set_bool(memory->out.axisYSetVelocityMode, false); + hal_set_bool(memory->out.axisZSetVelocityMode, false); + hal_set_bool(memory->out.axisASetVelocityMode, false); + hal_set_bool(memory->out.axisBSetVelocityMode, false); + hal_set_bool(memory->out.axisCSetVelocityMode, false); *mHalCout << "hal step mode is mpg" << endl; - *memory->out.feedValueSelected_mpg_feed = true; - *memory->out.feedValueSelected_continuous = false; - *memory->out.feedValueSelected_step = false; + hal_set_bool(memory->out.feedValueSelected_mpg_feed, true); + hal_set_bool(memory->out.feedValueSelected_continuous, false); + hal_set_bool(memory->out.feedValueSelected_step, false); } } // ---------------------------------------------------------------------- @@ -1203,14 +1206,14 @@ void Hal::setMacro3(bool enabled) { if (enabled) { - if (*memory->in.spindleIsOn) + if (hal_get_bool(memory->in.spindleIsOn)) { - *memory->out.spindleDoIncrease = true; + hal_set_bool(memory->out.spindleDoIncrease, true); } } else { - *memory->out.spindleDoIncrease = false; + hal_set_bool(memory->out.spindleDoIncrease, false); } setPin(enabled, KeyCodes::Buttons.spindle_plus.altText); } @@ -1219,14 +1222,14 @@ void Hal::setMacro4(bool enabled) { if (enabled) { - if (*memory->in.spindleIsOn) + if (hal_get_bool(memory->in.spindleIsOn)) { - *memory->out.spindleDoDecrease = true; + hal_set_bool(memory->out.spindleDoDecrease, true); } } else { - *memory->out.spindleDoDecrease = false; + hal_set_bool(memory->out.spindleDoDecrease, false); } setPin(enabled, KeyCodes::Buttons.spindle_minus.altText); } @@ -1295,7 +1298,7 @@ void Hal::setPin(bool enabled, size_t pinNumber, const char* pinName) { *mHalCout << "hal " << pinName << ((enabled) ? " enabled" : " disabled") << " (pin # " << pinNumber << ")" << endl; - *(memory->out.button_pin[pinNumber]) = enabled; + hal_set_bool((memory->out.button_pin[pinNumber]), enabled); } // ---------------------------------------------------------------------- void Hal::setPin(bool enabled, const char* pinName) @@ -1310,20 +1313,20 @@ void Hal::setJogCounts(const HandWheelCounters& counters) { // If axis is not homed we need to ask Teleop mode but we need to bypass that if machine is homed // https://forum.linuxcnc.org/49-basic-configuration/40581-how-to-configure-a-xhc-whb04b-pendant - if (*memory->out.axisXSelect && false == *memory->in.JointXisHomed) {requestTeleopMode(true);} - else if (*memory->out.axisYSelect && false == *memory->in.JointYisHomed) {requestTeleopMode(true);} - else if (*memory->out.axisZSelect && false == *memory->in.JointZisHomed) {requestTeleopMode(true);} - else if (*memory->out.axisASelect && false == *memory->in.JointAisHomed) {requestTeleopMode(true);} - else if (*memory->out.axisBSelect && false == *memory->in.JointBisHomed) {requestTeleopMode(true);} - else if (*memory->out.axisCSelect && false == *memory->in.JointCisHomed) {requestTeleopMode(true);} + if (hal_get_bool(memory->out.axisXSelect) && !hal_get_bool(memory->in.JointXisHomed)) {requestTeleopMode(true);} + else if (hal_get_bool(memory->out.axisYSelect) && !hal_get_bool(memory->in.JointYisHomed)) {requestTeleopMode(true);} + else if (hal_get_bool(memory->out.axisZSelect) && !hal_get_bool(memory->in.JointZisHomed)) {requestTeleopMode(true);} + else if (hal_get_bool(memory->out.axisASelect) && !hal_get_bool(memory->in.JointAisHomed)) {requestTeleopMode(true);} + else if (hal_get_bool(memory->out.axisBSelect) && !hal_get_bool(memory->in.JointBisHomed)) {requestTeleopMode(true);} + else if (hal_get_bool(memory->out.axisCSelect) && !hal_get_bool(memory->in.JointCisHomed)) {requestTeleopMode(true);} {requestManualMode(true);} - *memory->out.axisXJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_X); - *memory->out.axisYJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_Y); - *memory->out.axisZJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_Z); - *memory->out.axisAJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_A); - *memory->out.axisBJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_B); - *memory->out.axisCJogCounts = counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_C); + hal_set_si32(memory->out.axisXJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_X)); + hal_set_si32(memory->out.axisYJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_Y)); + hal_set_si32(memory->out.axisZJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_Z)); + hal_set_si32(memory->out.axisAJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_A)); + hal_set_si32(memory->out.axisBJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_B)); + hal_set_si32(memory->out.axisCJogCounts, counters.counts(HandWheelCounters::CounterNameToIndex::AXIS_C)); requestManualMode(false); requestTeleopMode(false); @@ -1341,7 +1344,7 @@ bool Hal::requestAutoMode(bool isRisingEdge) // ---------------------------------------------------------------------- bool Hal::requestManualMode(bool isRisingEdge) { - if(isRisingEdge && !*memory->in.isProgramIdle) + if(isRisingEdge && !hal_get_bool(memory->in.isProgramIdle)) { //Don't try to change to manual when not idle //When a program is running, this will fail @@ -1366,34 +1369,34 @@ bool Hal::requestJointMode(bool isRisingEdge) return requestMode(isRisingEdge, memory->out.doModeJoint, memory->in.isModeJoint); } // ---------------------------------------------------------------------- -bool Hal::requestMode(bool isRisingEdge, hal_bit_t *requestPin, hal_bit_t * modeFeedbackPin) +bool Hal::requestMode(bool isRisingEdge, hal_bool_t requestPin, hal_bool_t modeFeedbackPin) { if (isRisingEdge) { bool rv; - if (true == *modeFeedbackPin) + if (hal_get_bool(modeFeedbackPin)) { // shortcut for mode request which is already active return true; } // request mode - *requestPin = true; + hal_set_bool(requestPin, true); usleep(mHalRequestProfile.mode.holdMs * 1000); rv = waitForRequestedMode(modeFeedbackPin); - *requestPin = false; + hal_set_bool(requestPin, false); usleep(mHalRequestProfile.mode.spaceMs * 1000); return rv; } else { // on button released always clear request - *requestPin = false; + hal_set_bool(requestPin, false); return false; } return false; } // ---------------------------------------------------------------------- -bool Hal::waitForRequestedMode(volatile hal_bit_t * condition) +bool Hal::waitForRequestedMode(hal_bool_t condition) { if(mIsSimulationMode) { @@ -1405,7 +1408,7 @@ bool Hal::waitForRequestedMode(volatile hal_bit_t * condition) do { - if (false == *condition) + if (!hal_get_bool(condition)) { usleep(timeoutMs * 1000); } @@ -1413,8 +1416,8 @@ bool Hal::waitForRequestedMode(volatile hal_bit_t * condition) { return true; } - } while ((false == *condition) && (--timeouts) > 0); - if (false == *condition) + } while (!hal_get_bool(condition) && (--timeouts) > 0); + if (!hal_get_bool(condition)) { auto delay = (maxTimeouts - timeouts) * timeoutMs; std::cerr << "hal failed to wait for requested mode. waited " << delay << "ms\n"; @@ -1429,53 +1432,53 @@ bool Hal::waitForRequestedMode(volatile hal_bit_t * condition) // ---------------------------------------------------------------------- void Hal::toggleSpindleOverrideIncrease() { - if (*memory->out.spindleOverrideDoIncrease) + if (hal_get_bool(memory->out.spindleOverrideDoIncrease)) { - *memory->out.spindleOverrideDoIncrease = false; + hal_set_bool(memory->out.spindleOverrideDoIncrease, false); } else { - *memory->out.spindleOverrideScale = 0.01; - *memory->out.spindleOverrideDoIncrease = true; + hal_set_real(memory->out.spindleOverrideScale, 0.01); + hal_set_bool(memory->out.spindleOverrideDoIncrease, true); } } // ---------------------------------------------------------------------- void Hal::toggleSpindleOverrideDecrease() { - if (*memory->out.spindleOverrideDoDecrease) + if (hal_get_bool(memory->out.spindleOverrideDoDecrease)) { - *memory->out.spindleOverrideDoDecrease = false; + hal_set_bool(memory->out.spindleOverrideDoDecrease, false); } else { - *memory->out.spindleOverrideScale = 0.01; - *memory->out.spindleOverrideDoDecrease = true; + hal_set_real(memory->out.spindleOverrideScale, 0.01); + hal_set_bool(memory->out.spindleOverrideDoDecrease, true); } } // ---------------------------------------------------------------------- void Hal::toggleFeedrateIncrease() { - if (*memory->out.feedOverrideIncrease) + if (hal_get_bool(memory->out.feedOverrideIncrease)) { - *memory->out.feedOverrideIncrease = false; + hal_set_bool(memory->out.feedOverrideIncrease, false); } else { - *memory->out.feedOverrideScale = 0.01; - *memory->out.feedOverrideIncrease = true; + hal_set_real(memory->out.feedOverrideScale, 0.01); + hal_set_bool(memory->out.feedOverrideIncrease, true); } } // ---------------------------------------------------------------------- void Hal::toggleFeedrateDecrease() { - if (*memory->out.feedOverrideDecrease) + if (hal_get_bool(memory->out.feedOverrideDecrease)) { - *memory->out.feedOverrideDecrease = false; + hal_set_bool(memory->out.feedOverrideDecrease, false); } else { - *memory->out.feedOverrideScale = 0.01; - *memory->out.feedOverrideDecrease = true; + hal_set_real(memory->out.feedOverrideScale, 0.01); + hal_set_bool(memory->out.feedOverrideDecrease, true); } } } diff --git a/src/hal/user_comps/xhc-whb04b-6/hal.h b/src/hal/user_comps/xhc-whb04b-6/hal.h index 32be462b307..352d9a33508 100644 --- a/src/hal/user_comps/xhc-whb04b-6/hal.h +++ b/src/hal/user_comps/xhc-whb04b-6/hal.h @@ -96,82 +96,82 @@ class HalMemory public: //! to be connected to \ref halui.flood.is-on - hal_bit_t * floodIsOn{nullptr}; + hal_bool_t floodIsOn{nullptr}; //! to be connected to \ref halui.mist.is-on - hal_bit_t * mistIsOn{nullptr}; + hal_bool_t mistIsOn{nullptr}; //! to be connected to \ref halui.axis.x.pos-feedback - hal_float_t* axisXPosition{nullptr}; + hal_real_t axisXPosition{nullptr}; //! to be connected to \ref halui.axis.y.pos-feedback - hal_float_t* axisYPosition{nullptr}; + hal_real_t axisYPosition{nullptr}; //! to be connected to \ref halui.axis.z.pos-feedback - hal_float_t* axisZPosition{nullptr}; + hal_real_t axisZPosition{nullptr}; //! to be connected to \ref halui.axis.a.pos-feedback - hal_float_t* axisAPosition{nullptr}; + hal_real_t axisAPosition{nullptr}; //! to be connected to \ref halui.axis.b.pos-feedback - hal_float_t* axisBPosition{nullptr}; + hal_real_t axisBPosition{nullptr}; //! to be connected to \ref halui.axis.c.pos-feedback - hal_float_t* axisCPosition{nullptr}; + hal_real_t axisCPosition{nullptr}; //! to be connected to \ref halui.axis.x.pos-relative - hal_float_t* axisXPositionRelative{nullptr}; + hal_real_t axisXPositionRelative{nullptr}; //! to be connected to \ref halui.axis.y.pos-relative - hal_float_t* axisYPositionRelative{nullptr}; + hal_real_t axisYPositionRelative{nullptr}; //! to be connected to \ref halui.axis.z.pos-relative - hal_float_t* axisZPositionRelative{nullptr}; + hal_real_t axisZPositionRelative{nullptr}; //! to be connected to \ref halui.axis.a.pos-relative - hal_float_t* axisAPositionRelative{nullptr}; + hal_real_t axisAPositionRelative{nullptr}; //! to be connected to \ref halui.axis.b.pos-relative - hal_float_t* axisBPositionRelative{nullptr}; + hal_real_t axisBPositionRelative{nullptr}; //! to be connected to \ref halui.axis.c.pos-relative - hal_float_t* axisCPositionRelative{nullptr}; + hal_real_t axisCPositionRelative{nullptr}; //! to be connected to \ref halui.spindle.is-on - hal_bit_t * spindleIsOn{nullptr}; + hal_bool_t spindleIsOn{nullptr}; //! to be connected to \ref halui.spindle-override.value - hal_float_t* spindleOverrideValue{nullptr}; + hal_real_t spindleOverrideValue{nullptr}; //! To be connected to an encoded and correctly scaled value of an spindle feedback signal. //! See also \ref encoder and \ref scale. - hal_float_t* spindleSpeedCmd{nullptr}; + hal_real_t spindleSpeedCmd{nullptr}; //! to be connected to \ref halui.max-velocity.value - hal_float_t* feedOverrideMaxVel{nullptr}; + hal_real_t feedOverrideMaxVel{nullptr}; //! to be connected to \ref halui.feed-override.value - hal_float_t* feedOverrideValue{nullptr}; + hal_real_t feedOverrideValue{nullptr}; //! to be connected to \ref halui.program.is-running - hal_bit_t* isProgramRunning{nullptr}; + hal_bool_t isProgramRunning{nullptr}; //! to be connected to \ref halui.program.is-paused - hal_bit_t* isProgramPaused{nullptr}; + hal_bool_t isProgramPaused{nullptr}; //! to be connected to \ref halui.program.is-idle - hal_bit_t* isProgramIdle{nullptr}; + hal_bool_t isProgramIdle{nullptr}; //! to be connected to \ref halui.mode.is-auto - hal_bit_t* isModeAuto{nullptr}; + hal_bool_t isModeAuto{nullptr}; //! to be connected to \ref halui.mode.is-joint - hal_bit_t* isModeJoint{nullptr}; + hal_bool_t isModeJoint{nullptr}; //! to be connected to \ref halui.mode.is-manual - hal_bit_t* isModeManual{nullptr}; + hal_bool_t isModeManual{nullptr}; //! to be connected to \ref halui.mode.is-mdi - hal_bit_t* isModeMdi{nullptr}; + hal_bool_t isModeMdi{nullptr}; //! to be connected to \ref halui.mode.is-teleop - hal_bit_t* isModeTeleop{nullptr}; + hal_bool_t isModeTeleop{nullptr}; // If axis is not homed we need to ask Teleop mode but we need to bypass that if machine is homed // https://forum.linuxcnc.org/49-basic-configuration/40581-how-to-configure-a-xhc-whb04b-pendant - hal_bit_t* JointXisHomed{nullptr}; - hal_bit_t* JointYisHomed{nullptr}; - hal_bit_t* JointZisHomed{nullptr}; - hal_bit_t* JointAisHomed{nullptr}; - hal_bit_t* JointBisHomed{nullptr}; - hal_bit_t* JointCisHomed{nullptr}; + hal_bool_t JointXisHomed{nullptr}; + hal_bool_t JointYisHomed{nullptr}; + hal_bool_t JointZisHomed{nullptr}; + hal_bool_t JointAisHomed{nullptr}; + hal_bool_t JointBisHomed{nullptr}; + hal_bool_t JointCisHomed{nullptr}; //! to be connected to \ref halui.machine.is-on - hal_bit_t* isMachineOn{nullptr}; + hal_bool_t isMachineOn{nullptr}; In(); }; @@ -179,149 +179,149 @@ class HalMemory struct Out { public: - hal_bit_t* button_pin[64] = {nullptr}; + hal_bool_t button_pin[64] = {nullptr}; //! to be connected to \ref halui.flood.off - hal_bit_t * floodStop{nullptr}; + hal_bool_t floodStop{nullptr}; //! to be connected to \ref halui.flood.on - hal_bit_t * floodStart{nullptr}; + hal_bool_t floodStart{nullptr}; //! to be connected to \ref halui.mist.off - hal_bit_t * mistStop{nullptr}; + hal_bool_t mistStop{nullptr}; //! to be connected to \ref halui.mist.on - hal_bit_t * mistStart{nullptr}; + hal_bool_t mistStart{nullptr}; //! to be connected to \ref axis.x.jog-counts - hal_s32_t* axisXJogCounts{nullptr}; + hal_sint_t axisXJogCounts{nullptr}; //! to be connected to \ref axis.y.jog-counts - hal_s32_t* axisYJogCounts{nullptr}; + hal_sint_t axisYJogCounts{nullptr}; //! to be connected to \ref axis.z.jog-counts - hal_s32_t* axisZJogCounts{nullptr}; + hal_sint_t axisZJogCounts{nullptr}; //! to be connected to \ref axis.a.jog-counts - hal_s32_t* axisAJogCounts{nullptr}; + hal_sint_t axisAJogCounts{nullptr}; //! to be connected to \ref axis.b.jog-counts - hal_s32_t* axisBJogCounts{nullptr}; + hal_sint_t axisBJogCounts{nullptr}; //! to be connected to \ref axis.c.jog-counts - hal_s32_t* axisCJogCounts{nullptr}; + hal_sint_t axisCJogCounts{nullptr}; //! to be connected to \ref axis.x.jog-enable - hal_bit_t* axisXJogEnable{nullptr}; + hal_bool_t axisXJogEnable{nullptr}; //! to be connected to \ref axis.y.jog-enable - hal_bit_t* axisYJogEnable{nullptr}; + hal_bool_t axisYJogEnable{nullptr}; //! to be connected to \ref axis.z.jog-enable - hal_bit_t* axisZJogEnable{nullptr}; + hal_bool_t axisZJogEnable{nullptr}; //! to be connected to \ref axis.a.jog-enable - hal_bit_t* axisAJogEnable{nullptr}; + hal_bool_t axisAJogEnable{nullptr}; //! to be connected to \ref axis.b.jog-enable - hal_bit_t* axisBJogEnable{nullptr}; + hal_bool_t axisBJogEnable{nullptr}; //! to be connected to \ref axis.c.jog-enable - hal_bit_t* axisCJogEnable{nullptr}; + hal_bool_t axisCJogEnable{nullptr}; //! to be connected to \ref axis.x.jog-scale - hal_float_t* axisXJogScale{nullptr}; + hal_real_t axisXJogScale{nullptr}; //! to be connected to \ref axis.y.jog-scale - hal_float_t* axisYJogScale{nullptr}; + hal_real_t axisYJogScale{nullptr}; //! to be connected to \ref axis.z.jog-scale - hal_float_t* axisZJogScale{nullptr}; + hal_real_t axisZJogScale{nullptr}; //! to be connected to \ref axis.a.jog-scale - hal_float_t* axisAJogScale{nullptr}; + hal_real_t axisAJogScale{nullptr}; //! to be connected to \ref axis.b.jog-scale - hal_float_t* axisBJogScale{nullptr}; + hal_real_t axisBJogScale{nullptr}; //! to be connected to \ref axis.c.jog-scale - hal_float_t* axisCJogScale{nullptr}; + hal_real_t axisCJogScale{nullptr}; //! to be connected to \ref axis.x.jog-vel-mode - hal_bit_t* axisXSetVelocityMode{nullptr}; + hal_bool_t axisXSetVelocityMode{nullptr}; //! to be connected to \ref axis.y.jog-vel-mode - hal_bit_t* axisYSetVelocityMode{nullptr}; + hal_bool_t axisYSetVelocityMode{nullptr}; //! to be connected to \ref axis.z.jog-vel-mode - hal_bit_t* axisZSetVelocityMode{nullptr}; + hal_bool_t axisZSetVelocityMode{nullptr}; //! to be connected to \ref axis.a.jog-vel-mode - hal_bit_t* axisASetVelocityMode{nullptr}; + hal_bool_t axisASetVelocityMode{nullptr}; //! to be connected to \ref axis.b.jog-vel-mode - hal_bit_t* axisBSetVelocityMode{nullptr}; + hal_bool_t axisBSetVelocityMode{nullptr}; //! to be connected to \ref axis.c.jog-vel-mode - hal_bit_t* axisCSetVelocityMode{nullptr}; - - hal_bit_t* feedValueSelected_2{nullptr}; - hal_bit_t* feedValueSelected_5{nullptr}; - hal_bit_t* feedValueSelected_10{nullptr}; - hal_bit_t* feedValueSelected_30{nullptr}; - hal_bit_t* feedValueSelected_60{nullptr}; - hal_bit_t* feedValueSelected_100{nullptr}; - hal_bit_t* feedValueSelected_lead{nullptr}; - hal_bit_t* feedValueSelected_mpg_feed{nullptr}; - hal_bit_t* feedValueSelected_continuous{nullptr}; - hal_bit_t* feedValueSelected_step{nullptr}; + hal_bool_t axisCSetVelocityMode{nullptr}; + + hal_bool_t feedValueSelected_2{nullptr}; + hal_bool_t feedValueSelected_5{nullptr}; + hal_bool_t feedValueSelected_10{nullptr}; + hal_bool_t feedValueSelected_30{nullptr}; + hal_bool_t feedValueSelected_60{nullptr}; + hal_bool_t feedValueSelected_100{nullptr}; + hal_bool_t feedValueSelected_lead{nullptr}; + hal_bool_t feedValueSelected_mpg_feed{nullptr}; + hal_bool_t feedValueSelected_continuous{nullptr}; + hal_bool_t feedValueSelected_step{nullptr}; //! to be connected to \ref \ref halui.feed-override.scale - hal_float_t* feedOverrideScale{nullptr}; + hal_real_t feedOverrideScale{nullptr}; //! to be connected to \ref halui.feed-override.decrease - hal_bit_t * feedOverrideDecrease{nullptr}; + hal_bool_t feedOverrideDecrease{nullptr}; //! to be connected to \ref halui.feed-override.increase - hal_bit_t * feedOverrideIncrease{nullptr}; + hal_bool_t feedOverrideIncrease{nullptr}; //! to be connected to \ref halui.spindle.start - hal_bit_t* spindleStart{nullptr}; + hal_bool_t spindleStart{nullptr}; //! to be connected to \ref halui.spindle.stop - hal_bit_t* spindleStop{nullptr}; + hal_bool_t spindleStop{nullptr}; //! to be connected to \ref halui.spindle.forward - hal_bit_t* spindleDoRunForward{nullptr}; + hal_bool_t spindleDoRunForward{nullptr}; //! to be connected to \ref halui.spindle.reverse - hal_bit_t* spindleDoRunReverse{nullptr}; + hal_bool_t spindleDoRunReverse{nullptr}; //! to be connected to halui.spindle.decrease - hal_bit_t* spindleDoDecrease{nullptr}; + hal_bool_t spindleDoDecrease{nullptr}; //! to be connected to halui.spindle.increase - hal_bit_t* spindleDoIncrease{nullptr}; + hal_bool_t spindleDoIncrease{nullptr}; //! to be connected to halui.spindle-override.decrease - hal_bit_t* spindleOverrideDoDecrease{nullptr}; + hal_bool_t spindleOverrideDoDecrease{nullptr}; //! to be connected to halui.spindle-override.increase - hal_bit_t* spindleOverrideDoIncrease{nullptr}; + hal_bool_t spindleOverrideDoIncrease{nullptr}; //! to be connected to \ref \ref halui.spindle-override.scale - hal_float_t* spindleOverrideScale{nullptr}; + hal_real_t spindleOverrideScale{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisXSelect{nullptr}; + hal_bool_t axisXSelect{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisYSelect{nullptr}; + hal_bool_t axisYSelect{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisZSelect{nullptr}; + hal_bool_t axisZSelect{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisASelect{nullptr}; + hal_bool_t axisASelect{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisBSelect{nullptr}; + hal_bool_t axisBSelect{nullptr}; //!to be connected to \ref halui.axis.N.select - hal_bit_t* axisCSelect{nullptr}; + hal_bool_t axisCSelect{nullptr}; //! reflects the pendant's idle state - hal_bit_t* isPendantSleeping{nullptr}; + hal_bool_t isPendantSleeping{nullptr}; //! reflects pendant's connectivity - hal_bit_t* isPendantConnected{nullptr}; + hal_bool_t isPendantConnected{nullptr}; //! to be connected to \ref halui.program.run - hal_bit_t* doRunProgram{nullptr}; + hal_bool_t doRunProgram{nullptr}; //! to be connected to \ref halui.program.pause - hal_bit_t* doPauseProgram{nullptr}; + hal_bool_t doPauseProgram{nullptr}; //! to be connected to \ref halui.program.resume - hal_bit_t* doResumeProgram{nullptr}; + hal_bool_t doResumeProgram{nullptr}; //! to be connected to \ref halui.program.stop - hal_bit_t* doStopProgram{nullptr}; + hal_bool_t doStopProgram{nullptr}; //! to be connected to \ref halui.mode.auto - hal_bit_t* doModeAuto{nullptr}; + hal_bool_t doModeAuto{nullptr}; //! to be connected to \ref halui.mode.joint - hal_bit_t* doModeJoint{nullptr}; + hal_bool_t doModeJoint{nullptr}; //! to be connected to \ref halui.mode.manual - hal_bit_t* doModeManual{nullptr}; + hal_bool_t doModeManual{nullptr}; //! to be connected to \ref halui.mode.mdi - hal_bit_t* doModeMdi{nullptr}; + hal_bool_t doModeMdi{nullptr}; //! to be connected to \ref halui.mode.teleop - hal_bit_t* doModeTeleop{nullptr}; + hal_bool_t doModeTeleop{nullptr}; //! to be connected to \ref halui.machine.on - hal_bit_t* doMachineOn{nullptr}; + hal_bool_t doMachineOn{nullptr}; //! to be connected to \ref halui.machine.off - hal_bit_t* doMachineOff{nullptr}; + hal_bool_t doMachineOff{nullptr}; Out(); }; @@ -379,7 +379,7 @@ class Hal //! Sets the new feed rate. The step mode must be set accordingly. //! \param feedRate the new feed rate independent of step mode - void setStepSize(const real_t feedRate); + void setStepSize(const rtapi_real feedRate); //! If lead is active. void setLead(); //! Sets the hal state of the respective pin (reset). Usually called in case the reset @@ -422,13 +422,13 @@ class Hal void setFeedMinus(bool enabled); //! Returns the current Max Velocity value. //! \sa Hal::In::feedOverrideMaxVel - real_t getFeedOverrideMaxVel() const; + rtapi_real getFeedOverrideMaxVel() const; //! Returns the current feed override value. //! \sa Hal::In::feedOverrideValue //! \return the current feed override value v: 0 <= v <= 1 - real_t getFeedOverrideValue() const; + rtapi_real getFeedOverrideValue() const; //! \xrefitem HalMemory::Out::feedOverrideScale setter - void setFeedOverrideScale(real_t scale); + void setFeedOverrideScale(rtapi_real scale); //! Propagates the feed value 0.001 selection state to hal. //! \sa Hal::Out::feedValueSelected_2 @@ -461,13 +461,13 @@ class Hal //! Returns the spindle speed. //! \return the spindle speed in rounds per second - real_t getspindleSpeedCmd() const; - real_t getspindleSpeedChangeIncrease() const; - real_t getspindleSpeedChangeDecrease() const; + rtapi_real getspindleSpeedCmd() const; + rtapi_real getspindleSpeedChangeIncrease() const; + rtapi_real getspindleSpeedChangeDecrease() const; //! Returns the current spindle override value. //! \sa Hal::In::spindleOverrideValue //! \return the current spindle override value v: 0 <= v <= 1 - real_t getSpindleOverrideValue() const; + rtapi_real getSpindleOverrideValue() const; //! \sa setSpindleOverridePlus(bool, size_t) void setSpindleOverridePlus(bool enabled); //! \sa setSpindleOverrideMinus(bool, size_t) @@ -549,22 +549,22 @@ class Hal //! waits until a given pin is set to a requested state //! \param state requested state //! \param pin requested pin to compare with - void checkState(bool state, hal_bit_t *pin); + void checkState(bool state, hal_bool_t pin); //! Returns the axis position. //! \param absolute true absolute, false relative //! \return the absolute or relative position in machine units - real_t getAxisXPosition(bool absolute) const; + rtapi_real getAxisXPosition(bool absolute) const; //! \xrefitem getAxisXPosition(bool) - real_t getAxisYPosition(bool absolute) const; + rtapi_real getAxisYPosition(bool absolute) const; //! \xrefitem getAxisXPosition(bool) - real_t getAxisZPosition(bool absolute) const; + rtapi_real getAxisZPosition(bool absolute) const; //! \xrefitem getAxisXPosition(bool) - real_t getAxisAPosition(bool absolute) const; + rtapi_real getAxisAPosition(bool absolute) const; //! \xrefitem getAxisXPosition(bool) - real_t getAxisBPosition(bool absolute) const; + rtapi_real getAxisBPosition(bool absolute) const; //! \xrefitem getAxisXPosition(bool) - real_t getAxisCPosition(bool absolute) const; + rtapi_real getAxisCPosition(bool absolute) const; private: @@ -581,26 +581,26 @@ class Hal bool mIsSpindleDirectionForward{true}; Profiles::HalRequestProfile mHalRequestProfile; - //! //! Allocates new hal_bit_t pin according to \ref mIsSimulationMode. If \ref mIsSimulationMode then - //! mallocs memory, hal_pin_bit_new allocation otherwise. + //! //! Allocates new hal_bool_t pin according to \ref mIsSimulationMode. If \ref mIsSimulationMode then + //! mallocs memory, hal_pin_new_bool allocation otherwise. //! \param pin_name the pin name when registered to hal //! \param ptr will point to the allocated memory //! \param s size in bytes //! \return != 0 on error, 0 otherwise int newSimulatedHalPin(char* pin_name, void** ptr, int s); - //! \sa newBitHalPin(hal_pin_dir_t, hal_bit_t**, int, const char*, ...) - int newHalFloat(hal_pin_dir_t direction, hal_float_t** ptr, int componentId, const char* fmt, ...); - //! \sa newBitHalPin(hal_pin_dir_t, hal_bit_t**, int, const char*, ...) - int newHalSigned32(hal_pin_dir_t direction, hal_s32_t** ptr, int componentId, const char* fmt, ...); - //! \sa newBitHalPin(hal_pin_dir_t, hal_bit_t**, int, const char*, ...) - int newHalUnsigned32(hal_pin_dir_t direction, hal_u32_t** ptr, int componentId, const char* fmt, ...); + //! \sa newBitHalPin(hal_pin_dir_t, hal_bool_t*, int, const char*, ...) + int newHalFloat(hal_pin_dir_t direction, hal_real_t* ptr, int componentId, const char* fmt, ...); + //! \sa newBitHalPin(hal_pin_dir_t, hal_bool_t*, int, const char*, ...) + int newHalSigned32(hal_pin_dir_t direction, hal_sint_t* ptr, int componentId, const char* fmt, ...); + //! \sa newBitHalPin(hal_pin_dir_t, hal_bool_t*, int, const char*, ...) + int newHalUnsigned32(hal_pin_dir_t direction, hal_uint_t* ptr, int componentId, const char* fmt, ...); //! \param direction module input or output //! \param ptr will point to the allocated memory //! \param componentId hal id //! \param fmt the pin name when registered to hal //! \param ... va args //! \return != 0 on error, 0 otherwise - int newHalBit(hal_pin_dir_t direction, hal_bit_t** ptr, int componentId, const char* fmt, ...); + int newHalBit(hal_pin_dir_t direction, hal_bool_t* ptr, int componentId, const char* fmt, ...); //! allocates new hal pin according to \ref mIsSimulationMode //! \param pin pointer reference to the memory to be fred //! \post pin == nullptr @@ -619,7 +619,7 @@ class Hal //! \sa requestManualMode(bool) bool requestAutoMode(bool isRisingEdge); //! Requests manual mode if in MDI mode. Skips request if in AUTO mode. - //! \sa requestMode(bool, hal_bit_t*, hal_bit_t*) + //! \sa requestMode(bool, hal_bool_t, hal_bool_t) //! \return true if machine has selected the mode, false otherwise bool requestManualMode(bool isRisingEdge); //! \sa requestManualMode(bool) @@ -637,7 +637,7 @@ class Hal //! \param timeout_ms delay in [ms] in between condition is checks //! \param max_timeouts maximum number of checks //! \return true if condition was met, false otherwise - bool waitForRequestedMode(volatile hal_bit_t* condition); + bool waitForRequestedMode(hal_bool_t condition); //! Requests machine mode such as auto, mdi, manual. When toggling it introduces hold and space delay. //! \sa mModesRequestProfile @@ -645,7 +645,7 @@ class Hal //! \param modeFeedbackPin the (input) pin reflecting if the mode is set //! \return on rising edge: true if the machine has selected or is in the desired mode, false otherwise; //! on falling edge: false - bool requestMode(bool isRisingEdge, hal_bit_t* requestPin, hal_bit_t* modeFeedbackPin); + bool requestMode(bool isRisingEdge, hal_bool_t requestPin, hal_bool_t modeFeedbackPin); }; } #endif diff --git a/src/hal/utils/Submakefile b/src/hal/utils/Submakefile index 12d60b7b9de..8dafd9b040c 100644 --- a/src/hal/utils/Submakefile +++ b/src/hal/utils/Submakefile @@ -1,5 +1,10 @@ -HALCMDSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halcmd_main.c -HALSHSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halsh.c +HALCMDSRCS := \ + hal/utils/halcmd.c \ + hal/utils/halcmd_commands.cc \ + hal/utils/halcmd_main.c \ + hal/utils/setps_util.c + +HALSHSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halsh.c hal/utils/setps_util.c ifneq ($(READLINE_LIBS),) HALCMDSRCS += hal/utils/halcmd_completion.c @@ -15,15 +20,15 @@ TARGETS += ../tcl/hal.so ../bin/halcmd: $(call TOOBJS, $(HALCMDSRCS)) ../lib/liblinuxcncini.so.1 ../lib/liblinuxcnchal.so.0 $(ECHO) Linking $(notdir $@) - $(Q)$(CXX) $(LDFLAGS) -o $@ $^ $(READLINE_LIBS) + $(Q)$(CXX) $(LDFLAGS) -o $@ $^ $(READLINE_LIBS) -lfmt TARGETS += ../bin/halcmd -HALRMTSRCS := hal/utils/halrmt.c +HALRMTSRCS := hal/utils/halrmt.cc hal/utils/setps_util.c USERSRCS += $(HALRMTSRCS) -../bin/halrmt: $(call TOOBJS, $(HALRMTSRCS)) ../lib/liblinuxcnchal.so.0 +../bin/halrmt: $(call TOOBJS, $(HALRMTSRCS)) ../lib/liblinuxcnchal.so.0 ../lib/liblinuxcncini.so.1 $(ECHO) Linking $(notdir $@) - $(Q)$(CC) $(LDFLAGS) -o $@ $^ -lpthread + $(Q)$(CXX) $(LDFLAGS) -o $@ $^ -lfmt TARGETS += ../bin/halrmt ifneq ($(GTK_VERSION),) diff --git a/src/hal/utils/halcmd.c b/src/hal/utils/halcmd.c index c1e93556234..b366bae7802 100644 --- a/src/hal/utils/halcmd.c +++ b/src/hal/utils/halcmd.c @@ -296,7 +296,7 @@ static void quit(int sig) work for each command. */ -static int count_args(char **argv) { +static int count_args(const char **argv) { int i = 0; while(argv[i] && argv[i][0]) i++; return i; @@ -305,7 +305,7 @@ static int count_args(char **argv) { #define ARG(i) (argc > i ? argv[i] : NULL) #define REST(i) (argc > i ? argv + i : argv + argc) -static int parse_cmd1(char **argv) { +static int parse_cmd1(const char **argv) { struct halcmd_command *command = bsearch(argv[0], halcmd_commands, halcmd_ncommands, sizeof(struct halcmd_command), compare_command); @@ -420,7 +420,7 @@ static int parse_cmd1(char **argv) { int i; for(i=0; i * Copyright (C) 2003 John Kasunich * + * Copyright (C) 2026 B.Stultiens * * Other contributors: * Martin Kuhnle @@ -40,9 +41,7 @@ #include "config.h" #include // RTAPI realtime OS API #include // HAL public API decls -#include "../hal_priv.h" // private HAL decls #include "halcmd_commands.h" -#include #include // rtapi_strlcpy #include @@ -56,34 +55,38 @@ #include #include #include +#include #include - -static int unloadrt_comp(char *mod_name); -static void print_comp_info(char **patterns); -static void print_pin_info(int type, char **patterns); -static void print_pin_aliases(char **patterns); -static void print_param_aliases(char **patterns); -static void print_sig_info(int type, char **patterns); -static void print_script_sig_info(int type, char **patterns); -static void print_param_info(int type, char **patterns); -static void print_funct_info(char **patterns); -static void print_thread_info(char **patterns); -static void print_comp_names(char **patterns); -static void print_pin_names(char **patterns); -static void print_sig_names(char **patterns); -static void print_param_names(char **patterns); -static void print_funct_names(char **patterns); -static void print_thread_names(char **patterns); +#include + +#include "setps_util.h" + +static int unloadrt_comp(const char *mod_name); +static void print_comp_info(const char **patterns); +static void print_pin_info(int type, const char **patterns); +static void print_pin_aliases(const char **patterns); +static void print_param_aliases(const char **patterns); +static void print_sig_info(int type, const char **patterns); +static void print_script_sig_info(int type, const char **patterns); +static void print_param_info(int type, const char **patterns); +static void print_funct_info(const char **patterns); +static void print_thread_info(const char **patterns); +static void print_comp_names(const char **patterns); +static void print_pin_names(const char **patterns); +static void print_sig_names(const char **patterns); +static void print_param_names(const char **patterns); +static void print_funct_names(const char **patterns); +static void print_thread_names(const char **patterns); static void print_lock_status(); static void print_mem_status(); -static const char *data_type(int type); -static const char *data_type2(int type); -static const char *pin_data_dir(int dir); -static const char *param_data_dir(int dir); -static const char *data_arrow1(int dir); -static const char *data_arrow2(int dir); -static const char *data_value(int type, void *valptr); -static const char *data_value2(int type, void *valptr); +static const char *data_type(hal_type_t type); +static const char *data_type2(hal_type_t type); +static const char *pin_data_dir(hal_pdir_t dir); +static const char *param_data_dir(hal_pdir_t dir); +static const char *data_arrow1(hal_pdir_t dir); +static const char *data_arrow2(hal_pdir_t dir); +static std::string querydata_refstr_20(hal_type_t type, hal_refs_u u); +static std::string querydata_refstr(hal_type_t type, hal_refs_u u); static void save_comps(FILE *dst); static void save_aliases(FILE *dst); static void save_signals(FILE *dst, int only_unlinked); @@ -98,18 +101,18 @@ static int tmatch(int req_type, int type) { return req_type == -1 || type == req_type; } -static int match(char **patterns, char *value) { +static int match(const char **patterns, const char *value) { int i; if(!patterns || !patterns[0] || !patterns[0][0]) return 1; for(i=0; patterns[i] && *patterns[i]; i++) { - char *pattern = patterns[i]; + const char *pattern = patterns[i]; if(strncmp(pattern, value, strlen(pattern)) == 0) return 1; if (fnmatch(pattern, value, 0) == 0) return 1; } return 0; } -int do_lock_cmd(char *command) +int do_lock_cmd(const char *command) { int retval = 0; @@ -131,7 +134,7 @@ int do_lock_cmd(char *command) return retval; } -int do_unlock_cmd(char *command) +int do_unlock_cmd(const char *command) { int retval = 0; @@ -153,61 +156,57 @@ int do_unlock_cmd(char *command) return retval; } -int do_linkpp_cmd(char *first_pin_name, char *second_pin_name) +int do_linkpp_cmd(const char *pname1, const char *pname2) { - int retval; - hal_pin_t *first_pin, *second_pin; static int dep_msg_printed = 0; - if ( dep_msg_printed == 0 ) { - halcmd_warning("linkpp command is deprecated, use 'net'\n"); - dep_msg_printed = 1; - } - rtapi_mutex_get(&(hal_data->mutex)); - /* check if the pins are there */ - first_pin = halpr_find_pin_by_name(first_pin_name); - second_pin = halpr_find_pin_by_name(second_pin_name); - if (first_pin == NULL) { - /* first pin not found*/ - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin '%s' not found\n", first_pin_name); - return -EINVAL; - } else if (second_pin == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin '%s' not found\n", second_pin_name); - return -EINVAL; + halcmd_warning("linkpp command is deprecated, use 'net'\n"); + dep_msg_printed = 1; } - - /* give the mutex, as the other functions use their own mutex */ - rtapi_mutex_give(&(hal_data->mutex)); - - /* check that both pins have the same type, - don't want to create a sig, which after that won't be useful */ - if (first_pin->type != second_pin->type) { - halcmd_error("pins '%s' and '%s' not of the same type\n", - first_pin_name, second_pin_name); - return -EINVAL; + + hal_query_t p1 = {}; + p1.name = pname1; + int rv = hal_getref_p(&p1); + if(rv) { + // First pin not found + halcmd_error("pin '%s' not found\n", pname1); + return -EINVAL; } - - /* now create the signal */ - retval = hal_signal_new(first_pin_name, first_pin->type); - if (retval == 0) { - /* if it worked, link the pins to it */ - retval = hal_link(first_pin_name, first_pin_name); + hal_query_t p2 = {}; + p2.name = pname2; + rv = hal_getref_p(&p2); + if(rv) { + // Second pin not found + halcmd_error("pin '%s' not found\n", pname2); + return -EINVAL; + } - if ( retval == 0 ) { - /* if that worked, link the second pin to the new signal */ - retval = hal_link(second_pin_name, first_pin_name); - } + if(p1.pp.type != p2.pp.type) { + // Disjoint types + halcmd_error("pins '%s' and '%s' not of the same type\n", pname1, pname2); + return -EINVAL; } - if (retval < 0) { - halcmd_error("linkpp failed\n"); + + if(0 != (rv = hal_signal_new(pname1, p1.pp.type))) { + halcmd_error("linkpp_cmd: failed to create signal '%s' with type %d\n", pname1, (int)p1.pp.type); + return rv; } - return retval; + + if(0 != (rv = hal_link(pname1, pname1))) { + halcmd_error("linkpp_cmd: failed to link pin '%s' to signal '%s'\n", pname1, pname1); + return rv; + } + + if(0 != (rv = hal_link(pname2, pname1))) { + halcmd_error("linkpp_cmd: failed to link pin '%s' to signal '%s'\n", pname2, pname1); + return rv; + } + + return 0; } -int do_linkps_cmd(char *pin, char *sig) +int do_linkps_cmd(const char *pin, const char *sig) { int retval; @@ -221,12 +220,12 @@ int do_linkps_cmd(char *pin, char *sig) return retval; } -int do_linksp_cmd(char *sig, char *pin) { +int do_linksp_cmd(const char *sig, const char *pin) { return do_linkps_cmd(pin, sig); } -int do_unlinkp_cmd(char *pin) +int do_unlinkp_cmd(const char *pin) { int retval; @@ -240,7 +239,7 @@ int do_unlinkp_cmd(char *pin) return retval; } -int do_set_debug_cmd(char* level){ +int do_set_debug_cmd(const char *level){ int retval = -EINVAL; #if defined(RTAPI_USPACE) int m = 0; @@ -256,7 +255,7 @@ int do_set_debug_cmd(char* level){ return retval; } -int do_source_cmd(char *hal_filename) { +int do_source_cmd(const char *hal_filename) { FILE *f = fopen(hal_filename, "r"); char buf[MAX_CMD_LEN+1]; int fd; @@ -322,8 +321,8 @@ int do_unecho_cmd(void) { printf("Echo off\n"); return 0; } -int do_addf_cmd(char *func, char *thread, char **opt) { - char *position_str = opt ? opt[0] : NULL; +int do_addf_cmd(const char *func, const char *thread, const char **opt) { + const char *position_str = opt ? opt[0] : NULL; int position = -1; int retval; @@ -339,13 +338,13 @@ int do_addf_cmd(char *func, char *thread, char **opt) { return retval; } -int do_initf_cmd(char *func, char *thread, char **opt) { +int do_initf_cmd(const char *func, const char *thread, const char **opt) { /* usage: initf [position] position has the same meaning as in addf: +N from start of the init list (+1 = run first), -N from end (-1 = run last, default), 0 illegal. The function runs once in realtime context in a dedicated cycle before the cyclic funct list; next cyclic cycle wakes one period later. */ - char *position_str = opt ? opt[0] : NULL; + const char *position_str = opt ? opt[0] : NULL; int position = -1; int retval; @@ -364,7 +363,7 @@ int do_initf_cmd(char *func, char *thread, char **opt) { return retval; } -int do_alias_cmd(char *pinparam, char *name, char *alias) { +int do_alias_cmd(const char *pinparam, const char *name, const char *alias) { int retval; if ( strcmp (pinparam, "pin" ) == 0 ) { @@ -383,7 +382,7 @@ int do_alias_cmd(char *pinparam, char *name, char *alias) { return retval; } -int do_unalias_cmd(char *pinparam, char *name) { +int do_unalias_cmd(const char *pinparam, const char *name) { int retval; if (strcmp(pinparam, "pin") == 0) { retval = hal_pin_alias(name, NULL); @@ -400,7 +399,7 @@ int do_unalias_cmd(char *pinparam, char *name) { } return retval; } -int do_delf_cmd(char *func, char *thread) { +int do_delf_cmd(const char *func, const char *thread) { int retval; retval = hal_del_funct_from_thread(func, thread); @@ -414,131 +413,144 @@ int do_delf_cmd(char *func, char *thread) { return retval; } -static int preflight_net_cmd(char *signal, hal_sig_t *sig, char *pins[]) { - int i, type=-1, writers=0, bidirs=0, pincnt=0; - char *writer_name=NULL, *bidir_name=NULL; - /* if signal already exists, use its info */ - if (sig) { - type = sig->type; - writers = sig->writers; - bidirs = sig->bidirs; +struct net_cmd_data_t { + const char *writer_name; + const char *bidir_name; +}; + +static int preflight_net_cmd_cb(hal_query_t *q, void *arg) +{ + const char *signame = (const char *)arg; + net_cmd_data_t *ncd = (net_cmd_data_t *)q->callerdata.vpval; + + if(q->pp.signal && !strcmp(q->pp.signal, signame)) { + if(q->pp.dir == HAL_OUT) + ncd->writer_name = q->name; + if(q->pp.dir == HAL_IO) + ncd->bidir_name = ncd->writer_name = q->name; } + return 0; +} + +static int preflight_net_cmd(const char *signal, const hal_query_t *qsig, const char *pins[], hal_type_t *typep) +{ + hal_type_t type = qsig->sig.type; + int writers = qsig->sig.writers; + int bidirs = qsig->sig.bidirs; + int pincnt = 0; + net_cmd_data_t ncd = { NULL, NULL}; if(writers || bidirs) { - hal_pin_t *pin; - SHMFIELD(hal_pin_t) next; - for(next = hal_data->pin_list_ptr; next; next=pin->next_ptr) - { - pin = SHMPTR(next); - if(SHMPTR(pin->signal) == sig && pin->dir == HAL_OUT) - writer_name = pin->name; - if(SHMPTR(pin->signal) == sig && pin->dir == HAL_IO) - bidir_name = writer_name = pin->name; + hal_query_t qp = {}; + qp.qtype = HAL_QTYPE_PIN; + qp.callerdata.vpval = (void *)&ncd; + hal_list_p(&qp, preflight_net_cmd_cb, (void *)signal); + } + + for(int i = 0; pins[i] && *pins[i]; i++) { + hal_query_t qp = {}; + qp.qtype = HAL_QTYPE_PIN; + qp.name = pins[i]; + int rv = hal_getref_p(&qp); + if(rv) { + // In theory, other errors may occur... + halcmd_error("Pin '%s' does not exist\n", pins[i]); + return -ENOENT; } - } - for(i=0; pins[i] && *pins[i]; i++) { - hal_pin_t *pin = NULL; - pin = halpr_find_pin_by_name(pins[i]); - if(!pin) { - halcmd_error("Pin '%s' does not exist\n", - pins[i]); - return -ENOENT; + if(qp.pp.signal) { + if(strcmp(qp.pp.signal, signal)) { + halcmd_error("Pin '%s' was already linked to signal '%s'\n", qp.name, qp.pp.signal); + return -EINVAL; + } else { + // Already linked + pincnt++; + continue; + } } - if(SHMPTR(pin->signal) == sig) { - /* Already on this signal */ - pincnt++; - continue; - } else if(pin->signal != 0) { - hal_sig_t *osig = SHMPTR(pin->signal); - halcmd_error("Pin '%s' was already linked to signal '%s'\n", - pin->name, osig->name); - return -EINVAL; - } - if (type == -1) { - /* no pre-existing type, use this pin's type */ - type = pin->type; + + if(0 == type) { + // no pre-existing type, use this pin's type + type = qp.pp.type; } - if(type != pin->type) { - halcmd_error( - "Signal '%s' of type '%s' cannot add pin '%s' of type '%s'\n", - signal, data_type2(type), pin->name, data_type2(pin->type)); + if(type != qp.pp.type) { + halcmd_error("Signal '%s' of type '%s' cannot add pin '%s' of type '%s'\n", + signal, data_type2(type), qp.name, data_type2(qp.pp.type)); return -EINVAL; } - if(pin->dir == HAL_OUT) { + + if(HAL_OUT == qp.pp.dir) { if(writers || bidirs) { - dir_error: - halcmd_error( - "Signal '%s' can not add %s pin '%s', " - "it already has %s pin '%s'\n", - signal, pin_data_dir(pin->dir), pin->name, - bidir_name ? pin_data_dir(HAL_IO):pin_data_dir(HAL_OUT), - bidir_name ? bidir_name : writer_name); +dir_error: + halcmd_error( "Signal '%s' can not add %s pin '%s', it already has %s pin '%s'\n", + signal, pin_data_dir(qp.pp.dir), qp.name, + ncd.bidir_name ? pin_data_dir(HAL_IO) : pin_data_dir(HAL_OUT), + ncd.bidir_name ? ncd.bidir_name : ncd.writer_name); return -EINVAL; } - writer_name = pin->name; + ncd.writer_name = qp.name; writers++; } - if(pin->dir == HAL_IO) { + + if(HAL_IO == qp.pp.dir) { if(writers) { goto dir_error; } - bidir_name = pin->name; + ncd.bidir_name = qp.name; bidirs++; } pincnt++; } + *typep = type; if(pincnt) return 0; halcmd_error("'net' requires at least one pin, none given\n"); return -EINVAL; } -int do_net_cmd(char *signal, char *pins[]) { - hal_sig_t *sig; - int i, retval; - - rtapi_mutex_get(&(hal_data->mutex)); - /* see if signal already exists */ - sig = halpr_find_sig_by_name(signal); +int do_net_cmd(const char *signal, const char *pins[]) +{ + int rv; + hal_query_t qs = {}; + qs.name = signal; + int havesig = hal_getref_s(&qs); + if(0 != havesig && -ENOENT != havesig) { + halcmd_error("net_cmd: failed signal search error=%d\n", havesig); + return havesig; + } - /* verify that everything matches up (pin types, etc) */ - retval = preflight_net_cmd(signal, sig, pins); - if(retval < 0) { - rtapi_mutex_give(&(hal_data->mutex)); - return retval; + hal_type_t type = HAL_TYPE_UNINITIALIZED; + if(0 != (rv = preflight_net_cmd(signal, &qs, pins, &type))) { + return rv; } - { - hal_pin_t *pin = halpr_find_pin_by_name(signal); - if(pin) { - halcmd_error( - "Signal name '%s' must not be the same as a pin. " - "Did you omit the signal name?\n", - signal); - rtapi_mutex_give(&(hal_data->mutex)); - return -ENOENT; - } + hal_query_t qp = {}; + qp.name = signal; + if(0 == (rv = hal_getref_p(&qp))) { + halcmd_error("Signal name '%s' must not be the same as a pin. " + "Did you omit the signal name?\n", signal); + return -ENOENT; } - if(!sig) { - /* Create the signal with the type of the first pin */ - hal_pin_t *pin = halpr_find_pin_by_name(pins[0]); - rtapi_mutex_give(&(hal_data->mutex)); - if(!pin) { - return -ENOENT; + + if(-ENOENT == havesig) { + // Signal does not yet exist + if(0 == type) { + halcmd_error("Failed to determine type for signal '%s'\n", signal); + return -EINVAL; + } + if(0 != (rv = hal_signal_new(signal, type))) { + halcmd_error("Failed to create signal '%s'\n", signal); + return rv; } - retval = hal_signal_new(signal, pin->type); - } else { - /* signal already exists */ - rtapi_mutex_give(&(hal_data->mutex)); - } - /* add pins to signal */ - for(i=0; retval == 0 && pins[i] && *pins[i]; i++) { - retval = do_linkps_cmd(pins[i], signal); } - return retval; + for(int i = 0; pins[i] && *pins[i]; i++) { + if(0 != (rv = do_linkps_cmd(pins[i], signal))) { + return rv; + } + } + return 0; } #if 0 /* newinst deferred to version 2.2 */ @@ -583,35 +595,35 @@ int do_newinst_cmd(char *comp_name, char *inst_name) { return -EINVAL; } - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); while(hal_data->pending_constructor) { struct timespec ts = {0, 100 * 1000 * 1000}; // 100ms - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); nanosleep(&ts, NULL); - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); } rtapi_strlcpy(hal_data->constructor_prefix, inst_name, HAL_NAME_LEN); hal_data->constructor_prefix[HAL_NAME_LEN]=0; hal_data->pending_constructor = comp->make; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); if(fputc(' ', f) == EOF) { halcmd_error( "cannot write to proc entry: %s\n", strerror(errno)); fclose(f); - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); hal_data->pending_constructor = 0; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return -EINVAL; } if(fclose(f) != 0) { halcmd_error( "cannot close proc entry: %s\n", strerror(errno)); - rtapi_mutex_get(&(hal_data->mutex)); + halpr_mutex_acquire(); hal_data->pending_constructor = 0; - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); return -EINVAL; } @@ -626,7 +638,7 @@ int do_newinst_cmd(char *comp_name, char *inst_name) { hal_comp_t *inst = halpr_alloc_comp_struct(); if (inst == 0) { /* couldn't allocate structure */ - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); halcmd_error( "insufficient memory for instance '%s'\n", inst_name); return -ENOMEM; @@ -642,372 +654,175 @@ int do_newinst_cmd(char *comp_name, char *inst_name) { inst->next_ptr = hal_data->comp_list_ptr; hal_data->comp_list_ptr = SHMOFF(inst); - rtapi_mutex_give(&(hal_data->mutex)); + halpr_mutex_release(); } return 0; } #endif /* newinst deferred */ -int do_newsig_cmd(char *name, char *type) +static hal_type_t typestr_to_haltype(const char *type, bool anycase) { - int retval; - - if (strcasecmp(type, "bit") == 0) { - retval = hal_signal_new(name, HAL_BIT); - } else if (strcasecmp(type, "float") == 0) { - retval = hal_signal_new(name, HAL_FLOAT); - } else if (strcasecmp(type, "u32") == 0) { - retval = hal_signal_new(name, HAL_U32); - } else if (strcasecmp(type, "s32") == 0) { - retval = hal_signal_new(name, HAL_S32); - } else if (strcasecmp(type, "u64") == 0) { - retval = hal_signal_new(name, HAL_U64); - } else if (strcasecmp(type, "s64") == 0) { - retval = hal_signal_new(name, HAL_S64); - } else if (strcasecmp(type, "port") == 0) { - retval = hal_signal_new(name, HAL_PORT); - } else { - halcmd_error("Unknown signal type '%s'\n", type); - retval = -EINVAL; - } - if (retval < 0) { - halcmd_error("newsig failed\n"); - } - return retval; -} - -static int set_common(hal_type_t type, void *d_ptr, char *value) { - // This function assumes that the mutex is held - int retval = 0; - double fval; - long lval; - unsigned long ulval; - int64_t s64val; - uint64_t u64val; - unsigned uval; - char *cp = value; + static const struct { + const char *name; + hal_type_t type; + } htypes[] = { + { "bool", HAL_BOOL }, + { "real", HAL_REAL }, + { "sint", HAL_SINT }, + { "uint", HAL_UINT }, + { "port", HAL_PORT }, + { "bit", HAL_BOOL }, + { "float", HAL_REAL }, + { "u32", HAL_U32 }, + { "s32", HAL_S32 }, + { "u64", HAL_UINT }, + { "s64", HAL_SINT }, + { nullptr, HAL_TYPE_UNSPECIFIED } + }; - switch (type) { - case HAL_BIT: - if ((strcmp("1", value) == 0) || (strcasecmp("TRUE", value) == 0)) { - *(hal_bit_t *) (d_ptr) = 1; - } else if ((strcmp("0", value) == 0) - || (strcasecmp("FALSE", value)) == 0) { - *(hal_bit_t *) (d_ptr) = 0; - } else { - halcmd_error("value '%s' invalid for bit\n", value); - retval = -EINVAL; - } - break; - case HAL_FLOAT: - fval = strtod ( value, &cp ); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid character(s) in string */ - halcmd_error("value '%s' invalid for float\n", value); - retval = -EINVAL; - } else { - *((hal_float_t *) (d_ptr)) = fval; - } - break; - case HAL_S32: - lval = strtol(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - halcmd_error("value '%s' invalid for S32\n", value); - retval = -EINVAL; - } else { - *((hal_s32_t *) (d_ptr)) = lval; - } - break; - case HAL_U32: - ulval = strtoul(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - halcmd_error("value '%s' invalid for U32\n", value); - retval = -EINVAL; - } else { - *((hal_u32_t *) (d_ptr)) = ulval; - } - break; - case HAL_S64: - s64val = strtoll(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - halcmd_error("value '%s' invalid for S64\n", value); - retval = -EINVAL; - } else { - *((hal_s64_t *) (d_ptr)) = s64val; - } - break; - case HAL_U64: - u64val = strtoull(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - halcmd_error("value '%s' invalid for U64\n", value); - retval = -EINVAL; - } else { - *((hal_u64_t *) (d_ptr)) = u64val; - } - break; - case HAL_PORT: - uval = strtoul(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - halcmd_error("value '%s' invalid for PORT\n", value); - retval = -EINVAL; - } else { - if((*((hal_port_t*)d_ptr) != 0) && (hal_port_buffer_size(((hal_port_t*)d_ptr)) > 0)) { - halcmd_error("port is already allocated with %u bytes.\n", hal_port_buffer_size(((hal_port_t*)d_ptr))); - retval = -EINVAL; - } else { - retval = hal_port_alloc(uval, (hal_port_t *)d_ptr); - if(retval) - halcmd_error("failed to allocate PORT with size %u\n", uval); + int (*cmpfunc)(const char *, const char *) = anycase ? strcasecmp : strcmp; + for(int i = 0; htypes[i].name; i++) { + if(!cmpfunc(type, htypes[i].name)) { + return htypes[i].type; } } - break; - default: - /* Shouldn't get here, but just in case... */ - halcmd_error("bad type %d\n", type); - retval = -EINVAL; - } - return retval; + return HAL_TYPE_UNINITIALIZED; } -int do_setp_cmd(char *name, char *value) +int do_newsig_cmd(const char *name, const char *type) { - int retval; - hal_param_t *param; - hal_pin_t *pin; - hal_type_t type; - void *d_ptr; - - halcmd_info("setting parameter '%s' to '%s'\n", name, value); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search param list for name */ - param = halpr_find_param_by_name(name); - if (param == NULL) { - pin = halpr_find_pin_by_name(name); - if(pin == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("parameter or pin '%s' not found\n", name); - return -EINVAL; - } else { - /* found it */ - type = pin->type; - if(pin->dir == HAL_OUT) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin '%s' is not writable\n", name); - return -EINVAL; - } - if(pin->signal != 0) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin '%s' is connected to a signal\n", name); - return -EINVAL; - } - // d_ptr = (void*)SHMPTR(pin->dummysig); - d_ptr = (void*)&pin->dummysig; - } - } else { - /* found it */ - type = param->type; - /* is it read only? */ - if (param->dir == HAL_RO) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("param '%s' is not writable\n", name); - return -EINVAL; - } - d_ptr = SHMPTR(param->data_ptr); + hal_type_t htype = typestr_to_haltype(type, true); + if(HAL_TYPE_UNINITIALIZED == htype) { + halcmd_error("Unknown signal type '%s'\n", type); + return -EINVAL; } - retval = set_common(type, d_ptr, value); + int rv = hal_signal_new(name, htype); + if(rv < 0) + halcmd_error("newsig failed\n"); + return rv; +} - rtapi_mutex_give(&(hal_data->mutex)); - if (retval == 0) { - /* print success message */ - if(param) { - halcmd_info("Parameter '%s' set to %s\n", name, value); - } else { - halcmd_info("Pin '%s' set to %s\n", name, value); - } - } else { - halcmd_error("setp failed\n"); +int do_setp_cmd(const char *name, const char *value) +{ + hal_query_t q = {}; + q.name = name; + int rv = hal_set_p(&q, setps_common_cb, (void *)value); + if(rv) { + const char *tag; + switch(q.qtype) { + case HAL_QTYPE_PARAM: tag = "parameter"; break; + case HAL_QTYPE_PIN: tag = "pin"; break; + default: tag = "parameter or pin"; break; + } + halcmd_error("%s '%s': %s\n", tag, name, hal_strerror(rv)); } - return retval; - + return rv; } -int do_print_cmd(char *value) +int do_print_cmd(const char *value) { halcmd_error( "HALCMD MSG: %s\n",value ); return 0; } -int do_ptype_cmd(char *name) +int do_ptype_cmd(const char *name) { - hal_param_t *param; - hal_pin_t *pin; - hal_type_t type; - - rtapi_print_msg(RTAPI_MSG_DBG, "getting parameter '%s'\n", name); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search param list for name */ - param = halpr_find_param_by_name(name); - if (param) { - /* found it */ - type = param->type; - halcmd_output("%s\n", data_type2(type)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; + hal_query_t q = {}; + q.name = name; + int rv = hal_getref_p(&q); + if(!rv) { + halcmd_output("%s\n", data_type2(q.pp.type)); + } else { + const char *tag; + switch(q.qtype) { + case HAL_QTYPE_PARAM: tag = "parameter"; break; + case HAL_QTYPE_PIN: tag = "pin"; break; + default: tag = "parameter or pin"; break; + } + halcmd_error("%s '%s': %s\n", tag, name, hal_strerror(rv)); } - - /* not found, search pin list for name */ - pin = halpr_find_pin_by_name(name); - if(pin) { - /* found it */ - type = pin->type; - halcmd_output("%s\n", data_type2(type)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; - } - - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin or parameter '%s' not found\n", name); - return -EINVAL; + return rv; } - -int do_getp_cmd(char *name) +static std::string querydata_valuestr(hal_type_t type, const hal_query_value_u *v) { - hal_param_t *param; - hal_pin_t *pin; - hal_sig_t *sig; - hal_type_t type; - void *d_ptr; - - rtapi_print_msg(RTAPI_MSG_DBG, "getting parameter '%s'\n", name); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search param list for name */ - param = halpr_find_param_by_name(name); - if (param) { - /* found it */ - type = param->type; - d_ptr = SHMPTR(param->data_ptr); - halcmd_output("%s\n", data_value2((int) type, d_ptr)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; + switch(type) { + case HAL_BOOL: + return v->b ? "TRUE" : "FALSE"; + case HAL_REAL: + return fmt::format("{:.7g}", v->r); + case HAL_S32: + case HAL_SINT: + case HAL_PORT: + return fmt::format("{}", v->s); + case HAL_U32: + case HAL_UINT: + return fmt::format("{}", v->u); + default: + /* Shouldn't get here, but just in case... */ + return "unknown_type"; } - - /* not found, search pin list for name */ - pin = halpr_find_pin_by_name(name); - if(pin) { - /* found it */ - type = pin->type; - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - d_ptr = SHMPTR(sig->data_ptr); - } else { - sig = NULL; - d_ptr = &(pin->dummysig); - } - halcmd_output("%s\n", data_value2((int) type, d_ptr)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; - } - - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("pin or parameter '%s' not found\n", name); - return -EINVAL; } -int do_sets_cmd(char *name, char *value) +int do_getp_cmd(const char *name) { - int retval; - hal_sig_t *sig; - hal_type_t type; - void *d_ptr; - - rtapi_print_msg(RTAPI_MSG_DBG, "setting signal '%s'\n", name); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search signal list for name */ - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("signal '%s' not found\n", name); - return -EINVAL; - } - /* found it - it have a writer? if it is a port we can set its buffer size */ - if ((sig->type != HAL_PORT) && (sig->writers > 0)) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("signal '%s' already has writer(s)\n", name); - return -EINVAL; - } - /* no writer, so we can safely set it */ - type = sig->type; - d_ptr = SHMPTR(sig->data_ptr); - retval = set_common(type, d_ptr, value); - rtapi_mutex_give(&(hal_data->mutex)); - if (retval == 0) { - /* print success message */ - halcmd_info("Signal '%s' set to %s\n", name, value); + hal_query_t q = {}; + q.name = name; + int rv = hal_get_p(&q, NULL, NULL); + if(!rv) { + halcmd_output("%s\n", querydata_valuestr(q.pp.type, &q.pp.value).c_str()); } else { - halcmd_error("sets failed\n"); + const char *tag; + switch(q.qtype) { + case HAL_QTYPE_PARAM: tag = "parameter"; break; + case HAL_QTYPE_PIN: tag = "pin"; break; + default: tag = "parameter or pin"; break; + } + halcmd_error("%s '%s': %s\n", tag, name, hal_strerror(rv)); } - return retval; - + return rv; } -int do_stype_cmd(char *name) +int do_sets_cmd(const char *name, const char *value) { - hal_sig_t *sig; - hal_type_t type; - - rtapi_print_msg(RTAPI_MSG_DBG, "getting signal '%s'\n", name); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search signal list for name */ - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("signal '%s' not found\n", name); - return -EINVAL; + hal_query_t q = {}; + q.name = name; + int rv = hal_set_s(&q, setps_common_cb, (void *)value); + if(rv) { + halcmd_error("signal '%s': %s\n", name, hal_strerror(rv)); } - /* found it */ - type = sig->type; - halcmd_output("%s\n", data_type2(type)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; + return rv; } -int do_gets_cmd(char *name) +int do_stype_cmd(const char *name) { - hal_sig_t *sig; - hal_type_t type; - void *d_ptr; + hal_query_t q = {}; + q.name = name; + int rv = hal_getref_s(&q); + if(!rv) { + halcmd_output("%s\n", data_type2(q.sig.type)); + } else { + halcmd_error("signal '%s': %s\n", name, hal_strerror(rv)); + } + return rv; +} - rtapi_print_msg(RTAPI_MSG_DBG, "getting signal '%s'\n", name); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search signal list for name */ - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("signal '%s' not found\n", name); - return -EINVAL; +int do_gets_cmd(const char *name) +{ + hal_query_t q = {}; + q.name = name; + int rv = hal_get_s(&q, NULL, NULL); + if(!rv) { + halcmd_output("%s\n", querydata_valuestr(q.sig.type, &q.sig.value).c_str()); + } else { + halcmd_error("signal '%s': %s\n", name, hal_strerror(rv)); } - /* found it */ - type = sig->type; - d_ptr = SHMPTR(sig->data_ptr); - halcmd_output("%s\n", data_value2((int) type, d_ptr)); - rtapi_mutex_give(&(hal_data->mutex)); - return 0; + return rv; } -static int get_type(char ***patterns) { - char *typestr = NULL; +static int get_type(const char ***patterns) { + const char *typestr = NULL; if(!(*patterns)) return -1; if(!(*patterns)[0]) return -1; if((*patterns)[0][0] != '-' || (*patterns)[0][1] != 't') return -1; @@ -1019,19 +834,15 @@ static int get_type(char ***patterns) { *patterns += 2; } if(!typestr) return -1; - if(strcmp(typestr, "float") == 0) return HAL_FLOAT; - if(strcmp(typestr, "bit") == 0) return HAL_BIT; - if(strcmp(typestr, "s32") == 0) return HAL_S32; - if(strcmp(typestr, "u32") == 0) return HAL_U32; - if(strcmp(typestr, "s64") == 0) return HAL_S64; - if(strcmp(typestr, "u64") == 0) return HAL_U64; + hal_type_t htype = typestr_to_haltype(typestr, false); + if(htype != HAL_TYPE_UNINITIALIZED) + return htype; if(strcmp(typestr, "signed") == 0) return HAL_S32; if(strcmp(typestr, "unsigned") == 0) return HAL_U32; - if(strcmp(typestr, "port") == 0) return HAL_PORT; return -1; } -int do_show_cmd(char *type, char **patterns) +int do_show_cmd(const char *type, const char **patterns) { if (rtapi_get_msg_level() == RTAPI_MSG_NONE) { @@ -1091,7 +902,7 @@ int do_show_cmd(char *type, char **patterns) return 0; } -int do_list_cmd(char *type, char **patterns) +int do_list_cmd(const char *type, const char **patterns) { if ( !type) { halcmd_error("'list' requires type'\n"); @@ -1126,7 +937,7 @@ int do_list_cmd(char *type, char **patterns) return 0; } -int do_status_cmd(char *type) +int do_status_cmd(const char *type) { if (rtapi_get_msg_level() == RTAPI_MSG_NONE) { @@ -1149,13 +960,10 @@ int do_status_cmd(char *type) return 0; } -int do_loadrt_cmd(char *mod_name, char *args[]) +int do_loadrt_cmd(const char *mod_name, const char *args[]) { - char arg_string[MAX_CMD_LEN+1]; int m=0, n=0, retval; - hal_comp_t *comp; const char *argv[MAX_TOK+3]; - char *cp1; #if defined(RTAPI_USPACE) argv[m++] = "-Wn"; argv[m++] = mod_name; @@ -1227,174 +1035,128 @@ int do_loadrt_cmd(char *mod_name, char *args[]) return -1; } /* make the args that were passed to the module into a single string */ - n = 0; - arg_string[0] = '\0'; - while ( args[n] && args[n][0] != '\0' ) { - strncat(arg_string, args[n++], MAX_CMD_LEN); - strncat(arg_string, " ", MAX_CMD_LEN); + std::string arg_string; + for(int i = 0; args[i] && *args[i]; i++) { + if(i > 0) + arg_string += ' '; + arg_string += args[i]; } /* allocate HAL shmem for the string */ - cp1 = (char*)hal_malloc(strlen(arg_string)+1); - if ( cp1 == NULL ) { - halcmd_error("failed to allocate memory for module args\n"); - return -1; + char *halcpy = (char *)hal_malloc(arg_string.size() + 1); + if (NULL == halcpy) { + halcmd_error("failed to allocate memory for module args\n"); + return -1; } /* copy string to shmem */ - strcpy(cp1, arg_string); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search component list for the newly loaded component */ - comp = halpr_find_comp_by_name(mod_name); - if (comp == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("module '%s' not loaded\n", mod_name); - return -EINVAL; - } - /* link args to comp struct */ - comp->insmod_args = SHMOFF(cp1); - rtapi_mutex_give(&(hal_data->mutex)); + strcpy(halcpy, arg_string.c_str()); + hal_comp_insmod_args(mod_name, halcpy); + /* print success message */ halcmd_info("Realtime module '%s' loaded\n", mod_name); return 0; } -int do_delsig_cmd(char *mod_name) +static int delsig_cmd_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_sig_t) next; - int retval, retval1, n; - hal_sig_t *sig; - char sigs[MAX_EXPECTED_SIGS][HAL_NAME_LEN+1]; + std::vector *sigs = reinterpret_cast *>(arg); + sigs->push_back(q->name); + return 0; +} - /* check for "all" */ - if ( strcmp(mod_name, "all" ) != 0 ) { - retval = hal_signal_delete(mod_name); - if (retval == 0) { - /* print success message */ - halcmd_info("Signal '%s' deleted'\n", mod_name); - } - return retval; - } else { - /* build a list of signal(s) to delete */ - n = 0; - rtapi_mutex_get(&(hal_data->mutex)); - - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - /* we want to unload this signal, remember its name */ - if ( n < ( MAX_EXPECTED_SIGS - 1 ) ) { - snprintf(sigs[n], sizeof(sigs[n]), "%s", sig->name); - n++; - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); - sigs[n][0] = '\0'; +int do_delsig_cmd(const char *signame) +{ + if(strcmp(signame, "all")) { + // Only a single signal to delete + int rv = hal_signal_delete(signame); + // FIXME: This should keep quit on success and complain on failure. + // No news is good news mantra. + if(!rv) { + // print success message + halcmd_info("Signal '%s' deleted'\n", signame); + } + return rv; + } - if ( sigs[0][0] == '\0' ) { - /* desired signals not found */ - halcmd_error("no signals found to be deleted\n"); - return -1; - } - /* we now have a list of components, unload them */ - n = 0; - retval1 = 0; - while ( sigs[n][0] != '\0' ) { - retval = hal_signal_delete(sigs[n]); - /* check for fatal error */ - if ( retval < -1 ) { - return retval; - } - /* check for other error */ - if ( retval != 0 ) { - retval1 = retval; - } - if (retval == 0) { - /* print success message */ - halcmd_info("Signal '%s' deleted'\n", - sigs[n]); - } - n++; - } + // Build a list of signals to delete + std::vector sigs; + hal_query_t q = {}; + hal_list_s(&q, delsig_cmd_cb, (void *)&sigs); + + if(0 == sigs.size()) { + halcmd_error("no signals found to be deleted\n"); + return -1; + } + + for(const auto &sig : sigs) { + int rv = hal_signal_delete(sig.c_str()); + if(rv) { + halcmd_error("signal '%s' could not be deleted error=%d\n", sig.c_str(), rv); + return rv; + } + // FIXME: This should keep quit on success and complain on failure. + // No news is good news mantra. + halcmd_info("Signal '%s' deleted'\n", sig.c_str()); } - return retval1; + return 0; } -int do_unloadusr_cmd(char *mod_name) +static int do_unloadusr_cmd_cb(hal_query_t *q, void *) { - SHMFIELD(hal_comp_t) next; - int all; - hal_comp_t *comp; - pid_t ourpid = getpid(); + if(HAL_COMP_TYPE_USER == q->comp.type && q->comp.pid != q->callerdata.sival) + kill(abs(q->comp.pid), SIGTERM); + return 0; +} - /* check for "all" */ - if ( strcmp(mod_name, "all" ) == 0 ) { - all = 1; +int do_unloadusr_cmd(const char *mod_name) +{ + hal_query_t q = {}; + if(!strcmp(mod_name, "all")) { + q.callerdata.sival = (int)getpid(); + hal_list_comp(&q, do_unloadusr_cmd_cb, NULL); } else { - all = 0; - } - /* build a list of component(s) to unload */ - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_USER && comp->pid != ourpid) { - /* found a userspace component besides us */ - if ( all || ( strcmp(mod_name, comp->name) == 0 )) { - /* we want to unload this component, send it SIGTERM */ - kill(abs(comp->pid), SIGTERM); - } - } - next = comp->next_ptr; + int rv = hal_comp_by_name(mod_name, &q); + if(!rv) { + if(HAL_COMP_TYPE_USER == q.comp.type && q.comp.pid != (int)getpid()) + kill(abs(q.comp.pid), SIGTERM); + } } - rtapi_mutex_give(&(hal_data->mutex)); return 0; } - -int do_unloadrt_cmd(char *mod_name) +static int unloadrt_cmd_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_comp_t) next; - int retval, retval1, n, all; - hal_comp_t *comp; - char comps[64][HAL_NAME_LEN+1]; - - /* check for "all" */ - if ( strcmp(mod_name, "all" ) == 0 ) { - all = 1; - } else { - all = 0; + std::vector *comps = reinterpret_cast *>(arg); + if(HAL_COMP_TYPE_REALTIME == q->comp.type) { + comps->push_back(q->name); } - /* Build a list of component(s) to unload. hal_lib inserts new - components at the head of comp_list_ptr (see hal_init() in - hal_lib.c), so this traversal walks newest-first and produces - comps[] in newest-to-oldest order. The unload loop below relies - on that invariant: do not change one without the other. */ - n = 0; - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_REALTIME ) { - /* found a realtime component */ - if ( all || ( strcmp(mod_name, comp->name) == 0 )) { - /* we want to unload this component, remember its name */ - if ( n < 63 ) { - snprintf(comps[n], sizeof(comps[n]), "%s", comp->name); - n++; - } - } - } - next = comp->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); - /* mark end of list */ - comps[n][0] = '\0'; - if ( !all && ( comps[0][0] == '\0' )) { - /* desired component not found */ - halcmd_error("component '%s' is not loaded\n", mod_name); - return -1; + return 0; +} + +int do_unloadrt_cmd(const char *mod_name) +{ + if(strcmp(mod_name, "all")) { + int rv = hal_comp_by_name(mod_name, NULL); + if(rv) { + if(-ENOENT == rv) { + halcmd_error("component '%s' is not loaded\n", mod_name); + } else { + halcmd_error("hal_comp_by_name on '%s' returned error=%d\n", mod_name, rv); + } + return rv; + } + // One specific module and not 'all' + if(0 != (rv = unloadrt_comp(mod_name))) { + halcmd_error("unloadrt failed on '%s'\n", mod_name); + } + return rv; } + + // Need to unload all modules + // Build a list of loaded modules + std::vector comps; + hal_query_t q = {}; + hal_list_comp(&q, unloadrt_cmd_cb, (void *)&comps); + /* Unload newest first so dependent modules release their references before the ones they depend on are removed. This matters for kernel modules (RTAI) where rmmod refuses to unload an in-use @@ -1407,29 +1169,22 @@ int do_unloadrt_cmd(char *mod_name) this loop to match insmod order: you are doing the wrong thing, this IS already reverse-insmod order. See PR #3443 for an example of that exact mistake. */ - retval1 = 0; - for ( int i = 0; i < n; i++ ) { - // special case: initial prefix means it is not a real comp - if (strstr(comps[i],HAL_PSEUDO_COMP_PREFIX) == comps[i] ) { - continue; + int retval = 0; + for(const auto &comp : comps) { + // special case: pseudo prefix means it is not a real comp + if(0 == comp.find(HAL_PSEUDO_COMP_PREFIX)) { + continue; } - retval = unloadrt_comp(comps[i]); - /* check for fatal error */ - if ( retval < -1 ) { - return retval; - } - /* check for other error */ - if ( retval != 0 ) { - retval1 = retval; - } - } - if (retval1 < 0) { - halcmd_error("unloadrt failed\n"); + int rv = unloadrt_comp(comp.c_str()); + if(rv < -1) + return rv; // FIXME: This cannot happen because unloadrt_comp() only returns {0, -1} + if(rv) + retval = rv; } - return retval1; + return retval; } -static int unloadrt_comp(char *mod_name) +static int unloadrt_comp(const char *mod_name) { int retval; const char *argv[4]; @@ -1457,25 +1212,25 @@ static int unloadrt_comp(char *mod_name) return 0; } -int do_unload_cmd(char *mod_name) { +int do_unload_cmd(const char *mod_name) { if(strcmp(mod_name, "all") == 0) { int res = do_unloadusr_cmd(mod_name); if(res) return res; return do_unloadrt_cmd(mod_name); } else { - hal_comp_t *comp; - component_type_t type = COMPONENT_TYPE_UNKNOWN; - rtapi_mutex_get(&(hal_data->mutex)); - comp = halpr_find_comp_by_name(mod_name); - if(comp) type = comp->type; - rtapi_mutex_give(&(hal_data->mutex)); - if(type == COMPONENT_TYPE_UNKNOWN) { - halcmd_error("component '%s' is not loaded\n", - mod_name); + hal_query_t q = {}; + int rv = hal_comp_by_name(mod_name, &q); + if(0 != rv) { + if(-ENOENT == rv) + halcmd_error("component '%s' is not loaded\n", mod_name); + else + halcmd_error("do_unload_cmd: search component '%s' returned error=%d\n", mod_name, rv); return -1; } - if(type == COMPONENT_TYPE_REALTIME) return do_unloadrt_cmd(mod_name); - else return do_unloadusr_cmd(mod_name); + if(q.comp.type == HAL_COMP_TYPE_REALTIME) + return do_unloadrt_cmd(mod_name); + else + return do_unloadusr_cmd(mod_name); } } @@ -1516,13 +1271,18 @@ is not fixed or has regressed by debian jessie) } #include -#include + +static int get_all_comp_names_cb(hal_query_t *q, void *arg) +{ + std::set *comps = reinterpret_cast *>(arg); + comps->insert(q->name); + return 0; +} static std::set get_all_comp_names() { std::set result; - for(auto comp = hal_data->comp_list_ptr; comp; comp=comp->next_ptr) { - result.insert(comp->name); - } + hal_query_t q = {}; + hal_list_comp(&q, get_all_comp_names_cb, (void *)&result); return result; } @@ -1609,7 +1369,6 @@ int do_loadusr_cmd(const char *args[]) hal_ready(comp_id); if ( wait_comp_flag ) { int ready = 0, count=0, exited=0; - hal_comp_t *comp = NULL; retval = 0; while(!ready && !exited) { /* sleep for 10mS */ @@ -1626,12 +1385,11 @@ int do_loadusr_cmd(const char *args[]) } } /* check for program becoming ready */ - rtapi_mutex_get(&(hal_data->mutex)); - comp = halpr_find_comp_by_name(new_comp_name); - if(comp && comp->ready) { + hal_query_t q = {}; + int rv = hal_comp_by_name(new_comp_name, &q); + if(!rv && q.comp.ready) { ready = 1; } - rtapi_mutex_give(&(hal_data->mutex)); /* pacify the user */ count++; if(count == 200) { @@ -1690,527 +1448,444 @@ int do_loadusr_cmd(const char *args[]) } -int do_waitusr_cmd(char *comp_name) +int do_waitusr_cmd(const char *comp_name) { - hal_comp_t *comp; - int exited; - - if (*comp_name == '\0') { - halcmd_error("component name missing\n"); - return -EINVAL; + if (!comp_name || *comp_name == '\0') { + halcmd_error("component name missing\n"); + return -EINVAL; } - rtapi_mutex_get(&(hal_data->mutex)); - comp = halpr_find_comp_by_name(comp_name); - if (comp == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_info("component '%s' not found or already exited\n", comp_name); - return 0; + + hal_query_t q = {}; + int rv = hal_comp_by_name(comp_name, &q); + if (rv) { + halcmd_info("component '%s' not found or already exited\n", comp_name); + return 0; } - if (comp->type != COMPONENT_TYPE_USER) { - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_error("'%s' is not a userspace component\n", comp_name); - return -EINVAL; + if (q.comp.type != HAL_COMP_TYPE_USER) { + halcmd_error("'%s' is not a userspace component\n", comp_name); + return -EINVAL; } - rtapi_mutex_give(&(hal_data->mutex)); /* let the user know what is going on */ halcmd_info("Waiting for component '%s'\n", comp_name); - exited = 0; - while(!exited) { - /* sleep for 200mS */ - struct timespec ts = {0, 200 * 1000 * 1000}; - nanosleep(&ts, NULL); - /* check for component still around */ - rtapi_mutex_get(&(hal_data->mutex)); - comp = halpr_find_comp_by_name(comp_name); - if(comp == NULL) { - exited = 1; - } - rtapi_mutex_give(&(hal_data->mutex)); + while(1) { + /* sleep for 200mS */ + struct timespec ts = {0, 200 * 1000 * 1000}; + nanosleep(&ts, NULL); + /* check for component still around */ + if(0 != hal_comp_by_name(comp_name, NULL)) { + break; + } } halcmd_info("Component '%s' finished\n", comp_name); return 0; } - -static void print_comp_info(char **patterns) +static int print_comp_info_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_comp_t) next; - hal_comp_t *comp; + const char **patterns = (const char **)arg; + if(!match(patterns, q->name)) + return 0; + + switch(q->comp.type) { + case HAL_COMP_TYPE_USER: + case HAL_COMP_TYPE_REALTIME: + halcmd_output(" %5d %-4s %-*s", + q->comp.comp_id, + q->comp.type == HAL_COMP_TYPE_REALTIME ? "RT" : "User", + HAL_NAME_LEN, q->name); + if(q->comp.type == HAL_COMP_TYPE_USER) { + halcmd_output(" %5d %s", q->comp.pid, q->comp.ready ? "ready" : "initializing"); + } else { + halcmd_output(" %5s %s", "", q->comp.ready ? "ready" : "initializing"); + } + break; + case HAL_COMP_TYPE_OTHER: { + hal_query_t qc = {}; + // Need to reacquire the component name + int rv = hal_comp_by_id(q->comp.comp_id, &qc); + halcmd_output(" INST %s %s", !rv ? qc.name : "(unknown)", q->name); + } break; + default: + halcmd_output(" INVALID COMP TYPE %d for '%s'", (int)q->comp.type, q->name); + break; + } + halcmd_output("\n"); + return 0; +} +static void print_comp_info(const char **patterns) +{ if (scriptmode == 0) { halcmd_output("Loaded HAL Components:\n"); halcmd_output("ID Type %-*s PID State\n", HAL_NAME_LEN, "Name"); } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( match(patterns, comp->name) ) { - if(comp->type == COMPONENT_TYPE_OTHER) { - hal_comp_t *comp1 = halpr_find_comp_by_id(comp->comp_id & 0xffff); - halcmd_output(" INST %s %s", - comp1 ? comp1->name : "(unknown)", - comp->name); - } else { - halcmd_output(" %5d %-4s %-*s", - comp->comp_id, (comp->type == COMPONENT_TYPE_REALTIME) ? "RT" : "User", - HAL_NAME_LEN, comp->name); - if(comp->type == COMPONENT_TYPE_USER) { - halcmd_output(" %5d %s", comp->pid, comp->ready > 0 ? - "ready" : "initializing"); - } else { - halcmd_output(" %5s %s", "", comp->ready > 0 ? - "ready" : "initializing"); - } - } - halcmd_output("\n"); - } - next = comp->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + hal_list_comp(&q, print_comp_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_pin_info(int type, char **patterns) +static int print_pin_info_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_pin_t) next; - hal_pin_t *pin; - hal_comp_t *comp; - hal_sig_t *sig; - void *dptr; + const char **patterns = (const char **)arg; + if(!tmatch(q->callerdata.sival, q->pp.type) || !match(patterns, q->name)) + return 0; + + if (scriptmode == 0) { + halcmd_output(" %5d %5s %-3s %9s %s", + q->pp.comp_id, + data_type(q->pp.type), + pin_data_dir(q->pp.dir), + querydata_refstr_20(q->pp.type, q->pp.ref).c_str(), + q->name); + } else { + halcmd_output("%s %s %s %s %s", + q->pp.comp, + data_type(q->pp.type), + pin_data_dir(q->pp.dir), + querydata_refstr(q->pp.type, q->pp.ref).c_str(), + q->name); + } + if (q->pp.signal == NULL) { + halcmd_output("\n"); + } else { + halcmd_output(" %s %s\n", data_arrow1(q->pp.dir), q->pp.signal); + } + return 0; +} +static void print_pin_info(int type, const char **patterns) +{ if (scriptmode == 0) { halcmd_output("Component Pins:\n"); halcmd_output("Owner Type Dir Value Name\n"); } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if ( tmatch(type, pin->type) && match(patterns, pin->name) ) { - comp = SHMPTR(pin->owner_ptr); - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - dptr = SHMPTR(sig->data_ptr); - } else { - sig = NULL; - dptr = &(pin->dummysig); - } - if (scriptmode == 0) { - halcmd_output(" %5d %5s %-3s %9s %s", - comp->comp_id, - data_type((int) pin->type), - pin_data_dir((int) pin->dir), - data_value((int) pin->type, dptr), - pin->name); - } else { - halcmd_output("%s %s %s %s %s", - comp->name, - data_type((int) pin->type), - pin_data_dir((int) pin->dir), - data_value2((int) pin->type, dptr), - pin->name); - } - if (sig == NULL) { - halcmd_output("\n"); - } else { - halcmd_output(" %s %s\n", data_arrow1((int) pin->dir), sig->name); - } - } - next = pin->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + q.callerdata.sival = type; + hal_list_p(&q, print_pin_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_pin_aliases(char **patterns) +static int print_pin_aliases_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_pin_t) next; - hal_oldname_t *oldname; - hal_pin_t *pin; + const char **patterns = (const char **)arg; + if(q->pp.alias) { + /* name is an alias */ + if(!match(patterns, q->name) && !match(patterns, q->pp.alias)) + return 0; + if(scriptmode == 0) { + halcmd_output(" %-*s %s\n", HAL_NAME_LEN, q->name, q->pp.alias); + } else { + halcmd_output(" %s %s\n", q->name, q->pp.alias); + } + } + return 0; +} +static void print_pin_aliases(const char **patterns) +{ if (scriptmode == 0) { halcmd_output("Pin Aliases:\n"); halcmd_output(" %-*s %s\n", HAL_NAME_LEN, "Alias", "Original Name"); } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if ( pin->oldname != 0 ) { - /* name is an alias */ - oldname = SHMPTR(pin->oldname); - if ( match(patterns, pin->name) || match(patterns, oldname->name) ) { - if (scriptmode == 0) { - halcmd_output(" %-*s %s\n", HAL_NAME_LEN, pin->name, oldname->name); - } else { - halcmd_output(" %s %s\n", pin->name, oldname->name); - } - } - } - next = pin->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + hal_list_p(&q, print_pin_aliases_cb, (void *)patterns); halcmd_output("\n"); } -static void print_sig_info(int type, char **patterns) +static int print_sig_pin_info_cb(hal_query_t *q, void *) { - SHMFIELD(hal_sig_t) next; - hal_sig_t *sig; - void *dptr; - hal_pin_t *pin; + halcmd_output("%32s %s %s\n", "", data_arrow2(q->pp.dir), q->name); + return 0; +} + +static int print_sig_info_cb(hal_query_t *q, void *arg) +{ + const char **patterns = (const char **)arg; + if(!tmatch(q->callerdata.sival, q->sig.type) || !match(patterns, q->name)) + return 0; + + halcmd_output("%s %s %s\n", + data_type(q->sig.type), + querydata_refstr_20(q->sig.type, q->sig.ref).c_str(), + q->name); + + // List all pins connected to the signal + hal_query_t qs = {}; + qs.name = q->name; + hal_list_p_s(&qs, print_sig_pin_info_cb, NULL); + return 0; +} +static void print_sig_info(int type, const char **patterns) +{ if (scriptmode != 0) { print_script_sig_info(type, patterns); return; } halcmd_output("Signals:\n"); halcmd_output("Type Value Name (linked to)\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - if ( tmatch(type, sig->type) && match(patterns, sig->name) ) { - dptr = SHMPTR(sig->data_ptr); - halcmd_output("%s %s %s\n", data_type((int) sig->type), - data_value((int) sig->type, dptr), sig->name); - /* look for pin(s) linked to this signal */ - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - halcmd_output(" %s %s\n", - data_arrow2((int) pin->dir), pin->name); - pin = halpr_find_pin_by_sig(sig, pin); - } - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + + hal_query_t q = {}; + q.callerdata.sival = type; + hal_list_s(&q, print_sig_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_script_sig_info(int type, char **patterns) +static int print_script_sig_pin_info_cb(hal_query_t *q, void *) { - SHMFIELD(hal_sig_t) next; - hal_sig_t *sig; - void *dptr; - hal_pin_t *pin; + halcmd_output(" %s %s", data_arrow2(q->pp.dir), q->name); + return 0; +} - if (scriptmode == 0) { +static int print_script_sig_info_cb(hal_query_t *q, void *arg) +{ + const char **patterns = (const char **)arg; + if(!tmatch(q->callerdata.sival, q->sig.type) || !match(patterns, q->name)) + return 0; + + halcmd_output("%s %s %s", data_type(q->sig.type), querydata_refstr(q->sig.type, q->sig.ref).c_str(), q->name); + + // List all pins connected to the signal + hal_query_t qs = {}; + qs.name = q->name; + hal_list_p_s(&qs, print_script_sig_pin_info_cb, NULL); + halcmd_output("\n"); + return 0; +} + +static void print_script_sig_info(int type, const char **patterns) +{ + if(!scriptmode) return; - } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - if ( tmatch(type, sig->type) && match(patterns, sig->name) ) { - dptr = SHMPTR(sig->data_ptr); - halcmd_output("%s %s %s", data_type((int) sig->type), - data_value2((int) sig->type, dptr), sig->name); - /* look for pin(s) linked to this signal */ - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - halcmd_output(" %s %s", - data_arrow2((int) pin->dir), pin->name); - pin = halpr_find_pin_by_sig(sig, pin); - } - halcmd_output("\n"); - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.callerdata.sival = type; + hal_list_s(&q, print_script_sig_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_param_info(int type, char **patterns) +static int print_param_info_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_param_t) next; - hal_param_t *param; - hal_comp_t *comp; + const char **patterns = (const char **)arg; + if(!tmatch(q->callerdata.sival, q->pp.type) || !match(patterns, q->name)) + return 0; - if (scriptmode == 0) { + if(!scriptmode) { + halcmd_output(" %5d %5s %-3s %9s %s\n", + q->pp.comp_id, + data_type(q->pp.type), + param_data_dir(q->pp.dir), + querydata_refstr_20(q->pp.type, q->pp.ref).c_str(), + q->name); + } else { + halcmd_output("%s %s %s %s %s\n", + q->pp.comp, + data_type(q->pp.type), + param_data_dir(q->pp.dir), + querydata_refstr(q->pp.type, q->pp.ref).c_str(), + q->name); + } + return 0; +} + +static void print_param_info(int type, const char **patterns) +{ + if(!scriptmode) { halcmd_output("Parameters:\n"); halcmd_output("Owner Type Dir Value Name\n"); } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( tmatch(type, param->type), match(patterns, param->name) ) { - comp = SHMPTR(param->owner_ptr); - if (scriptmode == 0) { - halcmd_output(" %5d %5s %-3s %9s %s\n", - comp->comp_id, data_type((int) param->type), - param_data_dir((int) param->dir), - data_value((int) param->type, SHMPTR(param->data_ptr)), - param->name); - } else { - halcmd_output("%s %s %s %s %s\n", - comp->name, data_type((int) param->type), - param_data_dir((int) param->dir), - data_value2((int) param->type, SHMPTR(param->data_ptr)), - param->name); - } - } - next = param->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.callerdata.sival = type; + q.qtype = HAL_QTYPE_PARAM; + hal_list_p(&q, print_param_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_param_aliases(char **patterns) +static int print_param_aliases_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_param_t) next; - hal_oldname_t *oldname; - hal_param_t *param; + const char **patterns = (const char **)arg; + if(NULL == q->pp.alias) + return 0; + if(!match(patterns, q->name) && !match(patterns, q->pp.alias)) + return 0; - if (scriptmode == 0) { - halcmd_output("Parameter Aliases:\n"); - halcmd_output(" %-*s %s\n", HAL_NAME_LEN, "Alias", "Original Name"); + // name is an alias + if(!scriptmode) { + halcmd_output(" %-*s %s\n", HAL_NAME_LEN, q->name, q->pp.alias); + } else { + halcmd_output(" %s %s\n", q->name, q->pp.alias); } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( param->oldname != 0 ) { - /* name is an alias */ - oldname = SHMPTR(param->oldname); - if ( match(patterns, param->name) || match(patterns, oldname->name) ) { - if (scriptmode == 0) { - halcmd_output(" %-*s %s\n", HAL_NAME_LEN, param->name, oldname->name); - } else { - halcmd_output(" %s %s\n", param->name, oldname->name); - } - } - } - next = param->next_ptr; + return 0; +} + +static void print_param_aliases(const char **patterns) +{ + if(!scriptmode) { + halcmd_output("Parameter Aliases:\n"); + halcmd_output(" %-*s %s\n", HAL_NAME_LEN, "Alias", "Original Name"); } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; // Only parameters + hal_list_p(&q, print_param_aliases_cb, (void *)patterns); halcmd_output("\n"); } -static void print_funct_info(char **patterns) +static int print_funct_info_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_funct_t) next; - hal_funct_t *fptr; - hal_comp_t *comp; + const char **patterns = (const char **)arg; + if(!match(patterns, q->name)) + return 0; + if(!scriptmode) { + halcmd_output(" %05d %08llx %08llx %-3s %5d %s\n", + q->funct.comp_id, + (long long)q->funct.funct, + (long long)q->funct.arg, + "YES", // Always uses FP + q->funct.users, + q->name); + } else { + halcmd_output("%s %08llx %08llx %s %3d %s\n", + q->funct.comp, + (long long)q->funct.funct, + (long long)q->funct.arg, + "YES", // Always uses FP + q->funct.users, + q->name); + } + return 0; +} - if (scriptmode == 0) { - halcmd_output("Exported Functions:\n"); - halcmd_output("Owner CodeAddr Arg FP Users Name\n"); - } - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->funct_list_ptr; - while (next != 0) { - fptr = SHMPTR(next); - if ( match(patterns, fptr->name) ) { - comp = SHMPTR(fptr->owner_ptr); - if (scriptmode == 0) { - halcmd_output(" %05d %08lx %08lx %-3s %5d %s\n", - comp->comp_id, - (long)fptr->funct, - (long)fptr->arg, (fptr->uses_fp ? "YES" : "NO"), - fptr->users, fptr->name); - } else { - halcmd_output("%s %08lx %08lx %s %3d %s\n", - comp->name, - (long)fptr->funct, - (long)fptr->arg, (fptr->uses_fp ? "YES" : "NO"), - fptr->users, fptr->name); - } - } - next = fptr->next_ptr; +static void print_funct_info(const char **patterns) +{ + if(!scriptmode) { + halcmd_output("Exported Functions:\n"); + halcmd_output("Owner CodeAddr Arg FP Users Name\n"); } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + hal_list_funct(&q, print_funct_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_thread_info(char **patterns) +static int print_thread_info_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_thread_t) next_thread; - int n; - hal_thread_t *tptr; - hal_list_t *list_root, *list_entry; - hal_funct_entry_t *fentry; - hal_funct_t *funct; - - if (scriptmode == 0) { - halcmd_output("Realtime Threads:\n"); - halcmd_output(" Period FP Name ( Time, Max-Time )\n"); - } - rtapi_mutex_get(&(hal_data->mutex)); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - tptr = SHMPTR(next_thread); - if ( match(patterns, tptr->name) ) { - /* note that the scriptmode format string has no \n */ - char name[HAL_NAME_LEN+1]; - hal_pin_t* pin; - hal_sig_t *sig; - void *dptr; - - size_t ret = snprintf(name, sizeof(name), "%s.time",tptr->name); - if (ret >= sizeof(name)){ - rtapi_print_msg(RTAPI_MSG_ERR, - "unexpected: pin name too long for buffer %s",tptr->name); - } else { + const char **patterns = (const char **)arg; + if(!match(patterns, q->name)) + return 0; - pin = halpr_find_pin_by_name(name); - if (pin) { - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - dptr = SHMPTR(sig->data_ptr); - } else { - sig = NULL; - dptr = &(pin->dummysig); - } - - halcmd_output(((scriptmode == 0) ? "%11ld %-3s %20s ( %8ld, %8ld )\n" - : "%ld %s %s %8ld %ld"), - tptr->period, - (tptr->uses_fp ? "YES" : "NO"), - tptr->name, - (long)*(long*)dptr, - (long)tptr->maxtime); - } else { - rtapi_print_msg(RTAPI_MSG_ERR, - "unexpected: cannot find time pin for %s thread",tptr->name); - } - } + // The first callback is on the pure thread data + if(HAL_QTYPE_THREAD == q->qtype) { + char tname[HAL_NAME_LEN+1]; + char mname[HAL_NAME_LEN+1]; + size_t ret = snprintf(tname, sizeof(tname), "%s.time", q->name); + if (ret >= sizeof(tname)) { + rtapi_print_msg(RTAPI_MSG_ERR, "unexpected: time pin name too long for buffer %s\n", q->name); + return 0; + } + ret = snprintf(mname, sizeof(mname), "%s.tmax", q->name); + if (ret >= sizeof(mname)) { + rtapi_print_msg(RTAPI_MSG_ERR, "unexpected: tmax pin name too long for buffer %s\n", q->name); + return 0; + } + hal_query_t qt = {}; + qt.name = tname; + hal_query_t qm = {}; + qm.name = mname; + int rvt = hal_getref_p(&qt); + int rvm = hal_getref_p(&qm); + if(!rvt && !rvm) { + // note that the scriptmode format string has no \n + halcmd_output((!scriptmode ? "%11ld %-3s %20s ( %8ld, %8ld )\n" : "%ld %s %s %8ld %ld"), + q->thread.period, + "YES", // Always uses FP + q->name, + (long)hal_get_sint(qt.pp.ref.s), + (long)hal_get_sint(qm.pp.ref.s)); + } else { + rtapi_print_msg(RTAPI_MSG_ERR, "unexpected: cannot find time/tmax pin for %s thread\n", q->name); + } + } + // Any attached function has a different connection ID + if(HAL_QTYPE_THREAD_FUNCT == q->qtype) { + if(!scriptmode) { + halcmd_output(" %2d %s\n", q->thread.functidx + 1, q->thread.funct); + } else { + // scriptmode only uses one line per thread, which contains: + // thread period, FP flag, name, then all functs separated by spaces + halcmd_output(" %s", q->thread.funct); + } + } - list_root = &(tptr->funct_list); - list_entry = list_next(list_root); - n = 1; - while (list_entry != list_root) { - /* print the function info */ - fentry = reinterpret_cast(list_entry); - funct = SHMPTR(fentry->funct_ptr); - /* scriptmode only uses one line per thread, which contains: - thread period, FP flag, name, then all functs separated by spaces */ - if (scriptmode == 0) { - halcmd_output(" %2d %s\n", n, funct->name); - } else { - halcmd_output(" %s", funct->name); - } - n++; - list_entry = list_next(list_entry); - } - if (scriptmode != 0) { - halcmd_output("\n"); - } - } - next_thread = tptr->next_ptr; + if(scriptmode) { + halcmd_output("\n"); } - rtapi_mutex_give(&(hal_data->mutex)); - halcmd_output("\n"); + return 0; } -static void print_comp_names(char **patterns) +static void print_thread_info(const char **patterns) { - SHMFIELD(hal_comp_t) next; - hal_comp_t *comp; - - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( match(patterns, comp->name) ) { - halcmd_output("%s ", comp->name); - } - next = comp->next_ptr; + if(!scriptmode) { + halcmd_output("Realtime Threads:\n"); + halcmd_output(" Period FP Name ( Time, Max-Time )\n"); } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; // Callback on both threads and functions attached + hal_list_thread(&q, print_thread_info_cb, (void *)patterns); halcmd_output("\n"); } -static void print_pin_names(char **patterns) +static int print_any_names_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_pin_t) next; - hal_pin_t *pin; + const char **patterns = (const char **)arg; + if(!match(patterns, q->name)) + return 0; + halcmd_output("%s ", q->name); + return 0; +} - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if ( match(patterns, pin->name) ) { - halcmd_output("%s ", pin->name); - } - next = pin->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); +static void print_comp_names(const char **patterns) +{ + hal_query_t q = {}; + hal_list_comp(&q, print_any_names_cb, (void *)patterns); halcmd_output("\n"); } -static void print_sig_names(char **patterns) +static void print_pin_names(const char **patterns) { - SHMFIELD(hal_sig_t) next; - hal_sig_t *sig; - - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - if ( match(patterns, sig->name) ) { - halcmd_output("%s ", sig->name); - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; // Pins only + hal_list_p(&q, print_any_names_cb, (void *)patterns); halcmd_output("\n"); } -static void print_param_names(char **patterns) +static void print_sig_names(const char **patterns) { - SHMFIELD(hal_param_t) next; - hal_param_t *param; - - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( match(patterns, param->name) ) { - halcmd_output("%s ", param->name); - } - next = param->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + hal_list_s(&q, print_any_names_cb, (void *)patterns); halcmd_output("\n"); } -static void print_funct_names(char **patterns) +static void print_param_names(const char **patterns) { - SHMFIELD(hal_funct_t) next; - hal_funct_t *fptr; - - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->funct_list_ptr; - while (next != 0) { - fptr = SHMPTR(next); - if ( match(patterns, fptr->name) ) { - halcmd_output("%s ", fptr->name); - } - next = fptr->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; // Parameters only + hal_list_p(&q, print_any_names_cb, (void *)patterns); halcmd_output("\n"); } -static void print_thread_names(char **patterns) +static void print_funct_names(const char **patterns) { - SHMFIELD(hal_thread_t) next_thread; - hal_thread_t *tptr; + hal_query_t q = {}; + hal_list_funct(&q, print_any_names_cb, (void *)patterns); + halcmd_output("\n"); +} - rtapi_mutex_get(&(hal_data->mutex)); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - tptr = SHMPTR(next_thread); - if ( match(patterns, tptr->name) ) { - halcmd_output("%s ", tptr->name); - } - next_thread = tptr->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); +static void print_thread_names(const char **patterns) +{ + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD; // Only thread names + hal_list_thread(&q, print_any_names_cb, (void *)patterns); halcmd_output("\n"); } @@ -2235,325 +1910,150 @@ static void print_lock_status() halcmd_output(" HAL_LOCK_RUN - running/stopping HAL is locked\n"); } -template -int count_list(SHMFIELD(T) list_root) -{ - int n; - SHMFIELD(T) next; - - rtapi_mutex_get(&(hal_data->mutex)); - next = list_root; - n = 0; - while (next != 0) { - n++; - next = SHMPTR(next)->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); - return n; -} - static void print_mem_status() { - int active, recycled; - hal_pin_t *pin; - hal_param_t *param; + hal_statistics_t s = {}; + int rv = hal_statistics(&s); + if(0 != rv) { + halcmd_error("print_mem_status: failed to get HAL statistics, error=%d\n", rv); + return; + } halcmd_output("HAL memory status\n"); - halcmd_output(" used/total shared memory: %ld/%d\n", (long)(HAL_SIZE - hal_data->shmem_avail), HAL_SIZE); - // count components - active = count_list(hal_data->comp_list_ptr); - recycled = count_list(hal_data->comp_free_ptr); - halcmd_output(" active/recycled components: %d/%d\n", active, recycled); - // count pins - active = count_list(hal_data->pin_list_ptr); - recycled = count_list(hal_data->pin_free_ptr); - halcmd_output(" active/recycled pins: %d/%d\n", active, recycled); - // count parameters - active = count_list(hal_data->param_list_ptr); - recycled = count_list(hal_data->param_free_ptr); - halcmd_output(" active/recycled parameters: %d/%d\n", active, recycled); - // count aliases - rtapi_mutex_get(&(hal_data->mutex)); - { - SHMFIELD(hal_pin_t) next = hal_data->pin_list_ptr; - active = 0; - while (next != 0) { - pin = SHMPTR(next); - if ( pin->oldname != 0 ) active++; - next = pin->next_ptr; - } - } - { - SHMFIELD(hal_param_t) next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( param->oldname != 0 ) active++; - next = param->next_ptr; - } - } - rtapi_mutex_give(&(hal_data->mutex)); - recycled = count_list(hal_data->oldname_free_ptr); - halcmd_output(" active/recycled aliases: %d/%d\n", active, recycled); - // count signals - active = count_list(hal_data->sig_list_ptr); - recycled = count_list(hal_data->sig_free_ptr); - halcmd_output(" active/recycled signals: %d/%d\n", active, recycled); - // count functions - active = count_list(hal_data->funct_list_ptr); - recycled = count_list(hal_data->funct_free_ptr); - halcmd_output(" active/recycled functions: %d/%d\n", active, recycled); - // count threads - active = count_list(hal_data->thread_list_ptr); - recycled = count_list(hal_data->thread_free_ptr); - halcmd_output(" active/recycled threads: %d/%d\n", active, recycled); + halcmd_output(" used/total shared memory: %ld/%ld\n", (long)(s.mem_total - s.mem_free), (long)s.mem_total); + halcmd_output(" active/recycled components: %d/%d\n", s.ncomps, s.ncomps_free); + halcmd_output(" active/recycled pins: %d/%d\n", s.npins, s.npins_free); + halcmd_output(" active/recycled parameters: %d/%d\n", s.nparams, s.nparams_free); + halcmd_output(" active/recycled aliases: %d/%d\n", s.naliases, s.naliases_free); + halcmd_output(" active/recycled signals: %d/%d\n", s.nsignals, s.nsignals_free); + halcmd_output(" active/recycled functions: %d/%d\n", s.nfuncts, s.nfuncts_free); + halcmd_output(" active/recycled threads: %d/%d\n", s.nthreads, s.nthreads_free); } /* Switch function for pin/sig/param type for the print_*_list functions */ -static const char *data_type(int type) +static const char *data_type(hal_type_t type) { - const char *type_str; - switch (type) { - case HAL_BIT: - type_str = "bit "; - break; - case HAL_FLOAT: - type_str = "float"; - break; - case HAL_S32: - type_str = "s32 "; - break; - case HAL_U32: - type_str = "u32 "; - break; - case HAL_S64: - type_str = "s64 "; - break; - case HAL_U64: - type_str = "u64 "; - break; - case HAL_PORT: - type_str = "port "; - break; - default: - /* Shouldn't get here, but just in case... */ - type_str = "undef"; + case HAL_BOOL: return "bit "; + case HAL_REAL: return "float"; + case HAL_S32: return "s32 "; + case HAL_U32: return "u32 "; + case HAL_SINT: return "s64 "; + case HAL_UINT: return "u64 "; + case HAL_PORT: return "port "; + default: return "undef"; /* Shouldn't get here, but just in case... */ } - return type_str; } -static const char *data_type2(int type) +static const char *data_type2(hal_type_t type) { - const char *type_str; - switch (type) { - case HAL_BIT: - type_str = "bit"; - break; - case HAL_FLOAT: - type_str = "float"; - break; - case HAL_S32: - type_str = "s32"; - break; - case HAL_U32: - type_str = "u32"; - break; - case HAL_S64: - type_str = "s64"; - break; - case HAL_U64: - type_str = "u64"; - break; - case HAL_PORT: - type_str = "port"; - break; - default: - /* Shouldn't get here, but just in case... */ - type_str = "undef"; + case HAL_BOOL: return "bit"; + case HAL_REAL: return "float"; + case HAL_S32: return "s32"; + case HAL_U32: return "u32"; + case HAL_SINT: return "s64"; + case HAL_UINT: return "u64"; + case HAL_PORT: return "port"; + default: return "undef"; /* Shouldn't get here, but just in case... */ } - return type_str; } /* Switch function for pin direction for the print_*_list functions */ -static const char *pin_data_dir(int dir) +static const char *pin_data_dir(hal_pdir_t dir) { - const char *pin_dir; - switch (dir) { - case HAL_IN: - pin_dir = "IN"; - break; - case HAL_OUT: - pin_dir = "OUT"; - break; - case HAL_IO: - pin_dir = "I/O"; - break; - default: - /* Shouldn't get here, but just in case... */ - pin_dir = "???"; + case HAL_IN: return "IN"; + case HAL_OUT: return "OUT"; + case HAL_IO: return "I/O"; + default: return "???"; /* Shouldn't get here, but just in case... */ } - return pin_dir; } /* Switch function for param direction for the print_*_list functions */ -static const char *param_data_dir(int dir) +static const char *param_data_dir(hal_pdir_t dir) { - const char *param_dir; - switch (dir) { - case HAL_RO: - param_dir = "RO"; - break; - case HAL_RW: - param_dir = "RW"; - break; - default: - /* Shouldn't get here, but just in case... */ - param_dir = "??"; + case HAL_RO: return "RO"; + case HAL_RW: return "RW"; + default: return "??"; /* Shouldn't get here, but just in case... */ } - return param_dir; } /* Switch function for arrow direction for the print_*_list functions */ -static const char *data_arrow1(int dir) +static const char *data_arrow1(hal_pdir_t dir) { - const char *arrow; - switch (dir) { - case HAL_IN: - arrow = "<=="; - break; - case HAL_OUT: - arrow = "==>"; - break; - case HAL_IO: - arrow = "<=>"; - break; - default: - /* Shouldn't get here, but just in case... */ - arrow = "???"; + case HAL_IN: return "<=="; + case HAL_OUT: return "==>"; + case HAL_IO: return "<=>"; + default: return "???"; /* Shouldn't get here, but just in case... */ } - return arrow; } /* Switch function for arrow direction for the print_*_list functions */ -static const char *data_arrow2(int dir) +static const char *data_arrow2(hal_pdir_t dir) { - const char *arrow; - switch (dir) { - case HAL_IN: - arrow = "==>"; - break; - case HAL_OUT: - arrow = "<=="; - break; - case HAL_IO: - arrow = "<=>"; - break; - default: - /* Shouldn't get here, but just in case... */ - arrow = "???"; + case HAL_IN: return "==>"; + case HAL_OUT: return "<=="; + case HAL_IO: return "<=>"; + default: return "???"; /* Shouldn't get here, but just in case... */ } - return arrow; } /* Switch function to return var value for the print_*_info functions (scriptmode = 0) as well as save_params() and save_unconnected_input_pin_values(). The value is printed in a 20 character wide field. */ -static const char *data_value(int type, void *valptr) +static std::string querydata_refstr_20(hal_type_t type, hal_refs_u u) { - const char *value_str; - static char buf[21]; - - switch (type) { - case HAL_BIT: - if (*((char *) valptr) == 0) - value_str = " FALSE"; - else - value_str = " TRUE"; - break; - case HAL_FLOAT: - snprintf(buf, 21, "%20.7g", (double)*((hal_float_t *) valptr)); - value_str = buf; - break; + switch(type) { + case HAL_BOOL: + return fmt::format("{:>20s}", hal_get_bool(u.b) ? "TRUE" : "FALSE"); + case HAL_REAL: + return fmt::format("{:20.7g}", hal_get_real(u.r)); case HAL_S32: - snprintf(buf, 21, "%20ld", (long)*((hal_s32_t *) valptr)); - value_str = buf; - break; - case HAL_U32: - snprintf(buf, 21, " 0x%08lX", (unsigned long)*((hal_u32_t *) valptr)); - value_str = buf; - break; - case HAL_S64: - snprintf(buf, 21, "%20" PRId64, (int64_t)*((hal_s64_t *) valptr)); - value_str = buf; - break; - case HAL_U64: - snprintf(buf, 21, " 0x%016" PRIX64, (uint64_t)*((hal_u64_t *) valptr)); - value_str = buf; - break; + return fmt::format("{:20d}", (long)hal_get_si32(u.s)); + case HAL_SINT: case HAL_PORT: - snprintf(buf, 21, "%20u", hal_port_buffer_size((hal_port_t*) valptr)); - value_str = buf; - break; + return fmt::format("{:20d}", (long long)hal_get_sint(u.s)); + case HAL_U32: + return fmt::format(" 0x{:08X}", (unsigned long)hal_get_ui32(u.u)); + case HAL_UINT: + return fmt::format(" 0x{:016X}", (unsigned long long)hal_get_uint(u.u)); default: /* Shouldn't get here, but just in case... */ - value_str = " undef "; + return " undef "; } - return value_str; } /* Switch function to return var value in string form for the print_*_info functions (scriptmode = 1) and getp and gets command. The value is printed as a packed string (no whitespaces). */ -static const char *data_value2(int type, void *valptr) +static std::string querydata_refstr(hal_type_t type, hal_refs_u u) { - const char *value_str; - static char buf[21]; - - switch (type) { - case HAL_BIT: - if (*((char *) valptr) == 0) - value_str = "FALSE"; - else - value_str = "TRUE"; - break; - case HAL_FLOAT: - snprintf(buf, 14, "%.7g", (double)*((hal_float_t *) valptr)); - value_str = buf; - break; + switch(type) { + case HAL_BOOL: + return hal_get_bool(u.b) ? "TRUE" : "FALSE"; + case HAL_REAL: + return fmt::format("{:.7g}", hal_get_real(u.r)); case HAL_S32: - snprintf(buf, 14, "%ld", (long)*((hal_s32_t *) valptr)); - value_str = buf; - break; - case HAL_U32: - snprintf(buf, 14, "%lu", (unsigned long)*((hal_u32_t *) valptr)); - value_str = buf; - break; - case HAL_S64: - snprintf(buf, 21, "%" PRId64, (int64_t)*((hal_s64_t *) valptr)); - value_str = buf; - break; - case HAL_U64: - snprintf(buf, 21, "%" PRIu64, (uint64_t)*((hal_u64_t *) valptr)); - value_str = buf; - break; + return fmt::format("{}", hal_get_si32(u.s)); + case HAL_SINT: case HAL_PORT: - snprintf(buf, 14, "%u", hal_port_buffer_size((hal_port_t*) valptr)); - value_str = buf; - break; - + return fmt::format("{}", hal_get_sint(u.s)); + case HAL_U32: + return fmt::format("{}", hal_get_ui32(u.u)); + case HAL_UINT: + return fmt::format("{}", hal_get_uint(u.u)); default: /* Shouldn't get here, but just in case... */ - value_str = "unknown_type"; + return "unknown_type"; } - return value_str; } -int do_save_cmd(const char *type, char *filename) + +int do_save_cmd(const char *type, const char *filename) { FILE *dst; @@ -2626,300 +2126,310 @@ int do_save_cmd(const char *type, char *filename) return 0; } +struct _comp_save_data_t { + const char *name; + const char *insmod; +}; + +static int save_comp_cb(hal_query_t *q, void *arg) +{ + std::vector<_comp_save_data_t> *v = (std::vector<_comp_save_data_t> *)arg; + if(HAL_COMP_TYPE_REALTIME == q->comp.type) + v->push_back({q->name, q->comp.insmod}); + return 0; +} + static void save_comps(FILE *dst) { - SHMFIELD(hal_comp_t) next; - hal_comp_t *comp; + hal_query_t q = {}; + std::vector<_comp_save_data_t> compdata; + hal_list_comp(&q, save_comp_cb, (void *)&compdata); fprintf(dst, "# components\n"); - rtapi_mutex_get(&(hal_data->mutex)); - - int ncomps = 0; - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_REALTIME ) { - ncomps ++; - } - next = comp->next_ptr; - } - - if(!ncomps) { + if(0 == compdata.size()) { // No components found, bail - rtapi_mutex_give(&(hal_data->mutex)); return; - } - - std::vector comps(ncomps, NULL); - hal_comp_t **compptr = comps.data(); - next = hal_data->comp_list_ptr; - while(next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_REALTIME ) { - *compptr++ = SHMPTR(next); - } - next = comp->next_ptr; } - int i; - for(i=ncomps; i--;) - { - comp = comps[i]; - /* only print realtime components */ - if ( comp->insmod_args == 0 ) { - fprintf(dst, "#loadrt %s (not loaded by loadrt, no args saved)\n", comp->name); + for(auto i = compdata.rbegin(); i != compdata.rend(); ++i) { + if(NULL == i->insmod) { + fprintf(dst, "#loadrt %s (not loaded by loadrt, no args saved)\n", i->name); } else { - fprintf(dst, "loadrt %s %s\n", comp->name, - (char *)SHMPTR(comp->insmod_args)); + fprintf(dst, "loadrt %s %s\n", i->name, i->insmod); } } -#if 0 /* newinst deferred to version 2.2 */ - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == 2 ) { - hal_comp_t *comp1 = halpr_find_comp_by_id(comp->comp_id & 0xffff); - fprintf(dst, "newinst %s %s\n", comp1->name, comp->name); - } - next = comp->next_ptr; +} + +static int save_aliases_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + if(q->pp.alias) { + const char *s = q->qtype == HAL_QTYPE_PIN ? "pin" : "param"; + fprintf(fp, "alias %s %s %s\n", s, q->pp.alias, q->name); } -#endif - rtapi_mutex_give(&(hal_data->mutex)); + return 0; } static void save_aliases(FILE *dst) { - hal_pin_t *pin; - hal_param_t *param; - hal_oldname_t *oldname; - + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; fprintf(dst, "# pin aliases\n"); - rtapi_mutex_get(&(hal_data->mutex)); - { - SHMFIELD(hal_pin_t) next; - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if ( pin->oldname != 0 ) { - /* name is an alias */ - oldname = SHMPTR(pin->oldname); - fprintf(dst, "alias pin %s %s\n", oldname->name, pin->name); - } - next = pin->next_ptr; - } - } + hal_list_p(&q, save_aliases_cb, (void *)dst); + + q = {}; + q.qtype = HAL_QTYPE_PARAM; fprintf(dst, "# param aliases\n"); - { - SHMFIELD(hal_param_t) next; - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( param->oldname != 0 ) { - /* name is an alias */ - oldname = SHMPTR(param->oldname); - fprintf(dst, "alias param %s %s\n", oldname->name, param->name); - } - next = param->next_ptr; - } - } - rtapi_mutex_give(&(hal_data->mutex)); + hal_list_p(&q, save_aliases_cb, (void *)dst); } -static void save_signals(FILE *dst, int only_unlinked) +static int save_signals_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_sig_t) next; - hal_sig_t *sig; + FILE *fp = (FILE *)arg; + // FIXME: What about the bidirs? + if(!(q->callerdata.sival && (q->sig.writers || q->sig.readers))) + fprintf(fp, "newsig %s %s\n", q->name, data_type(q->sig.type)); + return 0; +} +static void save_signals(FILE *dst, int only_unlinked) +{ + hal_query_t q = {}; + q.callerdata.sival = only_unlinked; fprintf(dst, "# signals\n"); - rtapi_mutex_get(&(hal_data->mutex)); - - for( next = hal_data->sig_list_ptr; next; next = sig->next_ptr) { - sig = SHMPTR(next); - if(only_unlinked && (sig->readers || sig->writers)) continue; - fprintf(dst, "newsig %s %s\n", sig->name, data_type((int) sig->type)); + hal_list_s(&q, save_signals_cb, (void *)dst); +} + +static int save_links_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + if(q->pp.signal) { + const char *arrow_str = q->callerdata.sival ? data_arrow1(q->pp.dir) : ""; + fprintf(fp, "linkps %s %s %s\n", q->name, arrow_str, q->pp.signal); } - rtapi_mutex_give(&(hal_data->mutex)); + return 0; } static void save_links(FILE *dst, int arrow) { - SHMFIELD(hal_pin_t) next; - hal_pin_t *pin; - hal_sig_t *sig; - const char *arrow_str; - + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + q.callerdata.sival = arrow; fprintf(dst, "# links\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - if (arrow != 0) { - arrow_str = data_arrow1((int) pin->dir); - } else { - arrow_str = "\0"; - } - fprintf(dst, "linkps %s %s %s\n", pin->name, arrow_str, sig->name); - } - next = pin->next_ptr; + hal_list_p(&q, save_links_cb, (void *)dst); +} + +struct save_nets_state_t { + int state; + int first; +}; + +static int save_nets_3_outpins_cb(hal_query_t *q, void *arg) +{ + if(HAL_OUT == q->pp.dir) { + fprintf((FILE *)arg, " %s", q->name); + reinterpret_cast(q->callerdata.vpval)->state = 1; } - rtapi_mutex_give(&(hal_data->mutex)); + return 0; } -static void save_nets(FILE *dst, int arrow) +static int save_nets_3_iopins_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_sig_t) next; - hal_pin_t *pin; - hal_sig_t *sig; - const char *arrow_str; + if(HAL_IO == q->pp.dir) { + FILE *fp = (FILE *)arg; + save_nets_state_t *st = reinterpret_cast(q->callerdata.vpval); + fprintf(fp, " "); + if(st->state) { + fprintf(fp, "=> "); + st->state = 0; + } else if(!st->first) { + fprintf(fp, "<=> "); + } + fprintf(fp, "%s", q->name); + st->first = 0; + } + return 0; +} - fprintf(dst, "# nets\n"); - rtapi_mutex_get(&(hal_data->mutex)); +static int save_nets_3_inpins_cb(hal_query_t *q, void *arg) +{ + if(HAL_IN == q->pp.dir) { + FILE *fp = (FILE *)arg; + save_nets_state_t *st = reinterpret_cast(q->callerdata.vpval); + fprintf(fp, " "); + if(st->state) { + fprintf(fp, "=> "); + st->state = 0; + } + fprintf(fp, "%s", q->name); + } + return 0; +} + +static int save_nets_3_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + save_nets_state_t st = {.state = 0, .first = 1}; + hal_query_t qp; + + // If there are no pins connected to this signal, do nothing + if(!q->sig.writers && !q->sig.readers && !q->sig.bidirs) + return 0; + + fprintf(fp, "net %s", q->name); + + /* Step 1: Output pin, if any */ + qp = {}; + qp.name = q->name; + qp.callerdata.vpval = &st; // Counts pins + hal_list_p_s(&qp, save_nets_3_outpins_cb, arg); - for (next = hal_data->sig_list_ptr; next != 0; next = sig->next_ptr) { - sig = SHMPTR(next); - if(arrow == 3) { - int state = 0, first = 1; - - /* If there are no pins connected to this signal, do nothing */ - pin = halpr_find_pin_by_sig(sig, NULL); - if(!pin) continue; - - fprintf(dst, "net %s", sig->name); - - /* Step 1: Output pin, if any */ - - for(pin = halpr_find_pin_by_sig(sig, NULL); pin; - pin = halpr_find_pin_by_sig(sig, pin)) { - if(pin->dir != HAL_OUT) continue; - fprintf(dst, " %s", pin->name); - state = 1; - } - - /* Step 2: I/O pins, if any */ - for(pin = halpr_find_pin_by_sig(sig, NULL); pin; - pin = halpr_find_pin_by_sig(sig, pin)) { - if(pin->dir != HAL_IO) continue; - fprintf(dst, " "); - if(state) { fprintf(dst, "=> "); state = 0; } - else if(!first) { fprintf(dst, "<=> "); } - fprintf(dst, "%s", pin->name); - first = 0; - } - if(!first) state = 1; - - /* Step 3: Input pins, if any */ - for(pin = halpr_find_pin_by_sig(sig, NULL); pin; - pin = halpr_find_pin_by_sig(sig, pin)) { - if(pin->dir != HAL_IN) continue; - fprintf(dst, " "); - if(state) { fprintf(dst, "=> "); state = 0; } - fprintf(dst, "%s", pin->name); - } + /* Step 2: I/O pins, if any */ + qp = {}; + qp.name = q->name; + qp.callerdata.vpval = &st; + hal_list_p_s(&qp, save_nets_3_iopins_cb, arg); + + if(!st.first) + st.state = 1; + + /* Step 3: Input pins, if any */ + qp = {}; + qp.name = q->name; + qp.callerdata.vpval = &st; + hal_list_p_s(&qp, save_nets_3_inpins_cb, arg); + + fprintf(fp, "\n"); + return 0; +} - fprintf(dst, "\n"); - } else if(arrow == 2) { - /* If there are no pins connected to this signal, do nothing */ - pin = halpr_find_pin_by_sig(sig, NULL); - if(!pin) continue; - - fprintf(dst, "net %s", sig->name); - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - fprintf(dst, " %s", pin->name); - pin = halpr_find_pin_by_sig(sig, pin); - } - fprintf(dst, "\n"); - } else { - fprintf(dst, "newsig %s %s\n", - sig->name, data_type((int) sig->type)); - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - if (arrow != 0) { - arrow_str = data_arrow2((int) pin->dir); - } else { - arrow_str = "\0"; - } - fprintf(dst, "linksp %s %s %s\n", - sig->name, arrow_str, pin->name); - pin = halpr_find_pin_by_sig(sig, pin); - } - } +static void save_nets_3(FILE *dst) +{ + hal_query_t q = {}; + hal_list_s(&q, save_nets_3_cb, (void *)dst); +} + +static int save_nets_2_pins_cb(hal_query_t *q, void *arg) +{ + fprintf((FILE *)arg, " %s", q->name); + return 0; +} + +static int save_nets_2_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + + // If there are no pins connected to this signal, do nothing + if(!q->sig.writers && !q->sig.readers && !q->sig.bidirs) + return 0; + + fprintf(fp, "net %s", q->name); + hal_query_t qp = {}; + qp.name = q->name; + hal_list_p_s(&qp, save_nets_2_pins_cb, arg); + fprintf(fp, "\n"); + return 0; +} + +static void save_nets_2(FILE *dst) +{ + hal_query_t q = {}; + hal_list_s(&q, save_nets_2_cb, (void *)dst); +} + +static int save_nets_01_pins_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + const char *arrow_str = q->callerdata.sival ? data_arrow2(q->pp.dir) : ""; + fprintf(fp, "linksp %s %s %s\n", q->pp.signal, arrow_str, q->name); + return 0; +} + +static int save_nets_01_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + fprintf(fp, "newsig %s %s\n", q->name, data_type(q->sig.type)); + hal_query_t qp = {}; + qp.callerdata.sival = q->callerdata.sival; // Propagate arrow type + qp.name = q->name; + return hal_list_p_s(&qp, save_nets_01_pins_cb, arg); +} + +static void save_nets_01(FILE *dst, int arrow) +{ + hal_query_t q = {}; + q.callerdata.sival = arrow; + hal_list_s(&q, save_nets_01_cb, (void *)dst); +} + +static void save_nets(FILE *dst, int arrow) +{ + fprintf(dst, "# nets\n"); + switch(arrow) { + case 3: save_nets_3(dst); break; + case 2: save_nets_2(dst); break; + case 1: + case 0: save_nets_01(dst, arrow); break; + default: break; } - rtapi_mutex_give(&(hal_data->mutex)); } -static void save_params(FILE *dst) +static int save_params_cb(hal_query_t *q, void *arg) { - SHMFIELD(hal_param_t) next; - hal_param_t *param; + FILE *fp = (FILE *)arg; + if(HAL_RO != q->pp.dir) { + // Writable parameter, save its value + fprintf(fp, "setp %s %s\n", q->name, querydata_refstr_20(q->pp.type, q->pp.ref).c_str()); + } + return 0; +} +static void save_params(FILE *dst) +{ + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; fprintf(dst, "# parameter values\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if (param->dir != HAL_RO) { - /* param is writable, save its value */ - fprintf(dst, "setp %s %s\n", param->name, - data_value((int) param->type, SHMPTR(param->data_ptr))); - } - next = param->next_ptr; + hal_list_p(&q, save_params_cb, (void *)dst); +} + +static int save_threads_cb(hal_query_t *q, void *arg) +{ + if(HAL_QTYPE_THREAD_FUNCT == q->qtype) { + const char *f = q->thread.is_init ? "initf" : "addf"; + fprintf((FILE *)arg, "%s %s %s\n", f, q->thread.funct, q->name); } - rtapi_mutex_give(&(hal_data->mutex)); + return 0; } static void save_threads(FILE *dst) { - SHMFIELD(hal_thread_t) next_thread; - hal_thread_t *tptr; - hal_list_t *list_root, *list_entry; - hal_funct_entry_t *fentry; - hal_funct_t *funct; - + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; fprintf(dst, "# realtime thread/function links\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - tptr = SHMPTR(next_thread); - list_root = &(tptr->funct_list); - list_entry = list_next(list_root); - while (list_entry != list_root) { - /* print the function info */ - fentry = reinterpret_cast(list_entry); - funct = SHMPTR(fentry->funct_ptr); - fprintf(dst, "addf %s %s\n", funct->name, tptr->name); - list_entry = list_next(list_entry); - } - next_thread = tptr->next_ptr; + hal_list_thread(&q, save_threads_cb, (void *)dst); +} + +static int save_unconnected_input_pin_values_cb(hal_query_t *q, void *arg) +{ + FILE *fp = (FILE *)arg; + if(!q->pp.signal && (HAL_IN == q->pp.dir || HAL_IO == q->pp.dir)) { + fprintf(fp, "setp %s %s\n", q->name, querydata_refstr(q->pp.type, q->pp.ref).c_str()); } - rtapi_mutex_give(&(hal_data->mutex)); + return 0; } static void save_unconnected_input_pin_values(FILE *dst) { - hal_pin_t *pin; - void *dptr; - SHMFIELD(hal_pin_t) next; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; fprintf(dst, "# unconnected pin values\n"); - for(next = hal_data->pin_list_ptr; next; next=pin->next_ptr) - { - pin = SHMPTR(next); - if ( (pin->signal == 0) - && ( (pin->dir == HAL_IN) || (pin->dir == HAL_IO) ) - ) { - dptr = &(pin->dummysig); - fprintf(dst, "setp %s %s\n", - pin->name, data_value((int) pin->type, dptr)); - } - } + hal_list_p(&q, save_unconnected_input_pin_values_cb, (void *)dst); } -int do_setexact_cmd() { - int retval = 0; - rtapi_mutex_get(&(hal_data->mutex)); - if(hal_data->base_period) { +int do_setexact_cmd() +{ + int retval = hal_enforce_exact_base_period(); + if(0 != retval) { halcmd_error( "HAL_LIB: Cannot run 'setexact'" " after a thread has been created\n"); @@ -2929,13 +2439,11 @@ int do_setexact_cmd() { "HAL_LIB: HAL will pretend that the exact" " base period requested is possible.\n" "This mode is not suitable for running real hardware.\n"); - hal_data->exact_base_period = 1; } - rtapi_mutex_give(&(hal_data->mutex)); return retval; } -int do_help_cmd(char *command) +int do_help_cmd(const char *command) { if (!command) { print_help_commands(); diff --git a/src/hal/utils/halcmd_commands.h b/src/hal/utils/halcmd_commands.h index 49629b7d1e5..d16eb002754 100644 --- a/src/hal/utils/halcmd_commands.h +++ b/src/hal/utils/halcmd_commands.h @@ -45,47 +45,47 @@ RTAPI_BEGIN_DECLS -extern int do_addf_cmd(char *funct, char *thread, char *tokens[]); -extern int do_initf_cmd(char *funct, char *thread, char *tokens[]); -extern int do_alias_cmd(char *pinparam, char *name, char *alias); -extern int do_unalias_cmd(char *pinparam, char *name); -extern int do_delf_cmd(char *funct, char *thread); +extern int do_addf_cmd(const char *funct, const char *thread, const char *tokens[]); +extern int do_initf_cmd(const char *funct, const char *thread, const char *tokens[]); +extern int do_alias_cmd(const char *pinparam, const char *name, const char *alias); +extern int do_unalias_cmd(const char *pinparam, const char *name); +extern int do_delf_cmd(const char *funct, const char *thread); extern int do_echo_cmd(); extern int do_unecho_cmd(); -extern int do_linkps_cmd(char *pin, char *signal); -extern int do_linksp_cmd(char *signal, char *pin); +extern int do_linkps_cmd(const char *pin, const char *signal); +extern int do_linksp_cmd(const char *signal, const char *pin); extern int do_start_cmd(); extern int do_stop_cmd(); -extern int do_help_cmd(char *command); -extern int do_lock_cmd(char *command); -extern int do_unlock_cmd(char *command); -extern int do_linkpp_cmd(char *first_pin_name, char *second_pin_name); -extern int do_newsig_cmd(char *name, char *type); +extern int do_help_cmd(const char *command); +extern int do_lock_cmd(const char *command); +extern int do_unlock_cmd(const char *command); +extern int do_linkpp_cmd(const char *first_pin_name, const char *second_pin_name); +extern int do_newsig_cmd(const char *name, const char *type); #if 0 /* newinst deferred to version 2.2 */ extern int do_newinst_cmd(char *comp_name, char *inst_name); #endif -extern int do_net_cmd(char *signame, char *pins[]); -extern int do_setp_cmd(char *name, char *value); -extern int do_getp_cmd(char *name); -extern int do_sets_cmd(char *name, char *value); -extern int do_gets_cmd(char *name); -extern int do_print_cmd(char *value); -extern int do_ptype_cmd(char *name); -extern int do_stype_cmd(char *name); -extern int do_show_cmd(char *type, char **patterns); -extern int do_list_cmd(char *type, char **patterns); -extern int do_source_cmd(char *type); -extern int do_status_cmd(char *type); -extern int do_set_debug_cmd(char *level); -extern int do_delsig_cmd(char *mod_name); -extern int do_loadrt_cmd(char *mod_name, char *args[]); -extern int do_unlinkp_cmd(char *mod_name); -extern int do_unload_cmd(char *mod_name); -extern int do_unloadrt_cmd(char *mod_name); -extern int do_unloadusr_cmd(char *mod_name); +extern int do_net_cmd(const char *signame, const char *pins[]); +extern int do_setp_cmd(const char *name, const char *value); +extern int do_getp_cmd(const char *name); +extern int do_sets_cmd(const char *name, const char *value); +extern int do_gets_cmd(const char *name); +extern int do_print_cmd(const char *value); +extern int do_ptype_cmd(const char *name); +extern int do_stype_cmd(const char *name); +extern int do_show_cmd(const char *type, const char **patterns); +extern int do_list_cmd(const char *type, const char **patterns); +extern int do_source_cmd(const char *type); +extern int do_status_cmd(const char *type); +extern int do_set_debug_cmd(const char *level); +extern int do_delsig_cmd(const char *mod_name); +extern int do_loadrt_cmd(const char *mod_name, const char *args[]); +extern int do_unlinkp_cmd(const char *mod_name); +extern int do_unload_cmd(const char *mod_name); +extern int do_unloadrt_cmd(const char *mod_name); +extern int do_unloadusr_cmd(const char *mod_name); extern int do_loadusr_cmd(const char *args[]); -extern int do_waitusr_cmd(char *comp_name); -extern int do_save_cmd(const char *type, char *filename); +extern int do_waitusr_cmd(const char *comp_name); +extern int do_save_cmd(const char *type, const char *filename); extern int do_setexact_cmd(void); pid_t hal_systemv_nowait(const char *const argv[]); diff --git a/src/hal/utils/halcmd_completion.c b/src/hal/utils/halcmd_completion.c index 676bd9fa30c..bd8441a3fa7 100644 --- a/src/hal/utils/halcmd_completion.c +++ b/src/hal/utils/halcmd_completion.c @@ -41,10 +41,10 @@ #include "config.h" #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* private HAL decls */ #include #include #include +#include static int argno; @@ -134,111 +134,209 @@ static int writer_match(hal_pin_dir_t dir, int writers) { return 0; } -static void check_match_type_pin(const char *name) { - int next = hal_data->pin_list_ptr; - size_t sz = strcspn(name, " \t"); +typedef struct { + char name[HAL_NAME_LEN+1]; // HAL name strings + int val; + union { + struct { // Pins,params and signals + hal_pdir_t dir; + hal_type_t type; + const char *sig; // Pin is attached to a signal + const char *alias; // Pin/param has an alias + bool drive; // Signal has writers + }; + struct { // Components + hal_comp_type_t ctype; + bool ready; + }; + }; +} gendata_entry_t; + +typedef struct { + size_t na; + size_t n; + gendata_entry_t *data; // Array of fixed HAL name strings +} gendata_list_t; + +static inline void gendata_clr(gendata_list_t *g) +{ + g->n = 0; +} - while(next) { - hal_pin_t *pin = SHMPTR(next); - next = pin->next_ptr; - if ( sz == strlen(pin->name) && strncmp(name, pin->name, sz) == 0 ) { - match_type = pin->type; - match_direction = pin->dir; - return; +static gendata_entry_t *gendata_add(gendata_list_t *g, const char *s, int v) +{ + if(!g->data) { + g->n = 0; + g->na = 64; + g->data = (gendata_entry_t *)calloc(g->na, sizeof(*g->data)); + if(!g->data) { + g->na = 0; + return NULL; + } + } else if(g->n >= g->na) { + g->na *= 2; + g->data = reallocarray(g->data, g->na, sizeof(*g->data)); + if(!g->data) { + g->na = 0; + g->n = 0; + return NULL; } + memset(&g->data[g->n], 0, (g->na - g->n) * sizeof(*g->data)); } + strcpy(g->data[g->n].name, s); // This string should always fit + g->data[g->n].val = v; + g->n++; + return &g->data[g->n-1]; } -static void check_match_type_signal(const char *name) { - int next = hal_data->sig_list_ptr; - size_t sz = strcspn(name, " \t"); +static int match_pintype_cb(hal_query_t *q, void *arg) +{ + const char *name = (const char *)arg; + if (q->callerdata.uival == strlen(q->name) && !strncmp(name, q->name, q->callerdata.uival)) { + match_type = q->pp.type; + match_direction = q->pp.dir; + return 1; // Break the loop + } + return 0; +} - while(next) { - hal_sig_t *sig = SHMPTR(next); - next = sig->next_ptr; - if ( sz == strlen(sig->name) && strncmp(name, sig->name, sz) == 0 ) { - match_type = sig->type; - match_writers = sig->writers; - return; - } +static void check_match_type_pin(const char *name) +{ + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + q.callerdata.uival = strcspn(name, " \t"); + hal_list_p(&q, match_pintype_cb, (void *)name); +} + +static int match_sigtype_cb(hal_query_t *q, void *arg) +{ + const char *name = (const char *)arg; + if (q->callerdata.uival == strlen(q->name) && !strncmp(name, q->name, q->callerdata.uival)) { + match_type = q->sig.type; + match_writers = q->sig.writers > 0; + return 1; // Break the loop } + return 0; +} + +static void check_match_type_signal(const char *name) +{ + hal_query_t q = {}; + q.callerdata.uival = strcspn(name, " \t"); + hal_list_s(&q, match_sigtype_cb, (void *)name); +} + +static int genthread_cb(hal_query_t *q, void *arg) +{ + gendata_add((gendata_list_t *)arg, q->name, 0); + return 0; } static char *thread_generator(const char *text, int state) { + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->thread_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; // By default, we only get thread names + hal_list_thread(&q, genthread_cb, &gdl); + idx = 0; len = strlen(text); } - - while(next) { - hal_thread_t *thread = SHMPTR(next); - next = thread->next_ptr; - if ( strncmp(text, thread->name, len) == 0 ) - return strdup(thread->name); + for(; idx < gdl.n; idx++) { + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } return NULL; } -static char *parameter_generator(const char *text, int state) { +static int genpin_cb(hal_query_t *q, void *arg) +{ + gendata_list_t *gdl = (gendata_list_t *)arg; + gendata_entry_t *gde = gendata_add(gdl, q->name, 0); + if(!gde) + return 1; // Allocation error, just drop out + gde->dir = q->pp.dir; + gde->type = q->pp.type; + gde->sig = q->pp.signal; + gde->alias = q->pp.alias; + return 0; +} + +static void build_pinparam_list(gendata_list_t *gdlp, size_t *idx, int *len, const char *text, hal_qtype_t ctype) +{ + gendata_clr(gdlp); + hal_query_t q = {}; + q.qtype = ctype; + hal_list_p(&q, genpin_cb, gdlp); + *idx = 0; + *len = strlen(text); +} + +static char *parameter_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; + static size_t idx; static int aliased; - char *name; - - if(!state) { - next = hal_data->param_list_ptr; - len = strlen(text); + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_PARAM); aliased = 0; } - while(next) { - hal_param_t *param = SHMPTR(next); - switch (aliased) { - case 0: // alias (if any) has not been output - if (param->oldname != 0) { - // there's an alias, so use that and do not update the pin pointer - hal_oldname_t *oldname = SHMPTR(param->oldname); - name = oldname->name; - aliased = 1; - } else { - // no alias, so use the name and update the pin pointer - name = param->name; - next = param->next_ptr; - } - break; - case 1: // there is an alias, and it has been processed already - name = param->name; - next = param->next_ptr; - aliased = 0; - break; - default: - // shouldn't be able to get here, so assume we're done - rl_attempted_completion_over = 1; - return NULL; - break; + const char *name; + for(; idx < gdl.n; idx++) { + if(!aliased) { + if(gdl.data[idx].alias) { + name = gdl.data[idx].alias; + aliased = 1; + } else { + name = gdl.data[idx].name; + } + } else { + name = gdl.data[idx].name; + aliased = 0; + } + + if(!writer_match(gdl.data[idx].dir, match_writers)) { + idx -= aliased; + continue; + } + if(!direction_match(gdl.data[idx].dir, match_direction)) { + idx -= aliased; + continue; } - if ( strncmp(text, name, len) == 0 ) + if(!strncmp(text, name, len)) { + idx += 1 - aliased; return strdup(name); + } } return NULL; } +static int genfunct_cb(hal_query_t *q, void *arg) +{ + gendata_add((gendata_list_t *)arg, q->name, q->callerdata.sival); + return 0; +} + static char *funct_generator_common(const char *text, int state, int inuse) { + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->funct_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; + q.callerdata.sival = inuse; + hal_list_funct(&q, genfunct_cb, &gdl); + idx = 0; len = strlen(text); } - - while(next) { - hal_funct_t *funct = SHMPTR(next); - next = funct->next_ptr; - if (( strncmp(text, funct->name, len) == 0 ) - && (inuse == funct->users)) - return strdup(funct->name); + for(; idx < gdl.n; idx++) { + if(gdl.data[idx].val == inuse && !strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } return NULL; } @@ -251,103 +349,108 @@ static char *attached_funct_generator(const char *text, int state) { return funct_generator_common(text, state, 1); } -static char *signal_generator(const char *text, int state) { +static int gensignal_cb(hal_query_t *q, void *arg) +{ + gendata_list_t *gdl = (gendata_list_t *)arg; + gendata_entry_t *gde = gendata_add(gdl, q->name, 0); + if(!gde) + return 1; // Allocation error, just drop out + gde->type = q->sig.type; + gde->drive = q->sig.writers > 0; + return 0; +} + +static char *signal_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->sig_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; + hal_list_s(&q, gensignal_cb, &gdl); + idx = 0; len = strlen(text); } - - while(next) { - hal_sig_t *sig = SHMPTR(next); - next = sig->next_ptr; - if ( match_type != HAL_TYPE_UNSPECIFIED && match_type != sig->type ) continue; - if ( !writer_match( match_direction, sig->writers ) ) continue; - if ( strncmp(text, sig->name, len) == 0 ) - return strdup(sig->name); + for(; idx < gdl.n; idx++) { + if(match_type != HAL_TYPE_UNSPECIFIED && match_type != gdl.data[idx].type) + continue; + if(!writer_match(match_direction, gdl.data[idx].drive)) + continue; + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } return NULL; } -static char *getp_generator(const char *text, int state) { +static char *getp_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - static int what; - if(!state) { - what = 0; - next = hal_data->param_list_ptr; - len = strlen(text); + static size_t idx; + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_ANY); } - - if(what == 0) { - while(next) { - hal_param_t *param = SHMPTR(next); - next = param->next_ptr; - if ( strncmp(text, param->name, len) == 0 ) - return strdup(param->name); + for(; idx < gdl.n; idx++) { + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); } - what = 1; - next = hal_data->pin_list_ptr; - } - while(next) { - hal_pin_t *pin = SHMPTR(next); - next = pin->next_ptr; - if ( strncmp(text, pin->name, len) == 0 ) - return strdup(pin->name); } - return NULL; } -static char *setp_generator(const char *text, int state) { +static char *setp_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - static int what; - if(!state) { - what = 0; - next = hal_data->param_list_ptr; - len = strlen(text); - } - - if(what == 0) { - while(next) { - hal_param_t *param = SHMPTR(next); - next = param->next_ptr; - if ( param->dir != HAL_RO && strncmp(text, param->name, len) == 0 ) - return strdup(param->name); + static size_t idx; + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_ANY); + } + for(; idx < gdl.n; idx++) { + if(0 == (gdl.data[idx].dir & (HAL_WO | HAL_OUT)) || NULL != gdl.data[idx].sig) + continue; // Not writable or has a signal attached + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); } - what = 1; - next = hal_data->pin_list_ptr; } - while(next) { - hal_pin_t *pin = SHMPTR(next); - next = pin->next_ptr; - if ( pin->dir != HAL_OUT && pin->signal == 0 && - strncmp(text, pin->name, len) == 0 ) - return strdup(pin->name); - } - return NULL; } -static char *usrcomp_generator(const char *text, int state) { +static int gencomp_cb(hal_query_t *q, void *arg) +{ + gendata_list_t *gdl = (gendata_list_t *)arg; + gendata_entry_t *gde = gendata_add(gdl, q->name, 0); + if(!gde) + return 1; // Allocation error, just drop out + gde->ctype = q->comp.type; + gde->ready = q->comp.ready; + return 0; +} + +static char *usrcomp_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->comp_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; // By default, we only get thread names + hal_list_comp(&q, gencomp_cb, &gdl); + idx = 0; len = strlen(text); - if(strncmp(text, "all", len) == 0) + if(!strncmp(text, "all", len)) return strdup("all"); } - while(next) { - hal_comp_t *comp = SHMPTR(next); - next = comp->next_ptr; - if(comp->type != COMPONENT_TYPE_USER) continue; - if(strncmp(text, comp->name, len) == 0) - return strdup(comp->name); + for(; idx < gdl.n; idx++) { + if(gdl.data[idx].ctype != HAL_COMP_TYPE_USER) + continue; + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } rl_attempted_completion_over = 1; return NULL; @@ -355,129 +458,136 @@ static char *usrcomp_generator(const char *text, int state) { -static char *comp_generator(const char *text, int state) { +static char *comp_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->comp_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; // By default, we only get thread names + hal_list_comp(&q, gencomp_cb, &gdl); + idx = 0; len = strlen(text); - if(strncmp(text, "all", len) == 0) + if(!strncmp(text, "all", len)) return strdup("all"); } - while(next) { - hal_comp_t *comp = SHMPTR(next); - next = comp->next_ptr; - if ( strncmp(text, comp->name, len) == 0 ) - return strdup(comp->name); + for(; idx < gdl.n; idx++) { + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } rl_attempted_completion_over = 1; return NULL; } -static char *rtcomp_generator(const char *text, int state) { +static char *rtcomp_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - if(!state) { - next = hal_data->comp_list_ptr; + static size_t idx; + if(!state) { // Initial state, fill generator data + gendata_clr(&gdl); + hal_query_t q = {}; // By default, we only get thread names + hal_list_comp(&q, gencomp_cb, &gdl); + idx = 0; len = strlen(text); - if(strncmp(text, "all", len) == 0) + if(!strncmp(text, "all", len)) return strdup("all"); } - while(next) { - hal_comp_t *comp = SHMPTR(next); - next = comp->next_ptr; - if(comp->type == COMPONENT_TYPE_USER) continue; - if ( strncmp(text, comp->name, len) == 0 ) - return strdup(comp->name); + for(; idx < gdl.n; idx++) { + if(gdl.data[idx].ctype != HAL_COMP_TYPE_REALTIME) + continue; + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } rl_attempted_completion_over = 1; return NULL; } -static char *parameter_alias_generator(const char *text, int state) { +static char *parameter_alias_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - - if(!state) { - next = hal_data->param_list_ptr; - len = strlen(text); + static size_t idx; + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_PARAM); } - while(next) { - hal_param_t *param = SHMPTR(next); - next = param->next_ptr; - if (param->oldname==0) continue; // no alias here, move along - if ( strncmp(text, param->name, len) == 0 ) - return strdup(param->name); + for(; idx < gdl.n; idx++) { + if(!gdl.data[idx].alias) + continue; + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } return NULL; } -static char *pin_alias_generator(const char *text, int state) { +static char *pin_alias_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; - - if(!state) { - next = hal_data->pin_list_ptr; - len = strlen(text); + static size_t idx; + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_PIN); } - while(next) { - hal_pin_t *pin = SHMPTR(next); - next = pin->next_ptr; - if (pin->oldname==0) continue; // no alias here, move along - if ( strncmp(text, pin->name, len) == 0 ) - return strdup(pin->name); + for(; idx < gdl.n; idx++) { + if(!gdl.data[idx].alias) + continue; + if(!strncmp(text, gdl.data[idx].name, len)) { + return strdup(gdl.data[idx++].name); + } } return NULL; } -static char *pin_generator(const char *text, int state) { +static char *pin_generator(const char *text, int state) +{ + static gendata_list_t gdl = {}; static int len; - static int next; + static size_t idx; static int aliased; - char *name; - - if(!state) { - next = hal_data->pin_list_ptr; - len = strlen(text); + if(!state) { // Initial state, fill generator data + build_pinparam_list(&gdl, &idx, &len, text, HAL_QTYPE_PIN); aliased = 0; } - while(next) { - hal_pin_t *pin = SHMPTR(next); - switch (aliased) { - case 0: // alias (if any) has not been output - if (pin->oldname != 0) { - // there's an alias, so use that and do not update the pin pointer - hal_oldname_t *oldname = SHMPTR(pin->oldname); - name = oldname->name; - aliased = 1; - } else { - // no alias, so use the name and update the pin pointer - name = pin->name; - next = pin->next_ptr; - } - break; - case 1: // there is an alias, and it has been processed already - name = pin->name; - next = pin->next_ptr; - aliased = 0; - break; - default: - // shouldn't be able to get here, so assume we're done - rl_attempted_completion_over = 1; - return NULL; - break; + const char *name; + for(; idx < gdl.n; idx++) { + if(!aliased) { + if(gdl.data[idx].alias) { + name = gdl.data[idx].alias; + aliased = 1; + } else { + name = gdl.data[idx].name; + } + } else { + name = gdl.data[idx].name; + aliased = 0; + } + + if(!writer_match(gdl.data[idx].dir, match_writers)) { + idx -= aliased; + continue; } - if ( !writer_match( pin->dir, match_writers ) ) continue; - if ( !direction_match( pin->dir, match_direction ) ) continue; - if ( match_type != HAL_TYPE_UNSPECIFIED && match_type != pin->type ) continue; - if ( strncmp(text, name, len) == 0 ) + if(!direction_match(gdl.data[idx].dir, match_direction)) { + idx -= aliased; + continue; + } + if(match_type != HAL_TYPE_UNSPECIFIED && match_type != gdl.data[idx].type) { + idx -= aliased; + continue; + } + if(!strncmp(text, name, len)) { + idx += 1 - aliased; return strdup(name); + } } rl_attempted_completion_over = 1; return NULL; @@ -592,8 +702,6 @@ char **halcmd_completer(const char *text, int start, int end, hal_completer_func match_writers = -1; match_direction = -1; - rtapi_mutex_get(&(hal_data->mutex)); - if(startswith(buffer, "delsig ") && argno == 1) { result = func(text, signal_generator); } else if(startswith(buffer, "linkps ") && argno == 1) { @@ -722,19 +830,15 @@ char **halcmd_completer(const char *text, int start, int end, hal_completer_func } else if(startswith(buffer, "unload ") && argno == 1) { result = func(text, comp_generator); } else if(startswith(buffer, "source ") && argno == 1) { - rtapi_mutex_give(&(hal_data->mutex)); // leaves rl_attempted_completion_over = 0 to complete from filesystem return NULL; } else if(startswith(buffer, "loadusr ") && argno < 3) { - rtapi_mutex_give(&(hal_data->mutex)); // leaves rl_attempted_completion_over = 0 to complete from filesystem return func(text, loadusr_generator); } else if(startswith(buffer, "loadrt ") && argno == 1) { result = func(text, loadrt_generator); } - rtapi_mutex_give(&(hal_data->mutex)); - rl_attempted_completion_over = 1; return result; } diff --git a/src/hal/utils/halcmd_main.c b/src/hal/utils/halcmd_main.c index 6d50a853115..e475a32bbbe 100644 --- a/src/hal/utils/halcmd_main.c +++ b/src/hal/utils/halcmd_main.c @@ -42,7 +42,6 @@ #include #include #include -#include "../hal_priv.h" #include "halcmd.h" #include "halcmd_commands.h" #include "halcmd_completion.h" @@ -257,7 +256,7 @@ int main(int argc, char **argv) if(errorcount == 0 && argc > optind) { halcmd_set_filename(""); halcmd_set_linenumber(0); - retval = halcmd_parse_cmd(&argv[optind]); + retval = halcmd_parse_cmd((const char **)&argv[optind]); if (retval != 0) { errorcount++; } @@ -268,7 +267,7 @@ int main(int argc, char **argv) char *elineptr=eline, *elineend=eline + sizeof(eline); /* read command line(s) from 'srcfile' */ while (get_input(srcfile, raw_buf, MAX_CMD_LEN)) { - char *tokens[MAX_TOK+1]; + const char *tokens[MAX_TOK+1]; int newLinePos; halcmd_set_linenumber(linenumber++); @@ -340,42 +339,7 @@ int main(int argc, char **argv) */ static int release_HAL_mutex(void) { - int comp_id, mem_id, retval; - void *mem; - hal_data_t *hal_data; - - /* do RTAPI init */ - comp_id = rtapi_init("hal_unlocker"); - if (comp_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "ERROR: rtapi init failed\n"); - return -EINVAL; - } - /* get HAL shared memory block from RTAPI */ - mem_id = rtapi_shmem_new(HAL_KEY, comp_id, HAL_SIZE); - if (mem_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "ERROR: could not open shared memory\n"); - rtapi_exit(comp_id); - return -EINVAL; - } - /* get address of shared memory area */ - retval = rtapi_shmem_getptr(mem_id, &mem); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "ERROR: could not access shared memory\n"); - rtapi_exit(comp_id); - return -EINVAL; - } - /* set up internal pointers to shared mem and data structure */ - hal_data = (hal_data_t *) mem; - /* release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); - /* release RTAPI resources */ - rtapi_shmem_delete(mem_id, comp_id); - rtapi_exit(comp_id); - /* done */ - return 0; - + return hal_mutex_force_release() == 0 ? 0 : -EINVAL; } static char **completion_callback(const char *text, hal_generator_func cb) { @@ -431,7 +395,7 @@ static void print_help_general(int showR) printf(" help command Prints detailed help for 'command'\n\n"); } -#ifdef HAVE_READLINE +#if defined(HAVE_READLINE) || defined(HAVE_EDITLINE_READLINE_H) #include "halcmd_completion.h" static int get_input(FILE *srcfile, char *buf, size_t bufsize) { diff --git a/src/hal/utils/halcompile.g b/src/hal/utils/halcompile.g index 62c4da5d336..f51438a3b85 100644 --- a/src/hal/utils/halcompile.g +++ b/src/hal/utils/halcompile.g @@ -546,7 +546,7 @@ static int comp_id; if options.get("rtapi_app", 1): if options.get("constructable") and not options.get("singleton"): - print("static int export_1(char *prefix, char *argstr) {", file=f) + print("static int export_1(const char *prefix, const char *argstr) {", file=f) print(" int arg = simple_strtol(argstr, NULL, 0);", file=f) print(" return export(prefix, arg);", file=f) print("}" , file=f) diff --git a/src/hal/utils/halrmt.c b/src/hal/utils/halrmt.c deleted file mode 100644 index 5f6de73e660..00000000000 --- a/src/hal/utils/halrmt.c +++ /dev/null @@ -1,3628 +0,0 @@ -/******************************************************************** -* Description: halrmt.cc -* Simple telnet interface to LinuxCNC HAL commands (halcmd) -* -* Derived from work by jmkasunich -* -* Other contributors: -* Alex Joni -* -* Author: Eric H. Johnson -* License: GPL Version 2 -* System: Linux -* -* Copyright (c) 2006-2008 All rights reserved. -* -* Last change: -********************************************************************/ - -/******************************************************************* - Using halrmt: - - halrmt {-- --port --name --connectpw - --enablepw --sessions -ini } - - With -- --port Waits for socket connections (Telnet) on specified socket, without port - uses default port 5006. (note: linuxcncrsh uses 5007 as default) - With -- --name Sets the server name to specified name for Hello. - With -- --connectpw Sets the connection password to 'password'. Default EMC - With -- --enablepw Sets the enable password to 'password'. Default EMCTOO - With -- --sessions Sets the maximum number of simultaneous connextions - to max sessions. Default is no limit (-1). - With -- -ini , uses specified INI file instead of default emc.ini. - - There are six commands supported, Where the commands set and get contain HAL - specific sub-commands based on the commands supported by halcmd. Commands and - most parameters are not case sensitive. The exceptions are passwords, - file paths and text strings. - - The supported commands are as follows: - - ==> HELLO <== - - Hello - If a valid password was entered the server will respond with - - HELLO ACK - - Where server name and server version are looked up from the implementation. - if an invalid password or any other syntax error occurs then the server - responds with: - - HELLO NAK - - ==> Get <== - - The get command includes one of the hal sub-commands, described below and - zero or more additional parameters. - - ==> Set <== - - The set command inclides one of the hal sub-commands, described below and - one or more additional parameters. - - ==> Quit <== - - The quit command disconnects the associated socket connection. - - ==> Shutdown <== - - The shutdown command tells EMC to shutdown before quitting the connection. This - command may only be issued if the Hello has been successfully negotiated and the - connection has control of the CNC (see enable sub-command below). This command - has no parameters. - - ==> Help <== - - The help command will return help information in text format over the telnet - connection. If no parameters are specified, it will itemize the available commands. - If a command is specified, it will provide usage information for the specified - command. Help will respond regardless of whether a "Hello" has been - successfully negotiated. - - - HAL sub-commands: - - echo on | off - With get will return the current echo state, with set, sets the echo - state. When echo is on, all commands will be echoed upon receipt. This - state is local to each connection. - - verbose on | off - With get will return the current verbose state, with set, sets the - verbose state. When in verbose mode is on, all set commands return - positive acknowledgement in the form SET ACK. In addition, - text error messages will be issued when in verbose mode. This state - is local to each connection. - - enable | off - With get will return On or Off to indicate whether the current connection - is enabled to perform control functions. With set and a valid password, - the current connection is enabled for control functions. "OFF" may not - be used as a password and disables control functions for this connection. - - config [TBD] - - comm_mode ascii | binary - With get, will return the current communications mode. With set, will - set the communications mode to the specified mode. The binary protocol - is TBD. - - comm_prot - With get, returns the current protocol version used by the server, - with set, sets the server to use the specified protocol version, - provided it is lower than or equal to the highest version number - supported by the server implementation. - - Comps [] - - Get only, returns all components beginning with the specified substring. - If no substring is specified then it returns all components. - - Pins [] - - Get only, returns all information about all pins beginning with the - specified substring. If no substring is specified then it returns all pins. - - PinVals [] - - Get only, returns only value information about all pins beginning with the - specified substring. If no substring is specified then it returns all pins. - - Signals [] - - Get only, returns all information about all signals beginning with the - specified substring. If no substring is specified then it returns all signals. - - SigVals [] - - Get only, returns only value information about all signals beginning with the - specified substring. If no substring is specified then it returns all pins. - - Params [] - - Get only, returns all information about all parameters beginning with the - specified substring. If no substring is specified then it returns all - parameters. - - ParamVals [] - - Get only, returns only value information about all parameters beginning with the - specified substring. If no substring is specified then it returns all pins - parameters. - - Functs [] - - Get only, returns all information about all functions beginning with the - specified substring. If no substring is specified then it returns all - functions. - - Threads - - Get only, returns all information about all functions. - - Comp - - Get only, returns the component matching the specified name. - - Pin - - Get only, returns all information about the pin matching the specified - name. - - PinVal - - Get only, returns the value of the pin matching the specified name. - - Sig - - Get only, returns all information about the pin matching the specified - name. - - SigVal - - Get only, returns just the value of the signal matching the specified - name. - - Param - - Get only, returns all information about the parameter matching the - specified name. - - ParamVal - - Get only, returns just the value of the parameter matching the specified - name. - - Funct - - Get only, returns all information about the parameter matching the - specified name. - - Thread - - Get only, returns all information about the thread matching the - specified name. - - LoadRt - - Set only, loads the real time executable specified by name. - - Unload - - Set only, unloads the executable specified by name. - - LoadUsr - - Set only, loads the user executable specified by name. - - Linkps - - Set only, links the specified pin to the specified signal. - - Linksp - - Set only, links the specified signal to the specified pin. - - Linkpp - - Set only, links the pin specified by pin 1 with the pin specified by pin 2. - - Net - - Set only, nets the specified net list. - - Unlinkp - - Set only, unlinks the specified pins - - Lock - - Unlock - - NewSig - - Set only, creates the signal specified by name and of type specified by type. - - DelSig - - Set only, deletes the signal specified by name. - - SetP - - Set only, sets the parameter specified by name to the value specified by value. - - SetS - - Set only, sets the signal specified by name to the value specified by value. - - AddF [] - - Set only, adds the function specified by name, to the thread specified by - thread, with the optional parameters specified by parameters. - - DelF - - Set only, deletes the function specified by name. - - Save - - Start - - Stop - -****************************************************************************/ - -#include "config.h" - -#define _REENTRANT - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include // RTAPI realtime OS API -#include -#include // rtapi_strlcpy -#include // HAL public API decls -#include "../hal_priv.h" // private HAL decls - -/*********************************************************************** -* LOCAL FUNCTION DECLARATIONS * -************************************************************************/ - -/* These functions are used internally by this file. The code is at - the end of the file. */ - -#define MAX_TOK 20 -#define MAX_CMD_LEN 1024 -#define MAX_EXPECTED_SIGS 999 - -static int release_HAL_mutex(void); -static int do_help_cmd(char *command); -static int unloadrt_comp(char *mod_name); -static const char *data_type(int type); -static const char *pin_data_dir(int dir); -static const char *param_data_dir(int dir); -static const char *data_arrow1(int dir); -static const char *data_arrow2(int dir); -static char *data_value(int type, void *valptr); -static char *data_value2(int type, void *valptr); -static void save_comps(FILE *dst); -static void save_signals(FILE *dst); -static void save_links(FILE *dst, int arrows); -static void save_nets(FILE *dst, int arrows); -static void save_params(FILE *dst); -static void save_threads(FILE *dst); -static void print_help_general(int showR); - -/*********************************************************************** -* GLOBAL VARIABLES * -************************************************************************/ - -int comp_id = -1; /* -1 means hal_init() not called yet */ -int hal_flag = 0; /* used to indicate that halrmt might have the - hal mutex, so the sig handler can't just - exit, instead it must set 'done' */ -int done = 0; /* used to break out of processing loop */ -int linenumber=0; /* used to print linenumber on errors */ -int scriptmode = 0; /* used to make output "script friendly" (suppress headers) */ -int prompt_mode = 0; /* when getting input from stdin, print a prompt */ -char comp_name[HAL_NAME_LEN+1]; /* name for this instance of halrmt */ - -char pwd[16] = "EMC\0"; // Connect password -char enablePWD[16] = "EMCTOO\0"; // Enable password -char serverName[24] = "EMCNETSVR\0"; // Server name written in hello response -int sessions = 0; // Number of open sessions -int maxSessions = -1; // Maximum number of sessions to allow - -typedef struct { - int cliSock; - char hostName[80]; - char version[8]; - int linked; - int echo; - int verbose; - int enabled; - int commMode; - int commProt; - char inBuf[256]; - char outBuf[4096]; - char progName[256];} connectionRecType; - - -int port = 5006; -char errorStr[256]; - -int server_sockfd, client_sockfd; -socklen_t server_len, client_len; -struct sockaddr_in server_address; -struct sockaddr_in client_address; -int useSockets = 1; -int tokenIdx; -const char *delims = " \n\r\0"; -int connCount = -1; -int enabledConn = -1; - -typedef enum { - cmdHello, cmdSet, cmdGet, cmdQuit, cmdShutdown, cmdHelp, cmdUnknown} commandTokenType; - -typedef enum { - hcEcho, hcVerbose, hcEnable, hcConfig, hcCommMode, hcCommProt, - hcComps, hcPins, hcPinVals, hcSigs, hcSigVals, hcParams, hcParamVals, hcFuncts, hcThreads, - hcComp, hcPin, hcPinVal, hcSig, hcSigVal, hcParam, hcParamVal, hcFunct, hcThread, - hcLoadRt, hcUnload, hcLoadUsr, hcLinkps, hcLinksp, hcLinkpp, hcNet, hcUnlinkp, - hcLock, hcUnlock, hcNewSig, hcDelSig, hcSetP, hcSetS, hcAddF, hcDelF, - hcSave, hcStart, hcStop, hcUnknown - } halCommandType; - -typedef enum { - rtNoError, rtHandledNoError, rtStandardError, rtCustomError, rtCustomHandledError - } cmdResponseType; - -struct option longopts[] = { - {"port", 1, NULL, 'p'}, - {"name", 1, NULL, 'n'}, - {"sessions", 1, NULL, 's'}, - {"connectpw", 1, NULL, 'w'}, - {"enablepw", 1, NULL, 'e'}, - {NULL,0,NULL,0} -}; - -const char *commands[] = {"HELLO", "SET", "GET", "QUIT", "SHUTDOWN", "HELP", ""}; -const char *halCommands[] = { - "ECHO", "VERBOSE", "ENABLE", "CONFIG", "COMM_MODE", "COMM_PROT", - "COMPS", "PINS", "PINVALS", "SIGNALS", "SIGVALS", "PARAMS", "PARAMVALS", "FUNCTS", "THREADS", - "COMP", "PIN", "PINVAL", "SIGNAL", "SIGVAL", "PARAM", "PARAMVAL", "FUNCT", "THREAD", - "LOADRT", "UNLOAD", "LOADUSR", "LINKPS", "LINKSP", "LINKPP", "NET", "UNLINKP", - "LOCK", "UNLOCK", "NEWSIG", "DELSIG", "SETP", "SETS", "ADDF", "DELF", - "SAVE", "START", "STOP", ""}; - -#ifndef NO_INI - FILE *inifile = NULL; -#endif - - -/* signal handler */ -static void quit(int sig) -{ - (void)sig; - if ( hal_flag ) { - /* this process might have the hal mutex, so just set the - 'done' flag and return, exit after mutex work finishes */ - done = 1; - } else { - /* don't have to worry about the mutex, but if we just - return, we might return into the fgets() and wait - all day instead of exiting. So we exit from here. */ - if ( comp_id > 0 ) { - hal_exit(comp_id); - } - _exit(1); - } -} - -static void strupr(char *s) -{ - int i; - - for (i = 0; i < (int)strlen(s); i++) - if (s[i] > 96 && s[i] <= 'z') - s[i] -= 32; -} - -static int initSockets() -{ - int optval = 1; - - server_sockfd = socket(AF_INET, SOCK_STREAM, 0); - setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); - server_address.sin_family = AF_INET; - server_address.sin_addr.s_addr = htonl(INADDR_ANY); - server_address.sin_port = htons(port); - server_len = sizeof(server_address); - bind(server_sockfd, (struct sockaddr *)&server_address, server_len); - listen(server_sockfd, 5); - signal(SIGCHLD, SIG_IGN); - return 0; -} - -static int sockWrite(connectionRecType *context) -{ - rtapi_strxcat(context->outBuf, "\r\n"); - return write(context->cliSock, context->outBuf, strlen(context->outBuf)); -} - -static void sockWriteError(const char *nakStr, connectionRecType *context) -{ - if (context->verbose == 1) - snprintf(context->outBuf, sizeof(context->outBuf), "%s %s", nakStr, errorStr); - else - snprintf(context->outBuf, sizeof(context->outBuf), "%s", nakStr); - if(sockWrite(context) < 0) perror("sockWrite"); -} - -pid_t hal_systemv_nowait(char *const argv[], connectionRecType *context) { - pid_t pid; - int n; - const char *nakStr = "SET LOADRT NAK"; - - /* now we need to fork, and then exec .... */ - /* disconnect from the HAL shmem area before forking */ - hal_exit(comp_id); - comp_id = 0; - /* now the fork() */ - pid = fork(); - if ( pid < 0 ) { - /* fork failed */ -// halcmd_error("fork() failed\n"); - /* reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - if (comp_id < 0) { - fprintf(stderr, "halcmd: hal_init() failed after fork: %d\n", - comp_id ); - exit(-1); - } - hal_ready(comp_id); - return -1; - } - if ( pid == 0 ) { - /* child process */ - /* print debugging info if "very verbose" (-V) */ - for(n=0; argv[n] != NULL; n++) { - rtapi_print_msg(RTAPI_MSG_DBG, "%s ", argv[n] ); - } - if (n == 0) { - snprintf(errorStr, sizeof(errorStr), "hal_systemv_nowait: empty argv array passed in\n"); - sockWriteError(nakStr, context); - exit(1); - } - rtapi_print_msg(RTAPI_MSG_DBG, "\n" ); - /* call execv() to invoke command */ - execvp(argv[0], argv); - /* should never get here */ -// halcmd_error("execv(%s) failed\n", argv[0] ); - snprintf(errorStr, sizeof(errorStr), "execv(%s) failed", argv[0]); - sockWriteError(nakStr, context); - exit(1); - } - /* parent process */ - /* reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - - return pid; -} - -int hal_systemv(char *const argv[], connectionRecType *context) { - pid_t pid; - int status; - int retval; - const char *nakStr = "SET LOADRT NAK"; - - /* do the fork */ - pid = hal_systemv_nowait(argv, context); - /* this is the parent process, wait for child to end */ - retval = waitpid ( pid, &status, 0 ); - retval = 0; - if (comp_id < 0) { - fprintf(stderr, "halcmd: hal_init() failed after systemv: %d\n", comp_id ); - exit(-1); - } - hal_ready(comp_id); - /* check result of waitpid() */ - if ( retval < 0 ) { -// halcmd_error("waitpid(%d) failed: %s\n", pid, strerror(errno) ); - snprintf(errorStr, sizeof(errorStr), "waitpid(%d) failed: %s", pid, strerror(errno)); - sockWriteError(nakStr, context); - return -1; - } - if ( WIFEXITED(status) == 0 ) { -// halcmd_error("child did not exit normally\n"); - snprintf(errorStr, sizeof(errorStr), "child did not exit normally"); - sockWriteError(nakStr, context); - return -1; - } - retval = WEXITSTATUS(status); - if ( retval != 0 ) { -// halcmd_error("exit value: %d\n", retval ); - snprintf(errorStr, sizeof(errorStr), "exit value: %d", retval); - sockWriteError(nakStr, context); - return -1; - } - return 0; -} - - -/*********************************************************************** -* LOCAL FUNCTION DEFINITIONS * -************************************************************************/ - -/* release_HAL_mutex() unconditionally releases the hal_mutex - very useful after a program segfaults while holding the mutex -*/ -static int release_HAL_mutex(void) -{ - int comp_id, mem_id, retval; - void *mem; - hal_data_t *hal_data; - - /* do RTAPI init */ - comp_id = rtapi_init("hal_unlocker"); - if (comp_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, "ERROR: rtapi init failed\n"); - return -EINVAL; - } - /* get HAL shared memory block from RTAPI */ - mem_id = rtapi_shmem_new(HAL_KEY, comp_id, HAL_SIZE); - if (mem_id < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "ERROR: could not open shared memory\n"); - rtapi_exit(comp_id); - return -EINVAL; - } - /* get address of shared memory area */ - retval = rtapi_shmem_getptr(mem_id, &mem); - if (retval < 0) { - rtapi_print_msg(RTAPI_MSG_ERR, - "ERROR: could not access shared memory\n"); - rtapi_exit(comp_id); - return -EINVAL; - } - /* set up internal pointers to shared mem and data structure */ - hal_data = (hal_data_t *) mem; - /* release mutex */ - rtapi_mutex_give(&(hal_data->mutex)); - /* release RTAPI resources */ - rtapi_shmem_delete(mem_id, comp_id); - rtapi_exit(comp_id); - /* done */ - return 0; - -} - -static int doLock(char *command, connectionRecType *context) -{ - int retval = 0; - const char *nakStr = "SET LOCK NAK"; - - /* if command is blank, want to lock everything */ - if (*command == '\0') - retval = hal_set_lock(HAL_LOCK_ALL); - else if (strcmp(command, "none") == 0) - retval = hal_set_lock(HAL_LOCK_NONE); - else if (strcmp(command, "tune") == 0) - retval = hal_set_lock(HAL_LOCK_TUNE); - else if (strcmp(command, "all") == 0) - retval = hal_set_lock(HAL_LOCK_ALL); - - if (retval != 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Locking failed", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doUnlock(char *command, connectionRecType *context) -{ - int retval=0; - const char *nakStr = "SET UNLOCK NAK"; - - /* if command is blank, want to unlock everything */ - if (*command == '\0') - retval = hal_set_lock(HAL_LOCK_NONE); - else if (strcmp(command, "none") == 0) - retval = hal_set_lock(HAL_LOCK_NONE); - else if (strcmp(command, "tune") == 0) - retval = hal_set_lock(hal_get_lock() & ~HAL_LOCK_TUNE); - else if (strcmp(command, "all") == 0) - retval = hal_set_lock(HAL_LOCK_NONE); - - if (retval != 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Unlocking failed", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doLinkpp(char *first_pin_name, char *second_pin_name, connectionRecType *context) -{ - int retval; - hal_pin_t *first_pin, *second_pin; - const char *nakStr = "SET LINKPP NAK"; - - rtapi_mutex_get(&(hal_data->mutex)); - /* check if the pins are there */ - first_pin = halpr_find_pin_by_name(first_pin_name); - second_pin = halpr_find_pin_by_name(second_pin_name); - if (first_pin == NULL) { - /* first pin not found*/ - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), "HAL:%d: ERROR: pin '%s' not found\n", linenumber, first_pin_name); - sockWriteError(nakStr, context); - return -EINVAL; - } - else - if (second_pin == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), "HAL:%d: ERROR: pin '%s' not found", linenumber, second_pin_name); - sockWriteError(nakStr, context); - return -EINVAL; - } - - /* give the mutex, as the other functions use their own mutex */ - rtapi_mutex_give(&(hal_data->mutex)); - - /* check that both pins have the same type, - don't want to create a sig, which after that won't be useful */ - if (first_pin->type != second_pin->type) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: ERROR: pins '%s' and '%s' not of the same type", - linenumber, first_pin_name, second_pin_name); - sockWriteError(nakStr, context); - return -EINVAL; - } - - /* now create the signal */ - retval = hal_signal_new(first_pin_name, first_pin->type); - - if (retval == 0) { - /* if it worked, link the pins to it */ - retval = hal_link(first_pin_name, first_pin_name); - - if ( retval == 0 ) - /* if that worked, link the second pin to the new signal */ - retval = hal_link(second_pin_name, first_pin_name); - } - if (retval < 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: linkpp failed", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -int doLinkPS(char *pin, char *sig, connectionRecType *context) -{ - int retval; - const char *nakStr = "SET NET NAK"; - - retval = hal_link(pin, sig); - if (retval == 0) { - /* print success message */ -// halcmd_info("Pin '%s' linked to signal '%s'\n", pin, sig); - snprintf(errorStr, sizeof(errorStr), "Pin '%s' linked to signal '%s'", pin, sig); - sockWriteError(nakStr, context); - } else { -// halcmd_error("link failed\n"); - snprintf(errorStr, sizeof(errorStr), "link failed"); - sockWriteError(nakStr, context); - } - return retval; -} - - -static int preflightNet(char *signal, hal_sig_t *sig, char *pins[], connectionRecType *context) -{ - int i, type=-1, writers=0, bidirs=0, pincnt=0; - const char *nakStr = "SET NET NAK"; - - /* if signal already exists, use its info */ - if (sig) { - type = sig->type; - writers = sig->writers; - bidirs = sig->bidirs; - } - - for(i=0; pins[i] && *pins[i]; i++) { - hal_pin_t *pin = NULL; - pin = halpr_find_pin_by_name(pins[i]); - if(!pin) { -// halcmd_error("pin '%s' does not exist\n", pins[i]); - snprintf(errorStr, sizeof(errorStr), "pin '%s' does not exist", pins[i]); - sockWriteError(nakStr, context); - return -ENOENT; - } - if(SHMPTR(pin->signal) == sig) { - /* Already on this signal */ - pincnt++; - continue; - } else if(pin->signal != 0) { -// halcmd_error("pin '%s' was already linked\n", pin->name); - snprintf(errorStr, sizeof(errorStr), "pin '%s' was already linked", pin->name); - sockWriteError(nakStr, context); - return -EINVAL; - } - if (type == -1) { - /* no pre-existing type, use this pin's type */ - type = pin->type; - } - if(type != pin->type) { -// halcmd_error("Type mismatch on pin '%s'\n", pin->name); - snprintf(errorStr, sizeof(errorStr), "Type mismatch on pin '%s'", pin->name); - sockWriteError(nakStr, context); - return -EINVAL; - } - if(pin->dir == HAL_OUT) { - if(writers || bidirs) { -// halcmd_error("Signal '%s' can not add OUT pin '%s'\n", signal, pin->name); - snprintf(errorStr, sizeof(errorStr), "Signal '%s' can not add OUT pin '%s'", signal, pin->name); - sockWriteError(nakStr, context); - return -EINVAL; - } - writers++; - } - if(pin->dir == HAL_IO) { - if(writers) { -// halcmd_error("Signal '%s' can not add I/O pin '%s'\n", signal, pin->name); - snprintf(errorStr, sizeof(errorStr), "Signal '%s' can not add I/O pin '%s'", signal, pin->name); - sockWriteError(nakStr, context); - return -EINVAL; - } - bidirs++; - } - pincnt++; - } - if(pincnt) - return 0; -// halcmd_error("'net' requires at least one pin, none given\n"); - snprintf(errorStr, sizeof(errorStr), "'net' requires at least one pin, none given"); - sockWriteError(nakStr, context); - return -EINVAL; -} - - -int doNet(char *signal, char *pins[], connectionRecType *context) -{ - hal_sig_t *sig; - int i, retval; - const char *nakStr = "SET NET NAK"; - - rtapi_mutex_get(&(hal_data->mutex)); - /* see if signal already exists */ - sig = halpr_find_sig_by_name(signal); - - /* verify that everything matches up (pin types, etc) */ - retval = preflightNet(signal, sig, pins, context); - if(retval < 0) { - rtapi_mutex_give(&(hal_data->mutex)); - return retval; - } - - { - hal_pin_t *pin = halpr_find_pin_by_name(signal); - if(pin) { -// halcmd_error("Signal name '%s' must not be the same as a pin.\n", signal); - snprintf(errorStr, sizeof(errorStr), "Signal name '%s' must not be the same as a pin.", signal); - sockWriteError(nakStr, context); - rtapi_mutex_give(&(hal_data->mutex)); - return -ENOENT; - } - } - if(!sig) { - /* Create the signal with the type of the first pin */ - hal_pin_t *pin = halpr_find_pin_by_name(pins[0]); - rtapi_mutex_give(&(hal_data->mutex)); - if(!pin) { - return -ENOENT; - } - retval = hal_signal_new(signal, pin->type); - } else { - /* signal already exists */ - rtapi_mutex_give(&(hal_data->mutex)); - } - /* add pins to signal */ - for(i=0; retval == 0 && pins[i] && *pins[i]; i++) { - retval = doLinkPS(pins[i], signal, context); - } - - return retval; -} - - -static int doLink(char *pin, char *sig, connectionRecType *context) -{ - int retval; - const char *nakStr = "SET LINKPS NAK"; - - /* if sig is blank, want to unlink pin */ - if (*sig == '\0') { - /* unlink the pin */ - retval = hal_unlink(pin); - } else { - /* make the link */ - retval = hal_link(pin, sig); - } - if (retval != 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: link failed", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doNewsig(char *name, char *type, connectionRecType *context) -{ - int retval; - const char *nakStr = "SET NEWSIG NAK"; - - if (strcasecmp(type, "bit") == 0) - retval = hal_signal_new(name, HAL_BIT); - else - if (strcasecmp(type, "float") == 0) - retval = hal_signal_new(name, HAL_FLOAT); - else - if (strcasecmp(type, "u16") == 0) - retval = hal_signal_new(name, HAL_U32); - else - if (strcasecmp(type, "s32") == 0) - retval = hal_signal_new(name, HAL_S32); - else { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Unknown signal type '%s'", - linenumber, type); - sockWriteError(nakStr, context); - retval = -EINVAL; - } - if (retval < 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: newsig failed", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int set_common(hal_type_t type, void *d_ptr, char *value, connectionRecType *context) { - (void)context; - // This function assumes that the mutex is held - int retval = 0; - double fval; - long lval; - unsigned long ulval; - char *cp = value; - - switch (type) { - case HAL_BIT: - if ((strcmp("1", value) == 0) || (strcasecmp("TRUE", value) == 0)) { - *(hal_bit_t *) (d_ptr) = 1; - } else if ((strcmp("0", value) == 0) - || (strcasecmp("FALSE", value)) == 0) { - *(hal_bit_t *) (d_ptr) = 0; - } else { - retval = -EINVAL; - } - break; - case HAL_FLOAT: - fval = strtod ( value, &cp ); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid character(s) in string */ - retval = -EINVAL; - } else { - *((hal_float_t *) (d_ptr)) = fval; - } - break; - case HAL_S32: - lval = strtol(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - retval = -EINVAL; - } else { - *((hal_s32_t *) (d_ptr)) = lval; - } - break; - case HAL_U32: - ulval = strtoul(value, &cp, 0); - if ((*cp != '\0') && (!isspace(*cp))) { - /* invalid chars in string */ - retval = -EINVAL; - } else { - *((hal_u32_t *) (d_ptr)) = ulval; - } - break; - default: - /* Shouldn't get here, but just in case... */ - retval = -EINVAL; - } - return retval; -} - -static int doSetp(char *name, char *value, connectionRecType *context) -{ - const char *nakStr = "SET SETP NAK"; - int retval; - hal_param_t *param; - hal_pin_t *pin; - hal_type_t type; - void *d_ptr; - - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search param list for name */ - param = halpr_find_param_by_name(name); - if (param == NULL) { - pin = halpr_find_pin_by_name(name); - if(pin == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), - "HAL:%d: ERROR: parameter or pin '%s' not found\n", linenumber, name); - sockWriteError(nakStr, context); - return -EINVAL; - } else { - /* found it */ - type = pin->type; - if(pin->dir == HAL_OUT) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), - "HAL:%d: ERROR: pin '%s' is not writable\n", linenumber, name); - sockWriteError(nakStr, context); - return -EINVAL; - } - if(pin->signal != 0) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), - "HAL:%d: ERROR: pin '%s' is connected to a signal\n", linenumber, name); - sockWriteError(nakStr, context); - return -EINVAL; - } - // d_ptr = (void*)SHMPTR(pin->dummysig); - d_ptr = (void*)&pin->dummysig; - } - } else { - /* found it */ - type = param->type; - /* is it read only? */ - if (param->dir == HAL_RO) { - rtapi_mutex_give(&(hal_data->mutex)); - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: param '%s' is not writable\n", linenumber, name); - return -EINVAL; - } - d_ptr = SHMPTR(param->data_ptr); - } - - retval = set_common(type, d_ptr, value, context); - - rtapi_mutex_give(&(hal_data->mutex)); - if (retval != 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: setp failed\n", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doSets(char *name, char *value, connectionRecType *context) -{ - const char *nakStr = "SET SETS NAK"; - int retval; - hal_sig_t *sig; - hal_type_t type; - void *d_ptr; - - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search signal list for name */ - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), - "HAL:%d: ERROR: signal '%s' not found\n", linenumber, name); - sockWriteError(nakStr, context); - return -EINVAL; - } - /* found it - does it have a writer? */ - if (sig->writers > 0) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), - "HAL:%d: ERROR: signal '%s' already has writer(s)\n", linenumber, name); - sockWriteError(nakStr, context); - return -EINVAL; - } - /* no writer, so we can safely set it */ - type = sig->type; - d_ptr = SHMPTR(sig->data_ptr); - retval = set_common(type, d_ptr, value, context); - rtapi_mutex_give(&(hal_data->mutex)); - if (retval != 0) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: sets failed\n", linenumber); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doAddf(char *name, char *thread, char *parm, connectionRecType *context) -{ - int retval; - const char *nakStr = "SET ADDF NAK"; - - if (parm[0] == '\0') - /* no - add function at end of thread */ - retval = hal_add_funct_to_thread(name, thread, -1); - else - retval = hal_add_funct_to_thread(name, thread, atoi(parm)); - if (retval != 0) { - /* print fail message */ - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Unable to add function '%s' to thread '%s'", linenumber, name, thread); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doDelf(char *name, char *thread, connectionRecType *context) -{ - int retval; - const char *nakStr = "SET DELF NAK"; - - retval = hal_del_funct_from_thread(name, thread); - if (retval != 0) { - /* print success message */ - snprintf(errorStr, sizeof(errorStr), "Failed to remove function '%s' from thread '%s'", name, thread); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doStart(connectionRecType *context) -{ - int retval; - const char *nakStr = "SET START NAK"; - - retval = hal_start_threads(); - if (retval != 0) { - /* print success message */ - snprintf(errorStr, sizeof(errorStr), "Failed to start realtime threads"); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doStop(connectionRecType *context) -{ - int retval; - const char *nakStr = "SET STOP NAK"; - - retval = hal_stop_threads(); - if (retval != 0) { - /* print success message */ - snprintf(errorStr, sizeof(errorStr), "Unable to stop realtime threads"); - sockWriteError(nakStr, context); - } - return retval; -} - -static int doLoadRt(char *mod_name, char *args[], connectionRecType *context) -{ - char arg_string[MAX_CMD_LEN+1]; - int n=0, retval=0; - hal_comp_t *comp; - char *cp1; - const char *nakStr = "SET LOADRT NAK"; - -#if defined(RTAPI_USPACE) -#if 0 - argv[m++] = "-Wn"; - argv[m++] = mod_name; - argv[m++] = EMC2_BIN_DIR "/rtapi_app"; - argv[m++] = "load"; - argv[m++] = mod_name; - /* loop thru remaining arguments */ - while ( args[n] && args[n][0] != '\0' ) { - argv[m++] = args[n++]; - } - argv[m++] = NULL; -// retval = do_loadusr_cmd(argv); -#endif -#else - int m=0; - char *argv[MAX_TOK+3]; - static char *rtmod_dir = EMC2_RTLIB_DIR; - struct stat stat_buf; - char mod_path[MAX_CMD_LEN+1]; - - if (hal_get_lock()&HAL_LOCK_LOAD) { - snprintf(errorStr, sizeof(errorStr), "HAL is locked, loading of modules is not permitted"); - sockWriteError(nakStr, context); - return -EPERM; - } - if ( (strlen(rtmod_dir)+strlen(mod_name)+5) > MAX_CMD_LEN ) { - snprintf(errorStr, sizeof(errorStr), "Module path too long"); - sockWriteError(nakStr, context); - return -1; - } - - /* make full module name '/.o' */ - rtapi_strxcpy (mod_path, rtmod_dir); - rtapi_strxcat (mod_path, "/"); - rtapi_strxcat (mod_path, mod_name); - rtapi_strxcat (mod_path, MODULE_EXT); - /* is there a file with that name? */ - if ( stat(mod_path, &stat_buf) != 0 ) { - /* can't find it */ - snprintf(errorStr, sizeof(errorStr), "Can't find module '%s' in %s", mod_name, rtmod_dir); - sockWriteError(nakStr, context); - return -1; - } - - // TODO - FIXME - remove test after 2.2.x when blocks isn't functional anymore - if (strncmp(mod_name, "blocks", 6) == 0) { - //using RTAPI_MSG_ERR as that is the default warning level for halcmd - snprintf(errorStr, sizeof(errorStr), "blocks is deprecated, use the subcomponents generated by 'comp' instead"); - sockWriteError(nakStr, context); - } - - argv[0] = EMC2_BIN_DIR "/linuxcnc_module_helper"; - argv[1] = "insert"; - argv[2] = mod_path; - /* loop thru remaining arguments */ - n = 0; - m = 3; - while ( args[n] && args[n][0] != '\0' ) { - argv[m++] = args[n++]; - } - /* add a NULL to terminate the argv array */ - argv[m] = NULL; -/* snprintf(context->outBuf, sizeof(context->outBuf), "Setup argv %s %s %s", argv[0], argv[1], argv[2]); - sockWrite(context); - return 0; */ - - - retval = hal_systemv(argv, context); -#endif - - if ( retval != 0 ) { - snprintf(errorStr, sizeof(errorStr), "insmod failed, returned %d", retval); - sockWriteError(nakStr, context); - return -1; - } - /* make the args that were passed to the module into a single string */ - n = 0; - arg_string[0] = '\0'; - while ( args[n] && args[n][0] != '\0' ) { - strncat(arg_string, args[n++], MAX_CMD_LEN); - strncat(arg_string, " ", MAX_CMD_LEN); - } - /* allocate HAL shmem for the string */ - cp1 = hal_malloc(strlen(arg_string)+1); - if ( cp1 == NULL ) { - snprintf(errorStr, sizeof(errorStr), "failed to allocate memory for module args"); - sockWriteError(nakStr, context); - return -1; - } - /* copy string to shmem */ - strcpy (cp1, arg_string); - /* get mutex before accessing shared data */ - rtapi_mutex_get(&(hal_data->mutex)); - /* search component list for the newly loaded component */ - comp = halpr_find_comp_by_name(mod_name); - if (comp == NULL) { - rtapi_mutex_give(&(hal_data->mutex)); - snprintf(errorStr, sizeof(errorStr), "module '%s' not loaded", mod_name); - sockWriteError(nakStr, context); - return -EINVAL; - } - /* link args to comp struct */ - comp->insmod_args = SHMOFF(cp1); - rtapi_mutex_give(&(hal_data->mutex)); - /* print success message */ -// halcmd_info("Realtime module '%s' loaded\n", mod_name); - return 0; -} - -static int doDelsig(char *mod_name, connectionRecType *context) -{ - int next, retval, retval1, n; - hal_sig_t *sig; - char sigs[MAX_EXPECTED_SIGS][HAL_NAME_LEN+1]; - const char *nakStr = "SET DELSIG NAK"; - - /* check for "all" */ - if ( strcmp(mod_name, "all" ) != 0 ) { - retval = hal_signal_delete(mod_name); - return retval; - } - else { - /* build a list of signal(s) to delete */ - n = 0; - rtapi_mutex_get(&(hal_data->mutex)); - - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - /* we want to unload this signal, remember it's name */ - if (n < ( MAX_EXPECTED_SIGS - 1)) { - snprintf(sigs[n], sizeof(sigs[n]), "%s", sig->name); - n++; - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); - sigs[n][0] = '\0'; - - if (sigs[0][0] == '\0') { - /* desired signals not found */ - snprintf(errorStr, sizeof(errorStr), "HAL:%d: ERROR: no signals found to be deleted", linenumber); - sockWriteError(nakStr, context); - return -1; - } - /* we now have a list of components, unload them */ - n = 0; - retval1 = 0; - while (sigs[n][0] != '\0') { - retval = hal_signal_delete(sigs[n]); - /* check for fatal error */ - if (retval < -1) - return retval; - /* check for other error */ - if (retval != 0) - retval1 = retval; - n++; - } - } - return retval1; -} - -static int doUnload(char *mod_name, connectionRecType *context) -{ - int next, retval, retval1, n, all; - hal_comp_t *comp; - char comps[64][HAL_NAME_LEN+1]; - const char *nakStr = "SET UNLOAD NAK"; - - /* check for "all" */ - if ( strcmp(mod_name, "all" ) == 0 ) { - all = 1; - } else { - all = 0; - } - /* build a list of component(s) to unload */ - n = 0; - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_REALTIME ) { - /* found a realtime component */ - if ( all || ( strcmp(mod_name, comp->name) == 0 )) { - /* we want to unload this component, remember its name */ - if ( n < 63 ) { - snprintf(comps[n], sizeof(comps[n]), "%s", comp->name); - comps[n][HAL_NAME_LEN] = '\0'; - n++; - } - } - } - next = comp->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); - /* mark end of list */ - comps[n][0] = '\0'; - if ( !all && ( comps[0][0] == '\0' )) { - /* desired component not found */ -// halcmd_error("component '%s' is not loaded\n", mod_name); - snprintf(errorStr, sizeof(errorStr), "component '%s' is not loaded", mod_name); - sockWriteError(nakStr, context); - return -1; - } - /* we now have a list of components, unload them */ - n = 0; - retval1 = 0; - while ( comps[n][0] != '\0' ) { - retval = unloadrt_comp(comps[n++]); - /* check for fatal error */ - if ( retval < -1 ) { - return retval; - } - /* check for other error */ - if ( retval != 0 ) { - retval1 = retval; - } - } -/* if (retval1 < 0) { - snprintf(errorStr, sizeof(errorStr), "unloadrt failed"); - sockWriteError(nakStr, context); - } */ - return retval1; -} - -static int unloadrt_comp(char *mod_name) -{ - int retval, status; - char *argv[4]; - pid_t pid; - - /* now we need to fork, and then exec rmmod.... */ - /* disconnect from the HAL shmem area before forking */ - hal_exit(comp_id); - comp_id = 0; - /* now the fork() */ - pid = fork(); - if ( pid < 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: unloadrt fork() failed\n", linenumber); - /* reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - if (comp_id < 0) { - fprintf(stderr, "halrmt: hal_init() failed after fork: %d\n", - comp_id); - exit(-1); - } - hal_ready(comp_id); - return -1; - } - if ( pid == 0 ) { - /* this is the child process - prepare to exec() rmmod */ - argv[0] = EMC2_BIN_DIR "/linuxcnc_module_helper"; - argv[1] = "remove"; - argv[2] = mod_name; - /* add a NULL to terminate the argv array */ - argv[3] = NULL; - /* print debugging info if "very verbose" (-V) */ - rtapi_print_msg(RTAPI_MSG_DBG, "%s %s %s\n", argv[0], argv[1], argv[2] ); - /* call execv() to invoke rmmod */ - execv(argv[0], argv); - /* should never get here */ - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: execv(%s) failed\n", linenumber, argv[0] ); - exit(1); - } - /* this is the parent process, wait for child to end */ - retval = waitpid ( pid, &status, 0 ); - /* reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - if (comp_id < 0) { - fprintf(stderr, "halrmt: hal_init() failed after unloadrt: %d\n", - comp_id ); - exit(-1); - } - hal_ready(comp_id); - /* check result of waitpid() */ - if ( retval < 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: waitpid(%d) failed\n", linenumber, pid); - return -1; - } - if ( WIFEXITED(status) == 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: child did not exit normally\n", linenumber); - return -1; - } - retval = WEXITSTATUS(status); - if ( retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: rmmod failed, returned %d\n", linenumber, retval); - return -1; - } - /* print success message */ - rtapi_print_msg(RTAPI_MSG_INFO, "Realtime module '%s' unloaded\n", - mod_name); - return 0; -} - -static int doLoadUsr(char *args[]) -{ - int wait_flag, wait_comp_flag, name_flag, ignore_flag; - char *prog_name, *new_comp_name; - char prog_path[MAX_CMD_LEN+1]; - char *cp1, *cp2, *envpath; - struct stat stat_buf; - char *argv[MAX_TOK+1]; - int n, m, retval, status; - pid_t pid; - - if (hal_get_lock()&HAL_LOCK_LOAD) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: HAL is locked, loading of programs is not permitted\n", linenumber); - return -EPERM; - } - /* check for options (-w, -i, and/or -r) */ - wait_flag = 0; - wait_comp_flag = 0; - name_flag = 0; - ignore_flag = 0; - prog_name = NULL; - while ( **args == '-' ) { - /* this argument contains option(s) */ - cp1 = *args; - cp1++; - while ( *cp1 != '\0' ) { - if ( *cp1 == 'w' ) { - wait_flag = 1; - } else if ( *cp1 == 'W' ) { - wait_comp_flag = 1; - } else if ( *cp1 == 'i' ) { - ignore_flag = 1; - } else if ( *cp1 == 'n' ) { - name_flag = 1; - } else { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: unknown loadusr option '-%c'\n", linenumber, *cp1); - return -EINVAL; - } - cp1++; - } - /* move to next arg */ - args++; - } - /* get program and component name */ - if(name_flag) { - new_comp_name = *args++; - prog_name = *args++; - } else { - new_comp_name = prog_name = *args++; - } - /* need to find path to a program matching "prog_name" */ - prog_path[0] = '\0'; - if ( prog_path[0] == '\0' ) { - /* try the name by itself */ - rtapi_strlcpy(prog_path, prog_name, MAX_CMD_LEN); - rtapi_print_msg(RTAPI_MSG_DBG, "Trying '%s'\n", prog_path); - if ( stat(prog_path, &stat_buf) != 0 ) { - /* no luck, clear prog_path to indicate failure */ - prog_path[0] = '\0'; - } - } - if ( prog_path[0] == '\0' ) { - /* no luck yet, try the emc2/bin directory where - the halrmt executable is located */ - n = readlink("/proc/self/exe", prog_path, MAX_CMD_LEN-10); - if ( n > 0 ) { - prog_path[n] = '\0'; - /* have path to executabie, find last '/' */ - cp2 = ""; - cp1 = prog_path; - while ( *cp1 != '\0' ) { - if ( *cp1 == '/' ) { - cp2 = cp1; - } - cp1++; - } - if ( *cp2 == '/' ) { - /* chop "halrmt" from end of path */ - *(++cp2) = '\0'; - /* append the program name */ - strncat(prog_path, prog_name, MAX_CMD_LEN-strlen(prog_path)); - /* and try it */ - rtapi_print_msg(RTAPI_MSG_DBG, "Trying '%s'\n", prog_path); - if ( stat(prog_path, &stat_buf) != 0 ) { - /* no luck, clear prog_path to indicate failure */ - prog_path[0] = '\0'; - } - } - } - } - if ( prog_path[0] == '\0' ) { - /* no luck yet, try the user's PATH */ - envpath = getenv("PATH"); - if ( envpath != NULL ) { - while ( *envpath != '\0' ) { - /* copy a single directory from the PATH env variable */ - n = 0; - while ( (*envpath != ':') && (*envpath != '\0') && (n < MAX_CMD_LEN)) { - prog_path[n++] = *envpath++; - } - /* append '/' and program name */ - if ( n < MAX_CMD_LEN ) { - prog_path[n++] = '/'; - } - cp1 = prog_name; - while ((*cp1 != '\0') && ( n < MAX_CMD_LEN)) { - prog_path[n++] = *cp1++; - } - prog_path[n] = '\0'; - rtapi_print_msg(RTAPI_MSG_DBG, "Trying '%s'\n", prog_path); - if ( stat(prog_path, &stat_buf) != 0 ) { - /* no luck, clear prog_path to indicate failure */ - prog_path[0] = '\0'; - /* and get ready to try the next directory */ - if ( *envpath == ':' ) { - envpath++; - } - } else { - /* success, break out of loop */ - break; - } - } - } - } - if ( prog_path[0] == '\0' ) { - /* still can't find a program to run */ - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: Can't find program '%s'\n", linenumber, prog_name); - return -1; - } - - /* now we need to fork, and then exec the program.... */ - /* disconnect from the HAL shmem area before forking */ - hal_exit(comp_id); - comp_id = 0; - /* now the fork() */ - pid = fork(); - if ( pid < 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: loadusr fork() failed\n", linenumber); - /* reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - if (comp_id < 0) { - fprintf(stderr, "halrmt: hal_init() failed after fork: %d\n", - comp_id); - exit(-1); - } - hal_ready(comp_id); - return -1; - } - if ( pid == 0 ) { - /* this is the child process - prepare to exec() the program */ - argv[0] = prog_name; - /* loop thru remaining arguments */ - n = 0; - m = 1; - while ( args[n][0] != '\0' ) { - argv[m++] = args[n++]; - } - /* add a NULL to terminate the argv array */ - argv[m] = NULL; - /* print debugging info if "very verbose" (-V) */ - rtapi_print_msg(RTAPI_MSG_DBG, "%s ", argv[0] ); - n = 1; - while ( argv[n] != NULL ) { - rtapi_print_msg(RTAPI_MSG_DBG, "%s ", argv[n++] ); - } - rtapi_print_msg(RTAPI_MSG_DBG, "\n" ); - /* call execv() to invoke the program */ - execv(prog_path, argv); - /* should never get here */ - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: execv(%s) failed: %s\n", linenumber, prog_name, - strerror(errno)); - exit(1); - } - /* this is the parent process, reconnect to the HAL shmem area */ - comp_id = hal_init(comp_name); - if (comp_id < 0) { - fprintf(stderr, "halrmt: hal_init() failed after loadusr: %d\n", - comp_id); - exit(-1); - } - hal_ready(comp_id); - if ( wait_comp_flag ) { - int ready = 0, count=0; - int next; - while(!ready) { - struct timespec ts = {0, 10 * 1000 * 1000}; // 10ms - nanosleep(&ts, NULL); - retval = waitpid( pid, &status, WNOHANG ); - if(retval != 0) goto wait_common; - - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while(next) { - hal_comp_t *comp = SHMPTR(next); - next = comp->next_ptr; - if(strcmp(comp->name, new_comp_name) == 0 && comp->ready) { - ready = 1; - break; - } - } - rtapi_mutex_give(&(hal_data->mutex)); - - count++; - if(count == 100) { - fprintf(stderr, "Waiting for component '%s' to become ready.", - new_comp_name); - fflush(stderr); - } else if(count > 100 && count % 10 == 0) { - fprintf(stderr, "."); - fflush(stderr); - } - } - if (count >= 100) { - fprintf(stderr, "\n"); - } - rtapi_print_msg(RTAPI_MSG_INFO, "Component '%s' ready\n", new_comp_name); - } - if ( wait_flag ) { - /* wait for child process to complete */ - retval = waitpid ( pid, &status, 0 ); - /* check result of waitpid() */ -wait_common: - if ( retval < 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: waitpid(%d) failed\n", linenumber, pid); - return -1; - } - if ( WIFEXITED(status) == 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: program '%s' did not exit normally\n", linenumber, prog_name ); - return -1; - } - if ( ignore_flag == 0 ) { - retval = WEXITSTATUS(status); - if ( retval != 0 ) { - rtapi_print_msg(RTAPI_MSG_ERR, - "HAL:%d: ERROR: program '%s' failed, returned %d\n", linenumber, prog_name, retval ); - return -1; - } - } - /* print success message */ - rtapi_print_msg(RTAPI_MSG_INFO, "Program '%s' finished\n", prog_name); - } else { - /* print success message */ - rtapi_print_msg(RTAPI_MSG_INFO, "Program '%s' started\n", prog_name); - } - return 0; -} - -static void getCompInfo(char *pattern, connectionRecType *context) -{ - int next, len; - hal_comp_t *comp; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if (strncmp(pattern, comp->name, len) == 0) { - snprintf(context->outBuf, sizeof(context->outBuf), "COMP %s %02d %s", comp->name, comp->comp_id, (comp->type != COMPONENT_TYPE_USER) ? "RT " : "User"); - sockWrite(context); - } - next = comp->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - - -static void getPinInfo(char *pattern, int valuesOnly, connectionRecType *context) -{ - int next, len; - hal_pin_t *pin; - hal_comp_t *comp; - hal_sig_t *sig; - void *dptr; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if (strncmp(pattern, pin->name, len) == 0) { - comp = SHMPTR(pin->owner_ptr); - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - dptr = SHMPTR(sig->data_ptr); - } - else { - sig = NULL; - dptr = &(pin->dummysig); - } - if (valuesOnly == 0) - snprintf(context->outBuf, sizeof(context->outBuf), "PIN %s %s %02d %s %s", - pin->name, - data_value2((int) pin->type, dptr), - comp->comp_id, - data_type((int) pin->type), - pin_data_dir((int) pin->dir)); - else - snprintf(context->outBuf, sizeof(context->outBuf), "PINVAL %s %s", - pin->name, - data_value2((int) pin->type, dptr)); - sockWrite(context); - } - next = pin->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - - -static void getSigInfo(char *pattern, int valuesOnly, connectionRecType *context) -{ - int next, len; - hal_sig_t *sig; - void *dptr; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - if (strncmp(pattern, sig->name, len) == 0) { - dptr = SHMPTR(sig->data_ptr); - if (valuesOnly == 0) - snprintf(context->outBuf, sizeof(context->outBuf), "SIGNAL %s %s %s", - sig->name, - data_value((int) sig->type, dptr), - data_type((int) sig->type)); - else - snprintf(context->outBuf, sizeof(context->outBuf), "SIGNALVAL %s %s", sig->name, data_value((int) sig->type, dptr)); - sockWrite(context); - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void getParamInfo(char *pattern, int valuesOnly, connectionRecType *context) -{ - int next, len; - hal_param_t *param; - hal_comp_t *comp; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if ( strncmp(pattern, param->name, len) == 0 ) { - comp = SHMPTR(param->owner_ptr); - if (valuesOnly == 0) - snprintf(context->outBuf, sizeof(context->outBuf), "PARAM %s %s %02d %s %s", - param->name, - data_value((int) param->type, SHMPTR(param->data_ptr)), - comp->comp_id, - data_type((int) param->type), - param_data_dir((int) param->dir)); - else - snprintf(context->outBuf, sizeof(context->outBuf), "PARAMVAL %s %s", - param->name, - data_value((int) param->type, SHMPTR(param->data_ptr))); - sockWrite(context); - } - next = param->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void getFunctInfo(char *pattern, connectionRecType *context) -{ - int next, len; - hal_funct_t *fptr; - hal_comp_t *comp; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next = hal_data->funct_list_ptr; - while (next != 0) { - fptr = SHMPTR(next); - if (strncmp(pattern, fptr->name, len) == 0) { - comp = SHMPTR(fptr->owner_ptr); - snprintf(context->outBuf, sizeof(context->outBuf), "FUNCT %s %02d %08lX %08lX %s %3d", - fptr->name, - comp->comp_id, - (unsigned long)fptr->funct, - (unsigned long)fptr->arg, - (fptr->uses_fp ? "YES" : "NO"), - fptr->users); - sockWrite(context); - } - next = fptr->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void getThreadInfo(char *pattern, connectionRecType *context) -{ - int next_thread, len, n; - hal_thread_t *tptr; - hal_list_t *list_root, *list_entry; - hal_funct_entry_t *fentry; - hal_funct_t *funct; - - rtapi_mutex_get(&(hal_data->mutex)); - len = strlen(pattern); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - tptr = SHMPTR(next_thread); - if (strncmp(pattern, tptr->name, len) == 0) { - char name[HAL_NAME_LEN+1]; - hal_pin_t* pin; - hal_sig_t* sig; - void* dptr; - unsigned int runtime_pin_value; - - size_t ret = snprintf(name, sizeof(name), "%s.time",tptr->name); - if (ret >= sizeof(name)) { - rtapi_print_msg(RTAPI_MSG_ERR, - "unexpected: pin name too long for %s thread",tptr->name); - runtime_pin_value = 0; - } else { - pin = halpr_find_pin_by_name(name); - if (pin) { - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - dptr = SHMPTR(sig->data_ptr); - } else { - sig = NULL; - dptr = &(pin->dummysig); - } - runtime_pin_value = (int)*(int*)dptr; - } else { - runtime_pin_value = 0; - rtapi_print_msg(RTAPI_MSG_ERR, - "unexpected: cannot find time pin for %s thread",tptr->name); - } - } - - snprintf(context->outBuf, sizeof(context->outBuf), "THREAD %s %11u %s %u %u", - tptr->name, - (unsigned int)tptr->period, - (tptr->uses_fp ? "YES" : "NO "), - runtime_pin_value, - (unsigned int)tptr->maxtime); - sockWrite(context); - list_root = &(tptr->funct_list); - list_entry = list_next(list_root); - n = 1; - while (list_entry != list_root) { - /* print the function info */ - fentry = (hal_funct_entry_t *) list_entry; - funct = SHMPTR(fentry->funct_ptr); - /* scriptmode only uses one line per thread, which contains: - thread period, FP flag, name, then all functs separated by spaces */ - snprintf(context->outBuf, sizeof(context->outBuf), "SUBTHREAD %s %2d", funct->name, n); - sockWrite(context); - n++; - list_entry = list_next(list_entry); - } - } - next_thread = tptr->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - - -/* Switch function for pin/sig/param type for the print_*_list functions */ -static const char *data_type(int type) -{ - const char *type_str; - - switch (type) { - case HAL_BIT: - type_str = "bit "; - break; - case HAL_FLOAT: - type_str = "float"; - break; - case HAL_S32: - type_str = "s32 "; - break; - case HAL_U32: - type_str = "u32 "; - break; - default: - /* Shouldn't get here, but just in case... */ - type_str = "undef"; - } - return type_str; -} - -/* Switch function for pin direction for the print_*_list functions */ -static const char *pin_data_dir(int dir) -{ - const char *pin_dir; - - switch (dir) { - case HAL_IN: - pin_dir = "IN "; - break; - case HAL_OUT: - pin_dir = "OUT"; - break; - case HAL_IO: - pin_dir = "I/O"; - break; - default: - /* Shouldn't get here, but just in case... */ - pin_dir = "???"; - } - return pin_dir; -} - -/* Switch function for param direction for the print_*_list functions */ -static const char *param_data_dir(int dir) -{ - const char *param_dir; - - switch (dir) { - case HAL_RO: - param_dir = "RO"; - break; - case HAL_RW: - param_dir = "RW"; - break; - default: - /* Shouldn't get here, but just in case... */ - param_dir = "??"; - } - return param_dir; -} - -/* Switch function for arrow direction for the print_*_list functions */ -static const char *data_arrow1(int dir) -{ - const char *arrow; - - switch (dir) { - case HAL_IN: - arrow = "<=="; - break; - case HAL_OUT: - arrow = "==>"; - break; - case HAL_IO: - arrow = "<=>"; - break; - default: - /* Shouldn't get here, but just in case... */ - arrow = "???"; - } - return arrow; -} - -/* Switch function for arrow direction for the print_*_list functions */ -static const char *data_arrow2(int dir) -{ - const char *arrow; - - switch (dir) { - case HAL_IN: - arrow = "==>"; - break; - case HAL_OUT: - arrow = "<=="; - break; - case HAL_IO: - arrow = "<=>"; - break; - default: - /* Shouldn't get here, but just in case... */ - arrow = "???"; - } - return arrow; -} - -/* Switch function to return var value for the print_*_list functions */ -/* the value is printed in a fixed width field */ -static char *data_value(int type, void *valptr) -{ - char *value_str; - static char buf[15]; - - switch (type) { - case HAL_BIT: - if (*((char *) valptr) == 0) - value_str = " FALSE"; - else - value_str = " TRUE"; - break; - case HAL_FLOAT: - snprintf(buf, 14, "%12.7g", (double)*((hal_float_t *) valptr)); - value_str = buf; - break; - case HAL_S32: - snprintf(buf, 14, " %10ld", (long)*((hal_u32_t *) valptr)); - value_str = buf; - break; - case HAL_U32: - snprintf(buf, 14, " %08lX", (unsigned long)*((hal_u32_t *) valptr)); - value_str = buf; - break; - default: - /* Shouldn't get here, but just in case... */ - value_str = " undef "; - } - return value_str; -} - -/* Switch function to return var value in string form */ -/* the value is printed as a packed string (no whitespace */ -static char *data_value2(int type, void *valptr) -{ - char *value_str; - static char buf[15]; - - switch (type) { - case HAL_BIT: - if (*((char *) valptr) == 0) - value_str = "FALSE"; - else - value_str = "TRUE"; - break; - case HAL_FLOAT: - snprintf(buf, 14, "%.7g", (double)*((hal_float_t *) valptr)); - value_str = buf; - break; - case HAL_S32: - snprintf(buf, 14, "%ld", (long)*((hal_s32_t *) valptr)); - value_str = buf; - break; - case HAL_U32: - snprintf(buf, 14, "%lu", (unsigned long)*((hal_u32_t *) valptr)); - value_str = buf; - break; - default: - /* Shouldn't get here, but just in case... */ - value_str = "unknown_type"; - } - return value_str; -} - -static int doSave(char *type, char *filename, connectionRecType *context) -{ - FILE *dst; - const char *nakStr = "SET SAVE NAK"; - - if (rtapi_get_msg_level() == RTAPI_MSG_NONE) { - /* must be -Q, don't print anything */ - return 0; - } - if (*filename == '\0' ) - dst = stdout; - else { - dst = fopen(filename, "w" ); - if (dst == NULL) { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Can't open 'save' destination '%s'", linenumber, filename); - sockWriteError(nakStr, context); - return -1; - } - } - if (*type == '\0') - type = "all"; - if (strcmp(type, "all" ) == 0) { - /* save everything */ - save_comps(dst); - save_signals(dst); - save_links(dst, 0); - save_params(dst); - save_threads(dst); - } - else - if (strcmp(type, "comp") == 0) - save_comps(dst); - else - if (strcmp(type, "sig") == 0) - save_signals(dst); - else - if (strcmp(type, "link") == 0) - save_links(dst, 0); - else - if (strcmp(type, "linka") == 0) - save_links(dst, 1); - else - if (strcmp(type, "net") == 0) - save_nets(dst, 0); - else - if (strcmp(type, "neta") == 0) - save_nets(dst, 1); - else - if (strcmp(type, "param") == 0) - save_params(dst); - else - if (strcmp(type, "thread") == 0) - save_threads(dst); - else { - snprintf(errorStr, sizeof(errorStr), "HAL:%d: Unknown 'save' type '%s'", linenumber, type); - sockWriteError(nakStr, context); - fclose(dst); - return -1; - } - if (*filename != '\0' ) - fclose(dst); - return 0; -} - -static void save_comps(FILE *dst) -{ - int next; - hal_comp_t *comp; - - fprintf(dst, "# components\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->comp_list_ptr; - while (next != 0) { - comp = SHMPTR(next); - if ( comp->type == COMPONENT_TYPE_REALTIME ) { - /* only print realtime components */ - if ( comp->insmod_args == 0 ) { - fprintf(dst, "#loadrt %s (not loaded by loadrt, no args saved)\n", comp->name); - } else { - fprintf(dst, "loadrt %s %s\n", comp->name, - (char *)SHMPTR(comp->insmod_args)); - } - } - next = comp->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void save_signals(FILE *dst) -{ - int next; - hal_sig_t *sig; - - fprintf(dst, "# signals\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - fprintf(dst, "newsig %s %s\n", sig->name, data_type((int) sig->type)); - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void save_links(FILE *dst, int arrow) -{ - int next; - hal_pin_t *pin; - hal_sig_t *sig; - const char *arrow_str; - - fprintf(dst, "# links\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - while (next != 0) { - pin = SHMPTR(next); - if (pin->signal != 0) { - sig = SHMPTR(pin->signal); - if (arrow != 0) { - arrow_str = data_arrow1((int) pin->dir); - } else { - arrow_str = "\0"; - } - fprintf(dst, "linkps %s %s %s\n", pin->name, arrow_str, sig->name); - } - next = pin->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void save_nets(FILE *dst, int arrow) -{ - int next; - hal_pin_t *pin; - hal_sig_t *sig; - const char *arrow_str; - - fprintf(dst, "# nets\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->sig_list_ptr; - while (next != 0) { - sig = SHMPTR(next); - fprintf(dst, "newsig %s %s\n", sig->name, data_type((int) sig->type)); - pin = halpr_find_pin_by_sig(sig, NULL); - while (pin != NULL) { - if (arrow != 0) { - arrow_str = data_arrow2((int) pin->dir); - } else { - arrow_str = "\0"; - } - fprintf(dst, "linksp %s %s %s\n", sig->name, arrow_str, pin->name); - pin = halpr_find_pin_by_sig(sig, pin); - } - next = sig->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void save_params(FILE *dst) -{ - int next; - hal_param_t *param; - - fprintf(dst, "# parameter values\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->param_list_ptr; - while (next != 0) { - param = SHMPTR(next); - if (param->dir != HAL_RO) { - /* param is writable, save it's value */ - fprintf(dst, "setp %s %s\n", param->name, - data_value((int) param->type, SHMPTR(param->data_ptr))); - } - next = param->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static void save_threads(FILE *dst) -{ - int next_thread; - hal_thread_t *tptr; - hal_list_t *list_root, *list_entry; - hal_funct_entry_t *fentry; - hal_funct_t *funct; - - fprintf(dst, "# realtime thread/function links\n"); - rtapi_mutex_get(&(hal_data->mutex)); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - tptr = SHMPTR(next_thread); - list_root = &(tptr->funct_list); - list_entry = list_next(list_root); - while (list_entry != list_root) { - /* print the function info */ - fentry = (hal_funct_entry_t *) list_entry; - funct = SHMPTR(fentry->funct_ptr); - fprintf(dst, "addf %s %s\n", funct->name, tptr->name); - list_entry = list_next(list_entry); - } - next_thread = tptr->next_ptr; - } - rtapi_mutex_give(&(hal_data->mutex)); -} - -static int do_help_cmd(char *command) -{ - - if (strcmp(command, "help") == 0) { - printf("If you need help to use 'help', then I can't help you.\n"); - } else if (strcmp(command, "loadrt") == 0) { - printf("loadrt modname [modarg(s)]\n"); - printf(" Loads realtime HAL module 'modname', passing 'modargs'\n"); - printf(" to the module.\n"); - } else if (strcmp(command, "unloadrt") == 0) { - printf("unloadrt modname\n"); - printf(" Unloads realtime HAL module 'modname'. If 'modname'\n"); - printf(" is 'all', unloads all realtime modules.\n"); - } else if (strcmp(command, "loadusr") == 0) { - printf("loadusr [options] progname [progarg(s)]\n"); - printf(" Starts user space program 'progname', passing\n"); - printf(" 'progargs' to it. Options are:\n"); - printf(" -w wait for program to finish\n"); - printf(" -i ignore program return value (use with -w)\n"); - } else if ((strcmp(command, "linksp") == 0) || (strcmp(command,"linkps") == 0)) { - printf("linkps pinname [arrow] signame\n"); - printf("linksp signame [arrow] pinname\n"); - printf(" Links pin 'pinname' to signal 'signame'. Both forms do\n"); - printf(" the same thing. Use whichever makes sense. The optional\n"); - printf(" 'arrow' can be '==>', '<==', or '<=>' and is ignored. It\n"); - printf(" can be used in files to show the direction of data flow,\n"); - printf(" but don't use arrows on the command line.\n"); - } else if (strcmp(command, "linkpp") == 0) { - printf("linkpp firstpin secondpin\n"); - printf(" Creates a signal with the name of the first pin,\n"); printf(" then links both pins to the signal. \n"); - }else if (strcmp(command, "unlinkp") == 0) { - printf("unlinkp pinname\n"); - printf(" Unlinks pin 'pinname' if it is linked to any signal.\n"); - } else if (strcmp(command, "lock") == 0) { - printf("lock [all|tune|none]\n"); - printf(" Locks HAL to some degree.\n"); - printf(" none - no locking done.\n"); - printf(" tune - some tuning is possible (setp & such).\n"); - printf(" all - HAL completely locked.\n"); - } else if (strcmp(command, "unlock") == 0) { - printf("unlock [all|tune]\n"); - printf(" Unlocks HAL to some degree.\n"); - printf(" tune - some tuning is possible (setp & such).\n"); - printf(" all - HAL completely unlocked.\n"); - } else if (strcmp(command, "newsig") == 0) { - printf("newsig signame type\n"); - printf(" Creates a new signal called 'signame'. Type is 'bit',\n"); - printf(" 'float', 'u8', 's8', 'u16', 's16', 'u32', or 's32'.\n"); - } else if (strcmp(command, "delsig") == 0) { - printf("delsig signame\n"); - printf(" Deletes signal 'signame'. If 'signame is 'all',\n"); - printf(" deletes all signals\n"); - } else if (strcmp(command, "setp") == 0) { - printf("setp paramname value\n"); - printf("paramname = value\n"); - printf(" Sets parameter 'paramname' to 'value' (if writable).\n"); - printf(" 'setp' and '=' work the same, don't use '=' on the\n"); - printf(" command line. 'value' may be a constant such as 1.234\n"); - printf(" or TRUE, or a reference to an environment variable,\n"); -#ifdef NO_INI - printf(" using the syntax '$name'./n"); -#else - printf(" using the syntax '$name'. If option -i was given,\n"); - printf(" 'value' may also be a reference to an INI file entry\n"); - printf(" using the syntax '[section]name'.\n"); -#endif - } else if (strcmp(command, "sets") == 0) { - printf("sets signame value\n"); - printf(" Sets signal 'signame' to 'value' (if sig has no writers).\n"); - } else if (strcmp(command, "getp") == 0) { - printf("getp paramname\n"); - printf(" Gets the value of parameter 'paramname'.\n"); - } else if (strcmp(command, "gets") == 0) { - printf("gets signame\n"); - printf(" Gets the value of signal 'signame'.\n"); - } else if (strcmp(command, "addf") == 0) { - printf("addf functname threadname [position]\n"); - printf(" Adds function 'functname' to thread 'threadname'. If\n"); - printf(" 'position' is specified, adds the function to that spot\n"); - printf(" in the thread, otherwise adds it to the end. Negative\n"); - printf(" 'position' means position with respect to the end of the\n"); - printf(" thread. For example '1' is start of thread, '-1' is the\n"); - printf(" end of the thread, '-3' is third from the end.\n"); - } else if (strcmp(command, "delf") == 0) { - printf("delf functname threadname\n"); - printf(" Removes function 'functname' from thread 'threadname'.\n"); - } else if (strcmp(command, "show") == 0) { - printf("show [type] [pattern]\n"); - printf(" Prints info about HAL items of the specified type.\n"); - printf(" 'type' is 'comp', 'pin', 'sig', 'param', 'funct',\n"); - printf(" 'thread', or 'all'. If 'type' is omitted, it assumes\n"); - printf(" 'all' with no pattern. If 'pattern' is specified\n"); - printf(" it prints only those items whose names match the\n"); - printf(" pattern (no fancy regular expressions, just a simple\n"); - printf(" match: 'foo' matches 'foo', 'foobar' and 'foot' but\n"); - printf(" not 'fo' or 'frobz' or 'ffoo').\n"); - } else if (strcmp(command, "list") == 0) { - printf("list type [pattern]\n"); - printf(" Prints the names of HAL items of the specified type.\n"); - printf(" 'type' is 'comp', 'pin', 'sig', 'param', 'funct', or\n"); - printf(" 'thread'. If 'pattern' is specified it prints only\n"); - printf(" those names that match the pattern (no fancy regular\n"); - printf(" expressions, just a simple match: 'foo' matches 'foo',\n"); - printf(" 'foobar' and 'foot' but not 'fo' or 'frobz' or 'ffoo').\n"); - printf(" Names are printed on a single line, space separated.\n"); - } else if (strcmp(command, "status") == 0) { - printf("status [type]\n"); - printf(" Prints status info about HAL.\n"); - printf(" 'type' is 'lock', 'mem', or 'all'. \n"); - printf(" If 'type' is omitted, it assumes\n"); - printf(" 'all'.\n"); - } else if (strcmp(command, "save") == 0) { - printf("save [type] [filename]\n"); - printf(" Prints HAL state to 'filename' (or stdout), as a series\n"); - printf(" of HAL commands. State can later be restored by using\n"); - printf(" \"halrmt -f filename\".\n"); - printf(" Type can be 'comp', 'sig', 'link[a]', 'net[a]', 'param',\n"); - printf(" or 'thread'. ('linka' and 'neta' show arrows for pin\n"); - printf(" direction.) If 'type' is omitted or 'all', does the\n"); - printf(" equivalent of 'comp', 'sig', 'link', 'param', and 'thread'.\n"); - } else if (strcmp(command, "start") == 0) { - printf("start\n"); - printf(" Starts all realtime threads.\n"); - } else if (strcmp(command, "stop") == 0) { - printf("stop\n"); - printf(" Stops all realtime threads.\n"); - } else if (strcmp(command, "quit") == 0) { - printf("quit\n"); - printf(" Stop processing input and terminate halrmt (when\n"); - printf(" reading from a file or stdin).\n"); - } else if (strcmp(command, "exit") == 0) { - printf("exit\n"); - printf(" Stop processing input and terminate halrmt (when\n"); - printf(" reading from a file or stdin).\n"); - } else { - printf("No help for unknown command '%s'\n", command); - } - return 0; -} - -static void print_help_general(int showR) -{ - printf("\nUsage: halrmt [options] [cmd [args]]\n\n"); - printf("options:\n\n"); - printf(" -f [filename] Read commands from 'filename', not command\n"); - printf(" line. If no filename, read from stdin.\n"); -#ifndef NO_INI - printf(" -i filename Open INI file 'filename', allow commands\n"); - printf(" to get their values from INI file.\n"); -#endif - printf(" -q Quiet - print errors only (default).\n"); - printf(" -Q Very quiet - print nothing.\n"); - if (showR != 0) { - printf(" -R Release mutex (for crash recovery only).\n"); - } - printf(" -s Script friendly - don't print headers on output.\n"); - printf(" -v Verbose - print result of every command.\n"); - printf(" -V Very verbose - print lots of junk.\n"); - printf(" -h Help - print this help screen and exit.\n\n"); - printf("commands:\n\n"); - printf(" loadrt, unloadrt, loadusr, lock, unlock, linkps, linksp, linkpp,\n"); - printf(" unlinkp, newsig, delsig, setp, getp, sets, gets, addf, delf, show,\n"); - printf(" list, save, status, start, stop, quit, exit\n"); - printf(" help Lists all commands with short descriptions\n"); - printf(" help command Prints detailed help for 'command'\n\n"); -} - -static halCommandType lookupHalCommand(char *s) -{ - halCommandType i = hcEcho; - int temp; - - while (i < hcUnknown) { - if (strcmp(halCommands[i], s) == 0) return i; -// (int)i += 1; - temp = i; - temp++; - i = (halCommandType) temp; - } - return i; -} - - static int commandHello(connectionRecType *context) -{ - char *pch; -// const char *password = "EMC"; - - pch = strtok(NULL, delims); - if (pch == NULL) return -1; - if (strcmp(pch, pwd) != 0) return -1; - pch = strtok(NULL, delims); - if (pch == NULL) return -1; - rtapi_strxcpy(context->hostName, pch); - pch = strtok(NULL, delims); - if (pch == NULL) return -1; - context->linked = 1; - rtapi_strxcpy(context->version, pch); - printf("Connected to %s\n\r", context->hostName); - return 0; -} - -static cmdResponseType getEcho(char *s, connectionRecType *context) -{ - (void)s; - const char *pEchoStr = "ECHO %s"; - - if (context->echo == 1) snprintf(context->outBuf, sizeof(context->outBuf), pEchoStr, "ON"); - else snprintf(context->outBuf, sizeof(context->outBuf), pEchoStr, "OFF"); - return rtNoError; -} - -static cmdResponseType getVerbose(char *s, connectionRecType *context) -{ - (void)s; - const char *pVerboseStr = "VERBOSE %s"; - - if (context->verbose == 1) snprintf(context->outBuf, sizeof(context->outBuf), pVerboseStr, "ON"); - else snprintf(context->outBuf, sizeof(context->outBuf), pVerboseStr, "OFF"); - return rtNoError; -} - -static cmdResponseType getEnable(char *s, connectionRecType *context) -{ - (void)s; - const char *pEnableStr = "ENABLE %s"; - - if (context->cliSock == enabledConn) snprintf(context->outBuf, sizeof(context->outBuf), pEnableStr, "ON"); - else snprintf(context->outBuf, sizeof(context->outBuf), pEnableStr, "OFF"); - return rtNoError; -} - -static cmdResponseType getConfig(char *s, connectionRecType *context) -{ - (void)s; - const char *pConfigStr = "CONFIG"; - - rtapi_strxcpy(context->outBuf, pConfigStr); - return rtNoError; -} - -static cmdResponseType getCommMode(char *s, connectionRecType *context) -{ - (void)s; - const char *pCommModeStr = "COMM_MODE %s"; - - switch (context->commMode) { - case 0: snprintf(context->outBuf, sizeof(context->outBuf), pCommModeStr, "ASCII"); break; - case 1: snprintf(context->outBuf, sizeof(context->outBuf), pCommModeStr, "BINARY"); break; - } - return rtNoError; -} - -static cmdResponseType getCommProt(char *s, connectionRecType *context) -{ - (void)s; - const char *pCommProtStr = "COMM_PROT %s"; - - snprintf(context->outBuf, sizeof(context->outBuf), pCommProtStr, context->version); - return rtNoError; -} - -static cmdResponseType getComps(char *s, connectionRecType *context) -{ - if (s == NULL) - getCompInfo("", context); - else - getCompInfo(s, context); - return rtHandledNoError; -} - -static cmdResponseType getPins(char *s, connectionRecType *context) -{ - if (s == NULL) - getPinInfo("", 0, context); - else - getPinInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getPinVals(char *s, connectionRecType *context) - -{ - if (s == NULL) - getPinInfo("", 1, context); - else - getPinInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getSignals(char *s, connectionRecType *context) -{ - if (s == NULL) - getSigInfo("", 0, context); - else - getSigInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getSignalVals(char *s, connectionRecType *context) -{ - if (s == NULL) - getSigInfo("", 1, context); - else - getSigInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getParams(char *s, connectionRecType *context) -{ - if (s == NULL) - getParamInfo("", 0, context); - else - getParamInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getParamVals(char *s, connectionRecType *context) -{ - if (s == NULL) - getParamInfo("", 1, context); - else - getParamInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getFuncts(char *s, connectionRecType *context) -{ - if (s == NULL) - getFunctInfo("", context); - else - getFunctInfo(s, context); - return rtHandledNoError; -} - -static cmdResponseType getThreads(char *s, connectionRecType *context) -{ - if (s == NULL) - getThreadInfo("", context); - else - getThreadInfo(s, context); - return rtHandledNoError; -} - -static cmdResponseType getComp(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getCompInfo(s, context); - return rtHandledNoError; -} - -static cmdResponseType getPin(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getPinInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getPinVal(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getPinInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getSignal(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getSigInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getSignalVal(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getSigInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getParam(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getParamInfo(s, 0, context); - return rtHandledNoError; -} - -static cmdResponseType getParamVal(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getParamInfo(s, 1, context); - return rtHandledNoError; -} - -static cmdResponseType getFunct(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getFunctInfo(s, context); - return rtHandledNoError; -} - -static cmdResponseType getThread(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - getThreadInfo(s, context); - return rtHandledNoError; -} - -int commandGet(connectionRecType *context) -{ - static char *setNakStr = "GET NAK\r\n"; - static char *setCmdNakStr = "GET %s NAK\r\n"; - halCommandType cmd; - char *pch; - cmdResponseType ret = rtNoError; - - pch = strtok(NULL, delims); - if (pch == NULL) { - return write(context->cliSock, setNakStr, strlen(setNakStr)); - } - strupr(pch); - cmd = lookupHalCommand(pch); - switch (cmd) { - case hcEcho: ret = getEcho(pch, context); break; - case hcVerbose: ret = getVerbose(pch, context); break; - case hcEnable: ret = getEnable(pch, context); break; - case hcConfig: ret = getConfig(pch, context); break; - case hcCommMode: ret = getCommMode(pch, context); break; - case hcCommProt: ret = getCommProt(pch, context); break; - case hcComps: ret = getComps(strtok(NULL, delims), context); break; - case hcPins: ret = getPins(strtok(NULL, delims), context); break; - case hcPinVals: ret = getPinVals(pch, context); break; - case hcSigs: ret = getSignals(strtok(NULL, delims), context); break; - case hcSigVals: ret = getSignalVals(strtok(NULL, delims), context); break; - case hcParams: ret = getParams(strtok(NULL, delims), context); break; - case hcParamVals: ret = getParamVals(strtok(NULL, delims), context); break; - case hcFuncts: ret = getFuncts(strtok(NULL, delims), context); break; - case hcThreads: ret = getThreads(strtok(NULL, delims), context); break; - case hcComp: ret = getComp(strtok(NULL, delims), context); break; - case hcPin: ret = getPin(strtok(NULL, delims), context); break; - case hcPinVal: ret = getPinVal(strtok(NULL, delims), context); break; - case hcSig: ret = getSignal(strtok(NULL, delims), context); break; - case hcSigVal: ret = getSignalVal(strtok(NULL, delims), context); break; - case hcParam: ret = getParam(strtok(NULL, delims), context); break; - case hcParamVal: ret = getParamVal(strtok(NULL, delims), context); break; - case hcFunct: ret = getFunct(strtok(NULL, delims), context); break; - case hcThread: ret = getThread(strtok(NULL, delims), context); break; - case hcLoadRt: ; - case hcUnload: ; - case hcLoadUsr: ; - case hcLinkps: ; - case hcLinksp: ; - case hcLinkpp: ; - case hcNet: ; - case hcUnlinkp: ; - case hcLock: ; - case hcUnlock: ; - case hcNewSig: ; - case hcDelSig: ; - case hcSetP: ; - case hcSetS: ; - case hcAddF: ; - case hcDelF: ; - case hcSave: ; - case hcStart: ; - case hcStop: ; - case hcUnknown: ret = rtStandardError; - } - switch (ret) { - case rtNoError: // Standard ok response, just write value in buffer - sockWrite(context); - break; - case rtHandledNoError: // Custom ok response already handled, take no action - break; - case rtStandardError: // Standard error response - snprintf(context->outBuf, sizeof(context->outBuf), setCmdNakStr, pch); - sockWrite(context); - break; - case rtCustomError: // Custom error response entered in buffer - sockWrite(context); - break; - case rtCustomHandledError: ;// Custom error response handled, take no action - } - return 0; -} - -static int checkOnOff(char *s) -{ - static char *onStr = "ON"; - static char *offStr = "OFF"; - - if (s == NULL) return -1; - strupr(s); - if (strcmp(s, onStr) == 0) return 0; - if (strcmp(s, offStr) == 0) return 1; - return -1; -} - -static int checkBinaryASCII(char *s) -{ - static char *binaryStr = "BINARY"; - static char *ASCIIStr = "ASCII"; - - if (s == NULL) return -1; - strupr(s); - if (strcmp(s, ASCIIStr) == 0) return 0; - if (strcmp(s, binaryStr) == 0) return 1; - return -1; -} - -static cmdResponseType setEcho(char *s, connectionRecType *context) -{ - - switch (checkOnOff(s)) { - case -1: return rtStandardError; - case 0: context->echo = 1; break; - case 1: context->echo = 0; - } - return rtNoError; -} - -static cmdResponseType setVerbose(char *s, connectionRecType *context) -{ - - switch (checkOnOff(s)) { - case -1: return rtStandardError; - case 0: context->verbose = 1; break; - case 1: context->verbose = 0; - } - return rtNoError; -} - -static cmdResponseType setEnable(char *s, connectionRecType *context) -{ - if (strcmp(s, enablePWD) == 0) { - enabledConn = context->cliSock; - context->enabled = 1; - return rtNoError; - } - else - if (checkOnOff(s) == 1) { - context->enabled = 0; - enabledConn = -1; - return rtNoError; - } - else return rtStandardError; -} - -static cmdResponseType setConfig(char *s, connectionRecType *context) -{ - (void)s; - (void)context; - return rtNoError; -} - -static cmdResponseType setCommMode(char *s, connectionRecType *context) -{ - int ret; - - ret = checkBinaryASCII(s); - if (ret == -1) return rtStandardError; - context->commMode = ret; - return rtNoError; -} - -static cmdResponseType setCommProt(char *s, connectionRecType *context) -{ - (void)s; - char *pVersion; - - pVersion = strtok(NULL, delims); - if (pVersion == NULL) return rtStandardError; - rtapi_strxcpy(context->version, pVersion); - return rtNoError; -} - -static cmdResponseType setLoadRt(char *s, connectionRecType *context) -{ - char *pch; - char *args[MAX_TOK+3]; - int i; - - if (*s == '\0') return rtCustomHandledError; - i = 0; - pch = strtok(NULL, delims); - while (pch != NULL) { - args[i] = pch; - pch = strtok(NULL, delims); - i++; - } - args[i] = NULL; - if (doLoadRt(s, args, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setUnload(char *s, connectionRecType *context) -{ - if (doUnload(s, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setLoadUsr(char *s, connectionRecType *context) -{ - (void)context; - char *argv[MAX_TOK+1] = {NULL}; - - argv[0] = s; - argv[1] = "\0"; - if (doLoadUsr(argv) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setLinkps(char *p, char *s, connectionRecType *context) -{ - if ((p == NULL) || (s == NULL)) return rtStandardError; - if (doLink(p, s, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setLinksp(char *p, char *s, connectionRecType *context) -{ - if ((p == NULL) || (s == NULL)) return rtStandardError; - if (doLink(s, p, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setLinkpp(char *p1, char *p2, connectionRecType *context) -{ - if ((p1 == NULL) || (p2 == NULL)) return rtStandardError; - if (doLinkpp(p1, p2, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setNet(char *p1, connectionRecType *context) -{ - char *argv[MAX_TOK]; - int i; - char *pch; - - if (p1 == NULL) return rtStandardError; - i = 0; - - do { - pch = strtok(NULL, delims); - if (pch == NULL) break; - argv[i] = pch; - i++; - if (i >= MAX_TOK) return rtStandardError; // too many pins to link to the net - } while(1); - - if (i == 0) return rtStandardError; // no pins to link to the net - else - if (doNet(p1, argv, context) == 0) - return rtNoError; - else return rtCustomHandledError; -} - -static cmdResponseType setUnlink(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - if (doLink(s, "\0", context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setLock(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - if (doLock(s, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setUnlock(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - if (doUnlock(s, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setNewsig(char *s, char *t, connectionRecType *context) -{ - if ((s == NULL) || (t == NULL)) return rtStandardError; - if (doNewsig(s, t, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setDelsig(char *s, connectionRecType *context) -{ - if (s == NULL) return rtStandardError; - if (doDelsig(s, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setSetp(char *s, char *p, connectionRecType *context) -{ - if ((s == NULL) || (p == NULL)) return rtStandardError; - if (doSetp(s, p, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setSets(char *s, char *p, connectionRecType *context) -{ - if ((s == NULL) || (p == NULL)) return rtStandardError; - if (doSets(s, p, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setAddf(char *s, char *t, char *p, connectionRecType *context) -{ - if ((s == NULL) || (t == NULL)) return rtStandardError; - if (doAddf(s, t, p, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setDelf(char *s, char *t, connectionRecType *context) -{ - if ((s == NULL) || (t == NULL)) return rtStandardError; - if (doDelf(s, t, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setSave(char *type, char *fileName, connectionRecType *context) -{ - if (doSave(type, fileName, context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setStart(connectionRecType *context) -{ - if (doStart(context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -static cmdResponseType setStop(connectionRecType *context) -{ - if (doStop(context) == 0) - return rtNoError; - else - return rtCustomHandledError; -} - -#define MAX_TOKENS 5 - -int commandSet(connectionRecType *context) -{ - static char *setNakStr = "SET NAK\n\r"; - static char *setCmdNakStr = "SET %s NAK\n\r"; - static char *ackStr = "SET %s ACK\n\r"; - halCommandType cmd; - char *tokens[MAX_TOKENS]; - int i; - char *pch; - char *pcmd; - int retval = 0; - cmdResponseType ret = rtNoError; - - pcmd = strtok(NULL, delims); - if (pcmd == NULL) { - return write(context->cliSock, setNakStr, strlen(setNakStr)); - } - strupr(pcmd); - cmd = lookupHalCommand(pcmd); - if ((cmd >= hcCommProt) && (context->cliSock != enabledConn)) { - snprintf(context->outBuf, sizeof(context->outBuf), setCmdNakStr, pcmd); - return write(context->cliSock, context->outBuf, strlen(context->outBuf)); - } - pch = strtok(NULL, delims); - i = 0; - while (pch != NULL) { - tokens[i] = pch; - i++; - pch = strtok(NULL, delims); - } - switch (cmd) { - case hcEcho: ret = setEcho(tokens[0], context); break; - case hcVerbose: ret = setVerbose(tokens[0], context); break; - case hcEnable: ret = setEnable(tokens[0], context); break; - case hcConfig: ret = setConfig(tokens[0], context); break; - case hcCommMode: ret = setCommMode(tokens[0], context); break; - case hcCommProt: ret = setCommProt(tokens[0], context); break; - case hcComps: break; - case hcPins: break; - case hcPinVals: break; - case hcSigs: break; - case hcSigVals: break; - case hcParams: break; - case hcParamVals: break; - case hcFuncts: break; - case hcThreads: break; - case hcComp: break; - case hcPin: break; - case hcPinVal: break; - case hcSig: break; - case hcSigVal: break; - case hcParam: break; - case hcParamVal: break; - case hcFunct: break; - case hcThread: break; - case hcLoadRt: ret = setLoadRt(tokens[0], context); break; - case hcUnload: ret = setUnload(tokens[0], context); break; - case hcLoadUsr: ret = setLoadUsr(tokens[0], context); break; - case hcLinkps: setLinkps(tokens[0], tokens[1], context); break; - case hcLinksp: setLinksp(tokens[0], tokens[1], context); break; - case hcLinkpp: setLinkpp(tokens[0], tokens[1], context); break; - case hcNet: setNet(tokens[0], context); break; - case hcUnlinkp: setUnlink(tokens[0], context); break; - case hcLock: setLock(tokens[0], context); break; - case hcUnlock: setUnlock(tokens[0], context); break;; - case hcNewSig: setNewsig(tokens[0], tokens[1], context); break; - case hcDelSig: setDelsig(tokens[0], context); break; - case hcSetP: setSetp(tokens[0], tokens[1], context); break; - case hcSetS: setSets(tokens[0], tokens[1], context); break; - case hcAddF: setAddf(tokens[0], tokens[1], tokens[2], context); break; - case hcDelF: setDelf(tokens[0], tokens[1], context); break; - case hcSave: setSave(tokens[0], tokens[1], context); break; - case hcStart: setStart(context); break; - case hcStop: setStop(context); break; - case hcUnknown: ret = rtStandardError; - } - switch (ret) { - case rtNoError: - if (context->verbose) { - snprintf(context->outBuf, sizeof(context->outBuf), ackStr, pcmd); - retval = write(context->cliSock, context->outBuf, strlen(context->outBuf)); - } - break; - case rtHandledNoError: // Custom ok response already handled, take no action - break; - case rtStandardError: - snprintf(context->outBuf, sizeof(context->outBuf), setCmdNakStr, pcmd); - retval = write(context->cliSock, context->outBuf, strlen(context->outBuf)); - break; - case rtCustomError: // Custom error response entered in buffer - retval = write(context->cliSock, context->outBuf, strlen(context->outBuf)); - break; - case rtCustomHandledError: ;// Custom error response handled, take no action - } - return retval; -} - -int commandQuit(connectionRecType *context) -{ - printf("Closing connection with %s\n", context->hostName); - return -1; -} - -int commandShutdown(connectionRecType *context) -{ - if (context->cliSock == enabledConn) { - printf("Shutting down\n"); - hal_flag = 1; - hal_exit(comp_id); - exit(0); - return -1; - } - else - return 0; -} - -static int helpGeneral(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Available commands:\n\r"); - rtapi_strxcat(context->outBuf, " Hello \n\r"); - rtapi_strxcat(context->outBuf, " Get \n\r"); - rtapi_strxcat(context->outBuf, " Set \n\r"); - rtapi_strxcat(context->outBuf, " Quit\n\r"); - rtapi_strxcat(context->outBuf, " Shutdown\n\r"); - rtapi_strxcat(context->outBuf, " Help \n\r"); - sockWrite(context); - return 0; -} - -static int helpHello(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Usage:\n\r"); - rtapi_strxcat(context->outBuf, " Hello \n\rWhere:\n\r"); - rtapi_strxcat(context->outBuf, " Password is the connection password to allow communications with the CNC server.\n\r"); - rtapi_strxcat(context->outBuf, " Client Name is the name of client trying to connect, typically the network name of the client.\n\r"); - rtapi_strxcat(context->outBuf, " Protocol Version is the version of the protocol with which the client wishes to use.\n\r\n\r"); - rtapi_strxcat(context->outBuf, " With valid password, server responds with:\n\r"); - rtapi_strxcat(context->outBuf, " Hello Ack \n\rWhere:\n\r"); - rtapi_strxcat(context->outBuf, " Ack is acknowledging the connection has been made.\n\r"); - rtapi_strxcat(context->outBuf, " Server Name is the name of the EMC Server to which the client has connected.\n\r"); - rtapi_strxcat(context->outBuf, " Protocol Version is the client requested version or latest version support by server if"); - rtapi_strxcat(context->outBuf, " the client requests a version later than that supported by the server.\n\r\n\r"); - rtapi_strxcat(context->outBuf, " With invalid password, the server responds with:\n\r"); - rtapi_strxcat(context->outBuf, " Hello Nak\n\r"); - sockWrite(context); - return 0; -} - -static int helpGet(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Usage:\n\rGet \n\r"); - rtapi_strxcat(context->outBuf, " Get commands require that a hello has been successfully negotiated.\n\r"); - rtapi_strxcat(context->outBuf, " Emc command may be one of:\n\r"); - rtapi_strxcat(context->outBuf, " Comm_mode\n\r"); - rtapi_strxcat(context->outBuf, " Comm_prot\n\r"); - rtapi_strxcat(context->outBuf, " Comp outBuf, " Comps\n\r"); - rtapi_strxcat(context->outBuf, " Echo\n\r"); - rtapi_strxcat(context->outBuf, " Enable\n\r"); - rtapi_strxcat(context->outBuf, " Funct \n\r"); - rtapi_strxcat(context->outBuf, " Functs\n\r"); - rtapi_strxcat(context->outBuf, " Param \n\r"); - rtapi_strxcat(context->outBuf, " Params\n\r"); - rtapi_strxcat(context->outBuf, " ParamVal \n\r"); - rtapi_strxcat(context->outBuf, " ParamVals\n\r"); - rtapi_strxcat(context->outBuf, " Pin \n\r"); - rtapi_strxcat(context->outBuf, " PinVal \n\r"); - rtapi_strxcat(context->outBuf, " Pins\n\r"); - rtapi_strxcat(context->outBuf, " PinVals\n\r"); - rtapi_strxcat(context->outBuf, " Signal \n\r"); - rtapi_strxcat(context->outBuf, " Signals\n\r"); - rtapi_strxcat(context->outBuf, " SigVal \n\r"); - rtapi_strxcat(context->outBuf, " SigVals\n\r"); - rtapi_strxcat(context->outBuf, " Thread \n\r"); - rtapi_strxcat(context->outBuf, " Threads\n\r"); - rtapi_strxcat(context->outBuf, " Verbose\n\r"); -// rtapi_strxcat(outBuf, "CONFIG\n\r"); - sockWrite(context); - return 0; -} - -static int helpSet(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Usage:\n\r Set \n\r"); - rtapi_strxcat(context->outBuf, " Set commands require that a hello has been successfully negotiated,\n\r"); - rtapi_strxcat(context->outBuf, " in most instances requires that control be enabled by the connection.\n\r"); - rtapi_strxcat(context->outBuf, " The set commands not requiring control enabled are:\n\r"); - rtapi_strxcat(context->outBuf, " Comm_mode \n\r"); - rtapi_strxcat(context->outBuf, " Comm_prot \n\r"); - rtapi_strxcat(context->outBuf, " Echo \n\r"); - rtapi_strxcat(context->outBuf, " Enable \n\r"); - rtapi_strxcat(context->outBuf, " Verbose \n\r\n\r"); - rtapi_strxcat(context->outBuf, " The set commands requiring control enabled are:\n\r"); - rtapi_strxcat(context->outBuf, " Addf []\n\r"); - rtapi_strxcat(context->outBuf, " Delf \n\r"); - rtapi_strxcat(context->outBuf, " DelSig \n\r"); - rtapi_strxcat(context->outBuf, " Linkpp \n\r"); - rtapi_strxcat(context->outBuf, " Linkps \n\r"); - rtapi_strxcat(context->outBuf, " Linksp \n\r"); - rtapi_strxcat(context->outBuf, " Loadrt \n\r"); - rtapi_strxcat(context->outBuf, " Loadusr [ .. ]\n\r"); - rtapi_strxcat(context->outBuf, " Lock \n\r"); - rtapi_strxcat(context->outBuf, " Net [ .. \n\r"); - rtapi_strxcat(context->outBuf, " NewSig \n\r"); - rtapi_strxcat(context->outBuf, " Save [ []]\n\r"); - rtapi_strxcat(context->outBuf, " Setp \n\r"); - rtapi_strxcat(context->outBuf, " Sets \n\r"); - rtapi_strxcat(context->outBuf, " Start\n\r"); - rtapi_strxcat(context->outBuf, " Stop\n\r"); - rtapi_strxcat(context->outBuf, " Unlink \n\r"); - rtapi_strxcat(context->outBuf, " Unload \n\r"); - rtapi_strxcat(context->outBuf, " Unlock \n\r"); - - sockWrite(context); - return 0; -} - -static int helpQuit(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Usage:\n\r"); - rtapi_strxcat(context->outBuf, " The quit command has the server initiate a disconnect from the client,\n\r"); - rtapi_strxcat(context->outBuf, " the command has no parameters and no requirements to have negotiated\n\r"); - rtapi_strxcat(context->outBuf, " a hello, or be in control."); - sockWrite(context); - return 0; -} - -static int helpShutdown(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "Usage:\n\r"); - rtapi_strxcat(context->outBuf, " The shutdown command terminates the connection with all clients,\n\r"); - rtapi_strxcat(context->outBuf, " and initiates a shutdown of EMC. The command has no parameters, and\n\r"); - rtapi_strxcat(context->outBuf, " can only be issued by the connection having control.\n\r"); - sockWrite(context); - return 0; -} - -static int helpHelp(connectionRecType *context) -{ - snprintf(context->outBuf, sizeof(context->outBuf), "If you need help on help, it is time to look into another line of work.\n\r"); - sockWrite(context); - return 0; -} - -int commandHelp(connectionRecType *context) -{ - char *pch; - - pch = strtok(NULL, delims); - if (pch == NULL) return (helpGeneral(context)); - strupr(pch); - printf("Command = %s", pch); - if (strcmp(pch, "HELLO") == 0) return (helpHello(context)); - if (strcmp(pch, "GET") == 0) return (helpGet(context)); - if (strcmp(pch, "SET") == 0) return (helpSet(context)); - if (strcmp(pch, "QUIT") == 0) return (helpQuit(context)); - if (strcmp(pch, "SHUTDOWN") == 0) return (helpShutdown(context)); - if (strcmp(pch, "HELP") == 0) return (helpHelp(context)); - snprintf(context->outBuf, sizeof(context->outBuf), "%s is not a valid command.", pch); - sockWrite(context); - return 0; -} - -commandTokenType lookupToken(char *s) -{ - commandTokenType i = cmdHello; - int temp; - - while (i < cmdUnknown) { - if (strcmp(commands[i], s) == 0) return i; -// (int)i += 1; - temp = i; - temp++; - i = (commandTokenType) temp; - } - return i; -} - -int parseCommand(connectionRecType *context) -{ - int ret = 0; - char *pch; - char s[64]; - static char *helloNakStr = "HELLO NAK\r\n"; - static char *helloAckStr = "HELLO ACK %s 1.1\r\n"; - static char *setNakStr = "SET NAK\r\n"; - - pch = strtok(context->inBuf, delims); - snprintf(s, sizeof(s), helloAckStr, serverName); - if (pch != NULL) { - strupr(pch); - switch (lookupToken(pch)) { - case cmdHello: - if (commandHello(context) == -1) - ret = write(context->cliSock, helloNakStr, strlen(helloNakStr)); - else - ret = write(context->cliSock, s, strlen(s)); - break; - case cmdGet: - ret = commandGet(context); - break; - case cmdSet: - if (context->linked == 0) - ret = write(context->cliSock, setNakStr, strlen(setNakStr)); - else ret = commandSet(context); - break; - case cmdQuit: - ret = commandQuit(context); - break; - case cmdShutdown: - ret = commandShutdown(context); - break; - case cmdHelp: - ret = commandHelp(context); - break; - case cmdUnknown: ret = -2; - } - } - return ret; -} - -void *readClient(void *arg) -{ - (void)arg; - char str[1600]; - char buf[1600]; - unsigned int i, j; - int len; - int ret; - connectionRecType *context; - - -// res = 1; - context = (connectionRecType *) malloc(sizeof(connectionRecType)); - if(NULL == context) { - perror("readClient():malloc"); - abort(); // There is no "clean" way. Ensure we make some noise. - } - context->cliSock = client_sockfd; - context->linked = 0; - context->echo = 1; - context->verbose = 0; - rtapi_strxcpy(context->version, "1.0"); - rtapi_strxcpy(context->hostName, "Default"); - connCount++; - context->commMode = 0; - context->commProt = 0; - context->inBuf[0] = 0; - buf[0] = 0; - - while (1) { - len = read(context->cliSock, &str, 1600); - if (len <= 0) goto finished; - str[len] = 0; - rtapi_strxcat(buf, str); - if (!memchr(str, 0x0d, strlen(str))) continue; - if ((context->echo == 1) && (context->linked == 1)) { - ret = write(context->cliSock, &buf, strlen(buf)); - if (ret < 0) { - goto finished; - } - } - i = 0; - j = 0; - while (i <= strlen(buf)) { - if ((buf[i] != '\n') && (buf[i] != '\r')) { - context->inBuf[j] = buf[i]; - j++; - } - else if (j > 0) - { - context->inBuf[j] = 0; - if (parseCommand(context) == -1) goto finished; - j = 0; - } - i++; - } - buf[0] = 0; - } - -finished: - close(context->cliSock); - free(context); - pthread_exit((void *)0); -} - -/*********************************************************************** -* MAIN PROGRAM * -************************************************************************/ - - /* main() is responsible for parsing command line options, and then - parsing either a single command from the command line or a series - of commands from a file or standard input. It breaks the command[s] - into tokens, and passes them to parse_cmd() which does the actual - work for each command. -*/ - -int sockMain() -{ - pthread_t thrd; - int res; - - while (1) { - - client_len = sizeof(client_address); - client_sockfd = accept(server_sockfd, - (struct sockaddr *)&client_address, &client_len); - if (client_sockfd < 0) exit(0); - res = pthread_create(&thrd, NULL, readClient, (void *)NULL); - if (res != 0) - close(client_sockfd); - } - return 0; -} - -int main(int argc, char **argv) -{ - int n, fd; - int errorcount; - int opt; - char *cp1, *filename = NULL; - FILE *srcfile = NULL; - - /* set default level of output - 'quiet' */ - rtapi_set_msg_level(RTAPI_MSG_ERR); - /* set default for other options */ - // process halrmt command line args - while((opt = getopt_long(argc, argv, "e:n:p:s:w:", longopts, NULL)) != -1) { - switch(opt) { - case 'e': snprintf(enablePWD, sizeof(enablePWD), "%s", optarg); break; - case 'n': snprintf(serverName, sizeof(serverName), "%s", optarg); break; - case 'p': sscanf(optarg, "%d", &port); break; - case 's': sscanf(optarg, "%d", &maxSessions); break; - case 'w': snprintf(pwd, sizeof(pwd), "%s", optarg); break; - } - } - - /* start parsing halcmd options */ - n = optind; - while ((n < argc) && (argv[n][0] == '-')) { - cp1 = argv[n++]; - /* loop to parse grouped options */ - while (*(++cp1) != '\0') { - switch (*cp1) { - case 'R': - /* force an unlock of the HAL mutex - to be used after a segfault in a hal program */ - if (release_HAL_mutex() < 0) { - printf("halrmt: Release Mutex failed!\n"); - return 1; - } - return 0; - break; - case 'h': - /* -h = help */ - if (argc > n) { /* there are more arguments, n has been incremented already */ - do_help_cmd(argv[n]); - } else - print_help_general(1); - return 0; - break; - case 'q': - /* -q = quiet (default) */ - rtapi_set_msg_level(RTAPI_MSG_ERR); - break; - case 'Q': - /* -Q = very quiet */ - rtapi_set_msg_level(RTAPI_MSG_NONE); - break; - case 's': - /* script friendly mode */ - scriptmode = 1; - break; - case 'v': - /* -v = verbose */ - rtapi_set_msg_level(RTAPI_MSG_INFO); - break; - case 'V': - /* -V = very verbose */ - rtapi_set_msg_level(RTAPI_MSG_ALL); - break; - case 'f': - /* -f = read from file (or stdin) */ - if (srcfile == NULL) { - /* it's the first -f (ignore repeats) */ - if ((n < argc) && (argv[n][0] != '-')) { - /* there is a following arg, and it's not an option */ - filename = argv[n++]; - srcfile = fopen(filename, "r"); - if (srcfile == NULL) { - fprintf(stderr, - "Could not open command file '%s'\n", - filename); - exit(-1); - } - /* make sure file is closed on exec() */ - fd = fileno(srcfile); - fcntl(fd, F_SETFD, FD_CLOEXEC); - } else { - /* no filename followed -f option, use stdin */ - srcfile = stdin; - prompt_mode = 1; - } - } - break; -#ifndef NO_INI - case 'i': - /* -i = allow reading 'setp' values from an INI file */ - if (inifile == NULL) { - /* it's the first -i (ignore repeats) */ - if ((n < argc) && (argv[n][0] != '-')) { - /* there is a following arg, and it's not an option */ - filename = argv[n++]; - inifile = fopen(filename, "r"); - if (inifile == NULL) { - fprintf(stderr, - "Could not open INI file '%s'\n", - filename); - exit(-1); - } - /* make sure file is closed on exec() */ - fd = fileno(inifile); - fcntl(fd, F_SETFD, FD_CLOEXEC); - } else { - /* no filename followed -i option, error */ - fprintf(stderr, - "No missing INI filename for -i option\n"); - exit(-1); - } - } - break; -#endif /* NO_INI */ - default: - /* unknown option */ - printf("Unknown option '-%c'\n", *cp1); - break; - } - } - } - signal(SIGINT, quit); - signal(SIGTERM, quit); - signal(SIGPIPE, SIG_IGN); - /* at this point all options are parsed, connect to HAL */ - /* create a unique module name, to allow for multiple halrmt's */ - snprintf(comp_name, HAL_NAME_LEN, "halrmt%d", getpid()); - /* tell the signal handler that we might have the mutex */ - hal_flag = 1; - /* connect to the HAL */ - comp_id = hal_init(comp_name); - /* done with mutex */ - hal_flag = 0; - /* check result */ - if (comp_id < 0) { - fprintf(stderr, "halrmt: hal_init() failed: %d\n", comp_id ); - fprintf(stderr, "NOTE: 'rtapi' kernel module must be loaded\n" ); - return 1; - } - hal_ready(comp_id); - errorcount = 0; - initSockets(); - /* HAL init is OK, let's process the command(s) */ - /* tell the signal handler we might have the mutex */ - sockMain(); - hal_flag = 1; - hal_exit(comp_id); - if ( errorcount > 0 ) { - return 1; - } else { - return 0; - } -} - diff --git a/src/hal/utils/halrmt.cc b/src/hal/utils/halrmt.cc new file mode 100644 index 00000000000..cabccb67e36 --- /dev/null +++ b/src/hal/utils/halrmt.cc @@ -0,0 +1,3089 @@ +/******************************************************************** +* Description: halrmt.cc +* Simple telnet interface to LinuxCNC HAL commands (halcmd) +* +* Derived from work by jmkasunich +* +* Other contributors: +* Alex Joni +* +* Author: Eric H. Johnson +* License: GPL Version 2 +* System: Linux +* +* Copyright (c) 2006-2008 All rights reserved. +* Copyright (c) 2026 B.Stultiens +* +* Last change: +* 2026 - Mostly rewritten +********************************************************************/ + +//****************************************************************** +// Using halrmt: see man halrmt(1) +//****************************************************************** + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "setps_util.h" + +using namespace linuxcnc; + +#define NELEM(x) (sizeof(x) / sizeof(*(x))) + +// To prevent excessive hostnames only +#define MAX_HOSTNAME_SIZE 80 + +static std::string helloPwd = "EMC"; // Connect password +static std::string enablePwd = "EMCTOO"; // Enable password +static std::string serverName = "EMCNETSVR"; // Server name written in hello response +static int port = 5006; +static std::string inifilename; +static volatile int quitloop = 0; // Signal to main loop to exit +static int quiet = 0; + +static unsigned maxSessions = 0; // Maximum number of sessions to allow + +typedef struct { + int sock; // Client socket + std::vector toks; // Tokenized command + std::string inbuf; // Input buffer, contains all data from read() + std::string outbuf; // Output buffer, contains all data to write() + std::string hostname; // Name of the client + std::string version; // Client's version + std::string inifilename; // Local ini filename for the connection + bool halfclosed; + bool linked; + bool enabled; + bool echo; // Echo input + bool verbose; // Show GET/SET xxx ACK on every command + bool timestamp; + bool timefmt; + bool expand; // Enable INI-file expansion + bool header; // Show a header with PIN{VAL}S, PARAM{VAL}S, SIGNAL{VAL}S, FUNCTS, THREADS +} connectionRecType; + +static std::vector clients; // Client connections + + +typedef enum { cmdUnknown, cmdHello, cmdSet, cmdGet, cmdQuit, cmdShutdown, cmdHelp } cmdType; + +typedef enum { + hcUnknown, + hcEcho, hcVerbose, hcEnable, hcExpand, hcHeader, + hcTime, hcTimestamp, + hcIni, hcIniFile, + hcSave, + hcPin, hcPinVal, hcPins, hcPinVals, + hcParam, hcParamVal, hcParams, hcParamVals, + hcSig, hcSigVal, hcSigs, hcSigVals, + hcComp, hcComps, + hcFunct, hcFuncts, + hcThread, hcThreads, + hcLoadRt, hcUnload, hcLoadUsr, + hcLinkPS, hcLinkSP, hcNet, hcUnlinkP, + // hcLinkPP, -- Deprecated and now no longer implemented + hcLock, hcUnlock, + hcNewSig, hcDelSig, + hcSetP, hcSetS, + hcAddF, hcDelF, + hcStart, hcStop +} subCmdType; + +typedef enum { + rtOk, + rtError +} cmdResponseType; + +typedef struct { + cmdType command; + unsigned nargs; // Minimum number of arguments + const char *name; +} commandListType; + +// Must be sorted on 'name' +static const commandListType commandList[] = { + {cmdGet, 1, "GET" }, + {cmdHello, 2, "HELLO" }, + {cmdHelp, 0, "HELP" }, + {cmdQuit, 0, "QUIT" }, + {cmdSet, 1, "SET" }, + {cmdShutdown, 0, "SHUTDOWN"}, +}; + +enum accessLevelType { + alNone, // No restrictions + alHello, // Must have issued successful HELLO + alEnable // Must have issued successful SET ENABLE +}; + +typedef struct { + subCmdType command; + const char *name; + unsigned nget; // Minimum getter arg count (token count = nget + 2) + unsigned nset; // minimum setter arg count (token count = nget + 2) + cmdResponseType (*getter)(connectionRecType &); + cmdResponseType (*setter)(connectionRecType &); + accessLevelType acclvl; // Access level + const char *gethelp; // Argument list for GET + const char *sethelp; // Argument list for SET +} getsetListType; + +static void info(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void info(const char *fmt, ...) +{ + if(quiet > 0) + return; + va_list va; + va_start(va, fmt); + fprintf(stdout, "halrmt: "); + vfprintf(stdout, fmt, va); + fprintf(stdout, "\n"); + fflush(stdout); + va_end(va); +} + +static void error(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void error(const char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + fprintf(stderr, "halrmt: "); + vfprintf(stderr, fmt, va); + fprintf(stderr, "\n"); + fflush(stderr); + va_end(va); +} + +static void xperror(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void xperror(const char *fmt, ...) +{ + int en = errno; + va_list va; + va_start(va, fmt); + fprintf(stderr, "halrmt: "); + vfprintf(stderr, fmt, va); + fprintf(stderr, ": %s\n", strerror(en)); + fflush(stderr); + va_end(va); +} + +static void mysleep(double secs) +{ + struct timespec ts, rem; + ts.tv_sec = (time_t)secs; + ts.tv_nsec = 1000000000l * (secs - ts.tv_sec); +retry: + int err = nanosleep(&ts, &rem); + if(err < 0) { + if(EINTR == errno) { + ts = rem; + goto retry; + } + xperror("nanosleep"); + } +} + +static void flushall(void) +{ + // Try to write pending data to each socket + for(auto &c : clients) { + if(!c.outbuf.size()) + continue; + + ssize_t res = write(c.sock, c.outbuf.c_str(), c.outbuf.size()); + if (res < 0) { + if (errno != EINTR && errno != EAGAIN) { + xperror("flushall: client write()"); + // Make this connection to close/abort + c.halfclosed = true; + c.inbuf.clear(); + c.outbuf.clear(); + } + } else { + c.outbuf.erase(0, res); // Remove written data from buffer + } + } +} + +static void reply(connectionRecType &ctx, const std::string &s) +{ + if (ctx.timestamp) { + struct timeval tv; + gettimeofday(&tv, NULL); + if (ctx.timefmt) { + ctx.outbuf.append(fmt::format("{}.{:06d}: ", tv.tv_sec, tv.tv_usec)); + } else { + char tstr[32]; // Enough to hold 'yyyy-mm-dd hh:mm:ss.000000' + struct tm lt; + localtime_r(&tv.tv_sec, <); + strftime(tstr, sizeof(tstr), "%F %T", <); + ctx.outbuf.append(fmt::format("{}.{:06d}: ", tstr, tv.tv_usec)); + } + } + ctx.outbuf.append(s); +} + +static void replynl(connectionRecType &ctx, const std::string &s) +{ + reply(ctx, s + "\r\n"); +} + +static void errornl(connectionRecType &ctx, const std::string &s) +{ + reply(ctx, "error: " + s + "\r\n"); +} + +static void warnnl(connectionRecType &ctx, const std::string &s) +{ + reply(ctx, "warning: " + s + "\r\n"); +} + +static bool to_int(const std::string &s, int &i) +{ + try { + size_t pos; + i = std::stoi(s, &pos); + return pos == s.size(); + } catch (std::exception const &) { + return false; + } +} + + +static int compareNoCase(const std::string &a, const std::string &b) +{ + for (auto i = a.begin(), j = b.begin(); i != a.end() && j != b.end(); ++i, ++j) { + int d = std::toupper((unsigned char)*i) - std::toupper((unsigned char)*j); + if (d) + return d; // Trivial, difference in character sequence + } + // Until here, all characters are the same, but we may have broken out of + // the compare loop due to a difference in string length and both strings + // share the same prefix. + // Non-trivial compare, sizes differ on same string prefix: + // a=ABC + // b=ABC\0D + // We cannot use the difference between character ordinal because we have + // to account for embedded NUL characters. Therefore, we must use the sizes + // to determine rank. Using the difference of sizes also matches equal + // length, i.e. when the strings are equal. + return (int)((ssize_t)a.size() - (ssize_t)b.size()); +} + +// Support functions +static const char *data_type(hal_type_t type) +{ + switch (type) { + case HAL_BOOL: return "bool "; + case HAL_REAL: return "real "; + case HAL_S32: return "s32 "; + case HAL_U32: return "u32 "; + case HAL_SINT: return "sint "; + case HAL_UINT: return "uint "; + case HAL_PORT: return "port "; + default: return "undef"; // Shouldn't happen... + } +} + +/* Switch function for pin direction for the print_*_list functions */ +static const char *pin_data_dir(hal_pdir_t dir) +{ + switch (dir) { + case HAL_IN: return "IN "; + case HAL_OUT: return "OUT"; + case HAL_IO: return "I/O"; + default: return "???"; // Shouldn't happen... + } +} + +/* Switch function for param direction for the print_*_list functions */ +static const char *param_data_dir(hal_pdir_t dir) +{ + switch (dir) { + case HAL_RO: return "RO"; + case HAL_RW: return "RW"; + default: return "??"; // Shouldn't happen... + } +} + +/* Switch function for arrow direction for the print_*_list functions */ +static const char *data_arrow1(hal_pdir_t dir) +{ + switch (dir) { + case HAL_IN: return "<=="; + case HAL_OUT: return "==>"; + case HAL_IO: return "<=>"; + default: return "???"; // Shouldn't happen... + } +} + +/* Switch function for arrow direction for the print_*_list functions */ +static const char *data_arrow2(hal_pdir_t dir) +{ + switch (dir) { + case HAL_IN: return "==>"; + case HAL_OUT: return "<=="; + case HAL_IO: return "<=>"; + default: return "???"; // Shouldn't happen... + } +} + +static std::string data_value(hal_type_t type, hal_query_value_u val) +{ + switch (type) { + case HAL_BOOL: return val.b ? " TRUE" : " FALSE"; + case HAL_REAL: return fmt::format("{:12.7g}", val.r); + case HAL_PORT: // FIXME + case HAL_S32: + case HAL_SINT: return fmt::format(" {:10d}", val.s); + case HAL_U32: + case HAL_UINT: return fmt::format(" {:08X}", val.u); + default: return " undef "; + } +} + +static std::string data_value2(hal_type_t type, hal_query_value_u val) +{ + switch (type) { + case HAL_BOOL: return val.b ? "TRUE" : "FALSE"; + case HAL_REAL: return fmt::format("{:.7g}", val.r); + case HAL_PORT: // FIXME + case HAL_S32: + case HAL_SINT: return fmt::format("{}", val.s); + case HAL_U32: + case HAL_UINT: return fmt::format("{}", val.u); + default: return "unknown_type"; + } +} + +static std::optional getIniVar(connectionRecType &ctx, const std::string &var, const std::string §ion) +{ + if(ctx.inifilename.empty()) { + return std::nullopt; + } + + IniFile inifile(ctx.inifilename); + if(!inifile) { + return std::nullopt; + } + + return inifile.findString(var, section); +} + +static inline bool isEnabled(const connectionRecType &ctx) +{ + return ctx.enabled; +} + +static inline bool doDisable(connectionRecType &ctx) +{ + if (!isEnabled(ctx)) { + return false; + } + ctx.enabled = false; + info("Disabled '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + return true; +} + +static inline bool doEnable(connectionRecType &ctx) +{ + if (isEnabled(ctx)) { + return false; + } + ctx.enabled = true; + info("Enabled '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + return true; +} + +static inline bool doUnlink(connectionRecType &ctx) +{ + if (!ctx.linked) { + return false; + } + ctx.linked = false; + info("Unlinked '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + return true; +} + +static inline bool doLink(connectionRecType &ctx) +{ + if (ctx.linked) { + return false; + } + ctx.linked = true; + info("Linked '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + return true; +} + +typedef struct { + int value; + const char *keyword; +} keywordValueType; + +// Command argument keyword enum +enum { + kwOn, kwOff, + kwAll, kwLoad, kwConfig, kwParams, kwRun, kwTune, kwNone, +}; + +static int checkKeywords(const std::string &s, const keywordValueType *kv, size_t n) +{ + // Going through the list linearly is O(n), but the lists are no longer + // than 8 so binary search does not really make sense. + for (size_t i = 0; i < n; i++) { + if (!compareNoCase(kv[i].keyword, s)) + return kv[i].value; + } + return -1; +} + +static int checkOnOff(const std::string &s) +{ + static const keywordValueType kv[] = { + {kwOn, "ON" }, + {kwOff, "OFF" }, + {kwOn, "1" }, // Be tolerant + {kwOff, "0" }, + {kwOn, "TRUE" }, // Be very tolerant + {kwOff, "FALSE"}, + {kwOn, "YES" }, // Be extremely tolerant + {kwOff, "NO" }, + }; + return checkKeywords(s, kv, NELEM(kv)); +} + +static int checkLock(const std::string &s) +{ + static const keywordValueType kv[] = { + {kwAll, "ALL" }, + {kwLoad, "LOAD" }, + {kwConfig, "CONFIG"}, + {kwParams, "PARAMS"}, + {kwRun, "RUN" }, + {kwTune, "TUNE" }, + {kwNone, "NONE" }, + }; + return checkKeywords(s, kv, NELEM(kv)); +} + +static inline const char *onOff(bool b) +{ + return b ? "ON" : "OFF"; +} + +static std::string onOffString(const std::string &s, bool b) +{ + return fmt::format("{} {}", s, onOff(b)); +} + + +// Signal handler cannot call exit. +// Any exit in the signal handler would leave shared memory segments behind. +static void quitSig(int sig) +{ + (void)sig; + quitloop = 1; +} + +static pid_t halrmt_systemv_nowait(connectionRecType &ctx, const std::vector &argv) +{ + // Need program name and a NULL + if(argv.size() < 2) { + errornl(ctx, "halrmt_systemv_nowait: no program or arguments"); + return -1; + } + if(NULL != argv[argv.size()-1]) { + errornl(ctx, "halrmt_systemv_nowait: argument list not NULL terminated"); + return -1; + } + + // disconnect from the HAL shmem area before forking + hal_lib_exit(); + + int err; + pid_t pid = fork(); + switch(pid) { + case -1: // Error + err = errno; + hal_lib_init(); // Reconnect + errornl(ctx, fmt::format("halrmt_systemv_nowait: Fork failed: errno={} ({})", err, strerror(err))); + return -1; + case 0: // Child + // Restore signals to default before exec + signal(SIGINT, SIG_DFL); + signal(SIGQUIT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + signal(SIGHUP, SIG_DFL); + signal(SIGPIPE, SIG_DFL); + execvp(argv[0], (char * const *)argv.data()); + fprintf(stderr, "halrmt: Child execvp(%s,...) failed: %s\n", argv[0], strerror(errno)); + _exit(1); + break; + default: // Parent + hal_lib_init(); // Reconnect + break; + } + return pid; +} + +static int halrmt_systemv(connectionRecType &ctx, const std::vector &argv) +{ + int status; + + pid_t pid = halrmt_systemv_nowait(ctx, argv); + + do { +retry_wait: + int err = waitpid(pid, &status, 0); // Wait for the child to finish + if(err < 0) { + if(EINTR == errno) { + goto retry_wait; + } + errornl(ctx, fmt::format("halrmt_systemv: waitpid({}) failed, errno={} ({})", pid, errno, strerror(errno))); + return -1; + } + } while(!WIFEXITED(status) && !WIFSIGNALED(status)); + + int rv = WEXITSTATUS(status); + if(0 != rv) { + errornl(ctx, fmt::format("{}: exit value: {}", argv[0], rv)); + return -1; + } + return 0; +} + +/*********************************************************************** +* LOCAL FUNCTION DEFINITIONS * +************************************************************************/ + +static int unloadrt_cb(hal_query_t *q, void *arg) +{ + std::vector *comps = reinterpret_cast *>(arg); + if(HAL_COMP_TYPE_REALTIME == q->comp.type) { + comps->push_back(q->name); + } + return 0; +} + +static int unloadrt_comp(connectionRecType &ctx, const std::string &mod_name) +{ + std::vector argv; + +#if defined(RTAPI_USPACE) + argv.push_back(EMC2_BIN_DIR "/rtapi_app"); + argv.push_back("unload"); +#else + argv.push_back(EMC2_BIN_DIR "/linuxcnc_module_helper"); + argv.push_back("remove"); +#endif + argv.push_back(mod_name.c_str()); + argv.push_back(NULL); + + return halrmt_systemv(ctx, argv); +} + +// +// It turns out that it is not portable to reset the state of getopt, so that a +// different argv list can be parsed. +// https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=192834 +// +// (though that thread ends with the bug being closed as fixed in lenny, it is +// not fixed or has regressed by debian jessie) +// +static void reset_getopt_state() +{ +#ifdef __GNU_LIBRARY__ + optind = 0; +#else + optind = 1; +#endif +#ifdef HAVE_OPTRESET + optreset = 1; +#endif +} + +static std::string guess_comp_name(const std::string &prog_name) +{ + std::string name; + size_t pos = prog_name.find_last_of('/'); + if(std::string::npos != pos) { + name = prog_name.substr(pos + 1); + } else { + name = prog_name; + } + pos = name.find_last_of('.'); + if(std::string::npos != pos) { + name.erase(pos); + } + return name; +} + +static int get_all_comp_names_cb(hal_query_t *q, void *arg) +{ + std::set *comps = reinterpret_cast *>(arg); + comps->insert(q->name); + return 0; +} + +static std::set get_all_comp_names() { + std::set result; + hal_query_t q = {}; + hal_list_comp(&q, get_all_comp_names_cb, &result); + return result; +} + +static void warn_newly_loaded_comps(connectionRecType &ctx, std::set &names, const std::string &newname) +{ + auto new_names = get_all_comp_names(); + for(const auto &name : new_names) { + if(name == newname) continue; + if(names.find(name) == names.end()) { + errornl(ctx, fmt::format("While waiting for '{}', component '{}' loaded.\r\n" + "Did you specify the correct name via 'loadusr -Wn'?", + newname, name)); + flushall(); + } + } + std::swap(new_names, names); +} + +// +// FIXME: The loadUsr code will stall the entire process. We need to do this +// in a coroutine style for other connections to be served. +// +static int doLoadUsr(connectionRecType &ctx, const std::vector &args) +{ + int status; + + if(args.size() < 2) { + errornl(ctx, fmt::format("LoadUsr: Not enough arguments")); + return -EINVAL; + } + if(NULL != args[args.size() - 1]) { + errornl(ctx, fmt::format("LoadUsr: Argument list not NULL terminated")); + return -EINVAL; + } + + if(hal_get_lock() & HAL_LOCK_LOAD) { + errornl(ctx, "LoadUsr: HAL is locked, loading of programs is not permitted"); + return -EPERM; + } + + int wait_flag = 0; + int wait_comp_flag = 0; + int ignore_flag = 0; + std::string new_comp_name; + + /* check for options (-w, -i, and/or -r) */ + reset_getopt_state(); + int optc; + int argc = args.size() - 1; + while (-1 != (optc = getopt(argc, (char * const *)args.data(), "+wWin:"))) { + switch(optc) { + case 'w': wait_flag = 1; break; + case 'W': wait_comp_flag = 1; break; + case 'i': ignore_flag = 1; break; + case 'n': new_comp_name = optarg; break; + default: + errornl(ctx, fmt::format("LoadUsr: Invalid option '-{}'", isprint(optc) ? optc : '?')); + return -EINVAL; + } + } + std::vector argv; + for(unsigned i = optind; i < args.size(); i++) { + argv.push_back(args[i]); + } + // Double check argument list + if(argv.size() < 2) { + errornl(ctx, fmt::format("LoadUsr: Not enough arguments for halcmd_systemv")); + return -EINVAL; + } + if(NULL != argv[argv.size() - 1]) { + errornl(ctx, fmt::format("LoadUsr: Argument list not NULL terminated for halcmd_systemv")); + return -EINVAL; + } + + // Get component name + if(new_comp_name.empty()) { + new_comp_name = guess_comp_name(argv[0]); + } + + // Component status quo + std::set comp_names_pre = get_all_comp_names(); + + // Create the new user process + pid_t pid = halrmt_systemv_nowait(ctx, argv); + if(pid < 0) { + int err = errno; + errornl(ctx, fmt::format("LoadUsr: Failed to execute '{}'", argv[0])); + return -err; + } + + bool exited = false; + int err; + if(wait_comp_flag) { + bool ready = false; + int count = 0; + int retval = 0; + while(!ready && !exited) { + mysleep(0.01); + // Program done? + errno = 0; + retval = waitpid(pid, &status, WNOHANG); + err = errno; + if (retval != 0) { + if(EINTR == err) { + continue; + } + exited = true; + ready = false; + errornl(ctx, fmt::format("LoadUsr: waitpid failed '{}' ('{}') errno={}", argv[0], new_comp_name, err)); + break; + } + if(WIFEXITED(status)) { + errornl(ctx, fmt::format("LoadUsr: program '{}' terminated with code {}", argv[0], (int)WEXITSTATUS(status))); + exited = true; + ready = false; + break; + } + /* check for program becoming ready */ + hal_query_t q = {}; + int rv = hal_comp_by_name(new_comp_name.c_str(), &q); + if(!rv && q.comp.ready) { + ready = true; + break; + } + /* pacify the user */ + count++; + if(count >= 300 && 0 == (count % 200)) { + replynl(ctx, fmt::format("\nWaiting for component '{}' to become ready.", new_comp_name)); + warn_newly_loaded_comps(ctx, comp_names_pre, new_comp_name); + flushall(); + } else if(count > 200 && count % 10 == 0) { + reply(ctx, "."); + warn_newly_loaded_comps(ctx, comp_names_pre, new_comp_name); + flushall(); + } + } + if (count > 200) { + // terminate the ... pacifier + replynl(ctx, ""); + flushall(); + } + // did it work? + if (!ready) { + if (retval < 0) { + errornl(ctx, fmt::format("LoadUsr: waitpid({}) failed errno={} ({})", pid, err, strerror(err))); + } else { + errornl(ctx, fmt::format("LoadUsr: {} exited without becoming ready", argv[0])); + } + return -err; + } + } + + if (wait_flag) { + while(!exited) { + int rv = waitpid(pid, &status, 0); + err = errno; + if (rv < 0) { + if(EINTR == err) { + continue; + } + errornl(ctx, fmt::format("LoadUsr: waitpid({}) failed, errno={} ({})", pid, err, strerror(err))); + return -err; + } + if(WIFEXITED(status)) { + // Done... + break; + } + if(WIFSIGNALED(status)) { + errornl(ctx, fmt::format("LoadUsr: program '{}' did exit on signal {}", argv[0], WTERMSIG(status))); + return -ESRCH; + } + } + if (!ignore_flag) { + int rv = WEXITSTATUS(status); + if (0 != rv) { + errornl(ctx, fmt::format("LoadUsr: program '{}' failed, returned {}", argv[0], rv)); + return -ESRCH; + } + } + } + return 0; +} + +static int doLoadRt(connectionRecType &ctx, const std::vector &args) +{ + int retval; + std::vector argv; + +#if defined(RTAPI_USPACE) + argv.push_back("-W"); + argv.push_back("-n"); + argv.push_back(args[0].c_str()); + argv.push_back(EMC2_BIN_DIR "/rtapi_app"); + argv.push_back("load"); + for(unsigned i = 0; i < args.size(); i++) { + argv.push_back(args[i].c_str()); + } + argv.push_back(NULL); + retval = doLoadUsr(ctx, argv); +#else + if (hal_get_lock() & HAL_LOCK_LOAD) { + errornl(ctx, "LoadRt: HAL is locked, loading of modules is not permitted"); + return -EPERM; + } + + // Make full module name '/.o' + std::string mod_path = fmt::format("{}/{}{}", EMC2_RTLIB_DIR, args[0], MODULE_EXT); + + // Does the module exist? + struct stat stat_buf; + if (stat(mod_path.c_str(), &stat_buf) != 0 ) { + errornl(ctx, fmt::format("LoadRt: Can't find module '{}' in '{}'", args[0], EMC2_RTLIB_DIR)); + return -ENOENT; + } + + argv.push_back(EMC2_BIN_DIR "/linuxcnc_module_helper"); + argv.push_back("insert"); + for(unsigned i = 0; i < args.size(); i++) { + argv.push_back(args[i].c_str()); + } + argv.push_back(NULL); + + retval = halrmt_systemv(ctx, argv); +#endif + + if (0 != retval) { + errornl(ctx, fmt::format("LoadRt: insmod '{}' failed, returned {}", args[0], retval)); + return retval; + } + // Join the module arguments into a single string + std::string insmod = args[0]; + for(unsigned i = 1; i < args.size(); i++) { + insmod += ' '; + insmod += args[i]; + } + // Module argument string needs to go into hal memory + char *cptr = (char *)hal_malloc(insmod.size() + 1); + if (!cptr) { + errornl(ctx, "LoadRt: Failed to allocate HAL memory"); + return -ENOMEM; + } + strcpy(cptr, insmod.c_str()); + int rv = hal_comp_insmod_args(args[0].c_str(), cptr); + if(rv) { + errornl(ctx, fmt::format("LoadRt: module '{}' not loaded", args[0])); + return -EINVAL; + } + return 0; +} + +static int getCompInfo_cb(hal_query_t *q, void *arg) +{ + connectionRecType *ctx = reinterpret_cast(arg); + const std::string *pattern = reinterpret_cast(q->callerdata.cpval); + if(pattern->empty() || !fnmatch(pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + replynl(*ctx, fmt::format("COMP {:12s} {:3d} {}", + q->name, q->comp.comp_id, q->comp.type == HAL_COMP_TYPE_REALTIME ? "RT " : "User")); + } + return 0; +} + +static int getCompInfo(connectionRecType &ctx, const std::string &pattern) +{ + hal_query_t q = {}; + q.callerdata.cpval = &pattern; + if(ctx.header) { + replynl(ctx, fmt::format("COMP Name Id Type")); + } + return hal_list_comp(&q, getCompInfo_cb, &ctx); +} + +typedef struct { + connectionRecType *ctx; + const std::string *pattern; + int count; + bool valuesOnly; +} getXinfo_t; + +static int getPinInfo_cb(hal_query_t *q, void *arg) +{ + getXinfo_t *gpi = reinterpret_cast(arg); + if(gpi->pattern->empty() || !fnmatch(gpi->pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + gpi->count++; + if(gpi->valuesOnly) { + replynl(*gpi->ctx, fmt::format("PINVAL {:30s} {}", + q->name, data_value2(q->pp.type, q->pp.value))); + } else { + replynl(*gpi->ctx, fmt::format("PIN {:30s} {:11s} {:12s}({:3d}) {} {}", + q->name, data_value2(q->pp.type, q->pp.value), + q->pp.comp, q->pp.comp_id, data_type(q->pp.type), pin_data_dir(q->pp.dir))); + } + } + return 0; +} + +static std::pair getPinInfo(connectionRecType &ctx, const std::string &pattern, bool valuesOnly) +{ + getXinfo_t gpi = { &ctx, &pattern, 0, valuesOnly }; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + if(ctx.header) { + if(valuesOnly) + replynl(ctx, fmt::format("PINVAL Name Value")); + else + replynl(ctx, fmt::format("PIN Name Value Component ( id) Type Dir")); + } + return {hal_list_p(&q, getPinInfo_cb, &gpi), gpi.count}; +} + +static int getSigInfo_cb(hal_query_t *q, void *arg) +{ + getXinfo_t *gpi = reinterpret_cast(arg); + if(gpi->pattern->empty() || !fnmatch(gpi->pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + gpi->count++; + if(gpi->valuesOnly) { + replynl(*gpi->ctx, fmt::format("SIGNALVAL {:30s} {}", + q->name, data_value2(q->sig.type, q->sig.value))); + } else { + replynl(*gpi->ctx, fmt::format("SIGNAL {:30s} {:11s} {}", + q->name, data_value2(q->sig.type, q->sig.value), data_type(q->sig.type))); + } + } + return 0; +} + +static std::pair getSigInfo(connectionRecType &ctx, const std::string &pattern, bool valuesOnly) +{ + getXinfo_t gpi = { &ctx, &pattern, 0, valuesOnly }; + hal_query_t q = {}; + if(ctx.header) { + if(valuesOnly) + replynl(ctx, fmt::format("SIGNALVAL Name Value")); + else + replynl(ctx, fmt::format("SIGNAL Name Value Type")); + } + return {hal_list_s(&q, getSigInfo_cb, &gpi), gpi.count}; +} + +static int getParamInfo_cb(hal_query_t *q, void *arg) +{ + getXinfo_t *gpi = reinterpret_cast(arg); + if(gpi->pattern->empty() || !fnmatch(gpi->pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + gpi->count++; + if(gpi->valuesOnly) { + replynl(*gpi->ctx, fmt::format("PARAMVAL {:30s} {}", + q->name, data_value2(q->pp.type, q->pp.value))); + } else { + replynl(*gpi->ctx, fmt::format("PARAM {:30s} {:11s} {:12s}({:3d}) {} {}", + q->name, data_value2(q->pp.type, q->pp.value), + q->pp.comp, q->pp.comp_id, data_type(q->pp.type), param_data_dir(q->pp.dir))); + } + } + return 0; +} + +static std::pair getParamInfo(connectionRecType &ctx, const std::string &pattern, bool valuesOnly) +{ + getXinfo_t gpi = { &ctx, &pattern, 0, valuesOnly }; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; + if(ctx.header) { + if(valuesOnly) + replynl(ctx, fmt::format("PARAMVAL Name Value")); + else + replynl(ctx, fmt::format("PARAM Name Value Component ( id) Type Dir")); + } + return {hal_list_p(&q, getParamInfo_cb, &gpi), gpi.count}; +} + +static int getFunctInfo_cb(hal_query_t *q, void *arg) +{ + connectionRecType *ctx = reinterpret_cast(arg); + const std::string *pattern = reinterpret_cast(q->callerdata.cpval); + if(pattern->empty() || !fnmatch(pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + replynl(*ctx, fmt::format("FUNCT {:16s} {:12s}({:3d}) {:3d}", + q->name, q->funct.comp, q->funct.comp_id, q->funct.users)); + } + return 0; +} + +static int getFunctInfo(connectionRecType &ctx, const std::string &pattern) +{ + hal_query_t q = {}; + q.callerdata.cpval = reinterpret_cast(&pattern); + if(ctx.header) { + replynl(ctx, "FUNCT Name Component ( id) Users"); + } + return hal_list_funct(&q, getFunctInfo_cb, &ctx); +} + +static rtapi_sint getpin_sint(connectionRecType &ctx, const std::string &name) +{ + hal_query_t q = {}; + q.name = name.c_str(); + int rv = hal_get_p(&q, NULL, NULL); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot find thread's pin '{}', error={}", name, rv)); + return 0; + } + return q.pp.value.s; +} +static int getThreadInfo_cb(hal_query_t *q, void *arg) +{ + connectionRecType *ctx = reinterpret_cast(arg); + const std::string *pattern = reinterpret_cast(q->callerdata.cpval); + if(HAL_QTYPE_THREAD == q->qtype) { + // The thread reference + if(pattern->empty() || !fnmatch(pattern->c_str(), q->name, FNM_NOESCAPE|FNM_CASEFOLD)) { + rtapi_sint tp = getpin_sint(*ctx, fmt::format("{}.time", q->name)); + rtapi_sint tm = getpin_sint(*ctx, fmt::format("{}.tmax", q->name)); + replynl(*ctx, fmt::format("THREAD {:12s} {:11d} {} {}", q->name, q->thread.period, tp, tm)); + } + } else { + // The thread's function reference + replynl(*ctx, fmt::format("THREADFUNCT {:16s} {:2d}", q->thread.funct, q->thread.functidx + 1)); + } + return 0; +} + +static int getThreadInfo(connectionRecType &ctx, const std::string &pattern) +{ + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; + q.callerdata.cpval = reinterpret_cast(&pattern); + if(ctx.header) { + replynl(ctx, "THREAD Name Period time tmax"); + } + return hal_list_thread(&q, getThreadInfo_cb, &ctx); +} + +static int save_comps_cb(hal_query_t *q, void *arg) +{ + std::string *str = reinterpret_cast(arg); + if(strstr(q->name, HAL_PSEUDO_COMP_PREFIX) == q->name) { + // Those starting with '__' are fake components + return 0; + } + if(HAL_COMP_TYPE_REALTIME == q->comp.type) { + // Realtime components only + if(!q->comp.insmod) { + *str += fmt::format("# loadrt {} (not loaded by loadrt, no args saved)\n", q->name); + } else { + *str += fmt::format("loadrt {} {}\n", q->name, q->comp.insmod); + } + } + return 0; +} + +static void save_comps(std::string &dst) +{ + dst += "# components\n"; + hal_query_t q = {}; + hal_list_comp(&q, save_comps_cb, &dst); +} + +static int save_signals_cb(hal_query_t *q, void *arg) +{ + std::string *str = reinterpret_cast(arg); + *str += fmt::format("newsig {} {}\n", q->name, data_type(q->sig.type)); + return 0; +} + +static void save_signals(std::string &dst) +{ + dst += "# signals\n"; + hal_query_t q = {}; + hal_list_s(&q, save_signals_cb, &dst); +} + +static int save_links_cb(hal_query_t *q, void *arg) +{ + if(q->pp.signal) { + std::string *str = reinterpret_cast(arg); + const char *arrow_str = q->callerdata.sival ? data_arrow1(q->pp.dir) : ""; + *str += fmt::format("linkps {} {} {}\n", q->name, arrow_str, q->pp.signal); + } + return 0; +} + +static void save_links(std::string &dst, int arrow) +{ + dst += "# links\n"; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PIN; + q.callerdata.sival = arrow; + hal_list_p(&q, save_links_cb, &dst); +} + +static int save_nets_pins_cb(hal_query_t *q, void *arg) +{ + std::string *str = reinterpret_cast(arg); + const char *arrow_str = q->callerdata.sival ? data_arrow2(q->pp.dir) : ""; + *str += fmt::format("linksp {} {} {}\n", q->pp.signal, arrow_str, q->name); + return 0; +} + +static int save_nets_cb(hal_query_t *q, void *arg) +{ + std::string *str = reinterpret_cast(arg); + *str += fmt::format("newsig {} {}\n", q->name, data_type(q->sig.type)); + hal_query_t qp = {}; + qp.name = q->name; + qp.callerdata.sival = q->callerdata.sival; + return hal_list_p_s(&qp, save_nets_pins_cb, arg); +} +static void save_nets(std::string &dst, int arrow) +{ + dst += "# nets\n"; + hal_query_t q = {}; + q.callerdata.sival = arrow; + hal_list_s(&q, save_nets_cb, &dst); +} + +static int save_params_cb(hal_query_t *q, void *arg) +{ + std::string *str = reinterpret_cast(arg); + *str += fmt::format("setp {} {}\n", q->name, data_value(q->pp.type, q->pp.value).c_str()); + return 0; +} + +static void save_params(std::string &dst) +{ + dst += "# parameter values\n"; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_PARAM; + hal_list_p(&q, save_params_cb, &dst); +} + +static int save_threads_cb(hal_query_t *q, void *arg) +{ + if(HAL_QTYPE_THREAD_FUNCT == q->qtype) { + std::string *str = reinterpret_cast(arg); + *str += fmt::format("addf {} {}\n", q->thread.funct, q->name); + } + return 0; +} + +static void save_threads(std::string &dst) +{ + dst += "# realtime thread/function links\n"; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD_FUNCT; + hal_list_thread(&q, save_threads_cb, &dst); +} + +// initiate session +static int commandHello(connectionRecType &ctx) +{ + // HELLO [] + + if (ctx.toks[2].size() > MAX_HOSTNAME_SIZE) { + errornl(ctx, fmt::format("Hostname too long. Max length allowed is {}", MAX_HOSTNAME_SIZE)); + replynl(ctx, "HELLO NAK"); + return -1; + } + + // Repeating a HELLO means we disable and unlink. + // Linking needs to be reestablished + doDisable(ctx); + doUnlink(ctx); + + // On password errors, don't say too much. + if (ctx.toks[1] != helloPwd) { + replynl(ctx, "HELLO NAK"); + return -1; + } + + std::string version = "1.1"; + if (auto inistring = getIniVar(ctx, "VERSION", "EMC")) + version = *inistring; + + ctx.hostname = ctx.toks[2]; + + // ctx.version defaults to "1.1" when the context is created + if (ctx.toks.size() > 3) + ctx.version = ctx.toks[3]; + + if (ctx.version > version) { + warnnl(ctx, fmt::format("Requested version '{}' is newer than '{}' from [EMC]VERSION", ctx.version, version)); + } + + doLink(ctx); + replynl(ctx, fmt::format("HELLO ACK {} {}", serverName, version)); + return 0; +} + +int commandQuit(connectionRecType &ctx) +{ + doDisable(ctx); + ctx.halfclosed = true; + ctx.inbuf.clear(); // Zap any remaining input + info("Closing connection '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + replynl(ctx, "QUIT ACK"); + return 0; +} + +int commandShutdown(connectionRecType &ctx) +{ + if (isEnabled(ctx)) { + // A shutdown will disconnect all clients from halrmt + info("Shutdown initiated by '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + doDisable(ctx); + // Shutdown is not actually performed... + // It cannot work because there is no infrastructure in place to do a + // remote shutdown. + replynl(ctx, "SHUTDOWN ACK"); + return 0; + } + + errornl(ctx, "SHUTDOWN failed, not enabled"); + replynl(ctx, "SHUTDOWN NAK"); + return -1; +} + +static cmdResponseType getEcho(connectionRecType &ctx) +{ + // GET ECHO + replynl(ctx, onOffString("ECHO", ctx.echo)); + return rtOk; +} + +static cmdResponseType getVerbose(connectionRecType &ctx) +{ + // GET VERBOSE + replynl(ctx, onOffString("VERBOSE", ctx.verbose)); + return rtOk; +} + +static cmdResponseType getHeader(connectionRecType &ctx) +{ + // GET HEADER + replynl(ctx, onOffString("HEADER", ctx.header)); + return rtOk; +} + +static cmdResponseType getEnable(connectionRecType &ctx) +{ + // GET ENABLE + replynl(ctx, onOffString("ENABLE", isEnabled(ctx))); + return rtOk; +} + +static cmdResponseType getExpand(connectionRecType &ctx) +{ + // GET EXPAND + replynl(ctx, onOffString("EXPAND", ctx.expand)); + return rtOk; +} + +static cmdResponseType getComps(connectionRecType &ctx) +{ + // GET COMPS [prefix] + int rv; + if(ctx.toks.size() > 2) + rv = getCompInfo(ctx, ctx.toks[2].c_str()); + else + rv = getCompInfo(ctx, ""); + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType getPins(connectionRecType &ctx) +{ + // GET PINS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getPinInfo(ctx, ctx.toks[2], false); + } else { + rv = getPinInfo(ctx, "", false); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getPinVals(connectionRecType &ctx) +{ + // GET PINVALS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getPinInfo(ctx, ctx.toks[2], true); + } else { + rv = getPinInfo(ctx, "", true); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getSigs(connectionRecType &ctx) +{ + // GET SIGS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getSigInfo(ctx, ctx.toks[2], false); + } else { + rv = getSigInfo(ctx, "", false); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getSigVals(connectionRecType &ctx) +{ + // GET SIGVALS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getSigInfo(ctx, ctx.toks[2], true); + } else { + rv = getSigInfo(ctx, "", true); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getParams(connectionRecType &ctx) +{ + // GET PARAMS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getParamInfo(ctx, ctx.toks[2], false); + } else { + rv = getParamInfo(ctx, "", false); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getParamVals(connectionRecType &ctx) +{ + // GET PARAMVALS [prefix] + std::pair rv; + if(ctx.toks.size() > 2) { + rv = getParamInfo(ctx, ctx.toks[2], true); + } else { + rv = getParamInfo(ctx, "", true); + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getFuncts(connectionRecType &ctx) +{ + // GET FUNCTS [prefix] + int rv; + if(ctx.toks.size() > 2) { + rv = getFunctInfo(ctx, ctx.toks[2]); + } else { + rv = getFunctInfo(ctx, ""); + } + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType getIni(connectionRecType &ctx) +{ + // GET INI
+ auto inistring = getIniVar(ctx, ctx.toks[2], ctx.toks[3]); + if (inistring) { + replynl(ctx, fmt::format("INI [{}]{}={}", ctx.toks[3], ctx.toks[2], *inistring)); + return rtOk; + } else { + errornl(ctx, fmt::format("INI file entry '[{}]{}' not found", ctx.toks[3], ctx.toks[2])); + return rtError; + } +} + +static cmdResponseType getIniFile(connectionRecType &ctx) +{ + // GET INIFILE + replynl(ctx, fmt::format("INIFILE {}", ctx.inifilename)); + return rtOk; +} + +static cmdResponseType getThreads(connectionRecType &ctx) +{ + // GET THREADS [prefix] + int rv; + if(ctx.toks.size() > 2) { + rv = getThreadInfo(ctx, ctx.toks[2]); + } else { + rv = getThreadInfo(ctx, ""); + } + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType getComp(connectionRecType &ctx) +{ + // GET COMP + return 0 == getCompInfo(ctx, ctx.toks[2]) ? rtOk : rtError; +} + +static cmdResponseType getPin(connectionRecType &ctx) +{ + // GET PIN + std::pair rv = getPinInfo(ctx, ctx.toks[2], false); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Pin '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getPinVal(connectionRecType &ctx) +{ + // GET PINVAL + std::pair rv = getPinInfo(ctx, ctx.toks[2], true); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Pin '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getSig(connectionRecType &ctx) +{ + // GET SIGNAL + std::pair rv = getSigInfo(ctx, ctx.toks[2], false); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Signal '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getSigVal(connectionRecType &ctx) +{ + // GET SIGNALVAL + std::pair rv = getSigInfo(ctx, ctx.toks[2], true); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Signal '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getParam(connectionRecType &ctx) +{ + // GET PARAM + std::pair rv = getParamInfo(ctx, ctx.toks[2], false); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Parameter '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getParamVal(connectionRecType &ctx) +{ + // GET PARAMVAL + std::pair rv = getParamInfo(ctx, ctx.toks[2], true); + if(0 == rv.first && 0 == rv.second) { + errornl(ctx, fmt::format("Parameter '{}' not found", ctx.toks[2])); + return rtError; + } + return 0 == rv.first ? rtOk : rtError; +} + +static cmdResponseType getFunct(connectionRecType &ctx) +{ + // GET FUNCT + return 0 == getFunctInfo(ctx, ctx.toks[2]) ? rtOk : rtError; +} + +static cmdResponseType getThread(connectionRecType &ctx) +{ + // GET THREAD + return 0 == getThreadInfo(ctx, ctx.toks[2]) ? rtOk : rtError; +} + +static cmdResponseType getLock(connectionRecType &ctx) +{ + // GET LOCK + unsigned char lck = hal_get_lock(); + if(HAL_LOCK_NONE == lck) { + replynl(ctx, "LOCK none"); + } else if(HAL_LOCK_ALL == lck) { + replynl(ctx, "LOCK all"); + } else { +#define LOCK_ANY (HAL_LOCK_LOAD | HAL_LOCK_CONFIG | HAL_LOCK_PARAMS | HAL_LOCK_RUN) + std::string l; + if(lck & HAL_LOCK_LOAD) l += " load"; + if(lck & HAL_LOCK_CONFIG) l += " config"; + if(lck & HAL_LOCK_PARAMS) l += " params"; + if(lck & HAL_LOCK_RUN) l += " run"; + if(0 != (lck & ~LOCK_ANY)) { + l += fmt::format(" (unknown values: lock=0x{:02x})", lck); + } + replynl(ctx, fmt::format("LOCK{}", l)); +#undef LOCK_ANY + } + return rtOk; +} + +static int getNet_cb(hal_query_t *q, void *arg) +{ + connectionRecType *ctx = reinterpret_cast(arg); + replynl(*ctx, fmt::format("{} {} {}", q->pp.signal, data_arrow1(q->pp.dir), q->name)); + return 0; +} + +static cmdResponseType getNet(connectionRecType &ctx) +{ + // GET NET + hal_query_t q = {}; + q.name = ctx.toks[2].c_str(); + int rv = hal_list_p_s(&q, getNet_cb, &ctx); + if(0 == rv) { + return rtOk; + } else if(-ENOENT == rv) { + errornl(ctx, fmt::format("Signal '{}' not found", ctx.toks[2])); + return rtError; + } else { + errornl(ctx, fmt::format("Signal '{}' resulted in error={} ({})", ctx.toks[2], rv, hal_strerror(rv))); + return rtError; + } +} + +static cmdResponseType getTimestamp(connectionRecType &ctx) +{ + // GET TIMESTAMP + replynl(ctx, fmt::format("TIMESTAMP {} {}", onOff(ctx.timestamp), onOff(ctx.timefmt))); + return rtOk; +} + +static cmdResponseType getTime(connectionRecType &ctx) +{ + // GET TIME + struct timeval tv; + gettimeofday(&tv, NULL); + double t = (double)tv.tv_sec + tv.tv_usec * 1e-6; + replynl(ctx, fmt::format("TIME {}", t)); + return rtOk; +} + +static cmdResponseType setEcho(connectionRecType &ctx) +{ + // SET ECHO + switch (checkOnOff(ctx.toks[2])) { + default: errornl(ctx, fmt::format("Invalid argument '{}', must be {{on,off}}", ctx.toks[2])); return rtError; + case kwOn: ctx.echo = true; break; + case kwOff: ctx.echo = false; break; + } + return rtOk; +} + +static cmdResponseType setVerbose(connectionRecType &ctx) +{ + // SET VERBOSE + switch (checkOnOff(ctx.toks[2])) { + default: errornl(ctx, fmt::format("Invalid argument '{}', must be {{on,off}}", ctx.toks[2])); return rtError; + case kwOn: ctx.verbose = true; break; + case kwOff: ctx.verbose = false; break; + } + return rtOk; +} + +static cmdResponseType setHeader(connectionRecType &ctx) +{ + // SET HEADER + switch (checkOnOff(ctx.toks[2])) { + default: errornl(ctx, fmt::format("Invalid argument '{}', must be {{on,off}}", ctx.toks[2])); return rtError; + case kwOn: ctx.header = true; break; + case kwOff: ctx.header = false; break; + } + return rtOk; +} + +static cmdResponseType setEnable(connectionRecType &ctx) +{ + // SET ENABLE + if (ctx.toks[2] == enablePwd) { + doEnable(ctx); + return rtOk; + } + + if (!compareNoCase(ctx.toks[2], "OFF")) { + if (!isEnabled(ctx)) { + errornl(ctx, "Trying to set enable to off on a non-enabled link"); + return rtError; + } + doDisable(ctx); + return rtOk; + } + return rtError; +} + +static cmdResponseType setExpand(connectionRecType &ctx) +{ + // SET EXPAND + switch (checkOnOff(ctx.toks[2])) { + default: errornl(ctx, fmt::format("Invalid argument '{}', must be {{on,off}}", ctx.toks[2])); return rtError; + case kwOn: ctx.expand = true; break; + case kwOff: ctx.expand = false; break; + } + return rtOk; +} + +static cmdResponseType setLoadRt(connectionRecType &ctx) +{ + // SET LOADRT [args...] + if(REALTIME_TYPE_UNINITIALIZED == hal_get_realtime_type()) { + errornl(ctx, "Realtime has not been initialized."); + return rtError; + } + + std::vector args; + + for(unsigned i = 2; i < ctx.toks.size(); i++) { + args.push_back(ctx.toks[i]); + } + int rv = doLoadRt(ctx, args); + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType setUnload(connectionRecType &ctx) +{ + // SET UNLOAD |all + if(REALTIME_TYPE_UNINITIALIZED == hal_get_realtime_type()) { + errornl(ctx, "Realtime has not been initialized."); + return rtError; + } + + std::vector comps; + + if("all" == ctx.toks[2]) { + // Unload all components + // Gather all RT components + hal_query_t q = {}; + int rv = hal_list_comp(&q, unloadrt_cb, &comps); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to gather component list, error={} ({})", + ctx.toks[2], rv, hal_strerror(rv))); + return rtError; + } + } else { + // Unload one specific component + hal_query_t q = {}; + int rv = hal_comp_by_name(ctx.toks[2].c_str(), &q); + if(0 != rv) { + errornl(ctx, fmt::format("Component '{}' is not loaded, error={} ({})", + ctx.toks[2], rv, hal_strerror(rv))); + return rtError; + } + if(HAL_COMP_TYPE_REALTIME != q.comp.type) { + errornl(ctx, fmt::format("Component '{}' is not a real-time component", ctx.toks[2])); + return rtError; + } + comps.push_back(ctx.toks[2]); + } + + // Now unload the lot + for(const auto &comp : comps) { + int rv = unloadrt_comp(ctx, comp); + if(0 != rv) { + errornl(ctx, fmt::format("Component '{}' failed to unload, error={} ({})", + ctx.toks[2], rv, hal_strerror(rv))); + return rtError; + } + } + return rtOk; +} + +static cmdResponseType setLoadUsr(connectionRecType &ctx) +{ + // SET LOADUSR [arg [arg...]] + std::vector argv; + for(unsigned i = 2; i < ctx.toks.size(); i++) { + argv.push_back(ctx.toks[i].c_str()); + } + argv.push_back(NULL); + int rv = doLoadUsr(ctx, argv); + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType linkPS(connectionRecType &ctx, const std::string &pin, const std::string &sig) +{ + if(sig.empty()) { + int rv = hal_unlink(pin.c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to unlink '{}'", pin)); + return rtError; + } + } else { + int rv = hal_link(pin.c_str(), sig.c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to link pin '{}' to signal '{}'", pin, sig)); + return rtError; + } + } + return rtOk; +} + +static cmdResponseType setLinkPS(connectionRecType &ctx) +{ + // SET LINKPS [] + if(ctx.toks.size() > 3) + return linkPS(ctx, ctx.toks[2], ctx.toks[3]); + else + return linkPS(ctx, ctx.toks[2], ""); +} + +static cmdResponseType setLinkSP(connectionRecType &ctx) +{ + // SET LINKSP + return linkPS(ctx, ctx.toks[3], ctx.toks[2]); +} + +#if 0 +// This has been deprecated in halcmd for quite some time. +// No need to continue it. +static cmdResponseType setLinkPP(connectionRecType &ctx) +{ + // SET LINKPP + hal_query_t p1 = {}; + hal_query_t p2 = {}; + p1.qtype = HAL_QTYPE_PIN; + p1.name = ctx.toks[2].c_str(); + p2.qtype = HAL_QTYPE_PIN; + p2.name = ctx.toks[3].c_str(); + int pin1 = hal_getref_p(&p1); + int pin2 = hal_getref_p(&p2); + // Check if both pins exist + if (0 != pin1 || 0 != pin2) { + errornl(ctx, fmt::format("Pin '{}' not found", 0 != pin1 ? ctx.toks[2] : ctx.toks[3])); + return rtError; + } + + // Check that both pins have the same type + if (p1.pp.type != p2.pp.type) { + errornl(ctx, fmt::format("Pins '{}' and '{}' are not of same type ({} != {})", + ctx.toks[2], ctx.toks[3], (int)p1.pp.type, (int)p2.pp.type)); + return rtError; + } + + // Create the signal + int rv = hal_signal_new(ctx.toks[2].c_str(), p1.pp.type); + + if (0 == rv) { + // Link pin 1 to signal + rv = hal_link(ctx.toks[2].c_str(), ctx.toks[2].c_str()); + + if (0 == rv) { + // Link pin 2 to signal + rv = hal_link(ctx.toks[2].c_str(), ctx.toks[2].c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to link pin '{}' to signal '{}'", ctx.toks[3], ctx.toks[2])); + return rtError; + } + } else { + errornl(ctx, fmt::format("Failed to link pin '{}' to signal '{}'", ctx.toks[2], ctx.toks[2])); + return rtError; + } + } else { + errornl(ctx, fmt::format("Failed to create signal '{}'", ctx.toks[2])); + return rtError; + } + return rtOk; +} +#endif + +static cmdResponseType setNet(connectionRecType &ctx) +{ + // SET NET [pin [..]] + + hal_query_t qs = {}; + qs.name = ctx.toks[2].c_str(); + int havesig = hal_getref_s(&qs); + if(0 != havesig && -ENOENT != havesig) { + errornl(ctx, fmt::format("Failed to retrieve signal info for '{}' error={} ({})", + ctx.toks[2], havesig, hal_strerror(havesig))); + return rtError; + } + + // The type of the signal (to be) + hal_type_t ts = 0 == havesig ? qs.sig.type : HAL_TYPE_UNINITIALIZED; + + for(unsigned i = 3; i < ctx.toks.size(); i++) { + hal_query_t qp = {}; + qp.qtype = HAL_QTYPE_PIN; + qp.name = ctx.toks[i].c_str(); + int rv = hal_getref_p(&qp); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to retrieve pin info for '{}', error={} ({})", + ctx.toks[i], rv, hal_strerror(rv))); + return rtError; + } + if(HAL_TYPE_UNINITIALIZED == ts) { + ts = qp.pp.type; + } else if(ts != qp.pp.type) { + errornl(ctx, fmt::format("Type mismatch {} != {} ({}!={})", + data_type(ts), data_type(qp.pp.type), (int)ts, (int)qp.pp.type)); + return rtError; + } + if(HAL_OUT == qp.pp.dir && (qs.sig.writers > 0 || qs.sig.bidirs > 0)) { + if(qs.sig.writers > 0) + errornl(ctx, fmt::format("Cannot add OUT pin '{}', signal '{}' already has a writer", qp.name, qs.name)); + else + errornl(ctx, fmt::format("Cannot add OUT pin '{}', signal '{}' already has bidirs", qp.name, qs.name)); + return rtError; + } else if(HAL_IO == qp.pp.dir) { + qs.sig.bidirs++; + if(qs.sig.writers > 0) { + errornl(ctx, fmt::format("Cannot add IO pin '{}', signal '{}' already has a writer", qp.name, qs.name)); + return rtError; + } + } + } + + // Create the signal if it does not yet exist + if(-ENOENT == havesig) { + hal_query_t qp = {}; + qp.name = ctx.toks[2].c_str(); + int rv = hal_getref_p(&qp); + if(0 == rv) { + errornl(ctx, fmt::format("Signal name '{}' is already in use as a {} name", + ctx.toks[2], HAL_QTYPE_PIN == qp.qtype ? "pin" : "param")); + return rtError; + } + if(0 != (rv = hal_signal_new(ctx.toks[2].c_str(), ts))) { + errornl(ctx, fmt::format("Failed to create signal '{}', error={}", ctx.toks[2], rv)); + return rtError; + } + } + + // Link up all the pins + for(unsigned i = 3; i < ctx.toks.size(); i++) { + int rv = hal_link(ctx.toks[i].c_str(), ctx.toks[2].c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to add pin '{}' to signal '{}', error={}", ctx.toks[i], ctx.toks[2], rv)); + return rtError; + } + } + return rtOk; +} + +static cmdResponseType setUnlinkP(connectionRecType &ctx) +{ + // SET UNLINK + return linkPS(ctx, ctx.toks[2], ""); +} + +static cmdResponseType setLock(connectionRecType &ctx) +{ + // SET LOCK {all|load|config|params|run|tune|none} + int lck; + if((lck = checkLock(ctx.toks[2].c_str())) < 0) { + errornl(ctx, fmt::format("Invalid lock argument '{}'", ctx.toks[2])); + return rtError; + } + unsigned char old = hal_get_lock(); + int rv; + switch(lck) { + case kwAll: rv = hal_set_lock(HAL_LOCK_ALL); break; + case kwLoad: rv = hal_set_lock(old | HAL_LOCK_LOAD); break; + case kwConfig: rv = hal_set_lock(old | HAL_LOCK_CONFIG); break; + case kwParams: rv = hal_set_lock(old | HAL_LOCK_PARAMS); break; + case kwRun: rv = hal_set_lock(old | HAL_LOCK_RUN); break; + case kwTune: rv = hal_set_lock(HAL_LOCK_TUNE); break; + case kwNone: rv = hal_set_lock(HAL_LOCK_NONE); break; + default: + errornl(ctx, fmt::format("internal: Invalid lock key '{}'", lck)); + return rtError; + } + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType setUnlock(connectionRecType &ctx) +{ + // SET UNLOCK {all|load|config|params|run|tune|none} + int lck; + if((lck = checkLock(ctx.toks[2].c_str())) < 0) { + errornl(ctx, fmt::format("Invalid lock argument '{}'", ctx.toks[2])); + return rtError; + } + unsigned char old = hal_get_lock(); + int rv; + switch(lck) { + case kwAll: rv = hal_set_lock(HAL_LOCK_NONE); break; + case kwLoad: rv = hal_set_lock(old & ~HAL_LOCK_LOAD); break; + case kwConfig: rv = hal_set_lock(old & ~HAL_LOCK_CONFIG); break; + case kwParams: rv = hal_set_lock(old & ~HAL_LOCK_PARAMS); break; + case kwRun: rv = hal_set_lock(old & ~HAL_LOCK_RUN); break; + case kwTune: rv = hal_set_lock(old & ~HAL_LOCK_TUNE); break; + case kwNone: rv = 0; break; + default: + errornl(ctx, fmt::format("internal: Invalid lock key '{}'", lck)); + return rtError; + } + return 0 == rv ? rtOk : rtError; +} + +static hal_type_t haltype_from_str(const std::string &str) +{ + static const struct { + const char *name; + hal_type_t type; + } types[] = { + { "bit", HAL_BOOL }, + { "bool", HAL_BOOL }, + { "float", HAL_REAL }, + { "real", HAL_REAL }, + { "s32", HAL_S32 }, + { "s64", HAL_SINT }, + { "sint", HAL_SINT }, + { "u32", HAL_U32 }, + { "u64", HAL_UINT }, + { "uint", HAL_UINT }, + }; + for(unsigned i = 0; i < NELEM(types); i++) { + if(str == types[i].name) + return types[i].type; + } + return HAL_TYPE_UNSPECIFIED; +} + +static cmdResponseType setNewSig(connectionRecType &ctx) +{ + // SET NEWSIG + hal_type_t type = haltype_from_str(ctx.toks[3]); + if(type <= 0) { + errornl(ctx, fmt::format("Invalid type '{}'", ctx.toks[3])); + return rtError; + } + int rv = hal_signal_new(ctx.toks[2].c_str(), type); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot create signal '{}' with type '{}', error={}", ctx.toks[2], ctx.toks[3], rv)); + return rtError; + } + return rtOk; +} + +static int setDelSig_cb(hal_query_t *q, void *arg) +{ + std::vector *sigs = reinterpret_cast *>(arg); + sigs->push_back(q->name); + return 0; +} + +static cmdResponseType setDelSig(connectionRecType &ctx) +{ + // SET DELSIG + if(ctx.toks[2] == "all") { + std::vector sigs; + hal_query_t q = {}; + int rv = hal_list_s(&q, setDelSig_cb, &sigs); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to gather all signal names, error={}", rv)); + return rtError; + } + bool fail = false; + for(const auto &sig : sigs) { + rv = hal_signal_delete(sig.c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot delete signal '{}', error={}", sig, rv)); + fail = true; + } + } + if(fail) { + return rtError; + } + } else { + int rv = hal_signal_delete(ctx.toks[2].c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot delete signal '{}', error={}", ctx.toks[2], rv)); + return rtError; + } + } + return rtOk; +} + +static cmdResponseType setSetP(connectionRecType &ctx) +{ + // SET SETP + hal_query_t query = {}; + query.name = ctx.toks[2].c_str(); + int rv = hal_set_p(&query, setps_common_cb, ctx.toks[3].data()); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot setp '{}' to '{}', error={}", ctx.toks[2], ctx.toks[3], rv)); + return rtError; + } + return rtOk; +} + +static cmdResponseType setSetS(connectionRecType &ctx) +{ + // SET SETS + hal_query_t query = {}; + query.name = ctx.toks[2].c_str(); + int rv = hal_set_s(&query, setps_common_cb, ctx.toks[3].data()); + if(0 != rv) { + errornl(ctx, fmt::format("Cannot sets '{}' to '{}', error={}", ctx.toks[2], ctx.toks[3], rv)); + return rtError; + } + return rtOk; +} + +static cmdResponseType setAddf(connectionRecType &ctx) +{ + // SET ADDF [arg] + int cl = -1; + if (ctx.toks.size() > 4 && !to_int(ctx.toks[4], cl)) { + errornl(ctx, fmt::format("Invalid argument '{}', must be integer", ctx.toks[4])); + return rtError; + } + if(cl < -1) { + errornl(ctx, fmt::format("Invalid argument '{}', must be >= -1", ctx.toks[4])); + return rtError; + } + int rv = hal_add_funct_to_thread(ctx.toks[2].c_str(), ctx.toks[3].c_str(), cl); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to add fucntion '{}' to thread '{}', error={}", ctx.toks[2], ctx.toks[3], rv)); + return rtError; + } + return rtOk; +} + +static cmdResponseType setDelF(connectionRecType &ctx) +{ + // SET DELF + int rv = hal_del_funct_from_thread(ctx.toks[2].c_str(), ctx.toks[3].c_str()); + if(0 != rv) { + errornl(ctx, fmt::format("Failed to remove function '{}' from thread '{}'", ctx.toks[2], ctx.toks[3])); + return rtError; + } + return rtOk; +} + +static cmdResponseType setSave(connectionRecType &ctx) +{ + // SET SAVE {all,comp,sig,link,linka,net,neta,param,thread} [filename] + static std::set keys = {"all","comp","sig","link","linka","net","neta","param","thread"}; + + if(keys.end() == keys.find(ctx.toks[2])) { + errornl(ctx, fmt::format("Invalid save type '{}'", ctx.toks[2])); + return rtError; + } + std::string out; + if("all" == ctx.toks[2]) { + save_comps(out); + save_signals(out); + save_links(out, 0); + save_params(out); + save_threads(out); + } else if("comp" == ctx.toks[2]) { + save_comps(out); + } else if("sig" == ctx.toks[2]) { + save_signals(out); + } else if("link" == ctx.toks[2]) { + save_links(out, 0); + } else if("linka" == ctx.toks[2]) { + save_links(out, 1); + } else if("net" == ctx.toks[2]) { + save_nets(out, 0); + } else if("neta" == ctx.toks[2]) { + save_nets(out, 1); + } else if("param" == ctx.toks[2]) { + save_params(out); + } else if("thread" == ctx.toks[2]) { + save_threads(out); + } else { + errornl(ctx, fmt::format("internal: failed to match key '{}'", ctx.toks[2])); + return rtError; + } + if(ctx.toks.size() > 3) { + // Filename was specified + int fd = creat(ctx.toks[3].c_str(), 0644); + if(!fd) { + errornl(ctx, fmt::format("Cannot open '{}' for write ({})", ctx.toks[2], strerror(errno))); + return rtError; + } + size_t done = 0; + while(done < out.size()) { + ssize_t err = write(fd, out.c_str() + done, out.size() - done); + int e = errno; + if(err < 0) { + if(EINTR == e) + continue; + close(fd); + errornl(ctx, fmt::format("Write to '{}' failed written={} != size={} errno={} ({})", + ctx.toks[2], done, out.size(), e, strerror(e))); + return rtError; + } + done += err; + } + close(fd); + } else { + replynl(ctx, out); + } + return rtOk; +} + +static cmdResponseType setStart(connectionRecType &ctx) +{ + // SET START + if(REALTIME_TYPE_UNINITIALIZED == hal_get_realtime_type()) { + errornl(ctx, "Realtime has not been initialized."); + return rtError; + } + + int rv = hal_start_threads(); + if (rv != 0) { + errornl(ctx, fmt::format("Failed to start realtime threads, error={}", rv)); + } + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType setStop(connectionRecType &ctx) +{ + // SET STOP + if(REALTIME_TYPE_UNINITIALIZED == hal_get_realtime_type()) { + errornl(ctx, "Realtime has not been initialized."); + return rtError; + } + + int rv = hal_stop_threads(); + if (rv != 0) { + errornl(ctx, fmt::format("Unable to stop realtime threads, error={}", rv)); + } + return 0 == rv ? rtOk : rtError; +} + +static cmdResponseType setTimestamp(connectionRecType &ctx) +{ + // SET TIMESTAMP [ON|OFF] + switch (checkOnOff(ctx.toks[2])) { + default: errornl(ctx, fmt::format("Invalid argument '{}', must be {{on,off}}", ctx.toks[2])); return rtError; + case kwOn: ctx.timestamp = true; break; + case kwOff: ctx.timestamp = false; break; + } + + ctx.timefmt = ctx.toks.size() > 3 && kwOn == checkOnOff(ctx.toks[3]); + return rtOk; +} + +static cmdResponseType setIniFile(connectionRecType &ctx) +{ + // SET INIFILE + IniFile ini(ctx.toks[2]); // Try to open and parse + if(!ini) { + errornl(ctx, fmt::format("Invalid INI-file '{}'", ctx.toks[2])); + return rtError; + } + ctx.inifilename = ctx.toks[2]; + return rtOk; +} + +static cmdResponseType gsNotImpl(connectionRecType &) +{ + return rtError; +} + +static const getsetListType getsetList[] = { + { hcAddF, "ADDF", 0, 2, gsNotImpl, setAddf, alEnable, "", " [order]" }, + { hcComp, "COMP", 1, 0, getComp, gsNotImpl, alEnable, "", "" }, + { hcComps, "COMPS", 0, 0, getComps, gsNotImpl, alEnable, "[pattern]", "" }, + { hcDelF, "DELF", 0, 2, gsNotImpl, setDelF, alEnable, "", " " }, + { hcDelSig, "DELSIG", 0, 1, gsNotImpl, setDelSig, alEnable, "", "" }, + { hcEcho, "ECHO", 0, 1, getEcho, setEcho, alNone, "", "{on|off}" }, + { hcEnable, "ENABLE", 0, 1, getEnable, setEnable, alHello, "", "|{off}" }, + { hcExpand, "EXPAND", 0, 1, getExpand, setExpand, alHello, "", "{on|off}" }, + { hcFunct, "FUNCT", 1, 0, getFunct, gsNotImpl, alEnable, "", "" }, + { hcFuncts, "FUNCTS", 0, 0, getFuncts, gsNotImpl, alEnable, "[pattern]", "" }, + { hcHeader, "HEADER", 0, 1, getHeader, setHeader, alNone, "", "{on|off}" }, + { hcIni, "INI", 2, 0, getIni, gsNotImpl, alHello, "
", "" }, + { hcIniFile, "INIFILE", 0, 1, getIniFile, setIniFile, alHello, "", "" }, +// { hcLinkPP, "LINKPP", 0, 2, gsNotImpl, setLinkPP, alEnable, "", " " }, + { hcLinkPS, "LINKPS", 0, 1, gsNotImpl, setLinkPS, alEnable, "", " []" }, + { hcLinkSP, "LINKSP", 0, 2, gsNotImpl, setLinkSP, alEnable, "", " " }, + { hcLoadRt, "LOADRT", 0, 1, gsNotImpl, setLoadRt, alEnable, "", "" }, + { hcLock, "LOCK", 0, 1, getLock, setLock, alEnable, "", "{all|load|config|params|run|tune|none}" }, + { hcNet, "NET", 1, 2, getNet, setNet, alHello, "", " [pin [...]]" }, + { hcNewSig, "NEWSIG", 0, 2, gsNotImpl, setNewSig, alEnable, "", " " }, + { hcParam, "PARAM", 1, 0, getParam, gsNotImpl, alEnable, "", "" }, + { hcParams, "PARAMS", 0, 0, getParams, gsNotImpl, alEnable, "[pattern]", "" }, + { hcParamVal, "PARAMVAL", 1, 0, getParamVal, gsNotImpl, alEnable, "", "" }, + { hcParamVals, "PARAMVALS", 0, 0, getParamVals, gsNotImpl, alEnable, "[pattern]", "" }, + { hcPin, "PIN", 1, 0, getPin, gsNotImpl, alEnable, "", "" }, + { hcPins, "PINS", 0, 0, getPins, gsNotImpl, alEnable, "[pattern]", "" }, + { hcPinVal, "PINVAL", 1, 0, getPinVal, gsNotImpl, alEnable, "", "" }, + { hcPinVals, "PINVALS", 0, 0, getPinVals, gsNotImpl, alEnable, "[pattern]", "" }, + { hcSave, "SAVE", 0, 1, gsNotImpl, setSave, alEnable, + "", "{all,comp,sig,link,linka,net,neta,param,thread} [filename]" }, + { hcSetP, "SETP", 0, 2, gsNotImpl, setSetP, alEnable, "", " " }, + { hcSetS, "SETS", 0, 2, gsNotImpl, setSetS, alEnable, "", " " }, + { hcSig, "SIGNAL", 1, 0, getSig, gsNotImpl, alEnable, "", "" }, + { hcSigs, "SIGNALS", 0, 0, getSigs, gsNotImpl, alEnable, "[pattern]", "" }, + { hcSigVal, "SIGVAL", 1, 0, getSigVal, gsNotImpl, alEnable, "", "" }, + { hcSigVals, "SIGVALS", 0, 0, getSigVals, gsNotImpl, alEnable, "[pattern]", "" }, + { hcStart, "START", 0, 0, gsNotImpl, setStart, alEnable, "", "" }, + { hcStop, "STOP", 0, 0, gsNotImpl, setStop, alEnable, "", "" }, + { hcThread, "THREAD", 1, 0, getThread, gsNotImpl, alEnable, "", "" }, + { hcThreads, "THREADS", 0, 0, getThreads, gsNotImpl, alEnable, "[pattern]", "" }, + { hcTime, "TIME", 0, 0, getTime, gsNotImpl, alNone, "", "" }, + { hcTimestamp, "TIMESTAMP", 0, 1, getTimestamp, setTimestamp, alNone, "", "{on|off} [{on|off}]" }, + { hcUnlinkP, "UNLINKP", 0, 1, gsNotImpl, setUnlinkP, alEnable, "", "" }, + { hcUnload, "UNLOAD", 0, 1, gsNotImpl, setUnload, alEnable, "", "|" }, + { hcUnlock, "UNLOCK", 0, 1, gsNotImpl, setUnlock, alEnable, "", "{all|load|config|params|run|tune|none}" }, + { hcVerbose, "VERBOSE", 0, 1, getVerbose, setVerbose, alHello, "", "{on|off}" }, +}; + +static int cmpGSList(const void *a, const void *b) +{ + return compareNoCase(static_cast(a)->name, static_cast(b)->name); +} + +int commandGetSet(connectionRecType &ctx, cmdType getset) +{ + const char *sg = getset == cmdSet ? "SET" : "GET"; + if (ctx.toks.size() < 2) { + // Missing missing parameter + errornl(ctx, fmt::format("Must specify subcommand for {}", sg)); + replynl(ctx, fmt::format("{} NAK", sg)); + return -1; + } + + // Find the command in the list + getsetListType v = {}; + v.name = ctx.toks[1].c_str(); + void *_tag = bsearch(&v, getsetList, NELEM(getsetList), sizeof(getsetList[0]), cmpGSList); + const getsetListType *tag = static_cast(_tag); + if (!tag) { + errornl(ctx, fmt::format("Subcommand not found: {} {}", sg, ctx.toks[1])); + replynl(ctx, fmt::format("{} NAK", sg)); + return -1; + } + + if (getset == cmdGet) { + // GET X command + // Check for enough arguments + if (tag->nget + 2 > ctx.toks.size()) { + errornl(ctx, fmt::format("Too few arguments to GET {}, have {}, need {} or more", + tag->name, ctx.toks.size() - 2, tag->nget)); + replynl(ctx, fmt::format("GET {} NAK", tag->name)); + return -1; + } + cmdResponseType res = tag->getter(ctx); + switch (res) { + case rtOk: + if (ctx.verbose) { + replynl(ctx, fmt::format("GET {} ACK", tag->name)); + } + break; + case rtError: // Standard error response + replynl(ctx, fmt::format("GET {} NAK", tag->name)); + break; + default: replynl(ctx, fmt::format("internal: GET {} returned unknown value '{}'", tag->name, (int)res)); break; + } + } else { + // SET X command + // Check for enough arguments + if (tag->nset + 2 > ctx.toks.size()) { + errornl(ctx, fmt::format("Too few arguments to SET {}, have {}, need {} or more", + tag->name, ctx.toks.size() - 2, tag->nset)); + replynl(ctx, fmt::format("GET {} NAK", tag->name)); + return -1; + } + + if (tag->acclvl >= alHello && !ctx.linked) { + errornl(ctx, fmt::format("A HELLO must be successfully negotiated for SET {}", tag->name)); + replynl(ctx, fmt::format("SET {} NAK", tag->name)); + return -1; + } + + if (tag->acclvl >= alEnable && !isEnabled(ctx)) { + errornl(ctx, fmt::format("Connection must be enabled for SET {}", tag->name)); + replynl(ctx, fmt::format("SET {} NAK", tag->name)); + return -1; + } + + cmdResponseType res = tag->setter(ctx); + switch (res) { + case rtOk: + if (ctx.verbose) { + replynl(ctx, fmt::format("SET {} ACK", tag->name)); + } + break; + case rtError: // Standard error response + replynl(ctx, fmt::format("SET {} NAK", tag->name)); + break; + default: + replynl(ctx, fmt::format("internal: SET {} returned unknown value '{}'", tag->name, (int)res)); + break; + } + } + return 0; +} + +static int helpGeneral(connectionRecType &ctx) +{ + replynl(ctx, + "Available commands:\r\n" + " HELLO \r\n" + " GET [parameters...]\r\n" + " SET [parameters...]\r\n" + " SHUTDOWN\r\n" + " HELP \r\n"); + return 0; +} + +static int helpHello(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: HELLO []\r\n" + " Where:\r\n" + " - password: the connection password to allow communications with the server.\r\n" + " - clientname: the name of the client trying to connect.\r\n" + " - protover: the version of the protocol which the client wishes to use.\r\n" + " With valid password, server responds with:\r\n" + " HELLO ACK \r\n" + " Where:\r\n" + " - ACK: acknowledging the connection has been made.\r\n" + " - servername: the name of the LinuxCNC Server to which the client has connected.\r\n" + " - protover: the client requested version or latest version support by server if\r\n" + " the client requests a version later than that supported by the server.\r\n" + " With invalid password, the server responds with:\r\n" + " HELLO NAK\r\n"); + return 0; +} + +static int helpGet(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: GET [parameters...]\r\n" + " All get commands require that a HELLO has been successfully negotiated.\r\n" + " Command may be one of:"); + for (unsigned i = 0; i < NELEM(getsetList); i++) { + const getsetListType *gsl = &getsetList[i]; + if (gsl->getter == gsNotImpl) + continue; + replynl(ctx, fmt::format(" {} {}", gsl->name, gsl->gethelp)); + } + reply(ctx, "\r\n"); + return 0; +} + +static int helpSet(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: SET [parameters...]\r\n" + " All set commands require that a HELLO has been successfully negotiated.\r\n" + " Most set commands require exclusive control over the connection to\r\n" + " LinuxCNC by having successfully executed 'SET ENABLE '.\r\n" + " Set commands not requiring any access level control:"); + for (unsigned i = 0; i < NELEM(getsetList); i++) { + const getsetListType *gsl = &getsetList[i]; + if (gsl->setter == gsNotImpl || gsl->acclvl != alNone) + continue; + replynl(ctx, fmt::format(" {} {}", gsl->name, gsl->sethelp)); + } + reply(ctx, " Set commands requiring HELLO level control:"); + reply(ctx, "\r\n"); + for (unsigned i = 0; i < NELEM(getsetList); i++) { + const getsetListType *gsl = &getsetList[i]; + if (gsl->setter == gsNotImpl || gsl->acclvl != alHello) + continue; + replynl(ctx, fmt::format(" {} {}", gsl->name, gsl->sethelp)); + } + reply(ctx, "\r\n"); + replynl(ctx, " Set commands requiring control enabled:"); + for (unsigned i = 0; i < NELEM(getsetList); i++) { + const getsetListType *gsl = &getsetList[i]; + if (gsl->setter == gsNotImpl || gsl->acclvl != alEnable) + continue; + replynl(ctx, fmt::format(" {} {}", gsl->name, gsl->sethelp)); + } + reply(ctx, "\r\n"); + return 0; +} + +static int helpQuit(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: QUIT\r\n" + " The quit command disconnects the client from the server.\r\n" + " the command has no parameters and no requirements to have negotiated\r\n" + " a hello, or be in control.\r\n"); + return 0; +} + +static int helpShutdown(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: SHUTDOWN\r\n" + " The shutdown command terminates the connections with all clients.\r\n" + " No shutdown of LinuxCNC is performed or attempted. It is not possible\r\n" + " for halrmt to perform any clean shudown procedure.\r\n" + " The command has no parameters, and can only be issued on the connection\r\n" + " that has enable control.\r\n"); + return 0; +} + +static int helpHelp(connectionRecType &ctx) +{ + replynl(ctx, + "Usage: HELP HELP\r\n" + " You need help if you need help on help to help you with help.\r\n" + " It may be time to look into another line of work where computers are\r\n" + " no requirement. Computers will only remind you of the necessary evil\r\n" + " they represent and cause severe helplessness for those requesting help.\r\n"); + return 0; +} + +static int commandHelp(connectionRecType &ctx) +{ + if (ctx.toks.size() < 2) + return helpGeneral(ctx); + std::string s = ctx.toks[1]; + std::transform(s.begin(), s.end(), s.begin(), [](char c) { return std::toupper((unsigned char)c); }); + if (s == "HELLO") return helpHello(ctx); + if (s == "GET") return helpGet(ctx); + if (s == "SET") return helpSet(ctx); + if (s == "QUIT") return helpQuit(ctx); + if (s == "SHUTDOWN") return helpShutdown(ctx); + if (s == "HELP") return helpHelp(ctx); + errornl(ctx, fmt::format("{} is not a valid command. ({})", ctx.toks[1], s)); + return 0; +} + +static int cmpCmdList(const void *a, const void *b) +{ + return compareNoCase(static_cast(a)->name, static_cast(b)->name); +} + +static inline bool isidchar(int ch) +{ + return (::isascii(ch & 0xff) && ::isalnum(ch & 0xff)) || '_' == ch; +} + +static std::string resolveIni(connectionRecType &ctx, const std::string §ion, const std::string &variable) +{ + if(ctx.inifilename.empty()) + return ""; + + IniFile ini(ctx.inifilename); + if(!ini) + return ""; + + if(auto str = ini.findString(variable, section)) + return *str; + return ""; +} + +static void iniExpand(connectionRecType &ctx, std::string &line) +{ + if(!ctx.expand) + return; + std::string newline; + std::string section; + std::string variable; + enum { ST_START, ST_BOPEN, ST_BCLOSE, ST_POPEN, ST_VAR } state = ST_START; + for(const auto &ch : line) { + switch(state) { + default: + case ST_START: + if('[' == ch) { + state = ST_BOPEN; + } else { + newline += ch; + } + break; + case ST_BOPEN: // Seen '[' + if(']' == ch) { + state = ST_BCLOSE; + } else { + if(!isidchar(ch)) { + // Invalid char in section name. + newline += '[' + section + ch; + section.clear(); + state = ST_START; + } else { + section += ch; + } + } + break; + case ST_BCLOSE: // Seen '[section]' + if('(' == ch) { + state = ST_POPEN; + } else { + if(!isidchar(ch)) { + // Invalid char starting variable + newline += '[' + section + ']' + ch; + variable.clear(); + section.clear(); + state = ST_START; + } else { + state = ST_VAR; + variable += ch; + } + } + break; + case ST_VAR: // Seen '[section]x' + if(!isidchar(ch)) { + if(isspace(ch & 0xff)) { + // Have '[section]variable' --> resolve + newline += resolveIni(ctx, section, variable); + } else { + // Invalid termination --> restore + newline += '[' + section + ']' + variable; + } + newline += ch; + section.clear(); + variable.clear(); + state = ST_START; + } else { + variable += ch; + } + break; + case ST_POPEN: // Seen '[section](' + if(!isidchar(ch)) { + if(')' == ch) { + // Have '[section](variable)' --> resolve + newline += resolveIni(ctx, section, variable); + } else { + // Invalid termination --> restore + newline += '[' + section + "](" + variable + ch; + } + section.clear(); + variable.clear(); + state = ST_START; + } else { + variable += ch; + } + break; + } + } + + // We can terminate on end-of-string in any state + // Repair any intermediate + switch(state) { + default: + case ST_START: break; + case ST_BOPEN: newline += '[' + section; break; + case ST_BCLOSE: newline += '[' + section + ']'; break; + case ST_POPEN: newline += '[' + section + "](" + variable; break; + case ST_VAR: newline += resolveIni(ctx, section, variable); break; + } + line = newline; +} + +static int parseCommand(connectionRecType &ctx, std::string &line) +{ + static const char toksep[] = " \t\n\r"; + + size_t pos = 0; + ctx.toks.clear(); // Clear any previous commands/tokens + iniExpand(ctx, line); + while (pos < line.size()) { + // trim left + size_t lft = line.find_first_not_of(toksep, pos); + if (lft == std::string::npos) { + // No non-whitespace characters found to delimit the start + pos = line.size(); // All white-space until end + continue; + } + // Now have: + // arbitrary string with spaces + // ^ + // lft + size_t rgt = line.find_first_of(toksep, lft); + if (rgt == std::string::npos) { + // No whitespace characters found to delimit the end + // The current range [lft,size()) has the token + rgt = line.size(); + } + // Now have: + // arbitrary string with spaces + // ^ ^ + // lft rgt + ctx.toks.push_back(line.substr(lft, rgt - lft)); + pos = rgt; + } + + if (ctx.toks.size() < 1) + return 0; + + // Find the command in the list + commandListType v = {cmdUnknown, 0, ctx.toks[0].c_str()}; + void *_tag = bsearch(&v, commandList, NELEM(commandList), sizeof(commandList[0]), cmpCmdList); + const commandListType *tag = static_cast(_tag); + if (!tag) { + errornl(ctx, fmt::format("Command '{}' not found", ctx.toks[0])); + return 0; + } + + if (ctx.toks.size() < tag->nargs + 1) { + errornl(ctx, fmt::format("Too few arguments for '{}' command", ctx.toks[0])); + return 0; + } + + // Only echo when on, linked and never on HELLO commands + if (ctx.echo && ctx.linked && tag->command != cmdHello) + replynl(ctx, line); + + switch (tag->command) { + case cmdHello: commandHello(ctx); break; + case cmdSet: + case cmdGet: commandGetSet(ctx, tag->command); break; + case cmdQuit: commandQuit(ctx); break; + case cmdHelp: commandHelp(ctx); break; + case cmdShutdown: + if (!commandShutdown(ctx)) { + return -1; + } + break; + default: + replynl(ctx, fmt::format("internal: Invalid command ID '{}' on name='{}'", (int)tag->command, tag->name)); + break; + } + return 0; +} + +/*********************************************************************** +* MAIN PROGRAM * +************************************************************************/ + +static int initSocket() +{ + int optval = 1; + int err; + int sockfd; + struct sockaddr_in6 address = {}; + + sockfd = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (sockfd < 0) { + xperror("socket()"); + return -1; + } + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); + // Using AF_INET6 will also allow IPv4 to connect (v4-mapped-on-v6) + address.sin6_family = AF_INET6; + address.sin6_addr = IN6ADDR_ANY_INIT; + address.sin6_port = htons(port); + err = bind(sockfd, reinterpret_cast(&address), sizeof(address)); + if (err) { + close(sockfd); + xperror("bind()"); + return -1; + } + + err = listen(sockfd, 5); + if (err) { + close(sockfd); + xperror("listen()"); + return -1; + } + + return sockfd; +} + +static void closeClient(connectionRecType &ctx) +{ + if (ctx.sock < 0) + return; + info("Connection terminated '%s' (%d)", ctx.hostname.c_str(), ctx.sock); + close(ctx.sock); + ctx.sock = -1; +} + +static int sockMain(int svrfd) +{ + std::vector rdbuf(1600); // Declare at top, no need to realloc each round in the loop + std::vector pfds(2); + bool shutdown = false; + + while (!quitloop && (clients.size() || !shutdown)) { + // Make sure we have room for clients and server socket + pfds.resize(clients.size() + 1); + + // Setup poll data for all sockets + pfds[0].fd = svrfd; + pfds[0].events = POLLIN; + pfds[0].revents = 0; + int pto = -1; // Default to infinite poll timeout + if (shutdown) + pto = 0; // Immediate return in shutdown mode + + for (size_t i = 0; i < clients.size(); i++) { + // Close connection when about to shutdown and all is flushed. All + // clients should already have halfclosed set and the input buffer + // cleared. + if (!clients[i].outbuf.size() && shutdown) { + closeClient(clients[i]); + // poll will ignore this entry + } + pfds[i + 1].fd = clients[i].sock; + pfds[i + 1].events = POLLPRI | (!clients[i].halfclosed ? POLLIN : 0) | (clients[i].outbuf.size() ? POLLOUT : 0); + pfds[i + 1].revents = 0; + + // If there is still a full line of data in an input buffer then + // make poll return asap. It will still check the descriptors for + // I/O activity. + if (clients[i].inbuf.find_first_of("\r\n") != std::string::npos) + pto = 0; + } + + // Wait until something happens + int err = poll(pfds.data(), pfds.size(), pto); + if (err < 0) { + if (EINTR == errno) { + continue; + } else { + error("poll() returned errno=%d (%s), quiting", errno, strerror(errno)); + return EXIT_FAILURE; + } + } + + // Check server socket first + if (pfds[0].revents & POLLERR) { + // This should never happen...famous...last...words... + error("Server socket received an error on poll, quiting"); + return EXIT_FAILURE; + } else if (pfds[0].revents & POLLIN) { + // POLLIN on a listen socket means new connection available + int cfd; + struct sockaddr_in6 csa; + socklen_t csal = sizeof(csa); + cfd = accept4(svrfd, reinterpret_cast(&csa), &csal, SOCK_CLOEXEC | SOCK_NONBLOCK); + if (cfd < 0) { + switch (errno) { + // The usual errors that should make us retry: + case EAGAIN: + case ECONNABORTED: + break; + // Network related errors should be treated as EAGAIN according + // to accept(2) manual + case ENETDOWN: + case EPROTO: + case ENOPROTOOPT: + case EHOSTDOWN: + case ENONET: + case EHOSTUNREACH: + case EOPNOTSUPP: + case ENETUNREACH: + mysleep(1.0); // Don't busy loop waiting for the net to be up again + break; + // Various restartable errors + case ETIMEDOUT: // Linux kernel thingy, apparently + case ERESTART: // During trace (in accept(2) manual named ERESTARTSYS) + break; + default: + // Any other error will be fatal + xperror("accept()"); + return EXIT_FAILURE; + } + } else { + if (!maxSessions || clients.size() < maxSessions) { + // The accept has set non-blocking and close-on-exec. + // Disable Nagle's algo + int nd = 1; + setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &nd, sizeof(nd)); + connectionRecType cr = {}; + cr.sock = cfd; + cr.hostname = fmt::format("Default-{}", cfd); + cr.version = "1.1"; + cr.echo = true; + cr.inifilename = inifilename; // Inherit global default + clients.push_back(cr); + char addr[INET6_ADDRSTRLEN] = {}; + inet_ntop(AF_INET6, &csa.sin6_addr, addr, sizeof(addr)); + info("New connection from %s:%d", addr, ntohs(csa.sin6_port)); + } else { + close(cfd); + } + } + } + + // Note that we can have one extra client already added but it does not + // have a pfds entry. That happens when we accept a new connection + // above. However, we still need to check all other clients for + // read/write. + for (size_t i = 0; i < clients.size() && i < pfds.size() - 1; i++) { + if (pfds[i + 1].revents & POLLERR) { + // An error on a socket means we make it to close/abort + clients[i].halfclosed = true; + clients[i].inbuf.clear(); + clients[i].outbuf.clear(); + } + + if (pfds[i + 1].revents & POLLPRI) { + ssize_t res = recv(clients[i].sock, rdbuf.data(), rdbuf.size(), MSG_OOB); + if (res < 0) { + if (errno != EINTR && errno != EAGAIN) { + xperror("recv() OOB data"); + } + } else { + info("Received %zd bytes of OOB data (using telnet?), ignoring", res); + } + } + + if (pfds[i + 1].revents & POLLOUT) { + // Writable... + ssize_t res = write(clients[i].sock, clients[i].outbuf.c_str(), clients[i].outbuf.size()); + if (res < 0) { + if (errno != EINTR && errno != EAGAIN) { + xperror("client write()"); + // Make this connection to close/abort + clients[i].halfclosed = true; + clients[i].inbuf.clear(); + clients[i].outbuf.clear(); + } + } else { + clients[i].outbuf.erase(0, res); // Remove written data from buffer + } + } + + if (pfds[i + 1].revents & POLLIN) { + // Readable... + ssize_t len = read(clients[i].sock, rdbuf.data(), rdbuf.size()); + if (len < 0) { + if (errno != EAGAIN && errno != EINTR) { + xperror("client read()"); + // Make this connection to close but still try flush output + clients[i].halfclosed = true; + clients[i].inbuf.clear(); + } + } else if (0 == len) { + // Socket closed + info("Read close '%s' (%d)", clients[i].hostname.c_str(), clients[i].sock); + clients[i].halfclosed = true; + } else { + // Append the read data + clients[i].inbuf.append(rdbuf.data(), len); + } + } + + if (clients[i].halfclosed && !clients[i].inbuf.size() && !clients[i].outbuf.size()) { + // The input is closed and no more data to handle or write. + // Terminate the connection. + closeClient(clients[i]); + } + } + + // Remove fully closed clients + for (auto i = clients.begin(); i != clients.end();) { + if (-1 == i->sock) { + i = clients.erase(i); + } else { + ++i; + } + } + + // Handle input, one line at a time for each client (round robin) + for (auto i = clients.begin(); i != clients.end(); ++i) { + // Split into lines and send to parser + size_t nl = i->inbuf.find_first_of("\r\n"); + if (nl != std::string::npos) { + // Isolate the line and remove from input buffer + std::string line = i->inbuf.substr(0, nl); + // and remove any trailing \r\n too + size_t enl = i->inbuf.find_first_not_of("\r\n", nl); + i->inbuf.erase(0, enl); + if (line.size()) { + // Parse the line if there is something on it + // It returns non-zero when the shutdown has been executed + if (parseCommand(*i, line)) { + // We may still have data in the outbuf that needs to + // be flushed. Any remaining output will still be sent + // and then the client will be fully closed and removed. + shutdown = true; + // Halfclose all clients and zap remaining input. + for (auto c = clients.begin(); c != clients.end(); ++c) { + c->halfclosed = true; + c->inbuf.clear(); + } + } + } + } + // Else: Not a finished line, must wait for rest + } + } + + return 0; +} + +static void usage(void) +{ + static const char usage_str[] = + "Usage: halrmt [options]\n" + "Options:\n" + " -h,--help This help\n" + " -p,--port Listen on port 'num' (default=%d)\n" + " -n,--name Set this server's name to 'str' (default=%s)\n" + " -w,--connectpw Set connect/hello password to 'pwd' (default=%s)\n" + " -e,--enablepw Set enable password to 'pwd' (default=%s)\n" + " -s,--sessions Restrict number of session to 'num' (default=%u) (0 for no limit)\n" + " -i,--ini Use 'file' as inifile (default=env[INI_FILE_NAME])\n" + " -q,--quiet Don't print informational messages\n" + "\n" + "Session commands: Connect and use 'help', 'help get' and 'help set' for details.\n" + ; + printf(usage_str, port, serverName.c_str(), helloPwd.c_str(), enablePwd.c_str(), maxSessions); +} + +static bool check_white(const std::string &s) +{ + for (const char &c : s) { + if (std::iscntrl((unsigned char)c) || std::isspace((unsigned char)c)) + return true; + } + return false; +} + +static struct option longopts[] = { + {"help", 0, NULL, 'h'}, + {"name", 1, NULL, 'n'}, + {"port", 1, NULL, 'p'}, + {"connectpw", 1, NULL, 'w'}, + {"enablepw", 1, NULL, 'e'}, + {"sessions", 1, NULL, 's'}, + {"ini", 1, NULL, 'i'}, + {"quiet", 0, NULL, 'q'}, + {} +}; + +int main(int argc, char **argv) +{ + int optc; + int lose = 0; + char *eptr; + + /* set default level of output - 'quiet' */ + rtapi_set_msg_level(RTAPI_MSG_ERR); + /* set default for other options */ + // process halrmt command line args + while(-1 != (optc = getopt_long(argc, argv, "e:hi:n:p:qs:w:", longopts, NULL))) { + switch(optc) { + case 'h': + usage(); + return EXIT_FAILURE; + + case 'e': + enablePwd = optarg; + if (!compareNoCase(enablePwd, "OFF")) { + error("Invalid enable password. You cannot use 'OFF' as enable password"); + lose++; + } else { + if (check_white(enablePwd)) { + error("You cannot have control or space characters in the enable password"); + lose++; + } + } + break; + case 'i': { + inifilename = optarg; + IniFile ini(inifilename); // Parse file to see it alright (and cache it) + if(!ini) + lose++; + break; } + case 'q': + quiet++; + break; + case 'n': + serverName = optarg; + if (check_white(serverName)) { + error("You cannot have control or space characters in the server name"); + lose++; + } + break; + case 'w': + helloPwd = optarg; + if (check_white(helloPwd)) { + error("You cannot have control or space characters in the password"); + lose++; + } + break; + case 's': + maxSessions = strtoul(optarg, &eptr, 0); + if (eptr == optarg || *eptr) { + error("Invalid maxSessions '%s', must be integer in range [0,...)", optarg); + lose++; + } + break; + case 'p': + port = strtol(optarg, &eptr, 0); + if (eptr == optarg || *eptr || port <= 0 || port >= 65535) { + error("Invalid port '%s', must be integer in range [1,65534]", optarg); + lose++; + } + break; + + default: + lose++; + break; + } + } + + if(inifilename.empty()) { + const char *cptr = getenv("INI_FILE_NAME"); + if(!cptr) { + info("No inifile available"); + } else { + inifilename = cptr; + IniFile ini(inifilename); + if(!ini) + lose++; + } + } + + if(lose) + return EXIT_FAILURE; + + // Initialize the listen socket + int sockfd = initSocket(); + if (sockfd < 0) { + return EXIT_FAILURE; + } + + // Get us access to HAL + int rv = hal_lib_init(); + if(0 != rv) { + close(sockfd); + return EXIT_FAILURE; + } + + // Make sure we quit when requested + signal(SIGINT, quitSig); + signal(SIGQUIT, quitSig); + signal(SIGTERM, quitSig); + signal(SIGHUP, SIG_IGN); + signal(SIGPIPE, SIG_IGN); + + rv = sockMain(sockfd); + + // Disconnect from HAL shared memory + hal_lib_exit(); + + return rv; +} +// vim: ts=4 sw=4 et diff --git a/src/hal/utils/halsh.c b/src/hal/utils/halsh.c index a2ffe3fd39c..e0e4d70591c 100644 --- a/src/hal/utils/halsh.c +++ b/src/hal/utils/halsh.c @@ -81,7 +81,7 @@ static int halCmd(ClientData cd, Tcl_Interp *interp, int argc, const char **argv target_interp = interp; pending_cr = 0; - result = halcmd_parse_cmd((char **)argv+1); + result = halcmd_parse_cmd((const char **)argv+1); target_interp = NULL; if(result == 0) return TCL_OK; diff --git a/src/hal/utils/meter.c b/src/hal/utils/meter.c index 6b677928848..ef0be3b95e9 100644 --- a/src/hal/utils/meter.c +++ b/src/hal/utils/meter.c @@ -59,7 +59,6 @@ #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* private HAL decls */ #include #include @@ -79,9 +78,12 @@ typedef struct { int listnum; /* 0 = pin, 1 = signal, 2 = parameter */ char *pickname; /* name from list, not validated */ - hal_pin_t *pin; /* metadata (if it's a pin) */ - hal_sig_t *sig; /* metadata (if it's a signal) */ - hal_param_t *param; /* metadata (if it's a parameter) */ + hal_query_t qpin; + hal_query_t qsig; + hal_query_t qparam; + hal_query_t *pin; + hal_query_t *param; + hal_query_t *sig; GtkWidget *window; /* selection dialog window */ GtkWidget *notebook; /* pointer to the notebook */ GtkWidget *lists[3]; /* lists for pins, sigs, and params */ @@ -133,7 +135,7 @@ static void popup_probe_window(GtkWidget * widget, gpointer data); static void quit(int sig); static void exit_from_hal(void); static int refresh_value(gpointer data); -static char *data_value(int type, void *valptr); +static const char *data_value(hal_type_t type, hal_refs_u ref); static void create_probe_window(probe_t * probe); static void apply_selection(GtkWidget * widget, gpointer data); @@ -382,16 +384,38 @@ probe_t *probe_new(char *probe_name) return new; } +// for the callback data +typedef struct { + probe_t *probe; + const char *name; + int row; + int tab; + int match_row; + int match_tab; +} rowcolref_t; + +static int rowcol_cb(hal_query_t *q, void *arg) +{ + rowcolref_t *rcr = (rowcolref_t *)arg; + const char *name[2] = {}; + name[0] = q->name; + + add_to_list(rcr->probe->lists[rcr->tab], name, NUM_COLS); + if (!strcmp(q->name, rcr->name)) { + rcr->match_tab = rcr->tab; + rcr->match_row = rcr->row; + } + rcr->row++; + return 0; +} + void popup_probe_window(GtkWidget * widget, gpointer data) { (void)widget; probe_t *probe; - hal_pin_t *pin; - hal_sig_t *sig; - hal_param_t *param; - int next, row, match_row, tab, match_tab; - char *name[HAL_NAME_LEN + 1]; +// int next, row, match_row, tab, match_tab; +// char *name[HAL_NAME_LEN + 1]; /* get a pointer to the probe data structure */ @@ -417,63 +441,33 @@ void popup_probe_window(GtkWidget * widget, gpointer data) clear_list(probe->lists[1]); clear_list(probe->lists[2]); - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - match_tab = 0; - match_row = 0; - row = 0; - tab = 0; - while (next != 0) { - pin = SHMPTR(next); - *name = pin->name; - - add_to_list(probe->lists[tab], name, NUM_COLS); - if (probe->pin == pin) { - match_tab = tab; - match_row = row; - } - next = pin->next_ptr; - row++; - } + rowcolref_t rcr = {}; + rcr.probe = probe; + hal_query_t q = {}; - next = hal_data->sig_list_ptr; - row = 0; - tab = 1; - while (next != 0) { - sig = SHMPTR(next); - *name = sig->name; - - add_to_list(probe->lists[tab], name, NUM_COLS); - if (probe->sig == sig) { - match_tab = tab; - match_row = row; - } - next = sig->next_ptr; - row++; - } + q.qtype = HAL_QTYPE_PIN; + rcr.name = probe->pin->name; + hal_list_p(&q, rowcol_cb, &rcr); - next = hal_data->param_list_ptr; - row = 0; - tab = 2; - while (next != 0) { - param = SHMPTR(next); - *name = param->name; - - add_to_list(probe->lists[tab], name, NUM_COLS); - if (probe->param == param) { - match_tab = tab; - match_row = row; - } - next = param->next_ptr; - row++; - } + memset(&q, 0, sizeof(q)); + q.qtype = HAL_QTYPE_SIGNAL; + rcr.name = probe->sig->name; + rcr.tab = 1; + rcr.row = 0; + hal_list_s(&q, rowcol_cb, &rcr); + + memset(&q, 0, sizeof(q)); + q.qtype = HAL_QTYPE_PARAM; + rcr.name = probe->param->name; + rcr.tab = 2; + rcr.row = 0; + hal_list_p(&q, rowcol_cb, &rcr); - rtapi_mutex_give(&(hal_data->mutex)); gtk_widget_show_all(probe->window); if (probe->pickname != NULL) { - gtk_notebook_set_current_page(GTK_NOTEBOOK(probe->notebook), match_tab); - mark_selected_row(probe->lists[match_tab], match_row); + gtk_notebook_set_current_page(GTK_NOTEBOOK(probe->notebook), rcr.match_tab); + mark_selected_row(probe->lists[rcr.match_tab], rcr.match_row); } } @@ -493,8 +487,7 @@ static int refresh_value(gpointer data) { meter_t *meter; probe_t *probe; - char *value_str, *name_str; - hal_sig_t *sig; + const char *value_str, *name_str; static int first = 1; meter = (meter_t *) data; @@ -507,48 +500,34 @@ static int refresh_value(gpointer data) } } - rtapi_mutex_get(&(hal_data->mutex)); - if (probe->pin != NULL) { - if (probe->pin->name[0] == '\0') { - /* pin has been deleted, can't display it any more */ - probe->pin = NULL; - rtapi_mutex_give(&(hal_data->mutex)); - return 1; - } - name_str = probe->pin->name; - if (probe->pin->signal == 0) { - /* pin is unlinked, get data from dummysig */ - value_str = data_value(probe->pin->type, &(probe->pin->dummysig)); - } else { - /* pin is linked to a signal */ - sig = SHMPTR(probe->pin->signal); - value_str = data_value(probe->pin->type, SHMPTR(sig->data_ptr)); - } - } else if (probe->sig != NULL) { - if (probe->sig->name[0] == '\0') { - /* signal has been deleted, can't display it any more */ - probe->sig = NULL; - rtapi_mutex_give(&(hal_data->mutex)); - return 1; - } - name_str = probe->sig->name; - value_str = - data_value(probe->sig->type, SHMPTR(probe->sig->data_ptr)); - } else if (probe->param != NULL) { - if (probe->param->name[0] == '\0') { - /* parameter has been deleted, can't display it any more */ - probe->param = NULL; - rtapi_mutex_give(&(hal_data->mutex)); - return 1; - } - name_str = probe->param->name; - value_str = - data_value(probe->param->type, SHMPTR(probe->param->data_ptr)); + if(NULL != probe->pin) { + if(0 != hal_getref_p(probe->pin)) { + // Pin no longer exists + probe->pin = NULL; + return 1; + } + name_str = probe->pin->name; + value_str = data_value(probe->pin->pp.type, probe->pin->pp.ref); + } else if(NULL != probe->sig) { + if(0 != hal_getref_s(probe->sig)) { + // Signal no longer exists + probe->sig = NULL; + return 1; + } + name_str = probe->sig->name; + value_str = data_value(probe->sig->sig.type, probe->sig->sig.ref); + } else if(NULL != probe->param) { + if(0 != hal_getref_p(probe->param)) { + // Param no longer exists + probe->param = NULL; + return 1; + } + name_str = probe->param->name; + value_str = data_value(probe->param->pp.type, probe->param->pp.ref); } else { name_str = "-----"; value_str = "---"; } - rtapi_mutex_give(&(hal_data->mutex)); gtk_label_set_text(GTK_LABEL(meter->value_label), value_str); if (!small) { gtk_label_set_text(GTK_LABEL(meter->name_label), name_str); @@ -557,30 +536,37 @@ static int refresh_value(gpointer data) } /* Switch function to return var value for the print_*_list functions */ -static char *data_value(int type, void *valptr) +static const char *data_value(hal_type_t type, hal_refs_u ref) { char *value_str; - static char buf[25]; + static char buf[64]; switch (type) { - case HAL_BIT: - if (*((char *) valptr) == 0) - value_str = "FALSE"; - else - value_str = "TRUE"; - break; - case HAL_FLOAT: - snprintf(buf, 14, "%.7g", (double)*((hal_float_t *) valptr)); + case HAL_BOOL: + return hal_get_bool(ref.b) ? "TRUE" : "FALSE"; + case HAL_REAL: + snprintf(buf, sizeof(buf), "%.7g", (double)hal_get_real(ref.r)); value_str = buf; break; case HAL_S32: - snprintf(buf, 24, "%10ld", (long)*((hal_s32_t *) valptr)); + snprintf(buf, sizeof(buf), "%10ld", (long)hal_get_si32(ref.s)); value_str = buf; break; - case HAL_U32: - snprintf(buf, 24, "%10lu (0x%08lX)", (unsigned long)*((hal_u32_t *) valptr), - *((unsigned long *) valptr)); + case HAL_U32: { + unsigned long v = hal_get_ui32(ref.u); + snprintf(buf, sizeof(buf), "%10lu (0x%08lX)", v, v); value_str = buf; + } + break; + case HAL_SINT: + snprintf(buf, sizeof(buf), "%10lld", (long long)hal_get_sint(ref.s)); + value_str = buf; + break; + case HAL_UINT: { + unsigned long long v = hal_get_uint(ref.u); + snprintf(buf, sizeof(buf), "%10llu (0x%08llX)", v, v); + value_str = buf; + } break; default: /* Shouldn't get here, but just in case... */ @@ -597,7 +583,7 @@ static void create_probe_window(probe_t * probe) GtkWidget *scrolled_window; GtkTreeSelection *selection; - char *tab_label_text[3]; + const char *tab_label_text[3]; int n; /* create window, set size and title */ @@ -677,14 +663,32 @@ static void apply_selection(GtkWidget * widget, gpointer data) return; } if (probe->listnum == 0) { - /* search the pin list */ - probe->pin = halpr_find_pin_by_name(probe->pickname); + /* search the pin list */ + memset(&probe->qpin, 0, sizeof(probe->qpin)); + probe->qpin.name = probe->pickname; + probe->qpin.qtype = HAL_QTYPE_PIN; + if(0 == hal_getref_p(&probe->qpin)) + probe->pin = &probe->qpin; + else + probe->pin = NULL; } else if (probe->listnum == 1) { /* search the signal list */ - probe->sig = halpr_find_sig_by_name(probe->pickname); + memset(&probe->qsig, 0, sizeof(probe->qsig)); + probe->qsig.name = probe->pickname; + probe->qsig.qtype = HAL_QTYPE_SIGNAL; + if(0 == hal_getref_s(&probe->qsig)) + probe->sig = &probe->qsig; + else + probe->sig = NULL; } else if (probe->listnum == 2) { /* search the parameter list */ - probe->param = halpr_find_param_by_name(probe->pickname); + memset(&probe->qparam, 0, sizeof(probe->qparam)); + probe->qparam.name = probe->pickname; + probe->qparam.qtype = HAL_QTYPE_PARAM; + if(0 == hal_getref_p(&probe->qparam)) + probe->param = &probe->qparam; + else + probe->param = NULL; } /* at this point, the probe structure contain a pointer to the item we wish to display, or all three are NULL if the item doesn't exist */ diff --git a/src/hal/utils/miscgtk.c b/src/hal/utils/miscgtk.c index cfd3579b7e3..e6db7111e99 100644 --- a/src/hal/utils/miscgtk.c +++ b/src/hal/utils/miscgtk.c @@ -183,7 +183,7 @@ void gtk_label_size_to_fit(GtkLabel * label, const gchar * str) return; } -void add_to_list(GtkWidget *list, char *strs[], const int num_cols) +void add_to_list(GtkWidget *list, const char *strs[], const int num_cols) { GtkListStore *store; GtkTreeIter iter; @@ -201,7 +201,7 @@ void add_to_list(GtkWidget *list, char *strs[], const int num_cols) } } -void init_list(GtkWidget *list, char *titles[], const int len) +void init_list(GtkWidget *list, const char *titles[], const int len) { GtkCellRenderer *renderer; GtkListStore *store; diff --git a/src/hal/utils/miscgtk.h b/src/hal/utils/miscgtk.h index 153907d0fb3..45d1a2c9635 100644 --- a/src/hal/utils/miscgtk.h +++ b/src/hal/utils/miscgtk.h @@ -90,10 +90,10 @@ void gtk_label_set_text_if(GtkWidget * label, const gchar * text); void gtk_label_size_to_fit(GtkLabel * label, const gchar * str); /* Initialize a TreeView. */ -void init_list(GtkWidget *list, char *titles[], const int num_cols); +void init_list(GtkWidget *list, const char *titles[], const int num_cols); /* Add new row to a TreeView. */ -void add_to_list(GtkWidget *list, char *strs[], const int num); +void add_to_list(GtkWidget *list, const char *strs[], const int num); /* Clears all elements from a TreeView list. */ void clear_list(GtkWidget *list); diff --git a/src/hal/utils/scope.c b/src/hal/utils/scope.c index 720dbe6c102..45327d5ced4 100644 --- a/src/hal/utils/scope.c +++ b/src/hal/utils/scope.c @@ -50,7 +50,6 @@ static char *license = \ #include "config.h" #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* HAL private API decls */ #include #include "miscgtk.h" /* generic GTK stuff */ @@ -200,7 +199,8 @@ int main(int argc, gchar * argv[]) return -1; } - if (!halpr_find_funct_by_name("scope.sample")) { + int rv = hal_comp_by_name("scope.sample", NULL); + if (-ENOENT == rv) { char buf[1000]; snprintf(buf, sizeof(buf), EMC2_BIN_DIR "/halcmd loadrt scope_rt num_samples=%d", num_samples); @@ -211,8 +211,10 @@ int main(int argc, gchar * argv[]) } } else { /* scope_rt already loaded - we'll check if sample count matches later */ - rtapi_print_msg(RTAPI_MSG_DBG, - "SCOPE: scope_rt already loaded, requested %d samples\n", num_samples); + if(0 == rv) + rtapi_print_msg(RTAPI_MSG_DBG, "SCOPE: scope_rt already loaded, requested %d samples\n", num_samples); + else + rtapi_print_msg(RTAPI_MSG_DBG, "SCOPE: hal_comp_by_name() returned error %d\n", rv); } /* set up a shared memory region for the scope data */ shm_id = rtapi_shmem_new(SCOPE_SHM_KEY, comp_id, sizeof(scope_shm_control_t)); @@ -332,9 +334,6 @@ void start_capture(void) { int n; scope_chan_t *chan; - hal_pin_t *pin; - hal_sig_t *sig; - hal_param_t *param; if (ctrl_shm->state != IDLE) { /* already running! */ @@ -372,46 +371,48 @@ void start_capture(void) chan = &(ctrl_usr->chan[n]); /* find address of data in shared memory */ if ( chan->data_source_type == 0 ) { - /* channel source is a pin, point at it */ - pin = SHMPTR(chan->data_source); + /* channel source is a pin */ /* make sure it's still valid */ - if ( pin->name[0] == '\0' ) { - /* pin has been deleted */ - chan->data_source_type = -1; - chan->data_len = 0; - break; - } - /* point at pin data */ - if (pin->signal == 0) { - /* pin is unlinked, get data from dummysig */ - ctrl_shm->data_offset[n] = SHMOFF(&(pin->dummysig)); - } else { - /* pin is linked to a signal */ - sig = SHMPTR(pin->signal); - ctrl_shm->data_offset[n] = sig->data_ptr; - } + hal_query_t q = {}; + q.name = chan->name; + q.qtype = HAL_QTYPE_PIN; + if(0 == hal_getref_p(&q)) { + /* point at pin data */ + ctrl_shm->data_offset[n] = hal_reference_unmap(q.pp.ref.u); + } else { + /* pin no longer available */ + chan->data_source_type = -1; + chan->data_len = 0; + break; + } } else if ( chan->data_source_type == 1 ) { - /* channel source is a signal, point at it */ - sig = SHMPTR(chan->data_source); + /* channel source is a signal */ /* make sure it's still valid */ - if ( sig->name[0] == '\0' ) { - /* signal has been deleted */ + hal_query_t q = {}; + q.name = chan->name; + if(0 == hal_getref_s(&q)) { + ctrl_shm->data_offset[n] = hal_reference_unmap(q.sig.ref.u); + } else { + /* signal no longer available */ chan->data_source_type = -1; chan->data_len = 0; break; } - ctrl_shm->data_offset[n] = sig->data_ptr; } else if ( chan->data_source_type == 2 ) { - /* channel source is a parameter, point at it */ - param = SHMPTR(chan->data_source); + /* channel source is a parameter */ /* make sure it's still valid */ - if ( param->name[0] == '\0' ) { - /* param has been deleted */ - chan->data_source_type = -1; - chan->data_len = 0; - break; - } - ctrl_shm->data_offset[n] = param->data_ptr; + hal_query_t q = {}; + q.name = chan->name; + q.qtype = HAL_QTYPE_PARAM; + if(0 == hal_getref_p(&q)) { + /* point at param data */ + ctrl_shm->data_offset[n] = hal_reference_unmap(q.pp.ref.u); + } else { + /* param no longer available */ + chan->data_source_type = -1; + chan->data_len = 0; + break; + } } else { /* channel source is invalid */ chan->data_len = 0; @@ -510,8 +511,8 @@ static void init_usr_control_struct(void *shmem) /* save pointer to shared control structure */ ctrl_shm = shmem; - /* round size of shared struct up to a multiple of 4 for alignment */ - skip = (sizeof(scope_shm_control_t) + 3) & ~3; + /* round size of shared struct up to a multiple of 8 for alignment */ + skip = (sizeof(scope_shm_control_t) + 7) & ~7; /* the rest of the shared memory area is the data buffer */ ctrl_usr->buffer = (scope_data_t *) (((char *) (shmem)) + skip); /* is the realtime component loaded already? */ diff --git a/src/hal/utils/scope_disp.c b/src/hal/utils/scope_disp.c index a5fe9b9af4a..75b79d36f0d 100644 --- a/src/hal/utils/scope_disp.c +++ b/src/hal/utils/scope_disp.c @@ -42,7 +42,6 @@ #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* private HAL decls */ #include #include "miscgtk.h" /* generic GTK stuff */ @@ -155,21 +154,27 @@ static void calculate_offset(int chan_num) { for(n=0; n < ctrl_usr->samples; n++) { switch (type) { - case HAL_BIT: - if (dptr->d_u8) { + case HAL_BOOL: + if (dptr->b) { value = 1.0; } else { value = 0.0; }; break; - case HAL_FLOAT: - value = dptr->d_real; + case HAL_REAL: + value = dptr->r; break; case HAL_S32: - value = dptr->d_s32; + value = dptr->s; break; case HAL_U32: - value = dptr->d_u32; + value = dptr->u; + break; + case HAL_SINT: + value = dptr->s; + break; + case HAL_UINT: + value = dptr->u; break; default: value = 0.0; @@ -719,7 +724,7 @@ void draw_triggerline(int chan_num, int highlight) { if(dx < 5) dx = 5; if(dy < dx + 1) dy = dx + 1; - if(chan->data_type == HAL_BIT) + if(chan->data_type == HAL_BOOL) y1 = ypoffset; if(ctrl_shm->trig_edge) dy = -dy; @@ -814,21 +819,27 @@ void draw_waveform(int chan_num, int highlight) x2 = (n * xscale) - xoffset; /* calc y coordinate of this point */ switch (type) { - case HAL_BIT: - if (dptr->d_u8) { + case HAL_BOOL: + if (dptr->b) { fy = 1.0; } else { fy = 0.0; }; break; - case HAL_FLOAT: - fy = dptr->d_real; + case HAL_REAL: + fy = dptr->r; break; case HAL_S32: - fy = dptr->d_s32; + fy = dptr->s; break; case HAL_U32: - fy = dptr->d_u32; + fy = dptr->u; + break; + case HAL_SINT: + fy = dptr->s; + break; + case HAL_UINT: + fy = dptr->u; break; default: fy = 0.0; diff --git a/src/hal/utils/scope_files.c b/src/hal/utils/scope_files.c index a4f191259ff..618496fdfb7 100644 --- a/src/hal/utils/scope_files.c +++ b/src/hal/utils/scope_files.c @@ -43,7 +43,6 @@ #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* HAL private API decls */ #include #include "miscgtk.h" /* generic GTK stuff */ @@ -254,7 +253,7 @@ void write_log_file(char *filename) scope_vert_t *vert; hal_type_t type[16]; - char *label[16] = {}; + const char *label[16] = {}; char *old_locale, *saved_locale; int sample_len, chan_active, chan_num, sample_period_ns, samples, n; FILE *fp; @@ -569,30 +568,35 @@ void read_log_file(char *filename) int matched = 0; /* Try to find matching HAL pin */ - hal_pin_t *pin = halpr_find_pin_by_name(channel_names[i]); - if (pin != NULL) { + hal_query_t qp = {}; + qp.name = channel_names[i]; + qp.qtype = HAL_QTYPE_PIN; + if (0 == hal_getref_p(&qp)) { chan->data_source_type = 0; - chan->data_source = SHMOFF(pin); - chan->data_type = pin->type; - chan->name = pin->name; + chan->data_source = qp.pp.ref; + chan->data_type = qp.pp.type; + chan->name = qp.name; matched = 1; } else { /* Try to find matching HAL signal */ - hal_sig_t *sig = halpr_find_sig_by_name(channel_names[i]); - if (sig != NULL) { + hal_query_t qs = {}; + qs.name = channel_names[i]; + if (0 == hal_getref_s(&qs)) { chan->data_source_type = 1; - chan->data_source = SHMOFF(sig); - chan->data_type = sig->type; - chan->name = sig->name; + chan->data_source = qs.sig.ref; + chan->data_type = qs.sig.type; + chan->name = qs.name; matched = 1; } else { /* Try to find matching HAL parameter */ - hal_param_t *param = halpr_find_param_by_name(channel_names[i]); - if (param != NULL) { - chan->data_source_type = 2; - chan->data_source = SHMOFF(param); - chan->data_type = param->type; - chan->name = param->name; + hal_query_t qa = {}; + qa.name = channel_names[i]; + qa.qtype = HAL_QTYPE_PARAM; + if (0 == hal_getref_p(&qa)) { + chan->data_source_type = 0; + chan->data_source = qa.pp.ref; + chan->data_type = qa.pp.type; + chan->name = qa.name; matched = 1; } } @@ -606,8 +610,8 @@ void read_log_file(char *filename) "[CSV] %s", channel_names[i]); chan->data_source_type = -1; /* No source */ - chan->data_source = 0; - chan->data_type = HAL_FLOAT; /* Default to float for CSV data */ + memset(&chan->data_source, 0, sizeof(chan->data_source)); + chan->data_type = HAL_REAL; /* Default to float for CSV data */ chan->name = phantom_name; chan->is_phantom = 1; } @@ -615,23 +619,25 @@ void read_log_file(char *filename) /* Set up channel data length and scale limits based on type */ switch (chan->data_type) { - case HAL_BIT: - chan->data_len = sizeof(hal_bit_t); + case HAL_BOOL: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 2; break; - case HAL_FLOAT: - chan->data_len = sizeof(hal_float_t); + case HAL_REAL: + chan->data_len = sizeof(scope_data_t); chan->min_index = -36; chan->max_index = 36; break; case HAL_S32: - chan->data_len = sizeof(hal_s32_t); + case HAL_SINT: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 30; break; case HAL_U32: - chan->data_len = sizeof(hal_u32_t); + case HAL_UINT: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 30; break; @@ -742,17 +748,23 @@ void read_log_file(char *filename) /* Convert to appropriate type */ switch (channel_types[i]) { - case HAL_BIT: - dptr->d_u8 = (value != 0.0) ? 1 : 0; + case HAL_BOOL: + dptr->b = (value != 0.0) ? 1 : 0; break; - case HAL_FLOAT: - dptr->d_real = (real_t)value; + case HAL_REAL: + dptr->r = (rtapi_real)value; break; case HAL_S32: - dptr->d_s32 = (rtapi_s32)value; + dptr->s = (rtapi_s32)value; break; case HAL_U32: - dptr->d_u32 = (rtapi_u32)value; + dptr->u = (rtapi_u32)value; + break; + case HAL_SINT: + dptr->s = (rtapi_sint)value; + break; + case HAL_UINT: + dptr->u = (rtapi_uint)value; break; default: break; @@ -829,21 +841,27 @@ static void write_sample(FILE *fp, scope_data_t *dptr, hal_type_t type) { double data_value; switch (type) { - case HAL_BIT: - if (dptr->d_u8) { + case HAL_BOOL: + if (dptr->b) { data_value = 1.0; } else { data_value = 0.0; }; break; - case HAL_FLOAT: - data_value = dptr->d_real; + case HAL_REAL: + data_value = dptr->r; break; case HAL_S32: - data_value = dptr->d_s32; + data_value = dptr->s; break; case HAL_U32: - data_value = dptr->d_u32; + data_value = dptr->u; + break; + case HAL_SINT: + data_value = dptr->s; + break; + case HAL_UINT: + data_value = dptr->u; break; default: data_value = 0.0; diff --git a/src/hal/utils/scope_horiz.c b/src/hal/utils/scope_horiz.c index 5d1c7dc382f..dc5a92bfd1e 100644 --- a/src/hal/utils/scope_horiz.c +++ b/src/hal/utils/scope_horiz.c @@ -47,7 +47,6 @@ #include /* RTAPI realtime OS API */ #include #include /* HAL public API decls */ -#include "../hal_priv.h" /* private HAL decls */ #include #include "miscgtk.h" /* generic GTK stuff */ @@ -215,71 +214,68 @@ static void init_horiz_window(void) gtk_label_size_to_fit(GTK_LABEL(horiz->state_label), " TRIGGERED "); } +static int find_funct_cb(hal_query_t *q, void *arg) +{ + if(!strcmp((const char *)arg, q->name)) { + // The name will stick to q->name when we return from hal_list_funct() + return 1; // Positive, break the loop without error + } + return 0; +} + +static int find_threadfunct_cb(hal_query_t *q, void *arg) +{ + if(q->qtype == HAL_QTYPE_THREAD_FUNCT && !strcmp((const char *)arg, q->name)) { + // The name will stick to q->name when we return from hal_list_funct() + return 1; // Positive, break the loop without error + } + return 0; +} + static void init_acquire_function(void) { - hal_funct_t *funct; - int next_thread; - hal_thread_t *thread; - hal_list_t *list_root, *list_entry; - hal_funct_entry_t *fentry; scope_horiz_t *horiz; horiz = &(ctrl_usr->horiz); /* set watchdog to trip immediately once heartbeat funct is called */ ctrl_shm->watchdog = 10; /* is the realtime function present? */ - funct = halpr_find_funct_by_name("scope.sample"); - if (funct == NULL) { + hal_query_t q = {}; + int rv = hal_list_funct(&q, find_funct_cb, (void *)"scope.sample"); + if (rv <= 0) { /* realtime function not present - watchdog timeout will open a dialog asking the user to insmod the module */ return; } - if (funct->users == 0) { + if (q.funct.users == 0) { /* function not in use - watchdog timeout will open a dialog asking the user to select a thread */ return; } /* function is in use, find out which thread it is linked to */ - rtapi_mutex_get(&(hal_data->mutex)); - next_thread = hal_data->thread_list_ptr; - while (next_thread != 0) { - thread = SHMPTR(next_thread); - list_root = &(thread->funct_list); - list_entry = list_next(list_root); - while (list_entry != list_root) { - fentry = (hal_funct_entry_t *) list_entry; - if (funct == SHMPTR(fentry->funct_ptr)) { - /* found a match, update structure members */ - horiz->thread_name = thread->name; - horiz->thread_period_ns = thread->period; - /* done with hal data */ - rtapi_mutex_give(&(hal_data->mutex)); - /* reset watchdog to give RT code some time */ - ctrl_shm->watchdog = 1; - return; - } - list_entry = list_next(list_entry); - } - next_thread = thread->next_ptr; + hal_query_t qt = {}; + qt.qtype = HAL_QTYPE_THREAD_FUNCT; + if(hal_list_thread(&qt, find_threadfunct_cb, (void *)q.name) > 0) { + /* found a match, update structure members */ + horiz->thread_name = qt.name; + horiz->thread_period_ns = qt.thread.period; + /* reset watchdog to give RT code some time */ + ctrl_shm->watchdog = 1; } - /* didn't find a linked thread - should never get here, but... */ - rtapi_mutex_give(&(hal_data->mutex)); - return; } void handle_watchdog_timeout(void) { - hal_funct_t *funct; - /* stop sampling */ ctrl_shm->state = IDLE; ctrl_shm->samples = 0; /* does realtime function exist? */ - funct = halpr_find_funct_by_name("scope.sample"); - if (funct == NULL) { + hal_query_t q = {}; + int rv = hal_list_funct(&q, find_funct_cb, (void *)"scope.sample"); + if (rv <= 0) { /* function is not loaded */ dialog_realtime_not_loaded(); - } else if (funct->users == 0) { + } else if (q.funct.users == 0) { /* function is loaded, but not in a thread */ dialog_realtime_not_linked(); } else if (ctrl_shm->watchdog != 0) { @@ -485,15 +481,43 @@ static void dialog_realtime_not_loaded(void) } } +typedef struct { + scope_horiz_t *horiz; + int n; + int sel_row; +} listthreadcb_t; + +static int list_thread_cb(hal_query_t *q, void *arg) +{ + listthreadcb_t *ltc = (listthreadcb_t *)arg; + + if (q->thread.period <= 1000000000) { + const char *strs[2]; + char buf[BUFLEN + 1]; + /* period is less than 1 sec, add to list */ + double period = q->thread.period / 1000000000.0; + /* create a string for display */ + format_time_value(buf, BUFLEN, period); + strs[1] = buf; + /* get thread name */ + strs[0] = q->name; + /* add to list */ + add_to_list(ltc->horiz->thread_list, strs, NUM_COLS); + if ((ltc->horiz->thread_name != NULL) && (strcmp(ltc->horiz->thread_name, q->name) == 0)) { + /* found the current thread, remember it's row number */ + ltc->sel_row = ltc->n; + /* and make sure thread_period is correct */ + ltc->horiz->thread_period_ns = q->thread.period; + } + } + ltc->n++; + return 0; +} static void dialog_realtime_not_linked(void) { scope_horiz_t *horiz; - int next, sel_row, n; int retval; - double period; - hal_thread_t *thread; - char *strs[2]; char buf[BUFLEN + 1]; GtkWidget *hbox, *label; GtkWidget *content_area; @@ -501,7 +525,7 @@ static void dialog_realtime_not_linked(void) GtkWidget *scrolled_window; GtkTreeSelection *selection; - char *titles[NUM_COLS]; + const char *titles[NUM_COLS]; const char *title, *msg; horiz = &(ctrl_usr->horiz); @@ -589,37 +613,11 @@ static void dialog_realtime_not_linked(void) g_signal_connect(selection, "changed", G_CALLBACK(acquire_selection_made), horiz); - /* get mutex before traversing list */ - rtapi_mutex_get(&(hal_data->mutex)); - n = 0; - sel_row = -1; - next = hal_data->thread_list_ptr; - while (next != 0) { - thread = SHMPTR(next); - /* check thread period */ - if (thread->period <= 1000000000) { - /* period is less than 1 sec, add to list */ - period = thread->period / 1000000000.0; - /* create a string for display */ - format_time_value(buf, BUFLEN, period); - strs[1] = buf; - /* get thread name */ - strs[0] = thread->name; - /* add to list */ - add_to_list(horiz->thread_list, strs, NUM_COLS); - if ((horiz->thread_name != NULL) - && (strcmp(horiz->thread_name, thread->name) == 0)) { - /* found the current thread, remember it's row number */ - sel_row = n; - /* and make sure thread_period is correct */ - horiz->thread_period_ns = thread->period; - } - } - n++; - next = thread->next_ptr; - } - - rtapi_mutex_give(&(hal_data->mutex)); + /* traverse the thread list */ + listthreadcb_t ltc = { .horiz = horiz, .n = 0, .sel_row = -1 }; + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD; + hal_list_thread(&q, list_thread_cb, (void *)<c); /* set up the the layout for the multiplier spinbutton */ hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5); @@ -670,9 +668,9 @@ static void dialog_realtime_not_linked(void) ctrl_shm->rec_len = ctrl_shm->buf_len / 16; /* was a thread previously used? */ - if (sel_row > -1) { + if (ltc.sel_row > -1) { /* yes, preselect appropriate line */ - mark_selected_row(horiz->thread_list, sel_row); + mark_selected_row(horiz->thread_list, ltc.sel_row); } gtk_widget_show_all(dialog); @@ -845,24 +843,33 @@ static void acquire_selection_made(GtkWidget *widget, gpointer data) } } +static int find_thread_cb(hal_query_t *q, void *arg) +{ + if(!strcmp((const char *)arg, q->name)) { + // q->name will retain the name + return 1; // Break the loop but no error + } + return 0; +} + static int set_sample_thread_name(char *name) { scope_horiz_t *horiz; - hal_thread_t *thread; long max_mult; /* get a pointer to the horiz data structure */ horiz = &(ctrl_usr->horiz); /* look for a new thread that matches name*/ - thread = halpr_find_thread_by_name(name); - if (thread == NULL) { + hal_query_t q = {}; + q.qtype = HAL_QTYPE_THREAD; + if(hal_list_thread(&q, find_thread_cb, (void *)name) <= 0) { return -1; } /* shut down any prior thread */ deactivate_sample_thread(); /* save info about the thread */ - horiz->thread_name = thread->name; - horiz->thread_period_ns = thread->period; + horiz->thread_name = q.name; + horiz->thread_period_ns = q.thread.period; /* calc max possible mult (to keep sample period <= 1 sec */ max_mult = (1000000000 / horiz->thread_period_ns); if (max_mult > 1000) { @@ -1011,7 +1018,7 @@ static void calc_horiz_scaling(void) static void refresh_horiz_info(void) { scope_horiz_t *horiz; - gchar *name; + const gchar *name; static gchar tmp[BUFLEN + 1], rate[BUFLEN + 1], period[BUFLEN + 1]; static gchar scale[BUFLEN + 1], rec_len[BUFLEN + 1], msg[BUFLEN + 1]; double freqval; diff --git a/src/hal/utils/scope_rt.c b/src/hal/utils/scope_rt.c index bb683cb8254..cb3aca04b17 100644 --- a/src/hal/utils/scope_rt.c +++ b/src/hal/utils/scope_rt.c @@ -35,7 +35,6 @@ #include /* RTAPI realtime OS API */ #include /* RTAPI realtime module decls */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* HAL private API decls */ #include "scope_rt.h" /* scope related declarations */ #include @@ -103,7 +102,7 @@ int rtapi_app_main(void) num_samples = SCOPE_NUM_SAMPLES_MAX; } /* connect to scope shared memory block */ - skip = (sizeof(scope_shm_control_t) + 3) & ~3; + skip = (sizeof(scope_shm_control_t) + 7) & ~7; shm_size = skip + num_samples * sizeof(scope_data_t); shm_id = rtapi_shmem_new(SCOPE_SHM_KEY, comp_id, shm_size); if (shm_id < 0) { @@ -193,7 +192,7 @@ static void sample(void *arg, long period) ctrl_rt->auto_timer = 0; /* get info about channels */ for (n = 0; n < 16; n++) { - ctrl_rt->data_addr[n] = SHMPTR(ctrl_shm->data_offset[n]); + ctrl_rt->data_addr[n] = (hal_refs_u)(hal_uint_t)hal_reference_map(ctrl_shm->data_offset[n]); ctrl_rt->data_type[n] = ctrl_shm->data_type[n]; ctrl_rt->data_len[n] = ctrl_shm->data_len[n]; } @@ -263,30 +262,17 @@ static void capture_sample(void) dest = &(ctrl_rt->buffer[ctrl_shm->curr]); /* loop through all channels to acquire data */ for (n = 0; n < 16; n++) { - /* capture 1, 2, or 4 bytes, based on data size */ - switch (ctrl_rt->data_len[n]) { - case 1: - dest->d_u8 = *((unsigned char *) (ctrl_rt->data_addr[n])); - dest++; - break; - case 4: - dest->d_u32 = *((unsigned long *) (ctrl_rt->data_addr[n])); - dest++; - break; - case 8: - { - ireal_t sample_a, sample_b; - do { - sample_a = *((volatile ireal_t *) (ctrl_rt->data_addr[n])); - sample_b = *((volatile ireal_t *) (ctrl_rt->data_addr[n])); - } while( sample_a != sample_b ); - dest->d_ireal = sample_a; - dest++; - } - break; - default: - break; - } + if(0 == ctrl_rt->data_len[n]) // Unused channel + continue; + switch(ctrl_rt->data_type[n]) { + case HAL_BOOL: dest->b = hal_get_bool(ctrl_rt->data_addr[n].b); dest++; break; + case HAL_S32: dest->s = hal_get_si32(ctrl_rt->data_addr[n].s); dest++; break; + case HAL_U32: dest->u = hal_get_ui32(ctrl_rt->data_addr[n].u); dest++; break; + case HAL_SINT: dest->s = hal_get_sint(ctrl_rt->data_addr[n].s); dest++; break; + case HAL_UINT: dest->u = hal_get_uint(ctrl_rt->data_addr[n].u); dest++; break; + case HAL_REAL: dest->r = hal_get_real(ctrl_rt->data_addr[n].r); dest++; break; + default: break; + } } /* increment sample pointer */ ctrl_shm->curr += ctrl_shm->sample_len; @@ -297,13 +283,11 @@ static void capture_sample(void) } } -// TODO: type-independent way to get high bit -// #define SIGN_BIT (~(((ireal_t)~(ireal_t)0)>>1)) static int check_trigger(void) { static int compare_result = 0; int prev_compare_result; - scope_data_t *value, *level; + scope_data_t *level; /* has user forced trigger? */ if (ctrl_shm->force_trig != 0) { @@ -323,66 +307,33 @@ static int check_trigger(void) if (ctrl_shm->trig_chan == 0) { return 0; } - /* point a scope_data_t union at the signal value */ - value = ctrl_rt->data_addr[ctrl_shm->trig_chan - 1]; /* and at the trigger level */ level = &(ctrl_shm->trig_level); /* save previous compare result */ prev_compare_result = compare_result; /* compare actual value to trigger level */ switch (ctrl_rt->data_type[ctrl_shm->trig_chan - 1]) { - case HAL_BIT: - /* for bits, we don't even look at the trigger level */ - compare_result = value->d_u8; - break; - case HAL_FLOAT: - { - ireal_t tmp1, tmp2; - /* don't want to use the FPU in this function, so we use */ - /* a hack - see http://en.wikipedia.org/wiki/IEEE_754 */ - /* this _only_ works with IEEE-754 floating point numbers */ - /* and will probably fail for infinities, NANs, etc. */ - /* OK, here we go! */ - /* get the value as an integer */ - tmp1 = value->d_ireal; - /* get the trigger as an integer */ - tmp2 = level->d_ireal; - /* is the value negative? (highest bit) */ - if (tmp1 & 0x8000000000000000ull) { - /* yes, is the trigger level negative? */ - if (tmp2 & 0x8000000000000000ull) { - /* yes, make both positive */ - tmp1 ^= 0x8000000000000000ull; - tmp2 ^= 0x8000000000000000ull; - /* and compare them as unsigned ints */ - /* because of negation, we reverse the compare */ - compare_result = (tmp1 < tmp2); - } else { - /* trigger level positive, value negative */ - compare_result = 0; - } - } else { - /* value is positive, is trigger level negative? */ - if (tmp2 & 0x8000000000000000ull) { - /* trigger level negative, value positive */ - compare_result = 1; - } else { - /* both are positive */ - /* compare them as unsigned ints */ - compare_result = (tmp1 > tmp2); - } - } - } - break; + case HAL_BOOL: + compare_result = hal_get_bool(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].b); + break; case HAL_S32: - compare_result = (value->d_s32 > level->d_s32); - break; + compare_result = hal_get_si32(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].s) > level->s; + break; + case HAL_SINT: + compare_result = hal_get_sint(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].s) > level->s; + break; case HAL_U32: - compare_result = (value->d_u32 > level->d_u32); - break; + compare_result = hal_get_ui32(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].u) > level->u; + break; + case HAL_UINT: + compare_result = hal_get_uint(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].u) > level->u; + break; + case HAL_REAL: + compare_result = hal_get_real(ctrl_rt->data_addr[ctrl_shm->trig_chan - 1].r) > level->r; + break; default: - compare_result = 0; - break; + compare_result = 0; + break; } /* test for rising edge */ if (ctrl_shm->trig_edge && compare_result && !prev_compare_result) { @@ -411,8 +362,8 @@ static void init_rt_control_struct(void *shmem) } /* save pointer to shared control structure */ ctrl_shm = shmem; - /* round size of shared struct up to a multiple of 4 for alignment */ - skip = (sizeof(scope_shm_control_t) + 3) & ~3; + /* round size of shared struct up to a multiple of 8 for alignment */ + skip = (sizeof(scope_shm_control_t) + 7) & ~7; /* the rest of the shared memory area is the data buffer */ ctrl_rt->buffer = (scope_data_t *) (((char *) (shmem)) + skip); init_shm_control_struct(); @@ -431,9 +382,9 @@ static void init_shm_control_struct(void) for (n = 0; n < (int)sizeof(scope_shm_control_t); n++) { cp[n] = 0; } - /* round size of shared struct up to a multiple of 4 for alignment */ + /* round size of shared struct up to a multiple of 8 for alignment */ ctrl_shm->shm_size = shm_size; - skip = (sizeof(scope_shm_control_t) + 3) & ~3; + skip = (sizeof(scope_shm_control_t) + 7) & ~7; /* remainder of shmem area is buffer */ ctrl_shm->buf_len = (shm_size - skip) / sizeof(scope_data_t); /* init any non-zero fields */ diff --git a/src/hal/utils/scope_rt.h b/src/hal/utils/scope_rt.h index 0ab80599521..75606f6d10c 100644 --- a/src/hal/utils/scope_rt.h +++ b/src/hal/utils/scope_rt.h @@ -50,7 +50,7 @@ typedef struct { int mult_cntr; /* used to divide by 'mult' */ int auto_timer; /* delay timer for auto triggering */ char data_len[16]; /* data size for each channel */ - void *data_addr[16]; /* pointers to data for each channel */ + hal_refs_u data_addr[16]; /* pointers to data for each channel */ hal_type_t data_type[16]; /* data type for each channel */ } scope_rt_control_t; diff --git a/src/hal/utils/scope_shm.h b/src/hal/utils/scope_shm.h index 34dbb76be65..b0f6457f039 100644 --- a/src/hal/utils/scope_shm.h +++ b/src/hal/utils/scope_shm.h @@ -59,11 +59,10 @@ typedef enum { /* this struct holds a single value - one sample of one channel */ typedef union { - unsigned char d_u8; /* variable for bit */ - rtapi_u32 d_u32; /* variable for u32 */ - rtapi_s32 d_s32; /* variable for s32 */ - real_t d_real; /* variable for float */ - ireal_t d_ireal; /* intlike variable for float */ + rtapi_bool b; + rtapi_uint u; + rtapi_sint s; + rtapi_real r; } scope_data_t; /** This struct holds control data needed by both realtime and GUI code. @@ -90,7 +89,7 @@ typedef struct { int curr; /* R next sample to be acquired */ int samples; /* R number of valid samples */ scope_state_t state; /* RU current state */ - int data_offset[16]; /* U data addr in shmem for each channel */ + rtapi_intptr_t data_offset[16]; /* U data addr in shmem for each channel */ hal_type_t data_type[16]; /* U data type for each channel */ char data_len[16]; /* U data size, 0 if not to be acquired */ } scope_shm_control_t; diff --git a/src/hal/utils/scope_trig.c b/src/hal/utils/scope_trig.c index ddf6a168e3d..f9e47b2465f 100644 --- a/src/hal/utils/scope_trig.c +++ b/src/hal/utils/scope_trig.c @@ -45,7 +45,6 @@ #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -#include "../hal_priv.h" /* private HAL decls */ #include #include "miscgtk.h" /* generic GTK stuff */ @@ -136,8 +135,8 @@ void refresh_trigger(void) chan->vert_offset; /* apply type specific tweaks to trigger level */ switch (chan->data_type) { - case HAL_FLOAT: - ctrl_shm->trig_level.d_real = fp_level; + case HAL_REAL: + ctrl_shm->trig_level.r = fp_level; break; case HAL_S32: if (fp_level > 2147483647.0) { @@ -146,7 +145,7 @@ void refresh_trigger(void) if (fp_level < -2147483648.0) { fp_level = -2147483648.0; } - ctrl_shm->trig_level.d_s32 = fp_level; + ctrl_shm->trig_level.s = fp_level; break; case HAL_U32: if (fp_level > 4294967295.0) { @@ -155,12 +154,30 @@ void refresh_trigger(void) if (fp_level < 0.0) { fp_level = 0.0; } - ctrl_shm->trig_level.d_u32 = fp_level; + ctrl_shm->trig_level.u = fp_level; + break; + case HAL_SINT: + if (fp_level > (rtapi_real)RTAPI_SINT_MAX) { + fp_level = (rtapi_real)RTAPI_SINT_MAX; + } + if (fp_level < (rtapi_real)RTAPI_SINT_MIN) { + fp_level = (rtapi_real)RTAPI_SINT_MIN; + } + ctrl_shm->trig_level.s = fp_level; + break; + case HAL_UINT: + if (fp_level > (rtapi_real)RTAPI_UINT_MAX) { + fp_level = (rtapi_real)RTAPI_UINT_MAX; + } + if (fp_level < 0.0) { + fp_level = 0.0; + } + ctrl_shm->trig_level.u = fp_level; break; default: break; } - if (chan->data_type == HAL_BIT) { + if (chan->data_type == HAL_BOOL) { snprintf(buf, BUFLEN, " ---- "); gtk_widget_set_sensitive(GTK_WIDGET(trig->level_slider), 0); } else { @@ -299,7 +316,7 @@ static void dialog_select_trigger_source(void) { char *msg; int n; - char *strs[2], *titles[NUM_COLS]; + const char *strs[2], *titles[NUM_COLS]; char buf[BUFLEN + 1]; GtkWidget *label, *scrolled_window, *trig_list; GtkWidget *content_area; diff --git a/src/hal/utils/scope_usr.h b/src/hal/utils/scope_usr.h index 640d9772f39..ee0eaa2b21f 100644 --- a/src/hal/utils/scope_usr.h +++ b/src/hal/utils/scope_usr.h @@ -48,7 +48,7 @@ typedef struct { /* general data */ - gchar *thread_name; /* name of thread that does sampling */ + const gchar *thread_name; /* name of thread that does sampling */ long thread_period_ns; /* period of thread in nano-secs */ long sample_period_ns; /* sample period in nano-secs */ double sample_period; /* sample period as a double */ @@ -88,10 +88,10 @@ typedef struct { typedef struct { int data_source_type; /* 0 = pin, 1 = signal, 2 = param, -1 = no source assigned */ - int data_source; /* points to pin/param/signal struct */ - char *name; /* name of pin/sig/parameter */ + hal_refs_u data_source; /* points to pin/param/signal data source */ + const char *name; /* name of pin/sig/parameter */ hal_type_t data_type; /* data type */ - int data_len; /* data length */ + int data_len; /* data length (== 0 when chan not used; != 0 if used) */ double vert_offset; /* offset to be applied */ double saved_vert_offset; /* saved offset when AC coupling is enabled */ int ac_offset; /* TRUE if the signal should be AC-coupled */ diff --git a/src/hal/utils/scope_vert.c b/src/hal/utils/scope_vert.c index 67fa474ee22..30d19cfd64b 100644 --- a/src/hal/utils/scope_vert.c +++ b/src/hal/utils/scope_vert.c @@ -48,7 +48,6 @@ #include #include // rtapi_strlcpy() #include // HAL public API decls -#include "../hal_priv.h" // private HAL decls #include @@ -204,65 +203,69 @@ int set_channel_source(int chan_num, int type, char *name) { scope_vert_t *vert; scope_chan_t *chan; - hal_pin_t *pin; - hal_sig_t *sig; - hal_param_t *param; vert = &(ctrl_usr->vert); chan = &(ctrl_usr->chan[chan_num - 1]); /* locate the selected item in the HAL */ if (type == 0) { /* search the pin list */ - pin = halpr_find_pin_by_name(name); - if (pin == NULL) { + hal_query_t q = {}; + q.name = name; + q.qtype = HAL_QTYPE_PIN; + if(0 != hal_getref_p(&q)) { /* pin not found */ return -1; } chan->data_source_type = 0; - chan->data_source = SHMOFF(pin); - chan->data_type = pin->type; - chan->name = pin->name; + chan->data_source = q.pp.ref; + chan->data_type = q.pp.type; + chan->name = q.name; } else if (type == 1) { /* search the signal list */ - sig = halpr_find_sig_by_name(name); - if (sig == NULL) { + hal_query_t q = {}; + q.name = name; + if(0 != hal_getref_s(&q)) { /* signal not found */ return -1; } chan->data_source_type = 1; - chan->data_source = SHMOFF(sig); - chan->data_type = sig->type; - chan->name = sig->name; + chan->data_source = q.sig.ref; + chan->data_type = q.sig.type; + chan->name = q.name; } else if (type == 2) { /* search the parameter list */ - param = halpr_find_param_by_name(name); - if (param == NULL) { + hal_query_t q = {}; + q.name = name; + q.qtype = HAL_QTYPE_PARAM; + if(0 != hal_getref_p(&q)) { /* parameter not found */ return -1; } chan->data_source_type = 2; - chan->data_source = SHMOFF(param); - chan->data_type = param->type; - chan->name = param->name; + chan->data_source = q.pp.ref; + chan->data_type = q.pp.type; + chan->name = q.name; } switch (chan->data_type) { - case HAL_BIT: - chan->data_len = sizeof(hal_bit_t); + case HAL_BOOL: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 2; break; - case HAL_FLOAT: - chan->data_len = sizeof(hal_float_t); + case HAL_REAL: + chan->data_len = sizeof(scope_data_t); chan->min_index = -36; chan->max_index = 36; break; case HAL_S32: - chan->data_len = sizeof(hal_s32_t); + case HAL_SINT: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 30; break; case HAL_U32: - chan->data_len = sizeof(hal_u32_t); + case HAL_UINT: + chan->data_len = sizeof(scope_data_t); chan->min_index = -2; chan->max_index = 30; break; @@ -394,7 +397,7 @@ int set_vert_offset(double setting, int ac_coupled) /* copy the offset to restore when toggling AC coupling */ chan->saved_vert_offset = chan->vert_offset; /* update the offset display */ - if (chan->data_type == HAL_BIT) { + if (chan->data_type == HAL_BOOL) { snprintf(buf1, BUFLEN, "----"); } else { if(chan->ac_offset) { @@ -660,7 +663,7 @@ static void offset_button(GtkWidget * widget, gpointer gdata) return; } chan = &(ctrl_usr->chan[chan_num - 1]); - if (chan->data_type == HAL_BIT) { + if (chan->data_type == HAL_BOOL) { /* no offset for bits */ return; } @@ -876,6 +879,31 @@ static void change_page(GtkNotebook *notebook, GtkWidget *page, gtk_widget_grab_focus(GTK_WIDGET(vert->lists[page_num])); } +// for the callback data +typedef struct { + scope_vert_t *vert; + scope_chan_t *chan; + int row; + int tab; + int match_row; + int match_tab; +} rowcolref_t; + +static int rowcol_cb(hal_query_t *q, void *arg) +{ + rowcolref_t *rcr = (rowcolref_t *)arg; + const char *name[2] = {}; + name[0] = q->name; + + add_to_list(rcr->vert->lists[rcr->tab], name, NUM_COLS); + if (NULL != rcr->chan->name && !strcmp(rcr->chan->name, q->name)) { + rcr->match_tab = rcr->tab; + rcr->match_row = rcr->row; + } + rcr->row++; + return 0; +} + static gboolean dialog_select_source(int chan_num) { scope_vert_t *vert; @@ -886,16 +914,10 @@ static gboolean dialog_select_source(int chan_num) GtkWidget *label; GtkWidget *scrolled_window; - hal_pin_t *pin; - hal_sig_t *sig; - hal_param_t *param; - - char *tab_label_text[3]; - char *name[HAL_NAME_LEN + 1]; + const char *tab_label_text[3]; char signal_name[HAL_NAME_LEN + 1]; char title[BUFLEN]; - int next, n, tab, retval; - int row, match_tab, match_row; + int n, retval; vert = &(ctrl_usr->vert); chan = &(ctrl_usr->chan[chan_num - 1]); @@ -959,66 +981,35 @@ static gboolean dialog_select_source(int chan_num) G_CALLBACK(change_page), vert); /* populate the pin, signal, and parameter lists */ - rtapi_mutex_get(&(hal_data->mutex)); - next = hal_data->pin_list_ptr; - match_tab = -1; - match_row = 0; - row = 0; - tab = 0; - while (next != 0) { - pin = SHMPTR(next); - *name = pin->name; - - add_to_list(vert->lists[tab], name, NUM_COLS); - if (chan->name == *name) { - match_tab = tab; - match_row = row; - } - next = pin->next_ptr; - row++; - } + rowcolref_t rcr = {}; + rcr.vert = vert; + rcr.chan = chan; + rcr.match_tab = -1; - next = hal_data->sig_list_ptr; - row = 0; - tab = 1; - while (next != 0) { - sig = SHMPTR(next); - *name = sig->name; - - add_to_list(vert->lists[tab], name, NUM_COLS); - if (chan->name == *name) { - match_tab = tab; - match_row = row; - } - next = sig->next_ptr; - row++; - } + hal_query_t q = {}; - next = hal_data->param_list_ptr; - row = 0; - tab = 2; - while (next != 0) { - param = SHMPTR(next); - *name = param->name; - - add_to_list(vert->lists[tab], name, NUM_COLS); - if (chan->name == *name) { - match_tab = tab; - match_row = row; - } - next = param->next_ptr; - row++; - } + q.qtype = HAL_QTYPE_PIN; + hal_list_p(&q, rowcol_cb, &rcr); + + memset(&q, 0, sizeof(q)); + q.qtype = HAL_QTYPE_SIGNAL; + rcr.tab = 1; + rcr.row = 0; + hal_list_s(&q, rowcol_cb, &rcr); - rtapi_mutex_give(&(hal_data->mutex)); + memset(&q, 0, sizeof(q)); + q.qtype = HAL_QTYPE_PARAM; + rcr.tab = 2; + rcr.row = 0; + hal_list_p(&q, rowcol_cb, &rcr); gtk_widget_show_all(dialog); /* highlight the currently selected name */ /* set scrolling window to show the highlighted name */ - if (match_tab != -1) { - gtk_notebook_set_current_page(GTK_NOTEBOOK(vert->notebook), match_tab); - mark_selected_row(vert->lists[match_tab], match_row); + if (rcr.match_tab != -1) { + gtk_notebook_set_current_page(GTK_NOTEBOOK(vert->notebook), rcr.match_tab); + mark_selected_row(vert->lists[rcr.match_tab], rcr.match_row); } retval = gtk_dialog_run(GTK_DIALOG(dialog)); @@ -1060,7 +1051,7 @@ void channel_changed(void) scope_vert_t *vert; scope_chan_t *chan; GtkAdjustment *adj; - gchar *name; + const gchar *name; gchar buf1[BUFLEN + 1], buf2[BUFLEN + 1]; static int last_channel = 0; vert = &(ctrl_usr->vert); @@ -1101,7 +1092,7 @@ void channel_changed(void) gtk_label_set_text_if(vert->chan_num_label, buf1); gtk_label_set_text_if(vert->source_name_label, name); /* update the offset display */ - if (chan->data_type == HAL_BIT) { + if (chan->data_type == HAL_BOOL) { snprintf(buf1, BUFLEN, "----"); } else { if(chan->ac_offset) { diff --git a/src/hal/utils/setps_util.c b/src/hal/utils/setps_util.c new file mode 100644 index 00000000000..656a154bf6a --- /dev/null +++ b/src/hal/utils/setps_util.c @@ -0,0 +1,115 @@ +/* + * Common set_p and set_s callback for consistent value parsing + * + * Copyright (c) 2026 B.Stultiens + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#include +#include +#include +#include + +#include "setps_util.h" + +// +// Common callback parsing the string argument as a value. The actual prototype +// is: +// int setps_common_cb(hal_query_t *q, const char *value) +// +// It expects the q->qname to be set to allow error signalling of the HAL_PORT +// type that is not allowed in signals. +// +// Returns zero (0) on success or an appropriate negative errno value on error: +// -EINVAL - unsupported/illegal value +// -ERANGE - value out of range +// -EBADF - setting of q->pp.type/q->sig.type not supported +// -ENOMEM - failed to allocate memory for locale switching +// +int setps_common_cb(hal_query_t *q, void *arg) +{ + const char *value = (const char *)arg; + hal_query_value_u *qvp = HAL_QTYPE_SIGNAL == q->qtype ? &q->sig.value : &q->pp.value; + hal_type_t type = HAL_QTYPE_SIGNAL == q->qtype ? q->sig.type : q->pp.type; + char *eptr; + static const struct { + const char *name; + bool value; + } boolvals[] = { + {"TRUE", 1}, {"FALSE", 0}, + {"1", 1}, {"0", 0}, + {"ON", 1}, {"OFF", 0}, + {"YES", 1}, {"NO", 0}, + {NULL, 0} + }; + switch(type) { + case HAL_BOOL: + for(int i = 0; boolvals[i].name; i++) { + if(!strcasecmp(boolvals[i].name, value)) { + qvp->b = boolvals[i].value; + return 0; + } + } + return -EINVAL; + case HAL_S32: + case HAL_SINT: + errno = 0; + qvp->s = strtoll(value, &eptr, 0); + if(HAL_S32 == type && (qvp->s < RTAPI_INT32_MIN || qvp->s > RTAPI_INT32_MAX)) + return -ERANGE; + if(0 != errno) + return -errno; + if(value == eptr || (('\0' != *eptr) && !isspace((unsigned char)*eptr))) + return -EINVAL; // No data in string or trailing junk + break; + case HAL_PORT: + if(HAL_QTYPE_SIGNAL != q->qtype) { + // This is a setp call, don't allow port + return -EBADF; + } + /* Fallthrough */ + case HAL_U32: + case HAL_UINT: + errno = 0; + qvp->u = strtoull(value, &eptr, 0); + if((HAL_U32 == type || HAL_PORT == type) && qvp->u > RTAPI_UINT32_MAX) + return -ERANGE; + if(0 != errno) + return -errno; + if(value == eptr || (('\0' != *eptr) && !isspace((unsigned char)*eptr))) + return -EINVAL; // No data in string or trailing junk + break; + case HAL_REAL: { + // Switch locale so we always use decimal point + locale_t olc = uselocale((locale_t)0); + locale_t nlc = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); + if((locale_t)0 == nlc) + return -ENOMEM; + uselocale(nlc); + errno = 0; + qvp->r = strtod(value, &eptr); + int errnosave = errno; + uselocale(olc); + freelocale(nlc); + if(0 != errnosave) + return -errnosave; + if(value == eptr || (('\0' != *eptr) && !isspace((unsigned char)*eptr))) + return -EINVAL; // No data in string or trailing junk + break; } + default: + return -EBADF; + } + return 0; +} diff --git a/src/hal/utils/setps_util.h b/src/hal/utils/setps_util.h new file mode 100644 index 00000000000..6819582586b --- /dev/null +++ b/src/hal/utils/setps_util.h @@ -0,0 +1,35 @@ +/* + * Setp and sets comming callback for consistent valueparsing + * + * Copyright (c) 2026 B.Stultiens + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef __HAL_UTIL_SETPS_UTIL_H +#define __HAL_UTIL_SETPS_UTIL_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int setps_common_cb(hal_query_t *q, void *arg); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/rtapi/rtapi_mutex.h b/src/rtapi/rtapi_mutex.h index e00d0f2e748..c5bf07ae9f1 100644 --- a/src/rtapi/rtapi_mutex.h +++ b/src/rtapi/rtapi_mutex.h @@ -52,6 +52,9 @@ typedef unsigned long rtapi_mutex_t; static __inline__ void rtapi_mutex_give(unsigned long *mutex) { test_and_clear_bit(0, mutex); } + static __inline__ void rtapi_mutex_give_rd(unsigned long *mutex) { + test_and_set_bit(0, mutex); + } /** * @brief Non-blocking attempt to get the mutex. * @@ -67,6 +70,9 @@ typedef unsigned long rtapi_mutex_t; static __inline__ int rtapi_mutex_try(unsigned long *mutex) { return test_and_set_bit(0, mutex); } + static __inline__ int rtapi_mutex_try_rd(unsigned long *mutex) { + return !test_and_clear_bit(0, mutex); + } /** * @brief Blocking attempt to gGet the mutex. @@ -85,6 +91,15 @@ typedef unsigned long rtapi_mutex_t; #endif } } + static __inline__ void rtapi_mutex_get_rd(unsigned long *mutex) { + while (!test_and_clear_bit(0, mutex)) { +#if defined(__KERNEL__) + schedule(); +#else + sched_yield(); +#endif + } + } #endif diff --git a/src/rtapi/rtapi_stdint.h b/src/rtapi/rtapi_stdint.h index 06a4f6866a2..8941fff5964 100644 --- a/src/rtapi/rtapi_stdint.h +++ b/src/rtapi/rtapi_stdint.h @@ -79,5 +79,10 @@ typedef uintptr_t rtapi_uintptr_t; typedef double rtapi_real; typedef rtapi_s64 rtapi_sint; typedef rtapi_u64 rtapi_uint; +typedef rtapi_intptr_t rtapi_port; + +#define RTAPI_SINT_MAX RTAPI_INT64_MAX +#define RTAPI_SINT_MIN RTAPI_INT64_MIN +#define RTAPI_UINT_MAX RTAPI_UINT64_MAX #endif diff --git a/src/rtapi/uspace_rtapi_main.cc b/src/rtapi/uspace_rtapi_main.cc index 5876165e5e0..7027534607b 100644 --- a/src/rtapi/uspace_rtapi_main.cc +++ b/src/rtapi/uspace_rtapi_main.cc @@ -57,7 +57,6 @@ #include "rtapi.h" #include -#include "hal/hal_priv.h" #include "uspace_common.h" static RtapiApp &App(); @@ -334,19 +333,25 @@ static int do_newinst_cmd(const std::string &type, const std::string &name, cons return -1; } - hal_comp_t *(*find_comp_by_name)(char *) = DLSYM(module, "halpr_find_comp_by_name"); - if (!find_comp_by_name) { - rtapi_print_msg(RTAPI_MSG_ERR, "newinst: halpr_find_comp_by_name not found\n"); + int (*invoke_make)(const char *, const char *, const char *); + invoke_make = DLSYM(module, "hal_comp_invoke_make"); + if(!invoke_make) { + rtapi_print_msg(RTAPI_MSG_ERR, "newinst: hal_comp_invoke_make not found\n"); return -1; } - hal_comp_t *comp = find_comp_by_name((char *)type.c_str()); - if (!comp) { - rtapi_print_msg(RTAPI_MSG_ERR, "newinst: component %s not found\n", type.c_str()); + int rv = invoke_make(type.c_str(), name.c_str(), arg.c_str()); + if(rv) { + if(-ENOENT == rv) + rtapi_print_msg(RTAPI_MSG_ERR, "newinst: component %s not found\n", type.c_str()); + else if(-ENOEXEC == rv) + rtapi_print_msg(RTAPI_MSG_ERR, "newinst: component %s does not support instantiation\n", type.c_str()); + else + rtapi_print_msg(RTAPI_MSG_ERR, "newinst: component %s returned error %d\n", type.c_str(), rv); return -1; } - return comp->make((char *)name.c_str(), (char *)arg.c_str()); + return 0; } static int do_one_item( diff --git a/tests/halmodule.2/expected b/tests/halmodule.2/expected new file mode 100644 index 00000000000..aa4b59a081c --- /dev/null +++ b/tests/halmodule.2/expected @@ -0,0 +1,10 @@ +- [0, 0, 0, 0, 0, 0, 0] +0 [0, 0, 0, 0, 0, 0, 0] +1 [1, 0, 0, 1, 0, 1, 1] +2 [0, 1, 0, 1, 0, 1, 1] +3 [1, 1, 1, 1, 1, 1, 0] +- [1, 0, 0, 1, 0, 1, 1] +0 [1, 0, 0, 1, 0, 1, 1] +1 [0, 1, 0, 1, 0, 1, 1] +2 [1, 1, 1, 1, 1, 1, 0] +3 [0, 0, 0, 0, 0, 0, 0] diff --git a/tests/halmodule.2/halmodtest.py b/tests/halmodule.2/halmodtest.py new file mode 100755 index 00000000000..9d24d619fdb --- /dev/null +++ b/tests/halmodule.2/halmodtest.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 + +# +# This shows HAL with Python without creating a component. All functions that +# only require a mapped HAL shared memory segment will function fine without a +# component. +# That means hal.* functions will generally function as expected immediately +# after the HAL module is imported. +# + +import time +import hal + +# Wait for at least one thread cycle +def cycleWait(): + oldtime = time.time() + newval = oldval = hal.get_value("thread1.threadbeat") + while newval <= oldval: + if time.time() - oldtime >= 1.0: + sys.exit("error: cycleWait(): Timeout") + time.sleep(0.001) + newval = hal.get_value("thread1.threadbeat") + +# We need to make sure that the servo-thread ran at least +# once for the input to be copied to the output +cycleWait() + +sigs = [ "net-input-a", "net-input-b", + "and2.0.out", "or2.0.out", + "xor2.0.in0", "xor2.0.in1", + "net-output" ] + +def values(pfx): + out = [] + for s in sigs: + out.append(int(hal.get_value(s))) + print(f"{pfx} {out}") + +values("-") + +v = hal.get_s("net-input-a") +v += hal.get_s("net-input-b") * 2 + +for i in range(4): + hal.set_s("net-input-a", 0 != (i+v) & 1) + hal.set_s("net-input-b", 0 != (i+v) & 2) + # Output is set in the thread cycle, need at least + # one cycle after input change + cycleWait() + values(str(i)) + diff --git a/tests/halmodule.2/test.hal b/tests/halmodule.2/test.hal new file mode 100644 index 00000000000..cb0c62e1fc6 --- /dev/null +++ b/tests/halmodule.2/test.hal @@ -0,0 +1,32 @@ +# The goal of this test is to run the 'halmodtest.py' script that will read the +# pins *without* creating a component. We only need a mapped HAL shared memory +# segment for that. +# It is rather unimportant what is loaded. We just need to ensure we have a +# working HAL system and some pins we can look at. +loadrt threads + +loadrt and2 count=1 +loadrt or2 count=1 +loadrt xor2 count=1 + +addf and2.0 thread1 +addf or2.0 thread1 +addf xor2.0 thread1 + +net net-input-a and2.0.in0 or2.0.in0 +net net-input-b and2.0.in1 or2.0.in1 +net net-xor-a and2.0.out xor2.0.in0 +net net-xor-b or2.0.out xor2.0.in1 +net net-output xor2.0.out + +start + +# Show the initial state +loadusr -w ./halmodtest.py + +# Force some value change +sets net-input-a 1 +sets net-input-b 0 + +# This should show the changed state +loadusr -w ./halmodtest.py diff --git a/tests/halui/jogging/halui.ini b/tests/halui/jogging/halui.ini index 5696725b00a..774a99be13c 100644 --- a/tests/halui/jogging/halui.ini +++ b/tests/halui/jogging/halui.ini @@ -1,5 +1,6 @@ [EMC] -DEBUG = 0x7fffffff +#DEBUG = 0x7fffffff +DEBUG = 0x0 VERSION = 1.1 [DISPLAY] diff --git a/tests/halui/mdi/halui.ini b/tests/halui/mdi/halui.ini index 48132b818b3..eb8e99daf38 100644 --- a/tests/halui/mdi/halui.ini +++ b/tests/halui/mdi/halui.ini @@ -1,6 +1,7 @@ [EMC] VERSION = 1.1 -DEBUG = 0x7fffffff +#DEBUG = 0x7fffffff +DEBUG = 0x0 [DISPLAY] DISPLAY = ./test-ui.py diff --git a/tests/save.0/expected b/tests/save.0/expected index 1ad2895953a..833c015c198 100644 --- a/tests/save.0/expected +++ b/tests/save.0/expected @@ -1,8 +1,8 @@ # components -loadrt threads name1=fast period1=100000 +loadrt threads name1=fast period1=100000 #loadrt __fast (not loaded by loadrt, no args saved) -loadrt stepgen step_type=0 -loadrt sampler cfg=bb depth=4096 +loadrt stepgen step_type=0 +loadrt sampler cfg=bb depth=4096 # pin aliases # param aliases # signals