commit 35c5664cc327b175559323bc9c3224f8d56dea1b Author: Michel-FK Date: Sat Apr 3 23:13:40 2021 +0200 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c0133eb --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.o +fkgpiod +termfix diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..2cba2ac --- /dev/null +++ b/COPYING @@ -0,0 +1,458 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/Makefile b/Makefile new file mode 100755 index 0000000..7232141 --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +TOOLS_CFLAGS := -Wall -std=c99 -D _DEFAULT_SOURCE +# +# Programs +# +all: fkgpiod termfix + +fkgpiod: main.o daemon.o to_log.o parse_config.o mapping_list.o gpio_mapping.o gpio_utils.o gpio_axp209.o gpio_pcal6416a.o smbus.o uinput.o keydefs.o + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ + +termfix: termfix.o + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ + +# +# Objects +# + +%.o: %.c + $(CC) $(CFLAGS) $(TOOLS_CFLAGS) -c $< -o $@ + +clean: + rm -f *.o fkgpiod termfix diff --git a/daemon.c b/daemon.c new file mode 100644 index 0000000..2b650e9 --- /dev/null +++ b/daemon.c @@ -0,0 +1,183 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file daemon.c + * This file contains the daemon function for the FunKey S GPIO daemon + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "daemon.h" + +/* Process ID file descriptor */ +static int pid_fd; + +/* Process ID lock file name */ +static char *pid_lock_file; + +/* Signal handler */ +void signal_handler(int sig) +{ + switch(sig){ + case SIGHUP: + syslog(LOG_WARNING, "Received SIGHUP."); + break; + + case SIGINT: + case SIGTERM: + syslog(LOG_INFO, "Exiting."); + close(pid_fd); + unlink(pid_lock_file); + exit(EXIT_SUCCESS); + break; + + default: + syslog(LOG_WARNING, "Unhandled signal %s", strsignal(sig)); + } +} + +/* Get the pid from the pid lock file and terminate the daemon */ +void kill_daemon(char *pidfile) +{ + int n; + pid_t pid; + char str[10]; + + pid_fd = open(pidfile, O_RDONLY, 0600); + if (pid_fd < 0) { + perror(pidfile); + } else { + if (read(pid_fd, str, 10) > 0) { + pid = strtol(str, NULL, 0); + if (pid) { + printf("terminating %d\n", pid); + n = kill(pid, SIGTERM); + if (n < 0) { + perror("kill"); + } + } + } + close(pid_fd); + } +} + +/* Turn the running process into a daemon */ +void daemonize(char *rundir, char *pidfile) +{ + int pid, i; + char str[10]; + struct sigaction sa; + sigset_t ss; + + /* Check if parent process is already init */ + if (getppid() == 1) { + + /* Don't need to do it twice */ + return; + } + + /* Fork off the parent process */ + pid = fork(); + if (pid < 0) { + perror("first fork"); + exit(EXIT_FAILURE); + } else if (pid > 0) { + + /* Success. terminate the parent */ + exit(EXIT_SUCCESS); + } + + /* On success: the child process becomes the session leader */ + if (setsid() < 0) { + perror("set SID"); + exit(EXIT_FAILURE); + } + + /* Block these signals */ + sigemptyset(&ss); + sigaddset(&ss, SIGCHLD); + sigaddset(&ss, SIGTSTP); + sigaddset(&ss, SIGTTOU); + sigaddset(&ss, SIGTTIN); + sigprocmask(SIG_BLOCK, &ss, NULL); + + /* Handle these signals */ + sa.sa_handler = signal_handler; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sigaction(SIGHUP, &sa, NULL); + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + + /* Fork off for a second time to ensure that we get rid of the session + * leading process + */ + pid = fork(); + if (pid < 0) { + perror("second fork"); + exit(EXIT_FAILURE); + } else if (pid > 0) { + + /* Success. terminate the parent */ + exit(EXIT_SUCCESS); + } + + /* Set new file permissions */ + umask(0); + + /* Change the working directory to the root directory or another + * appropriated directory + */ + if (chdir(rundir) < 0) { + perror(rundir); + } + + /* Close all opened file descriptors */ + for (i = sysconf(_SC_OPEN_MAX); i >= 0; i--) { + close(i); + } + + /* Make sure there is only one daemon running at a time using a lock file */ + pid_lock_file = pidfile; + pid_fd = open(pidfile, O_RDWR | O_CREAT, 0600); + if (pid_fd < 0) { + syslog(LOG_INFO, "Could not open lock file %s. Exiting.", pidfile); + exit(EXIT_FAILURE); + } + if (lockf(pid_fd, F_TLOCK, 0) < 0) { + syslog(LOG_INFO, "Could not lock lock file %s. Exiting.", pidfile); + unlink(pidfile); + exit(EXIT_FAILURE); + } + sprintf(str, "%d\n", getpid()); + if (write(pid_fd, str, strlen(str)) < 0) { + perror(pidfile); + } + syslog(LOG_INFO, "Daemon running."); +} diff --git a/daemon.h b/daemon.h new file mode 100644 index 0000000..0ab6cb3 --- /dev/null +++ b/daemon.h @@ -0,0 +1,33 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file daemon.h + * This file contains the daemon function for the FunKey S GPIO daemon + */ + +#ifndef _DAEMON_H_ +#define _DAEMON_H_ + +void daemonize(char *rundir, char *pidfile); +void kill_daemon(char *pidfile); + +#endif diff --git a/gpio_axp209.c b/gpio_axp209.c new file mode 100755 index 0000000..a3d0c58 --- /dev/null +++ b/gpio_axp209.c @@ -0,0 +1,121 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_axp209.c + * This is the userland GPIO driver for the AXP209 PMIC + */ + +#include +#include +#include +#include +#include +#include +#include +#include "smbus.h" +#include "gpio_axp209.h" + +//#define DEBUG_AXP209 +#define ERROR_AXP209 + +#ifdef DEBUG_AXP209 + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef ERROR_AXP209 + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_ERROR(...) +#endif + +/* AXP209 I2C PMIC pseudo-file descriptor */ +static int fd_axp209; + +/* The I2C bus pseudo-file name */ +static const char i2c0_sysfs_filename[] = "/dev/i2c-0"; + +/* Initialize the AXP209 PMIC chip */ +bool axp209_init(void) +{ + /* Open the I2C bus pseudo-file */ + if ((fd_axp209 = open(i2c0_sysfs_filename,O_RDWR)) < 0) { + LOG_ERROR("Failed to open the I2C bus %s", i2c0_sysfs_filename); + return false; + } + + /* Acquire the bus access for the AXP209 PMIC chip */ + if (ioctl(fd_axp209, I2C_SLAVE, AXP209_I2C_ADDR) < 0) { + LOG_DEBUG("Failed to acquire bus access and/or talk to slave, trying to force it\n"); + if (ioctl(fd_axp209, I2C_SLAVE_FORCE, AXP209_I2C_ADDR) < 0) { + LOG_ERROR("Failed to acquire FORCED bus access and/or talk to slave.\n"); + return false; + } + } + + /* Set PEK Long press delay to 2.5s */ + if (i2c_smbus_write_byte_data(fd_axp209, AXP209_REG_PEK_PARAMS, 0x9F) < 0) { + LOG_ERROR("Cannot set AXP209 PEK Long press delay to 2.5s\n"); + } + + /* Set N_OE Shutdown delay to 3s*/ + if (i2c_smbus_write_byte_data(fd_axp209, AXP209_REG_32H, 0x47) < 0) { + LOG_ERROR("Cannot set AXP209 N_OE Shutdown delay to 3s\n"); + } + + /* Enable only chosen interrupts (PEK short and long presses)*/ + if (i2c_smbus_write_byte_data(fd_axp209, AXP209_INTERRUPT_BANK_3_ENABLE, + 0x03) < 0) { + LOG_ERROR("Cannot intiialize interrupt bank 3 for AXP209\n"); + } + return true; +} + +/* Deinitialize the AXP209 PMIC chip */ +bool axp209_deinit(void) +{ + + /* Close the I2C bus pseudo-file */ + close(fd_axp209); + return true; +} + +/* Read the AXP209 PMIC chip interrupt register bank 3 */ +int axp209_read_interrupt_bank_3(void) +{ + int value, result; + + value = i2c_smbus_read_byte_data(fd_axp209, AXP209_INTERRUPT_BANK_3_STATUS); + if (value < 0) { + return value; + } + + /* Clear the interrupts */ + result = i2c_smbus_write_byte_data(fd_axp209, AXP209_INTERRUPT_BANK_3_STATUS, 0xFF); + if (result < 0) { + return result; + } + LOG_DEBUG("READ AXP209_INTERRUPT_BANK_3_STATUS: 0x%02X\n", value); + return value & 0xFF; +} diff --git a/gpio_axp209.h b/gpio_axp209.h new file mode 100755 index 0000000..1d69459 --- /dev/null +++ b/gpio_axp209.h @@ -0,0 +1,59 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_axp209.h + * This is the userland GPIO driver for the AXP209 PMIC + */ + +#ifndef _GPIO_AXP209_H_ +#define _GPIO_AXP209_H_ + + +#include + +/* Chip physical address */ +#define AXP209_I2C_ADDR 0x34 + +/* Chip register adresses */ +#define AXP209_REG_32H 0x32 +#define AXP209_REG_PEK_PARAMS 0x36 +#define AXP209_INTERRUPT_BANK_1_ENABLE 0x40 +#define AXP209_INTERRUPT_BANK_1_STATUS 0x48 +#define AXP209_INTERRUPT_BANK_2_ENABLE 0x41 +#define AXP209_INTERRUPT_BANK_2_STATUS 0x49 +#define AXP209_INTERRUPT_BANK_3_ENABLE 0x42 +#define AXP209_INTERRUPT_BANK_3_STATUS 0x4A +#define AXP209_INTERRUPT_BANK_4_ENABLE 0x43 +#define AXP209_INTERRUPT_BANK_4_STATUS 0x4B +#define AXP209_INTERRUPT_BANK_5_ENABLE 0x44 +#define AXP209_INTERRUPT_BANK_5_STATUS 0x4C + +/* Masks */ +#define AXP209_INTERRUPT_PEK_SHORT_PRESS 0x02 +#define AXP209_INTERRUPT_PEK_LONG_PRESS 0x01 + +bool axp209_init(void); +bool axp209_deinit(void); +int axp209_read_interrupt_bank_3(void); + +#endif //_GPIO_AXP209_H_ diff --git a/gpio_mapping.c b/gpio_mapping.c new file mode 100755 index 0000000..b76d9b3 --- /dev/null +++ b/gpio_mapping.c @@ -0,0 +1,418 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_mapping.c + * This file contains the GPIO mapping functions + */ + +#include +#include +#include +#include +#include "gpio_utils.h" +#include "gpio_axp209.h" +#include "gpio_mapping.h" +#include "gpio_pcal6416a.h" +#include "mapping_list.h" +#include "parse_config.h" +#include "uinput.h" + +//#define DEBUG_GPIO +//#define DEBUG_PERIODIC_CHECK +#define ERROR_GPIO + +#ifdef DEBUG_GPIO + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef DEBUG_PERIODIC_CHECK + #define LOG_PERIODIC(...) printf(__VA_ARGS__); +#else + #define LOG_PERIODIC(...) +#endif + +#ifdef ERROR_GPIO + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_ERROR(...) +#endif + +/* These defines force to perform a GPIO sanity check after a timeout. + * If not declared, there will be no timeout and no periodical sanity check of + * GPIO expander values + */ +//#define TIMEOUT_SEC_SANITY_CHECK_GPIO_EXP 1 +#define TIMEOUT_MICROSEC_SANITY_CHECK_GPIO_EXP (30 * 1000) + +#define SHORT_PEK_PRESS_DURATION_US (200 * 1000) + +#define GPIO_PIN_I2C_EXPANDER_INTERRUPT ((('B' - '@') << 4) + 3) // PB3 +#define GPIO_PIN_AXP209_INTERRUPT ((('B' - '@') << 4) + 5) // PB5 + +#define SHORT_PEK_PRESS_GPIO_MASK (1 << 5) +#define NOE_GPIO_MASK (1 << 10) +#define SHELL_COMMAND_SHUTDOWN "sched_shutdown 0.1" + +static int fd_pcal6416a; +static int fd_axp209; +static uint32_t active_gpio_mask; +static uint32_t current_gpio_mask; + +/* Search for the GPIO mask into the mapping and apply the required actions */ +static void apply_mapping(mapping_list_t *list, uint32_t gpio_mask) +{ + mapping_t *mapping; + + /* Search the whole mapping sorted by decreasing simultaneous GPIO number + * The whole mapping must be checked, as several GPIO combinations may be + * active at the same time, and no longer matching combinations must be + * deactivated + */ + for (mapping = first_mapping(list); !last_mapping(list, mapping); + mapping = next_mapping(mapping)) { + if ((mapping->gpio_mask & gpio_mask) == mapping->gpio_mask) { + + /* If the current GPIO mask contains the mapping GPIO mask */ + LOG_DEBUG("Found matching mapping:\n"); +#ifdef DEBUG_GPIO + dump_mapping(mapping); +#endif // DEBUG_GPIO + if (mapping->activated == false) { + + /* Mapping is not yet active, subtract the matching GPIOs from + * the current GPIO mask and activate it + */ + gpio_mask ^= mapping->gpio_mask; + mapping->activated = true; + if (mapping->type == MAPPING_KEY) { + + /* Send the key down event */ + LOG_DEBUG("\t--> Key press %d\n", mapping->value.keycode); + sendKey(mapping->value.keycode, 1); + } else if (mapping->type == MAPPING_COMMAND) { + + /* Execute the corresponding Shell command */ + LOG_DEBUG("\t--> Execute Shell command \"%s\"\n", + mapping->value.command); + system(mapping->value.command); + } + } + } else if (mapping->activated) { + + /* Non-matching activated mapping, deactivate it */ + LOG_DEBUG("Found activated mapping:\n"); +#ifdef DEBUG_GPIO + dump_mapping(mapping); +#endif // DEBUG_GPIO + mapping->activated = false; + if (mapping->type == MAPPING_KEY) { + + /* Send the key up event */ + LOG_DEBUG("\t--> Key release %d\n", mapping->value.keycode); + sendKey(mapping->value.keycode, 0); + } + } + } +} + +/* Initialize the GPIO interrupt for the I2C expander chip */ +static bool init_gpio_interrupt(int gpio, int *fd, const char *edge) +{ + LOG_DEBUG("Initializing interrupt for GPIO P%c%d (%d)\n", + (gpio / 16) + '@', gpio % 16, gpio); + if (gpio_export(gpio) < 0) { + return false; + } + + /* Initializing the GPIO interrupt */ + if (*edge) { + if (gpio_set_edge(gpio, edge) < 0) { + return false; + } + } + + /* Open the GPIO pseudo-file */ + *fd = gpio_fd_open(gpio, O_RDONLY); + LOG_DEBUG("GPIO fd is: %d\n", *fd); + if (*fd < 0) { + return false; + } + return true; +} + +/* Deinitialize the GPIO interrupt for the I2C expander chip */ +static void deinit_gpio_interrupt(int fd) +{ + LOG_DEBUG("DeInitializing interrupt for GPIO fd %d\n", fd); + + /* Close the GPIO pseudo-file */ + gpio_fd_close(fd); +} + +/* Initialize the GPIO mapping */ +bool init_gpio_mapping(const char *config_filename, + mapping_list_t *mapping_list) +{ + init_mapping_list(mapping_list); + + /* Read the configuration file to get all valid GPIO mappings */ + if (parse_config_file(config_filename, mapping_list, &active_gpio_mask) == + false) { + return false; + } +#ifdef DEBUG_GPIO + printf("\nGPIO Map:\n=========\n"); + dump_mapping_list(mapping_list); +#endif // DEBUG_GPIO + + /* Force the NOE GPIO to be an active GPIO as it is not in the mapping */ + active_gpio_mask |= NOE_GPIO_MASK; + + /* Clear the current GPIO mask */ + current_gpio_mask = 0; + + /* Initialize the PCAL5616AHF I2C GPIO expander chip */ + if (pcal6416a_init() == false) { + return false; + } + + /* Initialize the GPIO interrupt for the I2C GPIO expander chip */ + LOG_DEBUG("Initialize interrupt for GPIO_PIN_I2C_EXPANDER_INTERRUPT\n"); + init_gpio_interrupt(GPIO_PIN_I2C_EXPANDER_INTERRUPT, &fd_pcal6416a, + "both"); + + /* Initialize the AXP209 PMIC */ + if (axp209_init() == false) { + return false; + } + + /* Initialize the GPIO interrupt for the AXP209 chip */ + LOG_DEBUG("Initialize interrupt for GPIO_PIN_AXP209_INTERRUPT\n"); + init_gpio_interrupt(GPIO_PIN_AXP209_INTERRUPT, &fd_axp209, ""); + return true; +} + +/* Deinitialize the GPIO mapping */ +void deinit_gpio_mapping(void) +{ + /* Deinitialize the GPIO interrupt for the I2C GPIO expander chip */ + LOG_DEBUG("DeInitiating interrupt for GPIO_PIN_I2C_EXPANDER_INTERRUPT\n"); + deinit_gpio_interrupt(fd_pcal6416a); + + /* Deinitialize the I2C GPIO expander chip */ + pcal6416a_deinit(); + + /* Deinitialize the GPIO interrupt for the AXP209 PMIC chip */ + LOG_DEBUG("DeInitiating interrupt for GPIO_PIN_AXP209_INTERRUPT\n"); + deinit_gpio_interrupt(fd_axp209); + + /* Deinitialize the AXP209 PMIC chip */ + axp209_deinit(); +} + +/* Handle the GPIO mapping (with interrupts) */ +void handle_gpio_mapping(mapping_list_t *list) +{ + int result, gpio, int_status, max_fd, fd, val_int_bank_3; + fd_set fds; + uint32_t interrupt_mask, previous_gpio_mask; + bool pcal6416a_interrupt = false; + bool axp209_interrupt = false; + bool forced_interrupt = false; + char buffer[2]; + mapping_t *mapping; + + /* Initialize masks */ + previous_gpio_mask = current_gpio_mask; + current_gpio_mask = 0; + + /* Listen to interrupts */ + FD_ZERO(&fds); + FD_SET(fd_pcal6416a, &fds); + FD_SET(fd_axp209, &fds); + max_fd = (fd_pcal6416a > fd_axp209) ? fd_pcal6416a : fd_axp209; +#ifdef TIMEOUT_MICROSEC_SANITY_CHECK_GPIO_EXP + struct timeval timeout = {0, TIMEOUT_MICROSEC_SANITY_CHECK_GPIO_EXP}; + result = select(max_fd + 1, NULL, NULL, &fds, &timeout); +#elif TIMEOUT_SEC_SANITY_CHECK_GPIO_EXP + struct timeval timeout = {TIMEOUT_SEC_SANITY_CHECK_GPIO_EXP, 0}; + result = select(max_fd + 1, NULL, NULL, &fds, &timeout); +#else + result = select(max_fd + 1, NULL, NULL, &fds, NULL); +#endif + if (result == 0) { + + /* Timeout case */ + LOG_PERIODIC("Timeout, forcing sanity check\n"); + + /* Timeout forces a "Found interrupt" event for sanity check */ + pcal6416a_interrupt = axp209_interrupt = forced_interrupt = true; + } else if (result < 0) { + + /* Error case */ + perror("select"); + return; + } else { + + /* Check which file descriptor is available for read */ + for (fd = 0; fd <= max_fd; fd++) { + if (FD_ISSET(fd, &fds)) { + + /* Rewind file and dummy read the current GPIO value */ + lseek(fd, 0, SEEK_SET); + if (read(fd, &buffer, 2) != 2) { + perror("read"); + break; + } + + /* Check if the interrupt is from I2C GPIO expander or AXP209 */ + if (fd == fd_pcal6416a) { + LOG_DEBUG("Found interrupt generated by PCAL6416AHF\r\n"); + pcal6416a_interrupt = true; + } else if (fd == fd_axp209) { + LOG_DEBUG("Found interrupt generated by AXP209\r\n"); + axp209_interrupt = true; + } + } + } + } + + /* Process the AXP209 interrupts, if any */ + if (axp209_interrupt) { + if (forced_interrupt) { + LOG_PERIODIC("Processing forced AXP209 interrupt\n"); + } else { + LOG_DEBUG("Processing real AXP209 interrupt\n"); + } + val_int_bank_3 = axp209_read_interrupt_bank_3(); + if (val_int_bank_3 < 0) { + LOG_DEBUG("Could not read AXP209 by I2C\n"); + return; + } + + /* Proccess the Power Enable Key (PEK) short keypress */ + if (val_int_bank_3 & AXP209_INTERRUPT_PEK_SHORT_PRESS) { + LOG_DEBUG("AXP209 short PEK key press detected\n"); + mapping = find_mapping(list, SHORT_PEK_PRESS_GPIO_MASK); + if (mapping != NULL) { + LOG_DEBUG("Found matching mapping:\n"); + dump_mapping(mapping); + if (mapping->type == MAPPING_KEY) { + LOG_DEBUG("\t--> Key press and release %d\n", + mapping->value.keycode); + sendKey(mapping->value.keycode, 1); + usleep(SHORT_PEK_PRESS_DURATION_US); + sendKey(mapping->value.keycode, 0); + } else if (mapping->type == MAPPING_COMMAND) { + LOG_DEBUG("\t--> Execute Shell command \"%s\"\n", + mapping->value.command); + system(mapping->value.command); + } + } + } + + /* Proccess the Power Enable Key (PEK) long keypress, the AXP209 + * will shutdown the system in 3s anyway + */ + if (val_int_bank_3 & AXP209_INTERRUPT_PEK_LONG_PRESS) { + LOG_DEBUG("AXP209 long PEK key press detected\n"); + LOG_DEBUG("\t--> Execute Shell command \"%s\"\n", + SHELL_COMMAND_SHUTDOWN); + system(SHELL_COMMAND_SHUTDOWN); + } + } + + /* Process the PCAL6416A interrupts, if any */ + if (pcal6416a_interrupt) { + if (forced_interrupt) { + LOG_PERIODIC("Processing forced PCAL6416AHF interrupt\n"); + } else { + LOG_DEBUG("Processing real PCAL6416AHF interrupt\n"); + } + + /* Read the interrupt mask */ + int_status = pcal6416a_read_mask_interrupts(); + if (int_status < 0) { + LOG_DEBUG("Could not read PCAL6416A interrupt status by I2C\n"); + return; + } + interrupt_mask = (uint32_t) int_status; + + /* Read the GPIO mask */ + current_gpio_mask = pcal6416a_read_mask_active_GPIOs(); + if (current_gpio_mask < 0) { + LOG_DEBUG("Could not read PCAL6416A active GPIOS by I2C\n"); + return; + } + + /* Keep only active GPIOS */ + interrupt_mask &= active_gpio_mask; + current_gpio_mask &= active_gpio_mask; + + /* Invert the active low N_NOE GPIO signal */ + current_gpio_mask ^= (NOE_GPIO_MASK); + + /* Sanity check: if we missed an interrupt for some reason, + * check if the GPIO value has changed and force it + */ + for (gpio = 0; gpio < MAX_NUM_GPIO; gpio++) { + if (interrupt_mask & (1 << gpio)) { + + /* Found the GPIO in the interrupt mask */ + LOG_DEBUG("\t--> Interrupt GPIO: %d\n", gpio); + } else if ((current_gpio_mask ^ previous_gpio_mask) & (1 << gpio)) { + + /* The GPIO is not in the interrupt mask, but has changed, force + * it + */ + LOG_DEBUG("\t--> No interrupt (missed) but value has changed on GPIO: %d\n", + gpio); + interrupt_mask |= 1 << gpio; + } + } + if (!interrupt_mask) { + + /* No change */ + return; + } + LOG_DEBUG("current_gpio_mask 0x%04X interrupt_mask 0x%04X\n", + current_gpio_mask, int_status); + + /* Proccess the N_OE signal from the magnetic Reed switch, the + * AXP209 will shutdown the system in 3s anyway + */ + if (interrupt_mask & NOE_GPIO_MASK) { + LOG_DEBUG("NOE detected\n"); + LOG_DEBUG("\t--> Execute Shell command \"%s\"\n", + SHELL_COMMAND_SHUTDOWN); + interrupt_mask &= ~NOE_GPIO_MASK; + system(SHELL_COMMAND_SHUTDOWN); + } + } + + /* Apply the mapping for the current gpio mask */ + apply_mapping(list, current_gpio_mask); + return; +} diff --git a/gpio_mapping.h b/gpio_mapping.h new file mode 100755 index 0000000..85d39b4 --- /dev/null +++ b/gpio_mapping.h @@ -0,0 +1,38 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_mapping.h + * This file contains the GPIO mapping functions + */ + +#ifndef _GPIO_MAPPING_H_ +#define _GPIO_MAPPING_H_ + +#include "mapping_list.h" + +bool init_gpio_mapping(const char* config_filename, + mapping_list_t *mapping_list); +void deinit_gpio_mapping(void); +void handle_gpio_mapping(mapping_list_t *mapping_list); + +#endif //_GPIO_MAPPING_H_ diff --git a/gpio_pcal6416a.c b/gpio_pcal6416a.c new file mode 100755 index 0000000..5b33dc8 --- /dev/null +++ b/gpio_pcal6416a.c @@ -0,0 +1,158 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_pcal6416a.c + * This is userland GPIO driver for the PCAL6416AHB I2C GPIO expander chip + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "smbus.h" +#include "gpio_pcal6416a.h" + +//#define DEBUG_PCAL6416A +#define ERROR_PCAL6416A + +#ifdef DEBUG_PCAL6416A + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef ERROR_PCAL6416A + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_ERROR(...) +#endif + +/* Structure to map I2C address and I2C GPIO expander name */ +typedef struct { + unsigned int address; + char *name; +} i2c_expander_t; + +/* PCAL6416A/PCAL9539A I2C GPIO expander chip pseudo-file descriptor */ +static int fd_i2c_expander; + +/* The I2C bus pseudo-file name */ +static char i2c0_sysfs_filename[] = "/dev/i2c-0"; + +/* PCAL6416A/PCAL9539A I2C GPIO expander chip I2C address */ +static unsigned int i2c_expander_addr; + +/* Map of I2C addresses / GPIO expander name */ +static i2c_expander_t i2c_chip[] = { + {PCAL9539A_I2C_ADDR, "PCAL9539A"}, + {PCAL6416A_I2C_ADDR, "PCAL6416A"}, + {0, NULL} +}; + +/* Initialize the PCAL6416A/PCAL9539A I2C GPIO expander chip */ +bool pcal6416a_init(void) +{ + int i; + + /* Open the I2C bus pseudo-file */ + if ((fd_i2c_expander = open(i2c0_sysfs_filename,O_RDWR)) < 0) { + LOG_ERROR("Failed to open the I2C bus %s", i2c0_sysfs_filename); + return false; + } + + /* Probing known I2C GPIO expander chips */ + for (i = 0, i2c_expander_addr = 0; i2c_chip[i].address; i++) { + + if (ioctl(fd_i2c_expander, I2C_SLAVE_FORCE, i2c_chip[i]) < 0 || + pcal6416a_read_mask_interrupts() < 0) { + LOG_DEBUG("Failed to acquire bus access and/or talk to slave %s at address 0x%02X.\n", + i2c_chip[i].name, i2c_chip[i].address); + } else { + LOG_DEBUG("Found I2C gpio expander chip %s at address 0x%02X\n", + i2c_chip[i].name, i2c_chip[i].address); + i2c_expander_addr = i2c_chip[i].address; + break; + } + } + + /* GPIO expander chip found? */ + if (!i2c_expander_addr) { + LOG_ERROR("Failed to acquire bus access and/or talk to slave, exit\n"); + return false; + } + i2c_smbus_write_word_data ( fd_i2c_expander, PCAL6416A_CONFIG, 0xffff); + i2c_smbus_write_word_data ( fd_i2c_expander, PCAL6416A_INPUT_LATCH, 0x0000); + i2c_smbus_write_word_data ( fd_i2c_expander, PCAL6416A_EN_PULLUPDOWN, 0xffff); + i2c_smbus_write_word_data ( fd_i2c_expander, PCAL6416A_SEL_PULLUPDOWN, 0xffff); + i2c_smbus_write_word_data ( fd_i2c_expander, PCAL6416A_INT_MASK, 0x0320); + return true; +} + +/* Deinitialize the PCAL6416A/PCAL9539A I2C GPIO expander chip */ +bool pcal6416a_deinit(void) +{ + + /* Close the I2C bus pseudo-file */ + close(fd_i2c_expander); + return true; +} + +/* Read the PCAL6416A/PCAL9539A I2C GPIO expander chip interrupt register */ +int pcal6416a_read_mask_interrupts(void) +{ + int val_int; + uint16_t val; + + val_int = i2c_smbus_read_word_data(fd_i2c_expander, PCAL6416A_INT_STATUS); + if (val_int < 0) { + return val_int; + } + val = val_int & 0xFFFF; + LOG_DEBUG("READ PCAL6416A_INT_STATUS : 0x%04X\n", val); + return (int) val; +} + +/* Read the PCAL6416A/PCAL9539A I2C GPIO expander chip active GPIO register */ +int pcal6416a_read_mask_active_GPIOs(void) +{ + int val_int; + uint16_t val; + + val_int = i2c_smbus_read_word_data(fd_i2c_expander, PCAL6416A_INPUT); + if (val_int < 0){ + return val_int; + } + val = val_int & 0xFFFF; + val = 0xFFFF - val; + LOG_DEBUG("READ PCAL6416A_INPUT (active GPIOs) : 0x%04X\n", val); + return (int) val; +} diff --git a/gpio_pcal6416a.h b/gpio_pcal6416a.h new file mode 100755 index 0000000..6a8bec0 --- /dev/null +++ b/gpio_pcal6416a.h @@ -0,0 +1,57 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_pcal6416a.h + * This is userland GPIO driver for the PCAL6416AHB I2C GPIO expander chip + */ + +#ifndef _GPIO_PCAL6416A_H_ +#define _GPIO_PCAL6416A_H_ + + +#include + +/* Chip physical address */ +#define PCAL6416A_I2C_ADDR 0x20 +#define PCAL9539A_I2C_ADDR 0x76 + +/* Chip register adresses */ +#define PCAL6416A_INPUT 0x00 /* Input port [RO] */ +#define PCAL6416A_DAT_OUT 0x02 /* GPIO DATA OUT [R/W] */ +#define PCAL6416A_POLARITY 0x04 /* Polarity Inversion port [R/W] */ +#define PCAL6416A_CONFIG 0x06 /* Configuration port [R/W] */ +#define PCAL6416A_DRIVE0 0x40 /* Output drive strength Port0 [R/W] */ +#define PCAL6416A_DRIVE1 0x42 /* Output drive strength Port1 [R/W] */ +#define PCAL6416A_INPUT_LATCH 0x44 /* Port0 Input latch [R/W] */ +#define PCAL6416A_EN_PULLUPDOWN 0x46 /* Port0 Pull-up/Pull-down enbl [R/W] */ +#define PCAL6416A_SEL_PULLUPDOWN 0x48 /* Port0 Pull-up/Pull-down slct [R/W] */ +#define PCAL6416A_INT_MASK 0x4A /* Interrupt mask [R/W] */ +#define PCAL6416A_INT_STATUS 0x4C /* Interrupt status [RO] */ +#define PCAL6416A_OUTPUT_CONFIG 0x4F /* Output port config [R/W] */ + +bool pcal6416a_init(void); +bool pcal6416a_deinit(void); +int pcal6416a_read_mask_interrupts(void); +int pcal6416a_read_mask_active_GPIOs(void); + +#endif //_GPIO_PCAL6416A_H_ diff --git a/gpio_utils.c b/gpio_utils.c new file mode 100755 index 0000000..9170a49 --- /dev/null +++ b/gpio_utils.c @@ -0,0 +1,170 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_utils.c + * This file contains the GPIO utility functions + */ + +#include +#include +#include +#include +#include +#include "gpio_utils.h" + +#define SYSFS_GPIO_DIR "/sys/class/gpio" +#define MAX_BUF 64 + +/* Export a GPIO in the sysfs pseudo-filesystem */ +int gpio_export(unsigned int gpio) +{ + int fd, len; + char buf[MAX_BUF]; + + fd = open(SYSFS_GPIO_DIR "/export", O_WRONLY); + if (fd < 0) { + perror("gpio/export"); + return fd; + } + len = snprintf(buf, sizeof (buf), "%d", gpio); + write(fd, buf, len); + close(fd); + return 0; +} + +/* Unexport a GPIO in the sysfs pseudo-filesystem */ +int gpio_unexport(unsigned int gpio) +{ + int fd, len; + char buf[MAX_BUF]; + + fd = open(SYSFS_GPIO_DIR "/unexport", O_WRONLY); + if (fd < 0) { + perror("gpio/export"); + return fd; + } + len = snprintf(buf, sizeof (buf), "%d", gpio); + write(fd, buf, len); + close(fd); + return 0; +} + +/* Set a GPIO direction in the sysfs pseudo-filesystem */ +int gpio_set_dir(unsigned int gpio, const char* dir) +{ + int fd; + char buf[MAX_BUF]; + + snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR "/gpio%d/direction", gpio); + fd = open(buf, O_WRONLY); + if (fd < 0) { + perror("gpio/direction"); + return fd; + } + write(fd, dir, sizeof (dir)+1); + close(fd); + return 0; +} + +/* Set a GPIO value in the sysfs pseudo-filesystem */ +int gpio_set_value(unsigned int gpio, unsigned int value) +{ + int fd; + char buf[MAX_BUF]; + + snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio); + fd = open(buf, O_WRONLY); + if (fd < 0) { + perror("gpio/set-value"); + return fd; + } + if (value) { + write(fd, "1", 2); + } else { + write(fd, "0", 2); + } + close(fd); + return 0; +} + +/* Get a GPIO value from the sysfs pseudo-filesystem */ +int gpio_get_value(unsigned int gpio, unsigned int *value) +{ + int fd; + char buf[MAX_BUF]; + char ch; + + snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio); + fd = open(buf, O_RDONLY); + if (fd < 0) { + perror("gpio/get-value"); + return fd; + } + read(fd, &ch, 1); + if (ch != '0') { + *value = 1; + } else { + *value = 0; + } + close(fd); + return 0; +} + +/* Set a GPIO interrupt edge in the sysfs pseudo-filesystem, must be a string + * among "none", "rising", "falling", or "both" + */ +int gpio_set_edge(unsigned int gpio, const char *edge) +{ + int fd; + char buf[MAX_BUF]; + + snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR "/gpio%d/edge", gpio); + fd = open(buf, O_WRONLY); + if (fd < 0) { + perror("gpio/set-edge"); + return fd; + } + write(fd, edge, strlen(edge) + 1); + close(fd); + return 0; +} + +/* Open a GPIO pseudo-file from the sysfs pseudo-filesystem */ +int gpio_fd_open(unsigned int gpio, unsigned int dir) +{ + int fd; + char buf[MAX_BUF]; + + snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio); + fd = open(buf, dir | O_NONBLOCK ); + if (fd < 0) { + perror("gpio/fd_open"); + } + return fd; +} + +/* Close a GPIO pseudo-file from the sysfs pseudo-filesystem */ +int gpio_fd_close(int fd) +{ + return close(fd); +} diff --git a/gpio_utils.h b/gpio_utils.h new file mode 100755 index 0000000..b5bf57b --- /dev/null +++ b/gpio_utils.h @@ -0,0 +1,40 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file gpio_utils.h + * This file contains the GPIO utility functions + */ + +#ifndef _GPIO_UTILS_H_ +#define _GPIO_UTILS_H_ + +int gpio_export(unsigned int gpio); +int gpio_unexport(unsigned int gpio); +int gpio_set_dir(unsigned int gpio, const char *dir); +int gpio_set_value(unsigned int gpio, unsigned int value); +int gpio_get_value(unsigned int gpio, unsigned int *value); +int gpio_set_edge(unsigned int gpio, const char *edge); +int gpio_fd_open(unsigned int gpio, unsigned int dir); +int gpio_fd_close(int fd); + +#endif // _GPIO_UTILS_H_ diff --git a/keydefs.c b/keydefs.c new file mode 100644 index 0000000..21b1d43 --- /dev/null +++ b/keydefs.c @@ -0,0 +1,575 @@ +/**** keydefs.c ****************************/ +/* M. Moller 2013-01-16 */ +/* Universal RPi GPIO keyboard daemon */ +/*******************************************/ + +/* + Copyright (C) 2013 Michael Moller. + This file is part of the Universal Raspberry Pi GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +#include "keydefs.h" + +const key_names_s key_names[] = { +/* + a subset of + sed 's/^#define \([^ \t]\+\)[ \t]*\([^\ \t]\+\)/ { \"\1\",\t\2 },/' /usr/include/linux/input.h + */ + { "KEY_RESERVED", 0 }, + { "KEY_ESC", 1 }, + { "KEY_1", 2 }, + { "KEY_2", 3 }, + { "KEY_3", 4 }, + { "KEY_4", 5 }, + { "KEY_5", 6 }, + { "KEY_6", 7 }, + { "KEY_7", 8 }, + { "KEY_8", 9 }, + { "KEY_9", 10 }, + { "KEY_0", 11 }, + { "KEY_MINUS", 12 }, + { "KEY_EQUAL", 13 }, + { "KEY_BACKSPACE", 14 }, + { "KEY_TAB", 15 }, + { "KEY_Q", 16 }, + { "KEY_W", 17 }, + { "KEY_E", 18 }, + { "KEY_R", 19 }, + { "KEY_T", 20 }, + { "KEY_Y", 21 }, + { "KEY_U", 22 }, + { "KEY_I", 23 }, + { "KEY_O", 24 }, + { "KEY_P", 25 }, + { "KEY_LEFTBRACE", 26 }, + { "KEY_RIGHTBRACE", 27 }, + { "KEY_ENTER", 28 }, + { "KEY_LEFTCTRL", 29 }, + { "KEY_A", 30 }, + { "KEY_S", 31 }, + { "KEY_D", 32 }, + { "KEY_F", 33 }, + { "KEY_G", 34 }, + { "KEY_H", 35 }, + { "KEY_J", 36 }, + { "KEY_K", 37 }, + { "KEY_L", 38 }, + { "KEY_SEMICOLON", 39 }, + { "KEY_APOSTROPHE", 40 }, + { "KEY_GRAVE", 41 }, + { "KEY_LEFTSHIFT", 42 }, + { "KEY_BACKSLASH", 43 }, + { "KEY_Z", 44 }, + { "KEY_X", 45 }, + { "KEY_C", 46 }, + { "KEY_V", 47 }, + { "KEY_B", 48 }, + { "KEY_N", 49 }, + { "KEY_M", 50 }, + { "KEY_COMMA", 51 }, + { "KEY_DOT", 52 }, + { "KEY_SLASH", 53 }, + { "KEY_RIGHTSHIFT", 54 }, + { "KEY_KPASTERISK", 55 }, + { "KEY_LEFTALT", 56 }, + { "KEY_SPACE", 57 }, + { "KEY_CAPSLOCK", 58 }, + { "KEY_F1", 59 }, + { "KEY_F2", 60 }, + { "KEY_F3", 61 }, + { "KEY_F4", 62 }, + { "KEY_F5", 63 }, + { "KEY_F6", 64 }, + { "KEY_F7", 65 }, + { "KEY_F8", 66 }, + { "KEY_F9", 67 }, + { "KEY_F10", 68 }, + { "KEY_NUMLOCK", 69 }, + { "KEY_SCROLLLOCK", 70 }, + { "KEY_KP7", 71 }, + { "KEY_KP8", 72 }, + { "KEY_KP9", 73 }, + { "KEY_KPMINUS", 74 }, + { "KEY_KP4", 75 }, + { "KEY_KP5", 76 }, + { "KEY_KP6", 77 }, + { "KEY_KPPLUS", 78 }, + { "KEY_KP1", 79 }, + { "KEY_KP2", 80 }, + { "KEY_KP3", 81 }, + { "KEY_KP0", 82 }, + { "KEY_KPDOT", 83 }, + + { "KEY_ZENKAKUHANKAKU", 85 }, + { "KEY_102ND", 86 }, + { "KEY_F11", 87 }, + { "KEY_F12", 88 }, + { "KEY_RO", 89 }, + { "KEY_KATAKANA", 90 }, + { "KEY_HIRAGANA", 91 }, + { "KEY_HENKAN", 92 }, + { "KEY_KATAKANAHIRAGANA", 93 }, + { "KEY_MUHENKAN", 94 }, + { "KEY_KPJPCOMMA", 95 }, + { "KEY_KPENTER", 96 }, + { "KEY_RIGHTCTRL", 97 }, + { "KEY_KPSLASH", 98 }, + { "KEY_SYSRQ", 99 }, + { "KEY_RIGHTALT", 100 }, + { "KEY_LINEFEED", 101 }, + { "KEY_HOME", 102 }, + { "KEY_UP", 103 }, + { "KEY_PAGEUP", 104 }, + { "KEY_LEFT", 105 }, + { "KEY_RIGHT", 106 }, + { "KEY_END", 107 }, + { "KEY_DOWN", 108 }, + { "KEY_PAGEDOWN", 109 }, + { "KEY_INSERT", 110 }, + { "KEY_DELETE", 111 }, + { "KEY_MACRO", 112 }, + { "KEY_MUTE", 113 }, + { "KEY_VOLUMEDOWN", 114 }, + { "KEY_VOLUMEUP", 115 }, + { "KEY_POWER", 116 }, /* SC System Power Down */ + { "KEY_KPEQUAL", 117 }, + { "KEY_KPPLUSMINUS", 118 }, + { "KEY_PAUSE", 119 }, + { "KEY_SCALE", 120 }, /* AL Compiz Scale (Expose) */ + + { "KEY_KPCOMMA", 121 }, + { "KEY_HANGEUL", 122 }, + { "KEY_HANGUEL", 122 /*KEY_HANGEUL*/ }, + { "KEY_HANJA", 123 }, + { "KEY_YEN", 124 }, + { "KEY_LEFTMETA", 125 }, + { "KEY_RIGHTMETA", 126 }, + { "KEY_COMPOSE", 127 }, + + { "KEY_STOP", 128 }, /* AC Stop */ + { "KEY_AGAIN", 129 }, + { "KEY_PROPS", 130 }, /* AC Properties */ + { "KEY_UNDO", 131 }, /* AC Undo */ + { "KEY_FRONT", 132 }, + { "KEY_COPY", 133 }, /* AC Copy */ + { "KEY_OPEN", 134 }, /* AC Open */ + { "KEY_PASTE", 135 }, /* AC Paste */ + { "KEY_FIND", 136 }, /* AC Search */ + { "KEY_CUT", 137 }, /* AC Cut */ + { "KEY_HELP", 138 }, /* AL Integrated Help Center */ + { "KEY_MENU", 139 }, /* Menu (show menu) */ + { "KEY_CALC", 140 }, /* AL Calculator */ + { "KEY_SETUP", 141 }, + { "KEY_SLEEP", 142 }, /* SC System Sleep */ + { "KEY_WAKEUP", 143 }, /* System Wake Up */ + { "KEY_FILE", 144 }, /* AL Local Machine Browser */ + { "KEY_SENDFILE", 145 }, + { "KEY_DELETEFILE", 146 }, + { "KEY_XFER", 147 }, + { "KEY_PROG1", 148 }, + { "KEY_PROG2", 149 }, + { "KEY_WWW", 150 }, /* AL Internet Browser */ + { "KEY_MSDOS", 151 }, + { "KEY_COFFEE", 152 }, /* AL Terminal Lock/Screensaver */ + { "KEY_SCREENLOCK", 152 /*KEY_COFFEE*/ }, + { "KEY_DIRECTION", 153 }, + { "KEY_CYCLEWINDOWS", 154 }, + { "KEY_MAIL", 155 }, + { "KEY_BOOKMARKS", 156 }, /* AC Bookmarks */ + { "KEY_COMPUTER", 157 }, + { "KEY_BACK", 158 }, /* AC Back */ + { "KEY_FORWARD", 159 }, /* AC Forward */ + { "KEY_CLOSECD", 160 }, + { "KEY_EJECTCD", 161 }, + { "KEY_EJECTCLOSECD", 162 }, + { "KEY_NEXTSONG", 163 }, + { "KEY_PLAYPAUSE", 164 }, + { "KEY_PREVIOUSSONG", 165 }, + { "KEY_STOPCD", 166 }, + { "KEY_RECORD", 167 }, + { "KEY_REWIND", 168 }, + { "KEY_PHONE", 169 }, /* Media Select Telephone */ + { "KEY_ISO", 170 }, + { "KEY_CONFIG", 171 }, /* AL Consumer Control Configuration */ + { "KEY_HOMEPAGE", 172 }, /* AC Home */ + { "KEY_REFRESH", 173 }, /* AC Refresh */ + { "KEY_EXIT", 174 }, /* AC Exit */ + { "KEY_MOVE", 175 }, + { "KEY_EDIT", 176 }, + { "KEY_SCROLLUP", 177 }, + { "KEY_SCROLLDOWN", 178 }, + { "KEY_KPLEFTPAREN", 179 }, + { "KEY_KPRIGHTPAREN", 180 }, + { "KEY_NEW", 181 }, /* AC New */ + { "KEY_REDO", 182 }, /* AC Redo/Repeat */ + + { "KEY_F13", 183 }, + { "KEY_F14", 184 }, + { "KEY_F15", 185 }, + { "KEY_F16", 186 }, + { "KEY_F17", 187 }, + { "KEY_F18", 188 }, + { "KEY_F19", 189 }, + { "KEY_F20", 190 }, + { "KEY_F21", 191 }, + { "KEY_F22", 192 }, + { "KEY_F23", 193 }, + { "KEY_F24", 194 }, + + { "KEY_PLAYCD", 200 }, + { "KEY_PAUSECD", 201 }, + { "KEY_PROG3", 202 }, + { "KEY_PROG4", 203 }, + { "KEY_DASHBOARD", 204 }, /* AL Dashboard */ + { "KEY_SUSPEND", 205 }, + { "KEY_CLOSE", 206 }, /* AC Close */ + { "KEY_PLAY", 207 }, + { "KEY_FASTFORWARD", 208 }, + { "KEY_BASSBOOST", 209 }, + { "KEY_PRINT", 210 }, /* AC Print */ + { "KEY_HP", 211 }, + { "KEY_CAMERA", 212 }, + { "KEY_SOUND", 213 }, + { "KEY_QUESTION", 214 }, + { "KEY_EMAIL", 215 }, + { "KEY_CHAT", 216 }, + { "KEY_SEARCH", 217 }, + { "KEY_CONNECT", 218 }, + { "KEY_FINANCE", 219 }, /* AL Checkbook/Finance */ + { "KEY_SPORT", 220 }, + { "KEY_SHOP", 221 }, + { "KEY_ALTERASE", 222 }, + { "KEY_CANCEL", 223 }, /* AC Cancel */ + { "KEY_BRIGHTNESSDOWN", 224 }, + { "KEY_BRIGHTNESSUP", 225 }, + { "KEY_MEDIA", 226 }, + + { "KEY_SWITCHVIDEOMODE", 227 }, /* Cycle between available video + outputs (Monitor/LCD/TV-out/etc) */ + { "KEY_KBDILLUMTOGGLE", 228 }, + { "KEY_KBDILLUMDOWN", 229 }, + { "KEY_KBDILLUMUP", 230 }, + + { "KEY_SEND", 231 }, /* AC Send */ + { "KEY_REPLY", 232 }, /* AC Reply */ + { "KEY_FORWARDMAIL", 233 }, /* AC Forward Msg */ + { "KEY_SAVE", 234 }, /* AC Save */ + { "KEY_DOCUMENTS", 235 }, + + { "KEY_BATTERY", 236 }, + + { "KEY_BLUETOOTH", 237 }, + { "KEY_WLAN", 238 }, + { "KEY_UWB", 239 }, + + { "KEY_UNKNOWN", 240 }, + + { "KEY_VIDEO_NEXT", 241 }, /* drive next video source */ + { "KEY_VIDEO_PREV", 242 }, /* drive previous video source */ + { "KEY_BRIGHTNESS_CYCLE", 243 }, /* brightness up, after max is min */ + { "KEY_BRIGHTNESS_ZERO", 244 }, /* brightness off, use ambient */ + { "KEY_DISPLAY_OFF", 245 }, /* display device to off state */ + + { "KEY_WIMAX", 246 }, + { "KEY_RFKILL", 247 }, /* Key that controls all radios */ + + { "KEY_MICMUTE", 248 }, /* Mute / unmute the microphone */ + +/* Code 255 is reserved for special needs of AT keyboard driver */ + + { "BTN_MISC", 0x100 }, + { "BTN_0", 0x100 }, + { "BTN_1", 0x101 }, + { "BTN_2", 0x102 }, + { "BTN_3", 0x103 }, + { "BTN_4", 0x104 }, + { "BTN_5", 0x105 }, + { "BTN_6", 0x106 }, + { "BTN_7", 0x107 }, + { "BTN_8", 0x108 }, + { "BTN_9", 0x109 }, + + { "BTN_MOUSE", 0x110 }, + { "BTN_LEFT", 0x110 }, + { "BTN_RIGHT", 0x111 }, + { "BTN_MIDDLE", 0x112 }, + { "BTN_SIDE", 0x113 }, + { "BTN_EXTRA", 0x114 }, + { "BTN_FORWARD", 0x115 }, + { "BTN_BACK", 0x116 }, + { "BTN_TASK", 0x117 }, + + { "BTN_JOYSTICK", 0x120 }, + { "BTN_TRIGGER", 0x120 }, + { "BTN_THUMB", 0x121 }, + { "BTN_THUMB2", 0x122 }, + { "BTN_TOP", 0x123 }, + { "BTN_TOP2", 0x124 }, + { "BTN_PINKIE", 0x125 }, + { "BTN_BASE", 0x126 }, + { "BTN_BASE2", 0x127 }, + { "BTN_BASE3", 0x128 }, + { "BTN_BASE4", 0x129 }, + { "BTN_BASE5", 0x12a }, + { "BTN_BASE6", 0x12b }, + { "BTN_DEAD", 0x12f }, + + { "BTN_GAMEPAD", 0x130 }, + { "BTN_A", 0x130 }, + { "BTN_B", 0x131 }, + { "BTN_C", 0x132 }, + { "BTN_X", 0x133 }, + { "BTN_Y", 0x134 }, + { "BTN_Z", 0x135 }, + { "BTN_TL", 0x136 }, + { "BTN_TR", 0x137 }, + { "BTN_TL2", 0x138 }, + { "BTN_TR2", 0x139 }, + { "BTN_SELECT", 0x13a }, + { "BTN_START", 0x13b }, + { "BTN_MODE", 0x13c }, + { "BTN_THUMBL", 0x13d }, + { "BTN_THUMBR", 0x13e }, + +#if 0 + + { "BTN_DIGI", 0x140 }, + { "BTN_TOOL_PEN", 0x140 }, + { "BTN_TOOL_RUBBER", 0x141 }, + { "BTN_TOOL_BRUSH", 0x142 }, + { "BTN_TOOL_PENCIL", 0x143 }, + { "BTN_TOOL_AIRBRUSH", 0x144 }, + { "BTN_TOOL_FINGER", 0x145 }, + { "BTN_TOOL_MOUSE", 0x146 }, + { "BTN_TOOL_LENS", 0x147 }, + { "BTN_TOOL_QUINTTAP", 0x148 }, /* Five fingers on trackpad */ + { "BTN_TOUCH", 0x14a }, + { "BTN_STYLUS", 0x14b }, + { "BTN_STYLUS2", 0x14c }, + { "BTN_TOOL_DOUBLETAP", 0x14d }, + { "BTN_TOOL_TRIPLETAP", 0x14e }, + { "BTN_TOOL_QUADTAP", 0x14f }, /* Four fingers on trackpad */ + + { "BTN_WHEEL", 0x150 }, + { "BTN_GEAR_DOWN", 0x150 }, + { "BTN_GEAR_UP", 0x151 }, + + { "KEY_OK", 0x160 }, + { "KEY_SELECT", 0x161 }, + { "KEY_GOTO", 0x162 }, + { "KEY_CLEAR", 0x163 }, + { "KEY_POWER2", 0x164 }, + { "KEY_OPTION", 0x165 }, + { "KEY_INFO", 0x166 }, /* AL OEM Features/Tips/Tutorial */ + { "KEY_TIME", 0x167 }, + { "KEY_VENDOR", 0x168 }, + { "KEY_ARCHIVE", 0x169 }, + { "KEY_PROGRAM", 0x16a }, /* Media Select Program Guide */ + { "KEY_CHANNEL", 0x16b }, + { "KEY_FAVORITES", 0x16c }, + { "KEY_EPG", 0x16d }, + { "KEY_PVR", 0x16e }, /* Media Select Home */ + { "KEY_MHP", 0x16f }, + { "KEY_LANGUAGE", 0x170 }, + { "KEY_TITLE", 0x171 }, + { "KEY_SUBTITLE", 0x172 }, + { "KEY_ANGLE", 0x173 }, + { "KEY_ZOOM", 0x174 }, + { "KEY_MODE", 0x175 }, + { "KEY_KEYBOARD", 0x176 }, + { "KEY_SCREEN", 0x177 }, + { "KEY_PC", 0x178 }, /* Media Select Computer */ + { "KEY_TV", 0x179 }, /* Media Select TV */ + { "KEY_TV2", 0x17a }, /* Media Select Cable */ + { "KEY_VCR", 0x17b }, /* Media Select VCR */ + { "KEY_VCR2", 0x17c }, /* VCR Plus */ + { "KEY_SAT", 0x17d }, /* Media Select Satellite */ + { "KEY_SAT2", 0x17e }, + { "KEY_CD", 0x17f }, /* Media Select CD */ + { "KEY_TAPE", 0x180 }, /* Media Select Tape */ + { "KEY_RADIO", 0x181 }, + { "KEY_TUNER", 0x182 }, /* Media Select Tuner */ + { "KEY_PLAYER", 0x183 }, + { "KEY_TEXT", 0x184 }, + { "KEY_DVD", 0x185 }, /* Media Select DVD */ + { "KEY_AUX", 0x186 }, + { "KEY_MP3", 0x187 }, + { "KEY_AUDIO", 0x188 }, /* AL Audio Browser */ + { "KEY_VIDEO", 0x189 }, /* AL Movie Browser */ + { "KEY_DIRECTORY", 0x18a }, + { "KEY_LIST", 0x18b }, + { "KEY_MEMO", 0x18c }, /* Media Select Messages */ + { "KEY_CALENDAR", 0x18d }, + { "KEY_RED", 0x18e }, + { "KEY_GREEN", 0x18f }, + { "KEY_YELLOW", 0x190 }, + { "KEY_BLUE", 0x191 }, + { "KEY_CHANNELUP", 0x192 }, /* Channel Increment */ + { "KEY_CHANNELDOWN", 0x193 }, /* Channel Decrement */ + { "KEY_FIRST", 0x194 }, + { "KEY_LAST", 0x195 }, /* Recall Last */ + { "KEY_AB", 0x196 }, + { "KEY_NEXT", 0x197 }, + { "KEY_RESTART", 0x198 }, + { "KEY_SLOW", 0x199 }, + { "KEY_SHUFFLE", 0x19a }, + { "KEY_BREAK", 0x19b }, + { "KEY_PREVIOUS", 0x19c }, + { "KEY_DIGITS", 0x19d }, + { "KEY_TEEN", 0x19e }, + { "KEY_TWEN", 0x19f }, + { "KEY_VIDEOPHONE", 0x1a0 }, /* Media Select Video Phone */ + { "KEY_GAMES", 0x1a1 }, /* Media Select Games */ + { "KEY_ZOOMIN", 0x1a2 }, /* AC Zoom In */ + { "KEY_ZOOMOUT", 0x1a3 }, /* AC Zoom Out */ + { "KEY_ZOOMRESET", 0x1a4 }, /* AC Zoom */ + { "KEY_WORDPROCESSOR", 0x1a5 }, /* AL Word Processor */ + { "KEY_EDITOR", 0x1a6 }, /* AL Text Editor */ + { "KEY_SPREADSHEET", 0x1a7 }, /* AL Spreadsheet */ + { "KEY_GRAPHICSEDITOR", 0x1a8 }, /* AL Graphics Editor */ + { "KEY_PRESENTATION", 0x1a9 }, /* AL Presentation App */ + { "KEY_DATABASE", 0x1aa }, /* AL Database App */ + { "KEY_NEWS", 0x1ab }, /* AL Newsreader */ + { "KEY_VOICEMAIL", 0x1ac }, /* AL Voicemail */ + { "KEY_ADDRESSBOOK", 0x1ad }, /* AL Contacts/Address Book */ + { "KEY_MESSENGER", 0x1ae }, /* AL Instant Messaging */ + { "KEY_DISPLAYTOGGLE", 0x1af }, /* Turn display (LCD) on and off */ + { "KEY_SPELLCHECK", 0x1b0 }, /* AL Spell Check */ + { "KEY_LOGOFF", 0x1b1 }, /* AL Logoff */ + + { "KEY_DOLLAR", 0x1b2 }, + { "KEY_EURO", 0x1b3 }, + + { "KEY_FRAMEBACK", 0x1b4 }, /* Consumer - transport controls */ + { "KEY_FRAMEFORWARD", 0x1b5 }, + { "KEY_CONTEXT_MENU", 0x1b6 }, /* GenDesc - system context menu */ + { "KEY_MEDIA_REPEAT", 0x1b7 }, /* Consumer - transport control */ + { "KEY_10CHANNELSUP", 0x1b8 }, /* 10 channels up (10+) */ + { "KEY_10CHANNELSDOWN", 0x1b9 }, /* 10 channels down (10-) */ + { "KEY_IMAGES", 0x1ba }, /* AL Image Browser */ + + { "KEY_DEL_EOL", 0x1c0 }, + { "KEY_DEL_EOS", 0x1c1 }, + { "KEY_INS_LINE", 0x1c2 }, + { "KEY_DEL_LINE", 0x1c3 }, + + { "KEY_FN", 0x1d0 }, + { "KEY_FN_ESC", 0x1d1 }, + { "KEY_FN_F1", 0x1d2 }, + { "KEY_FN_F2", 0x1d3 }, + { "KEY_FN_F3", 0x1d4 }, + { "KEY_FN_F4", 0x1d5 }, + { "KEY_FN_F5", 0x1d6 }, + { "KEY_FN_F6", 0x1d7 }, + { "KEY_FN_F7", 0x1d8 }, + { "KEY_FN_F8", 0x1d9 }, + { "KEY_FN_F9", 0x1da }, + { "KEY_FN_F10", 0x1db }, + { "KEY_FN_F11", 0x1dc }, + { "KEY_FN_F12", 0x1dd }, + { "KEY_FN_1", 0x1de }, + { "KEY_FN_2", 0x1df }, + { "KEY_FN_D", 0x1e0 }, + { "KEY_FN_E", 0x1e1 }, + { "KEY_FN_F", 0x1e2 }, + { "KEY_FN_S", 0x1e3 }, + { "KEY_FN_B", 0x1e4 }, + + { "KEY_BRL_DOT1", 0x1f1 }, + { "KEY_BRL_DOT2", 0x1f2 }, + { "KEY_BRL_DOT3", 0x1f3 }, + { "KEY_BRL_DOT4", 0x1f4 }, + { "KEY_BRL_DOT5", 0x1f5 }, + { "KEY_BRL_DOT6", 0x1f6 }, + { "KEY_BRL_DOT7", 0x1f7 }, + { "KEY_BRL_DOT8", 0x1f8 }, + { "KEY_BRL_DOT9", 0x1f9 }, + { "KEY_BRL_DOT10", 0x1fa }, + + { "KEY_NUMERIC_0", 0x200 }, /* used by phones, remote controls, */ + { "KEY_NUMERIC_1", 0x201 }, /* and other keypads */ + { "KEY_NUMERIC_2", 0x202 }, + { "KEY_NUMERIC_3", 0x203 }, + { "KEY_NUMERIC_4", 0x204 }, + { "KEY_NUMERIC_5", 0x205 }, + { "KEY_NUMERIC_6", 0x206 }, + { "KEY_NUMERIC_7", 0x207 }, + { "KEY_NUMERIC_8", 0x208 }, + { "KEY_NUMERIC_9", 0x209 }, + { "KEY_NUMERIC_STAR", 0x20a }, + { "KEY_NUMERIC_POUND", 0x20b }, + + { "KEY_CAMERA_FOCUS", 0x210 }, + { "KEY_WPS_BUTTON", 0x211 }, /* WiFi Protected Setup key */ + + { "KEY_TOUCHPAD_TOGGLE", 0x212 }, /* Request switch touchpad on or off */ + { "KEY_TOUCHPAD_ON", 0x213 }, + { "KEY_TOUCHPAD_OFF", 0x214 }, + + { "KEY_CAMERA_ZOOMIN", 0x215 }, + { "KEY_CAMERA_ZOOMOUT", 0x216 }, + { "KEY_CAMERA_UP", 0x217 }, + { "KEY_CAMERA_DOWN", 0x218 }, + { "KEY_CAMERA_LEFT", 0x219 }, + { "KEY_CAMERA_RIGHT", 0x21a }, + + { "BTN_TRIGGER_HAPPY", 0x2c0 }, + { "BTN_TRIGGER_HAPPY1", 0x2c0 }, + { "BTN_TRIGGER_HAPPY2", 0x2c1 }, + { "BTN_TRIGGER_HAPPY3", 0x2c2 }, + { "BTN_TRIGGER_HAPPY4", 0x2c3 }, + { "BTN_TRIGGER_HAPPY5", 0x2c4 }, + { "BTN_TRIGGER_HAPPY6", 0x2c5 }, + { "BTN_TRIGGER_HAPPY7", 0x2c6 }, + { "BTN_TRIGGER_HAPPY8", 0x2c7 }, + { "BTN_TRIGGER_HAPPY9", 0x2c8 }, + { "BTN_TRIGGER_HAPPY10", 0x2c9 }, + { "BTN_TRIGGER_HAPPY11", 0x2ca }, + { "BTN_TRIGGER_HAPPY12", 0x2cb }, + { "BTN_TRIGGER_HAPPY13", 0x2cc }, + { "BTN_TRIGGER_HAPPY14", 0x2cd }, + { "BTN_TRIGGER_HAPPY15", 0x2ce }, + { "BTN_TRIGGER_HAPPY16", 0x2cf }, + { "BTN_TRIGGER_HAPPY17", 0x2d0 }, + { "BTN_TRIGGER_HAPPY18", 0x2d1 }, + { "BTN_TRIGGER_HAPPY19", 0x2d2 }, + { "BTN_TRIGGER_HAPPY20", 0x2d3 }, + { "BTN_TRIGGER_HAPPY21", 0x2d4 }, + { "BTN_TRIGGER_HAPPY22", 0x2d5 }, + { "BTN_TRIGGER_HAPPY23", 0x2d6 }, + { "BTN_TRIGGER_HAPPY24", 0x2d7 }, + { "BTN_TRIGGER_HAPPY25", 0x2d8 }, + { "BTN_TRIGGER_HAPPY26", 0x2d9 }, + { "BTN_TRIGGER_HAPPY27", 0x2da }, + { "BTN_TRIGGER_HAPPY28", 0x2db }, + { "BTN_TRIGGER_HAPPY29", 0x2dc }, + { "BTN_TRIGGER_HAPPY30", 0x2dd }, + { "BTN_TRIGGER_HAPPY31", 0x2de }, + { "BTN_TRIGGER_HAPPY32", 0x2df }, + { "BTN_TRIGGER_HAPPY33", 0x2e0 }, + { "BTN_TRIGGER_HAPPY34", 0x2e1 }, + { "BTN_TRIGGER_HAPPY35", 0x2e2 }, + { "BTN_TRIGGER_HAPPY36", 0x2e3 }, + { "BTN_TRIGGER_HAPPY37", 0x2e4 }, + { "BTN_TRIGGER_HAPPY38", 0x2e5 }, + { "BTN_TRIGGER_HAPPY39", 0x2e6 }, + { "BTN_TRIGGER_HAPPY40", 0x2e7 }, +#endif + + { "LAST", -1 }, +}; diff --git a/keydefs.h b/keydefs.h new file mode 100644 index 0000000..098c81d --- /dev/null +++ b/keydefs.h @@ -0,0 +1,39 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file keydefs.h + * This file contains the key definitions + */ + +#ifndef _KEYDEFS_H_ +#define _KEYDEFS_H_ + +/* Structure to map key names and code */ +typedef struct { + char *name; + int code; +} key_names_s; + +extern const key_names_s key_names[]; + +#endif // _KEYDEFS_H_ diff --git a/main.c b/main.c new file mode 100644 index 0000000..c195852 --- /dev/null +++ b/main.c @@ -0,0 +1,184 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file main.c + * This file contains the main function for the FunKey S GPIO daemon + */ + +#include +#include +#include +#include +#include +#include +#include +#include "to_log.h" +#include "daemon.h" +#include "uinput.h" +#include "gpio_mapping.h" + +#define VERSION "0.0.1" +#define PID_FILE "/var/run/fkgpiod.pid" + +/* Background daemon flag */ +static bool daemon = false; + +/* GPIO configuration file name */ +static const char *config_file = "fkgpiod.conf"; + +/* Print usage information */ +static void print_usage(void) +{ + printf("Usage: fkgpiod [options] [config_file]\n"); + printf("Options:\n"); + printf(" -d, -D, --daemonize Launch as a background daemon\n"); + printf(" -h, -H, --help Print option help\n"); + printf(" -k, -K, --kill Kill background daemon\n"); + printf(" -v, --version Print version information\n"); +} + +/* Print version information */ +static void print_version(void) +{ + printf("fkgpiod version "VERSION"\n"); + printf("FunKey S GPIO daemon\n\n"); + printf("Copyright (C) 2021, Vincent Buso ,\n"); + printf("Copyright (C) 2021, Michel Stempin ,\n"); + printf("All rights reserved.\n"); + printf("Released under the GNU Lesser General Public License version 2.1 or later\n"); +} + +/* Parse command line options */ +static void parse_options(int argc, char *argv[]) +{ + struct option long_options[] = { + {"daemonize", 0, NULL, 0}, + {"help", 0, NULL, 0}, + {"kill", 0, NULL, 0}, + {"version", 0, NULL, 0}, + {0, 0, NULL, 0} + }; + int c, opt; + + while (true) { + c = getopt_long(argc, argv, "dDhHkKvV", long_options, &opt); + if (c == -1) { + + /* End of options */ + break; + } + if (c == 0) { + + /* Match long option names and convert them to short options */ + if (!strcmp(long_options[opt].name, "daemonize")) { + c = 'd'; + } else if (!strcmp(long_options[opt].name, "help")) { + c = 'h'; + } else if (!strcmp(long_options[opt].name, "kill")) { + c = 'k'; + } else if (!strcmp(long_options[opt].name, "version")) { + c = 'v'; + } + } + switch (c) { + case 'd': + case 'D': + + /* Daemonize */ + daemon = true; + break; + + case 'h': + case 'H': + + /* Help */ + print_usage(); + exit(EXIT_SUCCESS); + + case 'k': + case 'K': + + /* Kill running daemon */ + kill_daemon(PID_FILE); + exit(EXIT_SUCCESS); + + case 'v': + case 'V': + + /* Version */ + print_version(); + exit(EXIT_SUCCESS); + + default: + print_usage(); + exit(EXIT_FAILURE); + } + } + if (optind > argc) { + print_usage(); + exit(EXIT_FAILURE); + } else if (optind < argc) { + + /* Last argument is the GPIO confguration file name */ + config_file = strdup(argv[optind]); + } +} + +/* Entry point */ +int main(int argc, char *argv[]) +{ + mapping_list_t mapping_list; + + /* Parse command line options */ + parse_options(argc, argv); + if (daemon) { + + /* Run as a background daemon, redirect all output to syslog */ + openlog("fkgpiod", LOG_PERROR | LOG_PID | LOG_NDELAY, LOG_DAEMON); + to_log(&stdout); + to_log(&stderr); + daemonize("/", PID_FILE); + } + + /* Initialize the uinput device */ + init_uinput(); + + /* Initialize the GPIO mapping */ + init_gpio_mapping(config_file, &mapping_list); + while (true) { + + /* Main loop to handle the GPIOs */ + handle_gpio_mapping(&mapping_list); + } + + /*Deinitialize the GPIO mapping */ + deinit_gpio_mapping(); + + /* Close the uinput device */ + close_uinput(); + if (daemon) { + + /* Close the syslog */ + closelog(); + } + return EXIT_SUCCESS; +} diff --git a/mapping_list.c b/mapping_list.c new file mode 100644 index 0000000..469f819 --- /dev/null +++ b/mapping_list.c @@ -0,0 +1,292 @@ +/* + Copyright (C) 2020-2021 Michel Stempin + Mostly inspired from the Linux kernel lists + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file mapping_list.c + * This file contains the mapping list handling functions + */ + +#include +#include +#include +#include "mapping_list.h" +#include "parse_config.h" + +//#define DEBUG_MAPPING_LIST +#define ERROR_MAPPING_LIST + +#ifdef DEBUG_MAPPING_LIST + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef ERROR_MAPPING_LIST + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_ERROR(...) +#endif + +/* Compute the byte offset of a structure member */ +#undef offsetof +#ifdef __compiler_offsetof +#define offsetof(TYPE, MEMBER) __compiler_offsetof(TYPE, MEMBER) +#else +#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER) +#endif + +/* Retrieve a typed pointer to the structure containing the given member */ +#define container_of(ptr, type, member) ({ \ + void *__mptr = (void *)(ptr); \ + ((type *)(__mptr - offsetof(type, member))); }) + +/* Retrieve a typed list entry containing the given node as member */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/* Loop over the list nodes */ +#define list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/* Loop over the nodes of a list, the node may be destroyed safely during the + * process + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/* Add a mapping between a previous and a next one */ +static inline void list_add_between(struct mapping_list_t *new, + struct mapping_list_t *prev, struct mapping_list_t *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/* Add a mapping to the mapping list head */ +static inline void list_add(struct mapping_list_t *new, + struct mapping_list_t *head) +{ + list_add_between(new, head, head->next); +} + +/* Add a mapping to the mapping list tail */ +static inline void list_add_tail(struct mapping_list_t *new, + struct mapping_list_t *head) +{ + list_add_between(new, head->prev, head); +} + +/* Delete a mapping between a previous and a next one */ +static inline void list_delete_between(struct mapping_list_t *prev, + struct mapping_list_t *next) +{ + next->prev = prev; + prev->next = next; +} + +/* Delete a mapping from the mapping list */ +static inline void list_delete(struct mapping_list_t *entry) +{ + list_delete_between(entry->prev, entry->next); +} + +/* Initalize a mapping list */ +void init_mapping_list(mapping_list_t *list) +{ + list->next = list; + list->prev = list; +} + +/* Empty a mpping list */ +void reset_mapping_list(mapping_list_t *list) +{ + struct mapping_list_t *p, *n; + mapping_t *tmp; + + list_for_each_safe(p, n, list) { + tmp = list_entry(p, mapping_t, mappings); + list_delete(&tmp->mappings); + if (tmp->type == MAPPING_COMMAND) { + if (tmp->value.command != NULL) { + free(tmp->value.command); + } + } + free(tmp); + } +} + +/* Get a type pointer on the first mapping in a mapping list */ +mapping_t *first_mapping(mapping_list_t *list) +{ + return list_entry(list->next, mapping_t, mappings); +} + +/* Get a type pointer on the next mapping in a mapping list */ +mapping_t *next_mapping(mapping_t *mapping) +{ + return list_entry(mapping->mappings.next, __typeof__(*(mapping)), mappings); +} + +/* Check if the mapping is the last in the mapping list */ +bool last_mapping(const mapping_list_t *list, const mapping_t *mapping) +{ + return mapping->mappings.next->prev == list; +} + +/* Allocated and insert a mapping in the mapping list */ +bool insert_mapping(mapping_list_t *list, mapping_t *mapping) +{ + mapping_t *new_mapping, *next_mapping; + struct mapping_list_t *cur; + + new_mapping = (mapping_t *) malloc(sizeof (mapping_t)); + if (new_mapping == NULL) { + return false; + } + new_mapping->gpio_mask = mapping->gpio_mask; + new_mapping->type = mapping->type; + new_mapping->bit_count = mapping->bit_count; + new_mapping->activated = mapping->activated; + switch (mapping->type) { + case MAPPING_COMMAND: + new_mapping->value.command = strdup(mapping->value.command); + break; + + case MAPPING_KEY: + new_mapping->value.keycode = mapping->value.keycode; + break; + + default: + LOG_ERROR("Unknown mapping type %d\n", mapping->type); + return false; + } + + /* Insert the mapping before any mapping with the same count of simultaneous + * GPIOs, the list is thus kept in this order + */ + list_for_each(cur, list) { + next_mapping = list_entry(cur, mapping_t, mappings); + if (next_mapping->bit_count <= mapping->bit_count) { + list_add_between(&new_mapping->mappings, cur->prev, cur); + return true; + } + } + + /* By default, the ne mapping is inserted at the head position */ + list_add(&new_mapping->mappings, list); + return true; +} + +/* Find a mapping in a mappining list with the exact same GPIO mask */ +mapping_t *find_mapping(mapping_list_t *list, uint32_t gpio_mask) +{ + struct mapping_list_t *cur; + mapping_t *mapping; + + list_for_each(cur, list) { + mapping = list_entry(cur, mapping_t, mappings); + if (mapping->gpio_mask == gpio_mask) { + return mapping; + } + } + return NULL; +} + +/* Remove a mapping from the mapping list */ +bool remove_mapping(mapping_list_t *list, mapping_t *mapping) +{ + struct mapping_list_t *p; + mapping_t *tmp; + + list_for_each(p, list) { + tmp = list_entry(p, mapping_t, mappings); + if (tmp == mapping) { + list_delete(&tmp->mappings); + switch (tmp->type) { + case MAPPING_COMMAND: + if (tmp->value.command != NULL) { + free(tmp->value.command); + } + break; + + case MAPPING_KEY: + break; + + default: + LOG_ERROR("Unknown mapping type %d\n", tmp->type); + return false; + } + free(tmp); + return true; + } + } + return false; +} + +/* Dump a mapping */ +void dump_mapping(mapping_t *mapping) +{ + int i; + uint32_t gpio_mask; + + printf("mapping %p, prev %p, next %p\n", mapping, mapping->mappings.prev, + mapping->mappings.next); + printf("gpio_mask 0x%04X bit_count %d activated %s\n", mapping->gpio_mask, + mapping->bit_count, mapping->activated ? "true" : "false"); + printf("button%s ", mapping->bit_count == 1 ? " " : "s"); + for (i = 0, gpio_mask = mapping->gpio_mask; i < MAX_NUM_GPIO; + i++, gpio_mask >>= 1) { + if (gpio_mask & 1) { + printf("%s%s", gpio_name(i), gpio_mask == 1 ? "\n" : "+"); + } + } + switch (mapping->type) { + case MAPPING_COMMAND: + printf("command \"%s\"\n", mapping->value.command); + break; + + case MAPPING_KEY: + printf("keycode %s (%d)\n", keycode_name(mapping->value.keycode), + mapping->value.keycode); + break; + + default: + LOG_ERROR("Unknown mapping type %d\n", mapping->type); + break; + } +} + +/* Dump a mapping list */ +void dump_mapping_list(mapping_list_t *list) +{ + struct mapping_list_t *p; + mapping_t *tmp; + + list_for_each(p, list) { + tmp = list_entry(p, mapping_t, mappings); + dump_mapping(tmp); + printf("\n"); + } +} diff --git a/mapping_list.h b/mapping_list.h new file mode 100644 index 0000000..52f8fd3 --- /dev/null +++ b/mapping_list.h @@ -0,0 +1,72 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file mapping_list.h + * This file contains the mapping list handling functions + */ + +#ifndef _MAPPING_LIST_H_ +#define _MAPPING_LIST_H_ + +#include +#include + +#define MAX_NUM_GPIO 32 + +/* Definition of the different mapping types */ +#define MAPPING_TYPES \ + X(MAPPING_KEY, "KEY") \ + X(MAPPING_COMMAND, "COMMAND") + +/* Enumeration of the different mapping types */ +#undef X +#define X(a, b) a, +typedef enum {MAPPING_TYPES} mapping_type_t; + +typedef struct mapping_list_t { + struct mapping_list_t *next, *prev; +} mapping_list_t; + +typedef struct mapping_t { + struct mapping_list_t mappings; + uint32_t gpio_mask; + mapping_type_t type; + union { + char *command; + int keycode; + } value; + uint8_t bit_count; + bool activated; +} mapping_t; + +void init_mapping_list(mapping_list_t *list); +void reset_mapping_list(mapping_list_t *list); +mapping_t *first_mapping(mapping_list_t *list); +mapping_t *next_mapping(mapping_t *mapping); +bool last_mapping(const mapping_list_t *list, const mapping_t *mapping); +bool insert_mapping(mapping_list_t *list, mapping_t *mapping); +mapping_t *find_mapping(mapping_list_t *list, uint32_t gpio_mask); +bool remove_mapping(mapping_list_t *list, mapping_t *mapping); +void dump_mapping(mapping_t *mapping); +void dump_mapping_list(mapping_list_t *list); + +#endif // _MAPPING_LIST_H_ diff --git a/parse_config.c b/parse_config.c new file mode 100644 index 0000000..fb3c5a3 --- /dev/null +++ b/parse_config.c @@ -0,0 +1,501 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file parse_config.c + * This file contains the configuration parsing functions + */ + +#include +#include +#include +#include +#include +#include +#include +#include "keydefs.h" +#include "mapping_list.h" +#include "parse_config.h" +#include "uinput.h" + +//#define DEBUG_CONFIG +#define ERROR_CONFIG + +#ifdef DEBUG_CONFIG + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef ERROR_CONFIG + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_ERROR(...) +#endif + +#define MAX_BUFFER_LENGTH 256 +#define MAX_LINE_LENGTH 256 + +/* Structure to map command keywords and states */ +typedef struct { + const char *command; + parse_state_t state; +} keyword_t; + +#undef X +#define X(a, b) b, +//static const char *parse_state_names[] = {PARSE_STATES}; + +#undef X +#define X(a, b) b, +static const char *gpio_names[] = {GPIOS}; + +/* Map between command keywords and states */ +static const keyword_t valid_commands[] = { + {"MAP", STATE_MAP}, + {"UNMAP", STATE_UNMAP}, + {"RESET", STATE_RESET}, + {"LOAD", STATE_LOAD}, + {"SLEEP", STATE_SLEEP}, + {"KEYUP", STATE_KEYUP}, + {"KEYDOWN", STATE_KEYDOWN}, + {"KEYPRESS", STATE_KEYPRESS}, + {"TYPE", STATE_TYPE}, + {"HELP", STATE_HELP}, + {"", STATE_INVALID} +}; + +/* Map between function keywords and states */ +static const keyword_t valid_functions[] = { + {"KEY", STATE_KEY}, + {"COMMAND", STATE_COMMAND}, + {"", STATE_INVALID} +}; + +/* The command keywor state */ +static parse_state_t keyword; + +/* Buffer for argument parsing */ +static char buffer[MAX_BUFFER_LENGTH + 1]; + +/* Line buffer for parsing */ +static char line[MAX_LINE_LENGTH + 1]; + +/* Lookup a command parse state from a token */ +static parse_state_t lookup_command(char *token) +{ + int command; + + for (command = 0; valid_commands[command].state != STATE_INVALID; + command++) { + if (strcasecmp(token, valid_commands[command].command) == 0) { + keyword = valid_commands[command].state; + return keyword; + } + } + LOG_ERROR("Invalid keyword \"%s\"\n", token); + return STATE_INVALID; +} + +/* Lookup a function parse state from a token */ +static parse_state_t lookup_function(char *token) +{ + int command; + + for (command = 0; valid_functions[command].state != STATE_INVALID; + command++) { + if (strcasecmp(token, valid_functions[command].command) == 0) { + return valid_functions[command].state; + } + } + LOG_ERROR("Invalid keyword \"%s\"\n", token); + return STATE_INVALID; +} + +/* Lookup a GPIO number from a token */ +static int lookup_gpio(char *token) +{ + int button; + + for (button = 0; gpio_names[button] != NULL; button++) { + if (strcasecmp(token, gpio_names[button]) == 0) { + LOG_DEBUG("Found button \"%s\" (GPIO %d)\n", gpio_names[button], + button); + return button; + } + } + LOG_ERROR("Unknown button \"%s\"\n", token); + return -1; +} + +/* Lookup a key code from a token */ +static int lookup_key(char *token) +{ + int key; + + for (key = 0; key_names[key].code >= 0; key++) { + if (strcasecmp(token, key_names[key].name) == 0) { + LOG_DEBUG("Found keycode \"%s\" (%d)\n", key_names[key].name, + key_names[key].code); + return key; + } + } + LOG_ERROR("Unknown key \"%s\"\n", token); + return -1; +} + +/* Get a GPIO name */ +const char *gpio_name(uint8_t gpio) +{ + if (gpio < GPIO_LAST) { + return gpio_names[gpio]; + } + return "?"; +} + +/* Get a keycode name */ +const char *keycode_name(int keycode) +{ + int key; + + for (key = 0; key_names[key].code >= 0; key++) { + if (key_names[key].code == keycode) { + return key_names[key].name; + } + } + return "?"; +} + +/* Parse a configuration line */ +bool parse_config_line(char *line, mapping_list_t *list, + uint32_t *active_gpio_mask) +{ + int button_count = 0, button, key = 0; + parse_state_t state = STATE_INIT; + char *token, *next_token, *token_end = NULL, *s; + bool expecting_button = true; + uint32_t gpio_mask = 0; + mapping_t *existing_mapping, new_mapping; + + token = strtok_r(line, " \t", &next_token); + while (token != NULL) { + switch (state) { + case STATE_INIT: + state = lookup_command(token); + if (state == STATE_INVALID) { + return false; + } + break; + + case STATE_UNMAP: + case STATE_MAP: + if (strcasecmp(token, "TO") == 0) { + if (state != STATE_MAP) { + LOG_ERROR("Unexpected keyword \"TO\"\n"); + return false; + } + if (expecting_button == true) { + + /* Missing last button */ + LOG_ERROR("Missing last button\n"); + return false; + } else if (button_count == 0) { + + /* No button found */ + LOG_ERROR("No button found\n"); + return false; + } + state = STATE_FUNCTION; + break; + } + do { + token_end = strchr(token, '+'); + if (token_end != NULL) { + if (token_end == token) { + + /* Leading '+' */ + if (button_count == 0) { + + /* We need at least one button left of '+' */ + LOG_ERROR("Missing first button\n"); + return false; + } else if (expecting_button == true) { + + /* Exepecting a button, cannot have another '+' */ + LOG_ERROR("Missing button\n"); + return false; + } else { + + /* Skip leading '+' */ + token++; + expecting_button = true; + continue; + } + } + + /* Composite button definition, lookup buttons one by one */ + *token_end = '\0'; + } + + /* GPIO lookup */ + if (*token == '\0') { + break; + } + if ((button = lookup_gpio(token)) >= 0) { + button_count++; + expecting_button = false; + gpio_mask |= 1 << button; + } else { + return false; + } + if (token_end != NULL) { + token = token_end + 1; + expecting_button = true; + } + } while (token_end != NULL); + break; + + case STATE_RESET: + break; + + case STATE_LOAD: + state = STATE_FILE; + break; + + case STATE_SLEEP: + state = STATE_DELAY; + break; + + case STATE_KEYUP: + case STATE_KEYDOWN: + case STATE_KEYPRESS: + state = STATE_KEY; + break; + + case STATE_TYPE: + state = STATE_TEXT; + break; + + case STATE_DELAY: + for (s = token; *s; s++) { + if (!isdigit(*s)) { + LOG_ERROR("Invalid delay \"%s\"\n", token); + return false; + } + } + case STATE_FILE: + case STATE_TEXT: + strncpy(buffer, token, MAX_LINE_LENGTH); + break; + + case STATE_FUNCTION: + state = lookup_function(token); + if (state == STATE_INVALID) { + return false; + } + buffer[0] = '\0'; + break; + + case STATE_KEY: + if ((key = lookup_key(token)) >= 0) { + break; + } else { + return false; + } + break; + + case STATE_COMMAND: + if (buffer[0] != '\0') { + strncat(buffer, " ", MAX_BUFFER_LENGTH); + } + strncat(buffer, token, MAX_BUFFER_LENGTH); + break; + + default: + LOG_ERROR("Unknown state %d\n", state); + return false; + } + token = strtok_r(NULL, " \t", &next_token); + } + switch (state) { + case STATE_UNMAP: + LOG_DEBUG("UNMAP gpio_mask 0x%04X button_count %d\n", gpio_mask, + button_count); + existing_mapping = find_mapping(list, gpio_mask); + if (existing_mapping == NULL) { + LOG_ERROR("Cannot find mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + if (remove_mapping(list, existing_mapping) == false) { + LOG_ERROR("Cannot remove mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + *active_gpio_mask &= ~gpio_mask; + break; + + case STATE_RESET: + LOG_DEBUG("RESET\n"); + reset_mapping_list(list); + break; + + case STATE_FILE: + LOG_DEBUG("LOAD file \"%s\"\n", buffer); + return parse_config_file(buffer, list, active_gpio_mask); + break; + + case STATE_DELAY: + LOG_DEBUG("SLEEP delay %s ms\n", buffer); + usleep(atoi(buffer) * 1000); + break; + + case STATE_TEXT: + break; + + case STATE_KEY: + switch (keyword) { + case STATE_KEYUP: + sendKey(key, 0); + break; + + case STATE_KEYDOWN: + sendKey(key, 1); + break; + + case STATE_KEYPRESS: + sendKey(key, 1); + usleep(200 * 1000); + sendKey(key, 0); + break; + + case STATE_MAP: + LOG_DEBUG("MAP gpio_mask 0x%04X to key %d, button_count %d\n", + gpio_mask, key, button_count); + existing_mapping = find_mapping(list, gpio_mask); + if (existing_mapping != NULL) { + LOG_DEBUG("Existing mapping with gpio_mask 0x%04X found\n", + gpio_mask); + if (remove_mapping(list, existing_mapping) == false) { + LOG_ERROR("Cannot remove mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + } + new_mapping.gpio_mask = gpio_mask; + new_mapping.bit_count = button_count; + new_mapping.activated = false; + new_mapping.type = MAPPING_KEY; + new_mapping.value.keycode = key; + if (insert_mapping(list, &new_mapping) == false) { + LOG_ERROR("Cannot add mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + *active_gpio_mask |= gpio_mask; + break; + + default: + LOG_ERROR("Invalid keyword %d\n", keyword); + return false; + } + break; + + case STATE_COMMAND: + LOG_DEBUG("MAP gpio_mask 0x%04X to command \"%s\", button_count %d\n", + gpio_mask, buffer, button_count); + LOG_DEBUG("MAP gpio_mask 0x%04X to key %d, button_count %d\n", + gpio_mask, key, button_count); + existing_mapping = find_mapping(list, gpio_mask); + if (existing_mapping != NULL) { + LOG_DEBUG("Existing mapping with gpio_mask 0x%04X found\n", + gpio_mask); + if (remove_mapping(list, existing_mapping) == false) { + LOG_ERROR("Cannot remove mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + } + new_mapping.gpio_mask = gpio_mask; + new_mapping.bit_count = button_count; + new_mapping.activated = false; + new_mapping.type = MAPPING_COMMAND; + new_mapping.value.command = buffer; + if (insert_mapping(list, &new_mapping) == false) { + LOG_ERROR("Cannot add mapping with gpio_mask 0x%04X\n", + gpio_mask); + return false; + } + break; + + case STATE_MAP: + case STATE_LOAD: + case STATE_SLEEP: + case STATE_TYPE: + case STATE_HELP: + break; + + default: + LOG_ERROR("Unknown result state %d\n", state); + return false; + } + return true; +} + +/* Parse a configuration file */ +bool parse_config_file(const char *name, mapping_list_t *list, + uint32_t *active_gpio_mask) +{ + FILE *fp; + int line_number = 0; + + if ((fp = fopen(name, "r")) == NULL) { + LOG_ERROR("Cannot open file \"%s\"\n", name); + return false; + } + while (!feof(fp)) { + if (fgets(line, MAX_LINE_LENGTH, fp) != line) { + if (!feof(fp)) { + LOG_ERROR("Error reading file \"%s\": %s\n", name, + strerror(errno)); + fclose(fp); + return false; + } + } + line_number++; + if (line[0] == '#') { + + /* Skip comment lines */ + continue; + } + + /* Remove trailing CR/LF */ + strtok(line, "\r\n"); + + /* Parse a configuration line */ + if (parse_config_line(line, list, active_gpio_mask) == false) { + LOG_ERROR("line %d\n", line_number); + break; + } + } + fclose(fp); + return true; +} diff --git a/parse_config.h b/parse_config.h new file mode 100644 index 0000000..0eb6a20 --- /dev/null +++ b/parse_config.h @@ -0,0 +1,92 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file parse_config.h + * This file contains the configuration parsing functions + */ + +#ifndef _PARSE_H_ +#define _PARSE_H_ + +#include +#include +#include "mapping_list.h" + +/* Definition of the different hardware GPIOs */ +#define GPIOS \ + X(GPIO_RIGHT, "RIGHT") \ + X(GPIO_DOWN, "DOWN") \ + X(GPIO_L, "L") \ + X(GPIO_UP, "UP") \ + X(GPIO_LEFT, "LEFT") \ + X(GPIO_MENU, "MENU") \ + X(GPIO_START, "START") \ + X(GPIO_FN, "FN") \ + X(GPIO_NU1, "") \ + X(GPIO_NU2, "") \ + X(GPIO_NU3, "") \ + X(GPIO_X, "X") \ + X(GPIO_A, "A") \ + X(GPIO_Y, "Y") \ + X(GPIO_B, "B") \ + X(GPIO_R, "R") \ + X(GPIO_LAST, NULL) + +/* Enumeration of the different hardware GPIOs */ +#undef X +#define X(a, b) a, +typedef enum {GPIOS} button_t; + +/* Definition of the different parse states */ +#define PARSE_STATES \ + X(STATE_INIT, "INIT") \ + X(STATE_MAP, "MAP") \ + X(STATE_UNMAP, "UNMAP") \ + X(STATE_RESET, "RESET") \ + X(STATE_LOAD, "LOAD") \ + X(STATE_FILE, "FILE") \ + X(STATE_SLEEP, "SLEEP") \ + X(STATE_DELAY, "DELAY") \ + X(STATE_KEYUP, "KEYUP") \ + X(STATE_KEYDOWN, "KEYDOWN") \ + X(STATE_KEYPRESS, "KEYPRESS") \ + X(STATE_TYPE, "TYPE") \ + X(STATE_TEXT, "TEXT") \ + X(STATE_FUNCTION, "FUNCTION") \ + X(STATE_KEY, "KEY") \ + X(STATE_COMMAND, "COMMAND")\ + X(STATE_HELP, "HELP") \ + X(STATE_INVALID, "INVALID") + +/* Enumeration of the different parse states */ +#undef X +#define X(a, b) a, +typedef enum {PARSE_STATES} parse_state_t; + +const char *gpio_name(uint8_t gpio); +const char *keycode_name(int keycode); +bool parse_config_line(char *line, mapping_list_t *list, + uint32_t *active_gpio_mask); +bool parse_config_file(const char *name, mapping_list_t *list, + uint32_t *active_gpio_mask); + +#endif //_PARSE_H_ diff --git a/smbus.c b/smbus.c new file mode 100755 index 0000000..a85d727 --- /dev/null +++ b/smbus.c @@ -0,0 +1,224 @@ +/* + smbus.c - SMBus level access helper functions + + Copyright (C) 1995-1997 Simon G. Vogl + Copyright (C) 1998-1999 Frodo Looijaard + Copyright (C) 2012-2013 Jean Delvare + + 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 "smbus.h" +#include +#include +#include +#include + +/* Compatibility defines */ +#ifndef I2C_SMBUS_I2C_BLOCK_BROKEN +#define I2C_SMBUS_I2C_BLOCK_BROKEN I2C_SMBUS_I2C_BLOCK_DATA +#endif +#ifndef I2C_FUNC_SMBUS_PEC +#define I2C_FUNC_SMBUS_PEC I2C_FUNC_SMBUS_HWPEC_CALC +#endif + +__s32 i2c_smbus_access(int file, char read_write, __u8 command, + int size, union i2c_smbus_data *data) +{ + struct i2c_smbus_ioctl_data args; + __s32 err; + + args.read_write = read_write; + args.command = command; + args.size = size; + args.data = data; + + err = ioctl(file, I2C_SMBUS, &args); + if (err == -1) + err = -errno; + return err; +} + + +__s32 i2c_smbus_write_quick(int file, __u8 value) +{ + return i2c_smbus_access(file, value, 0, I2C_SMBUS_QUICK, NULL); +} + +__s32 i2c_smbus_read_byte(int file) +{ + union i2c_smbus_data data; + int err; + + err = i2c_smbus_access(file, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &data); + if (err < 0) + return err; + + return 0x0FF & data.byte; +} + +__s32 i2c_smbus_write_byte(int file, __u8 value) +{ + return i2c_smbus_access(file, I2C_SMBUS_WRITE, value, + I2C_SMBUS_BYTE, NULL); +} + +__s32 i2c_smbus_read_byte_data(int file, __u8 command) +{ + union i2c_smbus_data data; + int err; + + err = i2c_smbus_access(file, I2C_SMBUS_READ, command, + I2C_SMBUS_BYTE_DATA, &data); + if (err < 0) + return err; + + return 0x0FF & data.byte; +} + +__s32 i2c_smbus_write_byte_data(int file, __u8 command, __u8 value) +{ + union i2c_smbus_data data; + data.byte = value; + return i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_BYTE_DATA, &data); +} + +__s32 i2c_smbus_read_word_data(int file, __u8 command) +{ + union i2c_smbus_data data; + int err; + + err = i2c_smbus_access(file, I2C_SMBUS_READ, command, + I2C_SMBUS_WORD_DATA, &data); + if (err < 0) + return err; + + return 0x0FFFF & data.word; +} + +__s32 i2c_smbus_write_word_data(int file, __u8 command, __u16 value) +{ + union i2c_smbus_data data; + data.word = value; + return i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_WORD_DATA, &data); +} + +__s32 i2c_smbus_process_call(int file, __u8 command, __u16 value) +{ + union i2c_smbus_data data; + data.word = value; + if (i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_PROC_CALL, &data)) + return -1; + else + return 0x0FFFF & data.word; +} + +/* Returns the number of read bytes */ +__s32 i2c_smbus_read_block_data(int file, __u8 command, __u8 *values) +{ + union i2c_smbus_data data; + int i, err; + + err = i2c_smbus_access(file, I2C_SMBUS_READ, command, + I2C_SMBUS_BLOCK_DATA, &data); + if (err < 0) + return err; + + for (i = 1; i <= data.block[0]; i++) + values[i-1] = data.block[i]; + return data.block[0]; +} + +__s32 i2c_smbus_write_block_data(int file, __u8 command, __u8 length, + const __u8 *values) +{ + union i2c_smbus_data data; + int i; + if (length > I2C_SMBUS_BLOCK_MAX) + length = I2C_SMBUS_BLOCK_MAX; + for (i = 1; i <= length; i++) + data.block[i] = values[i-1]; + data.block[0] = length; + return i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_BLOCK_DATA, &data); +} + +/* Returns the number of read bytes */ +/* Until kernel 2.6.22, the length is hardcoded to 32 bytes. If you + ask for less than 32 bytes, your code will only work with kernels + 2.6.23 and later. */ +__s32 i2c_smbus_read_i2c_block_data(int file, __u8 command, __u8 length, + __u8 *values) +{ + union i2c_smbus_data data; + int i, err; + + if (length > I2C_SMBUS_BLOCK_MAX) + length = I2C_SMBUS_BLOCK_MAX; + data.block[0] = length; + + err = i2c_smbus_access(file, I2C_SMBUS_READ, command, + length == 32 ? I2C_SMBUS_I2C_BLOCK_BROKEN : + I2C_SMBUS_I2C_BLOCK_DATA, &data); + if (err < 0) + return err; + + for (i = 1; i <= data.block[0]; i++) + values[i-1] = data.block[i]; + return data.block[0]; +} + +__s32 i2c_smbus_write_i2c_block_data(int file, __u8 command, __u8 length, + const __u8 *values) +{ + union i2c_smbus_data data; + int i; + if (length > I2C_SMBUS_BLOCK_MAX) + length = I2C_SMBUS_BLOCK_MAX; + for (i = 1; i <= length; i++) + data.block[i] = values[i-1]; + data.block[0] = length; + return i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_I2C_BLOCK_BROKEN, &data); +} + +/* Returns the number of read bytes */ +__s32 i2c_smbus_block_process_call(int file, __u8 command, __u8 length, + __u8 *values) +{ + union i2c_smbus_data data; + int i, err; + + if (length > I2C_SMBUS_BLOCK_MAX) + length = I2C_SMBUS_BLOCK_MAX; + for (i = 1; i <= length; i++) + data.block[i] = values[i-1]; + data.block[0] = length; + + err = i2c_smbus_access(file, I2C_SMBUS_WRITE, command, + I2C_SMBUS_BLOCK_PROC_CALL, &data); + if (err < 0) + return err; + + for (i = 1; i <= data.block[0]; i++) + values[i-1] = data.block[i]; + return data.block[0]; +} diff --git a/smbus.h b/smbus.h new file mode 100755 index 0000000..18a5305 --- /dev/null +++ b/smbus.h @@ -0,0 +1,61 @@ +/* + smbus.h - SMBus level access helper functions + + Copyright (C) 1995-97 Simon G. Vogl + Copyright (C) 1998-99 Frodo Looijaard + + 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 LIB_I2C_SMBUS_H +#define LIB_I2C_SMBUS_H + +#define I2C_API_VERSION 0x100 + +#include +#include + +extern __s32 i2c_smbus_access(int file, char read_write, __u8 command, + int size, union i2c_smbus_data *data); + +extern __s32 i2c_smbus_write_quick(int file, __u8 value); +extern __s32 i2c_smbus_read_byte(int file); +extern __s32 i2c_smbus_write_byte(int file, __u8 value); +extern __s32 i2c_smbus_read_byte_data(int file, __u8 command); +extern __s32 i2c_smbus_write_byte_data(int file, __u8 command, __u8 value); +extern __s32 i2c_smbus_read_word_data(int file, __u8 command); +extern __s32 i2c_smbus_write_word_data(int file, __u8 command, __u16 value); +extern __s32 i2c_smbus_process_call(int file, __u8 command, __u16 value); + +/* Returns the number of read bytes */ +extern __s32 i2c_smbus_read_block_data(int file, __u8 command, __u8 *values); +extern __s32 i2c_smbus_write_block_data(int file, __u8 command, __u8 length, + const __u8 *values); + +/* Returns the number of read bytes */ +/* Until kernel 2.6.22, the length is hardcoded to 32 bytes. If you + ask for less than 32 bytes, your code will only work with kernels + 2.6.23 and later. */ +extern __s32 i2c_smbus_read_i2c_block_data(int file, __u8 command, __u8 length, + __u8 *values); +extern __s32 i2c_smbus_write_i2c_block_data(int file, __u8 command, __u8 length, + const __u8 *values); + +/* Returns the number of read bytes */ +extern __s32 i2c_smbus_block_process_call(int file, __u8 command, __u8 length, + __u8 *values); + +#endif /* LIB_I2C_SMBUS_H */ diff --git a/termfix.c b/termfix.c new file mode 100644 index 0000000..d1a1631 --- /dev/null +++ b/termfix.c @@ -0,0 +1,64 @@ +/* + Copyright (C) 2020-2021 Vincent Buso + Copyright (C) 2020-2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file termfix.c + * This file contains a function to unlock and force a vt back into text mode + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + if (argc != 2) { + printf("usage: termfix /dev/ttyX\n"); + return 2; + } + + int fd = open(argv[1], O_RDWR, 0); + int res = ioctl(fd, VT_UNLOCKSWITCH, 1); + + if (res != 0) { + perror("ioctl VT_UNLOCKSWITCH failed"); + return 3; + } + + ioctl(fd, KDSETMODE, KD_TEXT); + + if (res != 0) { + perror("ioctl KDSETMODE failed"); + return 3; + } + + printf("Success\n"); + + return res; +} diff --git a/to_log.c b/to_log.c new file mode 100644 index 0000000..d4c0501 --- /dev/null +++ b/to_log.c @@ -0,0 +1,85 @@ +/* + Copyright (C) 2020-2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file to_log.c + * This file contains the syslog redirection functions + */ + +#define _GNU_SOURCE +#include +#include +#include + +/* Ordered map of log priority level and string prefix */ +static char const *priority[] = { + "EMERG: ", + "ALERT: ", + "CRIT: ", + "ERR: ", + "WARNING: ", + "NOTICE: ", + "INFO: ", + "DEBUG: " +}; + +/* Cookie I/O function to redirect file output to syslog */ +static size_t writer(void *cookie, char const *data, size_t length) +{ + (void) cookie; + int p = LOG_DEBUG, l; + + /* Look for a priority prefix, if any */ + do { + l = strlen(priority[p]); + } while (memcmp(data, priority[p], l) && --p >= 0); + if (p < 0) { + p = LOG_INFO; + } else { + data += l; + length -= l; + } + + /* Strip leading spaces */ + while (*data == ' ') { + ++data; + --length; + } + syslog(p, "%.*s", (int) length, data); + return length; +} + +/* Dummy Cookie IO function */ +static int noop(void) +{ + return 0; +} + +/* Cookie I/O function structure */ +static cookie_io_functions_t log_fns = { + (void *) noop, (void *) writer, (void *) noop, (void *) noop +}; + +/* Redirect given file output descriptor to syslog */ +void to_log(FILE **pfp) +{ + setvbuf(*pfp = fopencookie(NULL, "w", log_fns), NULL, _IOLBF, 0); +} diff --git a/to_log.h b/to_log.h new file mode 100644 index 0000000..a5cc4f2 --- /dev/null +++ b/to_log.h @@ -0,0 +1,34 @@ +/* + Copyright (C) 2021 Michel Stempin + + This file is part of the FunKey S GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +/** + * @file to_log.h + * This file contains the syslog redirection functions + */ + +#ifndef _TO_LOG_H_ +#define _TO_LOG_H_ + +#include + +void to_log(FILE **pfp); + +#endif // _TO_LOG_H_ diff --git a/uinput.c b/uinput.c new file mode 100755 index 0000000..5bba55a --- /dev/null +++ b/uinput.c @@ -0,0 +1,286 @@ +/**** uinput.c *****************************/ +/* M. Moller 2013-01-16 */ +/* Universal RPi GPIO keyboard daemon */ +/*******************************************/ + +/* + Copyright (C) 2013 Michael Moller. + This file is part of the Universal Raspberry Pi GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +//#include "uinput_linux.h" +//#include "config.h" +//include "daemon.h" +#include "uinput.h" +#include + +//#define DEBUG_UINPUT +#define ERROR_UINPUT + +#ifdef DEBUG_UINPUT + #define LOG_DEBUG(...) printf(__VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +#ifdef ERROR_UINPUT + #define LOG_ERROR(...) fprintf(stderr, "ERR: " __VA_ARGS__); +#else + #define LOG_DEBUG(...) +#endif + +/* For compatibility with kernels having dates on 32 bits */ +struct timeval_compat +{ + unsigned int tv_sec; + long int tv_usec; +}; + +struct input_event_compat { + struct timeval_compat time; + unsigned short type; + unsigned short code; + unsigned int value; +}; + +#if TEST_UINPUT +static int sendRel(int dx, int dy); +#endif +static int sendSync(void); + +#if TEST_UINPUT +static struct input_event uidev_ev; +#endif +static int uidev_fd; +/*static keyinfo_s lastkey;*/ + +#define die(str, args...) do { \ + perror(str); \ + return(EXIT_FAILURE); \ + } while(0) + +int init_uinput(void) +{ + int fd; + struct uinput_user_dev uidev; + int i; + + fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); + if(fd < 0) + die("/dev/uinput"); + + if(ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0) + die("error: ioctl"); + if(ioctl(fd, UI_SET_EVBIT, EV_REP) < 0) + die("error: ioctl"); + if(ioctl(fd, UI_SET_KEYBIT, BTN_LEFT) < 0) + die("error: ioctl"); + + if(ioctl(fd, UI_SET_EVBIT, EV_REL) < 0) + die("error: ioctl"); + if(ioctl(fd, UI_SET_RELBIT, REL_X) < 0) + die("error: ioctl"); + if(ioctl(fd, UI_SET_RELBIT, REL_Y) < 0) + die("error: ioctl"); + + /* don't forget to add all the keys! */ + for(i=0; i<256; i++){ + if(ioctl(fd, UI_SET_KEYBIT, i) < 0) + die("error: ioctl"); + } + + memset(&uidev, 0, sizeof(uidev)); + snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-sample"); + uidev.id.bustype = BUS_USB; + uidev.id.vendor = 0x1; + uidev.id.product = 0x1; + uidev.id.version = 1; + + /*if(write(fd, &uidev, sizeof(uidev)) < 0) + die("error: write");*/ + + if(ioctl(fd, UI_DEV_SETUP, &uidev) < 0) + die("error: ioctl"); + + if(ioctl(fd, UI_DEV_CREATE) < 0) + die("error: ioctl"); + + uidev_fd = fd; + + sleep(1); + + return 0; +} + +#if TEST_UINPUT +int test_uinput(void) +{ + int dx, dy; + int i; + + //srand(time(NULL)); + int op = 1; + + while(1) { + //switch(rand() % 4) { + switch(op) { + case 0: + dx = -10; + dy = -1; + break; + case 1: + dx = 10; + dy = 1; + break; + case 2: + dx = -1; + dy = 10; + break; + case 3: + dx = 1; + dy = -10; + break; + } + + /*k = send_gpio_keys(21, 1); + sendKey(k, 0);*/ + sendKey(KEY_D, 0); + + for(i = 0; i < 20; i++) { + //sendKey(KEY_D, 1); + //sendKey(KEY_D, 0); + sendRel(dx, dy); + + usleep(15000); + } + + sleep(10); + } +} +#endif + +int close_uinput(void) +{ + sleep(2); + + if(ioctl(uidev_fd, UI_DEV_DESTROY) < 0) + die("error: ioctl"); + + close(uidev_fd); + + return 0; +} + +int sendKey(int key, int value) +{ + struct input_event_compat ie; + //memset(&uidev_ev, 0, sizeof(struct input_event)); + //gettimeofday(&uidev_ev.time, NULL); + ie.type = EV_KEY; + ie.code = key; + ie.value = value; + ie.time.tv_sec = 0; + ie.time.tv_usec = 0; + LOG_DEBUG("sendKey: %d = %d\n", key, value); + if(write(uidev_fd, &ie, sizeof(struct input_event_compat)) < 0) + die("error: write"); + + sendSync(); + + return 0; +} + +#if TEST_UINPUT +static int sendRel(int dx, int dy) +{ + memset(&uidev_ev, 0, sizeof(struct input_event)); + uidev_ev.type = EV_REL; + uidev_ev.code = REL_X; + uidev_ev.value = dx; + if(write(uidev_fd, &uidev_ev, sizeof(struct input_event)) < 0) + die("error: write"); + + memset(&uidev_ev, 0, sizeof(struct input_event)); + uidev_ev.type = EV_REL; + uidev_ev.code = REL_Y; + uidev_ev.value = dy; + if(write(uidev_fd, &uidev_ev, sizeof(struct input_event)) < 0) + die("error: write"); + + sendSync(); + + return 0; +} +#endif + +static int sendSync(void) +{ + LOG_DEBUG("sendSync\n"); + //memset(&uidev_ev, 0, sizeof(struct input_event)); + struct input_event ie; + ie.type = EV_SYN; + ie.code = SYN_REPORT; + ie.value = 0; + ie.time.tv_sec = 0; + ie.time.tv_usec = 0; + if(write(uidev_fd, &ie, sizeof(struct input_event)) < 0) + die("error: sendSync - write"); + + return 0; +} + +#if 0 +int send_gpio_keys(int gpio, int value) +{ + int k; + int xio; + restart_keys(); + while( got_more_keys(gpio) ){ + k = get_next_key(gpio); + if(is_xio(gpio) && value){ /* xio int-pin is active low */ + xio = get_curr_xio_no(); + poll_iic(xio); + last_iic_key(&lastkey); + } + else if(k<0x300){ + sendKey(k, value); + if(value && got_more_keys(gpio)){ + /* release the current key, so the next one can be pressed */ + sendKey(k, 0); + } + lastkey.key = k; + lastkey.val = value; + } + } + return k; +} + +void get_last_key(keyinfo_s *kp) +{ + kp->key = lastkey.key; + kp->val = lastkey.val; +} +#endif diff --git a/uinput.h b/uinput.h new file mode 100755 index 0000000..59704bd --- /dev/null +++ b/uinput.h @@ -0,0 +1,36 @@ +/**** uinput.h *****************************/ +/* M. Moller 2013-01-16 */ +/* Universal RPi GPIO keyboard daemon */ +/*******************************************/ + +/* + Copyright (C) 2013 Michael Moller. + This file is part of the Universal Raspberry Pi GPIO keyboard daemon. + + This is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The software 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. +*/ + +#ifndef _UINPUT_H_ +#define _UINPUT_H_ + +int init_uinput(void); +int test_uinput(void); +int close_uinput(void); +int send_gpio_keys(int gpio, int value); +int sendKey(int key, int value); +//void get_last_key(keyinfo_s *kp); + +#endif //_UINPUT_H_ diff --git a/uinput_linux.h b/uinput_linux.h new file mode 100755 index 0000000..c9e677e --- /dev/null +++ b/uinput_linux.h @@ -0,0 +1,232 @@ +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ +/* + * User level driver support for input subsystem + * + * Heavily based on evdev.c by Vojtech Pavlik + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Aristeu Sergio Rozanski Filho + * + * Changes/Revisions: + * 0.5 08/13/2015 (David Herrmann & + * Benjamin Tissoires ) + * - add UI_DEV_SETUP ioctl + * - add UI_ABS_SETUP ioctl + * - add UI_GET_VERSION ioctl + * 0.4 01/09/2014 (Benjamin Tissoires ) + * - add UI_GET_SYSNAME ioctl + * 0.3 24/05/2006 (Anssi Hannula ) + * - update ff support for the changes in kernel interface + * - add UINPUT_VERSION + * 0.2 16/10/2004 (Micah Dowty ) + * - added force feedback support + * - added UI_SET_PHYS + * 0.1 20/06/2002 + * - first public version + */ +#ifndef _UAPI__UINPUT_H_ +#define _UAPI__UINPUT_H_ + +#include +#include + +#define UINPUT_VERSION 5 +#define UINPUT_MAX_NAME_SIZE 80 + +struct uinput_ff_upload { + __u32 request_id; + __s32 retval; + struct ff_effect effect; + struct ff_effect old; +}; + +struct uinput_ff_erase { + __u32 request_id; + __s32 retval; + __u32 effect_id; +}; + +/* ioctl */ +#define UINPUT_IOCTL_BASE 'U' +#define UI_DEV_CREATE _IO(UINPUT_IOCTL_BASE, 1) +#define UI_DEV_DESTROY _IO(UINPUT_IOCTL_BASE, 2) + +struct uinput_setup { + struct input_id id; + char name[UINPUT_MAX_NAME_SIZE]; + __u32 ff_effects_max; +}; + +/** + * UI_DEV_SETUP - Set device parameters for setup + * + * This ioctl sets parameters for the input device to be created. It + * supersedes the old "struct uinput_user_dev" method, which wrote this data + * via write(). To actually set the absolute axes UI_ABS_SETUP should be + * used. + * + * The ioctl takes a "struct uinput_setup" object as argument. The fields of + * this object are as follows: + * id: See the description of "struct input_id". This field is + * copied unchanged into the new device. + * name: This is used unchanged as name for the new device. + * ff_effects_max: This limits the maximum numbers of force-feedback effects. + * See below for a description of FF with uinput. + * + * This ioctl can be called multiple times and will overwrite previous values. + * If this ioctl fails with -EINVAL, it is recommended to use the old + * "uinput_user_dev" method via write() as a fallback, in case you run on an + * old kernel that does not support this ioctl. + * + * This ioctl may fail with -EINVAL if it is not supported or if you passed + * incorrect values, -ENOMEM if the kernel runs out of memory or -EFAULT if the + * passed uinput_setup object cannot be read/written. + * If this call fails, partial data may have already been applied to the + * internal device. + */ +#define UI_DEV_SETUP _IOW(UINPUT_IOCTL_BASE, 3, struct uinput_setup) + +struct uinput_abs_setup { + __u16 code; /* axis code */ + /* __u16 filler; */ + struct input_absinfo absinfo; +}; + +/** + * UI_ABS_SETUP - Set absolute axis information for the device to setup + * + * This ioctl sets one absolute axis information for the input device to be + * created. It supersedes the old "struct uinput_user_dev" method, which wrote + * part of this data and the content of UI_DEV_SETUP via write(). + * + * The ioctl takes a "struct uinput_abs_setup" object as argument. The fields + * of this object are as follows: + * code: The corresponding input code associated with this axis + * (ABS_X, ABS_Y, etc...) + * absinfo: See "struct input_absinfo" for a description of this field. + * This field is copied unchanged into the kernel for the + * specified axis. If the axis is not enabled via + * UI_SET_ABSBIT, this ioctl will enable it. + * + * This ioctl can be called multiple times and will overwrite previous values. + * If this ioctl fails with -EINVAL, it is recommended to use the old + * "uinput_user_dev" method via write() as a fallback, in case you run on an + * old kernel that does not support this ioctl. + * + * This ioctl may fail with -EINVAL if it is not supported or if you passed + * incorrect values, -ENOMEM if the kernel runs out of memory or -EFAULT if the + * passed uinput_setup object cannot be read/written. + * If this call fails, partial data may have already been applied to the + * internal device. + */ +#define UI_ABS_SETUP _IOW(UINPUT_IOCTL_BASE, 4, struct uinput_abs_setup) + +#define UI_SET_EVBIT _IOW(UINPUT_IOCTL_BASE, 100, int) +#define UI_SET_KEYBIT _IOW(UINPUT_IOCTL_BASE, 101, int) +#define UI_SET_RELBIT _IOW(UINPUT_IOCTL_BASE, 102, int) +#define UI_SET_ABSBIT _IOW(UINPUT_IOCTL_BASE, 103, int) +#define UI_SET_MSCBIT _IOW(UINPUT_IOCTL_BASE, 104, int) +#define UI_SET_LEDBIT _IOW(UINPUT_IOCTL_BASE, 105, int) +#define UI_SET_SNDBIT _IOW(UINPUT_IOCTL_BASE, 106, int) +#define UI_SET_FFBIT _IOW(UINPUT_IOCTL_BASE, 107, int) +#define UI_SET_PHYS _IOW(UINPUT_IOCTL_BASE, 108, char*) +#define UI_SET_SWBIT _IOW(UINPUT_IOCTL_BASE, 109, int) +#define UI_SET_PROPBIT _IOW(UINPUT_IOCTL_BASE, 110, int) + +#define UI_BEGIN_FF_UPLOAD _IOWR(UINPUT_IOCTL_BASE, 200, struct uinput_ff_upload) +#define UI_END_FF_UPLOAD _IOW(UINPUT_IOCTL_BASE, 201, struct uinput_ff_upload) +#define UI_BEGIN_FF_ERASE _IOWR(UINPUT_IOCTL_BASE, 202, struct uinput_ff_erase) +#define UI_END_FF_ERASE _IOW(UINPUT_IOCTL_BASE, 203, struct uinput_ff_erase) + +/** + * UI_GET_SYSNAME - get the sysfs name of the created uinput device + * + * @return the sysfs name of the created virtual input device. + * The complete sysfs path is then /sys/devices/virtual/input/--NAME-- + * Usually, it is in the form "inputN" + */ +#define UI_GET_SYSNAME(len) _IOC(_IOC_READ, UINPUT_IOCTL_BASE, 44, len) + +/** + * UI_GET_VERSION - Return version of uinput protocol + * + * This writes uinput protocol version implemented by the kernel into + * the integer pointed to by the ioctl argument. The protocol version + * is hard-coded in the kernel and is independent of the uinput device. + */ +#define UI_GET_VERSION _IOR(UINPUT_IOCTL_BASE, 45, unsigned int) + +/* + * To write a force-feedback-capable driver, the upload_effect + * and erase_effect callbacks in input_dev must be implemented. + * The uinput driver will generate a fake input event when one of + * these callbacks are invoked. The userspace code then uses + * ioctls to retrieve additional parameters and send the return code. + * The callback blocks until this return code is sent. + * + * The described callback mechanism is only used if ff_effects_max + * is set. + * + * To implement upload_effect(): + * 1. Wait for an event with type == EV_UINPUT and code == UI_FF_UPLOAD. + * A request ID will be given in 'value'. + * 2. Allocate a uinput_ff_upload struct, fill in request_id with + * the 'value' from the EV_UINPUT event. + * 3. Issue a UI_BEGIN_FF_UPLOAD ioctl, giving it the + * uinput_ff_upload struct. It will be filled in with the + * ff_effects passed to upload_effect(). + * 4. Perform the effect upload, and place a return code back into + the uinput_ff_upload struct. + * 5. Issue a UI_END_FF_UPLOAD ioctl, also giving it the + * uinput_ff_upload_effect struct. This will complete execution + * of our upload_effect() handler. + * + * To implement erase_effect(): + * 1. Wait for an event with type == EV_UINPUT and code == UI_FF_ERASE. + * A request ID will be given in 'value'. + * 2. Allocate a uinput_ff_erase struct, fill in request_id with + * the 'value' from the EV_UINPUT event. + * 3. Issue a UI_BEGIN_FF_ERASE ioctl, giving it the + * uinput_ff_erase struct. It will be filled in with the + * effect ID passed to erase_effect(). + * 4. Perform the effect erasure, and place a return code back + * into the uinput_ff_erase struct. + * 5. Issue a UI_END_FF_ERASE ioctl, also giving it the + * uinput_ff_erase_effect struct. This will complete execution + * of our erase_effect() handler. + */ + +/* + * This is the new event type, used only by uinput. + * 'code' is UI_FF_UPLOAD or UI_FF_ERASE, and 'value' + * is the unique request ID. This number was picked + * arbitrarily, above EV_MAX (since the input system + * never sees it) but in the range of a 16-bit int. + */ +#define EV_UINPUT 0x0101 +#define UI_FF_UPLOAD 1 +#define UI_FF_ERASE 2 + +struct uinput_user_dev { + char name[UINPUT_MAX_NAME_SIZE]; + struct input_id id; + __u32 ff_effects_max; + __s32 absmax[ABS_CNT]; + __s32 absmin[ABS_CNT]; + __s32 absfuzz[ABS_CNT]; + __s32 absflat[ABS_CNT]; +}; +#endif /* _UAPI__UINPUT_H_ */