diff --git b/AUTHORS a/AUTHORS new file mode 100644 index 0000000..b9e2f40 --- /dev/null +++ a/AUTHORS @@ -0,0 +1 @@ +Stéphane Raimbault diff --git b/COPYING a/COPYING new file mode 100644 index 0000000..d60c31a --- /dev/null +++ a/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, 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 or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +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 give any other recipients of the Program a copy of this License +along with the Program. + +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 Program or any portion +of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +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 Program, 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 Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) 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; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, 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 executable. However, as a +special exception, the source code 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. + +If distribution of executable or 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 counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program 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. + + 5. 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 Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program 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 to +this License. + + 7. 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 Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program 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 Program. + +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. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program 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. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 Program +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 Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, 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 + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git b/COPYING.LIB a/COPYING.LIB new file mode 100644 index 0000000..eb685a5 --- /dev/null +++ a/COPYING.LIB @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, 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 library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + 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 Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, 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 or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the 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 a program 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. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + 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, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +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 compile 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) 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. + + c) 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. + + d) 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 source code 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 to +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 Library 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 + + Appendix: How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git b/ChangeLog a/ChangeLog new file mode 100644 index 0000000..e69de29 --- /dev/null +++ a/ChangeLog diff --git b/INSTALL a/INSTALL new file mode 100644 index 0000000..095b1eb --- /dev/null +++ a/INSTALL @@ -0,0 +1,231 @@ +Installation Instructions +************************* + +Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004 Free +Software Foundation, Inc. + +This file is free documentation; the Free Software Foundation gives +unlimited permission to copy, distribute and modify it. + +Basic Installation +================== + +These are generic installation instructions. + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, and a +file `config.log' containing compiler output (useful mainly for +debugging `configure'). + + It can also use an optional file (typically called `config.cache' +and enabled with `--cache-file=config.cache' or simply `-C') that saves +the results of its tests to speed up reconfiguring. (Caching is +disabled by default to prevent problems with accidental use of stale +cache files.) + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If you are using the cache, and at +some point `config.cache' contains results you don't want to keep, you +may remove or edit it. + + The file `configure.ac' (or `configure.in') is used to create +`configure' by a program called `autoconf'. You only need +`configure.ac' if you want to change it or regenerate `configure' using +a newer version of `autoconf'. + +The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. If you're + using `csh' on an old version of System V, you might need to type + `sh ./configure' instead to prevent `csh' from trying to execute + `configure' itself. + + Running `configure' takes awhile. While running, it prints some + messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + 3. Optionally, type `make check' to run any self-tests that come with + the package. + + 4. Type `make install' to install the programs and any data files and + documentation. + + 5. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + +Compilers and Options +===================== + +Some systems require unusual options for compilation or linking that the +`configure' script does not know about. Run `./configure --help' for +details on some of the pertinent environment variables. + + You can give `configure' initial values for configuration parameters +by setting variables in the command line or in the environment. Here +is an example: + + ./configure CC=c89 CFLAGS=-O2 LIBS=-lposix + + *Note Defining Variables::, for more details. + +Compiling For Multiple Architectures +==================================== + +You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you must use a version of `make' that +supports the `VPATH' variable, such as GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. + + If you have to use a `make' that does not support the `VPATH' +variable, you have to compile the package for one architecture at a +time in the source code directory. After you have installed the +package for one architecture, use `make distclean' before reconfiguring +for another architecture. + +Installation Names +================== + +By default, `make install' will install the package's files in +`/usr/local/bin', `/usr/local/man', etc. You can specify an +installation prefix other than `/usr/local' by giving `configure' the +option `--prefix=PREFIX'. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +give `configure' the option `--exec-prefix=PREFIX', the package will +use PREFIX as the prefix for installing programs and libraries. +Documentation and other data files will still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=DIR' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + +Optional Features +================= + +Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + +Specifying the System Type +========================== + +There may be some features `configure' cannot figure out automatically, +but needs to determine by the type of machine the package will run on. +Usually, assuming the package is built to be run on the _same_ +architectures, `configure' can figure that out, but if it prints a +message saying it cannot guess the machine type, give it the +`--build=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name which has the form: + + CPU-COMPANY-SYSTEM + +where SYSTEM can have one of these forms: + + OS KERNEL-OS + + See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the machine type. + + If you are _building_ compiler tools for cross-compiling, you should +use the `--target=TYPE' option to select the type of system they will +produce code for. + + If you want to _use_ a cross compiler, that generates code for a +platform different from the build platform, you should specify the +"host" platform (i.e., that on which the generated programs will +eventually be run) with `--host=TYPE'. + +Sharing Defaults +================ + +If you want to set default values for `configure' scripts to share, you +can create a site shell script called `config.site' that gives default +values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Defining Variables +================== + +Variables not defined in a site shell script can be set in the +environment passed to `configure'. However, some packages may run +configure again during the build, and the customized values of these +variables may be lost. In order to avoid this problem, you should set +them in the `configure' command line, using `VAR=value'. For example: + + ./configure CC=/usr/local2/bin/gcc + +will cause the specified gcc to be used as the C compiler (unless it is +overridden in the site shell script). + +`configure' Invocation +====================== + +`configure' recognizes the following options to control how it operates. + +`--help' +`-h' + Print a summary of the options to `configure', and exit. + +`--version' +`-V' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`--cache-file=FILE' + Enable the cache: use and save the results of the tests in FILE, + traditionally `config.cache'. FILE defaults to `/dev/null' to + disable caching. + +`--config-cache' +`-C' + Alias for `--cache-file=config.cache'. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`configure' also accepts some other, not widely useful, options. Run +`configure --help' for more details. + diff --git b/Makefile.am a/Makefile.am new file mode 100644 index 0000000..1bfdcf4 --- /dev/null +++ a/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=src diff --git b/NEWS a/NEWS new file mode 100644 index 0000000..e69de29 --- /dev/null +++ a/NEWS diff --git b/README a/README new file mode 100644 index 0000000..fc0f906 --- /dev/null +++ a/README @@ -0,0 +1,8 @@ +Libmodbus is a library to send/receive data with a device which uses +ModBus protocol. This library can use a serial port or an Ethernet +connexion. + +The functions included in the library have been derived from the +Modicon Modbus Protocol Reference Guide which can be obtained from +Schneider at www.schneiderautomation.com. + diff --git b/autogen.sh a/autogen.sh new file mode 100755 index 0000000..4f81538 --- /dev/null +++ a/autogen.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# Run this to generate all the initial makefiles, etc. + +srcdir=`dirname $0` +test -z "$srcdir" && srcdir=. +ORIGDIR=`pwd` +cd $srcdir + +PROJECT=libGtkEntryMask + +DIE=0 + +have_libtool=false +if libtoolize --version < /dev/null > /dev/null 2>&1 ; then + libtool_version=`libtoolize --version | sed 's/^[^0-9]*\([0-9.][0-9.]*\).*/\1/'` + case $libtool_version in + 1.4*|1.5*) + have_libtool=true + ;; + esac +fi +if $have_libtool ; then : ; else + echo + echo "You must have libtool 1.4 installed to compile $PROJECT." + echo "Install the appropriate package for your distribution," + echo "or get the source tarball at http://ftp.gnu.org/gnu/libtool/" + DIE=1 +fi + +(autoconf --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "You must have autoconf installed to compile $PROJECT." + echo "Install the appropriate package for your distribution," + echo "or get the source tarball at http://ftp.gnu.org/gnu/autoconf/" + DIE=1 +} + +if automake-1.7 --version < /dev/null > /dev/null 2>&1 ; then + AUTOMAKE=automake-1.7 + ACLOCAL=aclocal-1.7 +else + echo + echo "You must have automake 1.7.x installed to compile $PROJECT." + echo "Install the appropriate package for your distribution," + echo "or get the source tarball at http://ftp.gnu.org/gnu/automake/" + DIE=1 +fi + +if test "$DIE" -eq 1; then + exit 1 +fi + +if test -z "$AUTOGEN_SUBDIR_MODE"; then + if test -z "$*"; then + echo "I am going to run ./configure with no arguments - if you wish " + echo "to pass any to it, please specify them on the $0 command line." + fi +fi + +$ACLOCAL $ACLOCAL_FLAGS || exit 1 +libtoolize --force || exit 1 +$AUTOMAKE --add-missing || exit 1 +autoconf || exit 1 +cd $ORIGDIR + +if test -z "$AUTOGEN_SUBDIR_MODE"; then + $srcdir/configure --enable-maintainer-mode "$@" + + echo + echo "Now type 'make' to compile $PROJECT." +fi diff --git b/configure.ac a/configure.ac new file mode 100644 index 0000000..211ae10 --- /dev/null +++ a/configure.ac @@ -0,0 +1,34 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.59) +AC_INIT(libmodbus, 1.2, stephane.raimbault@free.fr) +AM_INIT_AUTOMAKE(libmodbus, 1.2.0) + +# Checks for programs. +AC_PROG_CC +AC_PROG_MAKE_SET +AC_PROG_LIBTOOL + +# Checks for libraries. +AM_PATH_GLIB_2_0(2.0.0,,AC_MSG_ERROR(libmodbus needs GLib 2.X)) + +# Checks for header files. +AC_HEADER_STDC +AC_CHECK_HEADERS([arpa/inet.h fcntl.h netinet/in.h stdlib.h string.h sys/ioctl.h sys/socket.h sys/time.h termio.h termios.h unistd.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_TYPE_SIZE_T +AC_HEADER_TIME + +# Checks for library functions. +AC_FUNC_MALLOC +AC_FUNC_SELECT_ARGTYPES +AC_CHECK_FUNCS([inet_ntoa memset select socket]) + +AC_CONFIG_FILES([ + Makefile + src/Makefile + ]) +AC_OUTPUT diff --git b/src/Makefile.am a/src/Makefile.am new file mode 100644 index 0000000..a8c71a1 --- /dev/null +++ a/src/Makefile.am @@ -0,0 +1,12 @@ +lib_LTLIBRARIES = libmodbus.la +libmodbus_la_SOURCES = modbus.c modbus.h + +bin_PROGRAMS = test-modbus +test_modbus_SOURCES = test-modbus.c +test_modbus_INCLUDES = @GLIB_CFLAGS@ +test_modbus_LDADD = libmodbus.la @GLIB_LIBS@ + +INCLUDES = @GLIB_CFLAGS@ +LDADD = @GLIB_LIBS@ +CLEANFILES = *~ + diff --git b/src/modbus.c a/src/modbus.c new file mode 100644 index 0000000..a68ddfc --- /dev/null +++ a/src/modbus.c @@ -0,0 +1,1334 @@ +/* + Copyright (C) 2001-2005 Stéphane Raimbault + + This library 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 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + + The functions included here have been derived from the Modicon + Modbus Protocol Reference Guide which can be obtained from + Schneider at www.schneiderautomation.com. + + Documentation: + http://www.easysw.com/~mike/serial/serial.html +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* TCP */ +#include +#include +#include +#include +#include +#include + +#include "modbus.h" + +#define UNKNOWN_ERROR_MSG "Not defined in modbus specification" + +static const int SIZE_TAB_ERROR_MSG = 12; +static const char *TAB_ERROR_MSG[] = { + /* 0x00 */ UNKNOWN_ERROR_MSG, + /* 0x01 */ "Illegal function code", + /* 0x02 */ "Illegal data address", + /* 0x03 */ "Illegal data value", + /* 0x04 */ "Slave device or server failure", + /* 0x05 */ "Acknowledge", + /* 0x06 */ "Slave device or server busy", + /* 0x07 */ "Negative acknowledge", + /* 0x08 */ "Memory parity error", + /* 0x09 */ UNKNOWN_ERROR_MSG, + /* 0x0A */ "Gateway path unavailable", + /* 0x0B */ "Target device failed to respond" +}; + +/* Table of CRC values for high-order byte */ +static unsigned char table_crc_hi[] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, + 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, + 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, + 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, + 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 +}; + +/* Table of CRC values for low-order byte */ +static unsigned char table_crc_lo[] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, + 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, + 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, + 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, + 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, + 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, + 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, + 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, + 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, + 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, + 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, + 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, + 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, + 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, + 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, + 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, + 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, + 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, + 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, + 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, + 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, + 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, + 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, + 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, + 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 +}; + +/* Local declaration */ +static int read_reg_response(modbus_param_t *mb_param, + int *data_dest, + unsigned char *query); + +static void error_treat(int ret, const char *message, modbus_param_t *mb_param) +{ + if (ret == -1) + perror(message); + g_print("\n\nERROR %s\n\n", message); + + if (mb_param->type_com == RTU) { + tcflush(mb_param->fd, TCIOFLUSH); + } else { + modbus_close(mb_param); + modbus_connect(mb_param); + } +} + +static unsigned int compute_response_size(modbus_param_t *mb_param, + unsigned char *query) +{ + int response_size_computed; + int offset; + + offset = mb_param->header_length; + + switch (query[offset + 1]) { + case 0x01: { + /* Header + nb values (code from force_multiple_coils) */ + int coil_count = (query[offset + 4] << 8) | query[offset + 5]; + response_size_computed = 3 + + (coil_count / 8) + ((coil_count % 8) ? 1 : 0); + } break; + case 0x03: + /* Header + 2 * nb values */ + response_size_computed = 3 + + 2 * (query[offset + 4] << 8 | query[offset + 5]); + break; + case 0x07: + response_size_computed = 4; + break; + default: + response_size_computed = 6; + } + + response_size_computed += offset + mb_param->checksum_size; + + return response_size_computed; +} + +/* The following functions construct the required query into + a modbus query packet */ +int build_request_packet_rtu(int slave, int function, int start_addr, + int count, unsigned char *packet) +{ + packet[0] = slave; + packet[1] = function; + packet[2] = start_addr >> 8; + packet[3] = start_addr & 0x00ff; + packet[4] = count >> 8; + packet[5] = count & 0x00ff; + + return PRESET_QUERY_SIZE_RTU; +} + +int build_request_packet_tcp(int slave, int function, int start_addr, + int count, unsigned char *packet) +{ + static unsigned short t_id = 0; + + /* Transaction ID */ + if (t_id < USHRT_MAX) + t_id++; + else + t_id = 0; + packet[0] = t_id >> 8; + packet[1] = t_id & 0x00ff; + + /* Protocol Modbus */ + packet[2] = 0; + packet[3] = 0; + + /* Length to fix later with set_packet_length_tcp (4 and 5) */ + + packet[6] = 0xFF; + packet[7] = function; + packet[8] = start_addr >> 8; + packet[9] = start_addr & 0x00ff; + packet[10] = count >> 8; + packet[11] = count & 0x00ff; + + return PRESET_QUERY_SIZE_TCP; +} + +void set_packet_length_tcp(unsigned char *packet, size_t packet_size) +{ + unsigned short mbap_length; + + /* Substract MBAP header length */ + mbap_length = packet_size - 6; + + packet[4] = mbap_length >> 8; + packet[5] = mbap_length & 0x00FF; +} + +int build_request_packet(modbus_param_t *mb_param, int slave, + int function, int start_addr, + int count, unsigned char *packet) +{ + if (mb_param->type_com == RTU) + return build_request_packet_rtu(slave, function, start_addr, + count, packet); + else + return build_request_packet_tcp(slave, function, start_addr, + count, packet); +} + +/* Fast CRC */ +static unsigned short crc16(unsigned char *buffer, + unsigned short buffer_length) +{ + unsigned char crc_hi = 0xFF; /* high CRC byte initialized */ + unsigned char crc_lo = 0xFF; /* low CRC byte initialized */ + unsigned int i; /* will index into CRC lookup */ + + /* pass through message buffer */ + while (buffer_length--) { + i = crc_hi ^ *buffer++; /* calculate the CRC */ + crc_hi = crc_lo ^ table_crc_hi[i]; + crc_lo = table_crc_lo[i]; + } + + return (crc_hi << 8 | crc_lo); +} + +/* Function to send a query out to a modbus slave */ +static int modbus_query(modbus_param_t *mb_param, unsigned char *query, + size_t query_size) +{ + int write_ret; + unsigned short s_crc; + int i; + + if (mb_param->type_com == RTU) { + s_crc = crc16(query, query_size); + query[query_size++] = s_crc >> 8; + query[query_size++] = s_crc & 0x00FF; + } else { + set_packet_length_tcp(query, query_size); + } + + if (mb_param->debug) { + g_print("\n"); + for (i = 0; i < query_size; i++) + g_print("[%.2X]", query[i]); + + g_print("\n"); + } + + if (mb_param->type_com == RTU) + write_ret = write(mb_param->fd, query, query_size); + else + write_ret = send(mb_param->fd, query, query_size, 0); + + /* Return the number of bytes written (0 to n) + or PORT_SOCKET_FAILURE on error */ + if ((write_ret == -1) || (write_ret != query_size)) { + error_treat(write_ret, "Write port/socket failure", mb_param); + write_ret = PORT_SOCKET_FAILURE; + } + + return write_ret; +} + +#define WAIT_DATA() \ +{ \ + while ((select_ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv)) == -1) { \ + if (errno == EINTR) { \ + g_print("A non blocked signal was caught\n"); \ + /* Necessary after an error */ \ + FD_ZERO(&rfds); \ + FD_SET(mb_param->fd, &rfds); \ + } else { \ + error_treat(select_ret, "Select failure", mb_param); \ + return SELECT_FAILURE; \ + } \ + } \ + \ + if (select_ret == 0) { \ + /* Call to error_treat is done later to manage exceptions */ \ + return COMM_TIME_OUT; \ + } \ +} + +/* Function to monitor for the reply from the modbus slave. + This function blocks for timeout seconds if there is no reply. + + Returns: + - error_code 0 == OK, < 0 == error + - (arg) total number of characters received. +*/ +int receive_response(modbus_param_t *mb_param, + int response_size_computed, + unsigned char *response, + int *response_size) +{ + int select_ret; + int read_ret; + fd_set rfds; + struct timeval tv; + int size_to_read; + unsigned char *p_response; + + if (mb_param->debug) + g_print("Waiting for response (%d)...\n", response_size_computed); + + /* Add a file descriptor to the set */ + FD_ZERO(&rfds); + FD_SET(mb_param->fd, &rfds); + + /* Wait for a response */ + tv.tv_sec = 0; + tv.tv_usec = TIME_OUT_BEGIN_OF_TRAME; + + WAIT_DATA(); + + /* Read the trame */ + (*response_size) = 0; + size_to_read = response_size_computed; + p_response = response; + + while (select_ret) { + if (mb_param->type_com == RTU) + read_ret = read(mb_param->fd, p_response, size_to_read); + else + read_ret = recv(mb_param->fd, p_response, size_to_read, 0); + + if (read_ret == -1) { + error_treat(read_ret, "Read port/socket failure", mb_param); + return PORT_SOCKET_FAILURE; + } else { + /* Sums bytes received */ + (*response_size) += read_ret; + + /* Display the hex code of each + * character received */ + if (mb_param->debug) { + int i; + for (i=0; i < read_ret; i++) + g_print("<%.2X>", p_response[i]); + } + /* Moves the pointer to receive other datas */ + p_response = &(p_response[read_ret]); + size_to_read = response_size_computed - (*response_size); + + if ((*response_size) > MAX_PACKET_SIZE) { + error_treat(0, "Too many datas", mb_param); + return TOO_MANY_DATAS; + } + } + + if (size_to_read > 0) { + /* If no character at the buffer wait + TIME_OUT_END_OF_TRAME before to generate an error. + */ + tv.tv_sec = 0; + tv.tv_usec = TIME_OUT_END_OF_TRAME; + + WAIT_DATA(); + } else { + /* All chars are received */ + select_ret = FALSE; + } + } + + if (mb_param->debug) + g_print("\n"); + + /* OK */ + return 0; +} + +static int check_crc16(modbus_param_t *mb_param, + unsigned char *response, + int response_size) +{ + int ret; + + if (mb_param->type_com == RTU) { + unsigned short crc_calc; + unsigned short crc_received; + unsigned char recv_crc_hi; + unsigned char recv_crc_lo; + + crc_calc = crc16(response, response_size - 2); + + recv_crc_hi = (unsigned) response[response_size - 2]; + recv_crc_lo = (unsigned) response[response_size - 1]; + + crc_received = response[response_size - 2]; + crc_received = (unsigned) crc_received << 8; + crc_received = crc_received | + (unsigned) response[response_size - 1]; + + /* Check CRC of response */ + if (crc_calc == crc_received) { + ret = TRUE; + } else { + char *message; + message = g_strdup_printf( + "invalid crc received %0X - crc_calc %0X", + crc_received, crc_calc); + error_treat(0, message, mb_param); + g_free(message); + ret = INVALID_CRC; + } + } else { + /* In TCP, CRC doesn't exist but it doesn't check + length because it's not really useful */ + ret = TRUE; + } + + return ret; +} + +/* Function to the correct response is returned and that the checksum + is correct. + + Returns: + - the numbers of values (bits or word) if success + - less than 0 for exception errors + + Note: All functions used for sending or receiving data via modbus + return these values. +*/ + +static int modbus_response(modbus_param_t *mb_param, + unsigned char *query, + unsigned char *response) +{ + int response_size; + int response_size_computed; + int offset = mb_param->header_length; + int error_code; + + response_size_computed = compute_response_size(mb_param, query); + error_code = receive_response(mb_param, response_size_computed, + response, &response_size); + if (error_code == 0) { + /* No error */ + int ret; + + ret = check_crc16(mb_param, response, response_size); + if (ret != TRUE) + return ret; + + /* Good response */ + switch (response[offset + 1]) { + case 0x01: + case 0x02: + /* Read functions 1 value = 1 byte */ + response_size = response[offset + 2]; + break; + case 0x03: + case 0x04: + /* Read functions 1 value = 2 bytes */ + response_size = response[offset + 2] / 2; + break; + case 0x0F: + case 0x10: + /* N Write functions */ + response_size = response[offset + 4] << 8 | + response[offset + 5]; + break; + case 0x11: + /* Report slave ID (bytes received) */ + break; + default: + /* 1 Write functions & others */ + response_size = 1; + } + + } else if (error_code == COMM_TIME_OUT && + response_size == offset + 3 + mb_param->checksum_size) { + /* Optimisation allowed because exception response is + the smallest trame in modbus protocol (3) so always + raise an timeout error */ + int ret; + + /* CRC */ + ret = check_crc16(mb_param, response, response_size); + if (ret != TRUE) + return ret; + + /* Check for exception response + 0x80 + function */ + if (0x80 + query[offset + 1] == response[offset + 1]) { + + if (response[offset + 2] < SIZE_TAB_ERROR_MSG) { + error_treat(0, + TAB_ERROR_MSG[response[offset + 2]], + mb_param); + /* Modbus error code (negative) */ + return -response[offset + 2]; + } else { + /* The chances are low to hit this + case but can avoid a vicious + segfault */ + char *message; + message = g_strdup_printf( + "Invalid exception code %d", + response[offset + 2]); + error_treat(0, message, mb_param); + g_free(message); + return INVALID_EXCEPTION_CODE; + } + } + } else if (error_code == COMM_TIME_OUT) { + error_treat(0, "Communication time out", mb_param); + return COMM_TIME_OUT; + } else { + return error_code; + } + + return response_size; +} + +/* Read IO status */ +static int read_io_status(modbus_param_t *mb_param, int slave, int function, + int start_addr, int count, int *data_dest) +{ + int query_size; + int query_ret; + int response_ret; + + unsigned char query[MIN_QUERY_SIZE]; + unsigned char response[MAX_PACKET_SIZE]; + + query_size = build_request_packet(mb_param, slave, function, + start_addr, count, query); + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) { + int i, temp, bit; + int pos = 0; + int processed = 0; + int offset; + int offset_length; + + response_ret = modbus_response(mb_param, query, response); + offset = mb_param->header_length; + + offset_length = offset + response_ret; + for (i = offset; i < offset_length; i++) { + /* Shift reg hi_byte to temp */ + temp = response[3 + i]; + + for (bit = 0x01; + (bit & 0xff) && (processed < count);) { + data_dest[pos++] = + (temp & bit) ? TRUE : FALSE; + processed++; + bit = bit << 1; + } + + } + } else { + response_ret = query_ret; + } + + return response_ret; +} + +/* Reads the boolean status of coils and sets the array elements + in the destination to TRUE or FALSE */ +int read_coil_status(modbus_param_t *mb_param, int slave, int start_addr, + int count, int *data_dest) +{ + int function = 0x01; + int status; + + status = read_io_status(mb_param, slave, function, start_addr, + count, data_dest); + + if (status > 0) + status = count; + + return status; +} + +/* Same as read_coil_status but reads the slaves input table */ +int read_input_status(modbus_param_t *mb_param, int slave, int start_addr, + int count, int *data_dest) +{ + int function = 0x02; + int status; + + status = read_io_status(mb_param, slave, function, start_addr, + count, data_dest); + + if (status > 0) + status = count; + + return status; +} + +/* Read the data from a modbus slave and put that data into an array */ +static int read_registers(modbus_param_t *mb_param, int slave, int function, + int start_addr, int count, int *data_dest) +{ + int query_size; + int status; + int query_ret; + unsigned char query[MIN_QUERY_SIZE]; + + query_size = build_request_packet(mb_param, slave, function, + start_addr, count, query); + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) + status = read_reg_response(mb_param, data_dest, query); + else + status = query_ret; + + return status; +} + +/* Read the holding registers in a slave and put the data into an + array */ +int read_holding_registers(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *data_dest) +{ + int function = 0x03; + int status; + + if (count > MAX_READ_HOLD_REGS) { + g_print("WARNING Too many holding registers requested\n"); + count = MAX_READ_HOLD_REGS; + } + + status = read_registers(mb_param, slave, function, + start_addr, count, data_dest); + return status; +} + +/* Read the input registers in a slave and put the data into + an array */ +int read_input_registers(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *data_dest) +{ + int function = 0x04; + int status; + + if (count > MAX_READ_INPUT_REGS) { + g_print("WARNING Too many input registers requested\n"); + count = MAX_READ_INPUT_REGS; + } + + status = read_registers(mb_param, slave, function, + start_addr, count, data_dest); + + return status; +} + +/* Reads the response data from a slave and puts the data into an + array */ +static int read_reg_response(modbus_param_t *mb_param, int *data_dest, + unsigned char *query) +{ + unsigned char response[MAX_PACKET_SIZE]; + int response_ret; + int offset; + int i; + + response_ret = modbus_response(mb_param, query, response); + + offset = mb_param->header_length; + + /* If response_ret is negative, the loop is jumped ! */ + for (i = 0; i < response_ret; i++) { + /* shift reg hi_byte to temp OR with lo_byte */ + data_dest[i] = response[offset + 3 + (i << 1)] << 8 | + response[offset + 4 + (i << 1)]; + } + + return response_ret; +} + +/* Gets the raw data from the input stream */ +static int preset_response(modbus_param_t *mb_param, unsigned char *query) +{ + int ret; + unsigned char response[MAX_PACKET_SIZE]; + + ret = modbus_response(mb_param, query, response); + + return ret; +} + +/* Sends a value to a register in a slave */ +static int set_single(modbus_param_t *mb_param, int slave, int function, + int addr, int value) +{ + int status; + int query_size; + int query_ret; + unsigned char query[MAX_PACKET_SIZE]; + + query_size = build_request_packet(mb_param, slave, function, + addr, value, query); + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) + status = preset_response(mb_param, query); + else + status = query_ret; + + return status; +} + + +/* Turn on or off a single coil on the slave device */ +int force_single_coil(modbus_param_t *mb_param, int slave, + int coil_addr, int state) +{ + int function = 0x05; + int status; + + if (state) + state = 0xFF00; + + status = set_single(mb_param, slave, function, coil_addr, state); + + return status; +} + +/* Sets a value in one holding register in the slave device */ +int preset_single_register(modbus_param_t *mb_param, int slave, + int reg_addr, int value) +{ + int function = 0x06; + int status; + + status = set_single(mb_param, slave, function, reg_addr, value); + + return status; +} + +/* Takes an array of ints and sets or resets the coils on a slave + appropriatly */ +int force_multiple_coils(modbus_param_t *mb_param, int slave, + int start_addr, int coil_count, + int *data_src) +{ + int function = 0x0F; + int i; + int byte_count; + int query_size; + int coil_check = 0; + int status; + int query_ret; + + unsigned char query[MAX_PACKET_SIZE]; + + if (coil_count > MAX_WRITE_COILS) { + g_print("WARNING Writing to too many coils\n"); + coil_count = MAX_WRITE_COILS; + } + + query_size = build_request_packet(mb_param, slave, function, + start_addr, coil_count, query); + byte_count = (coil_count / 8) + ((coil_count % 8) ? 1 : 0); + query[query_size++] = byte_count; + + for (i = 0; i < byte_count; i++) { + int bit; + int pos = 0; + + bit = 0x01; + query[query_size] = 0; + + while ((bit & 0xFF) && (coil_check++ < coil_count)) { + if (data_src[pos++]) + query[query_size] |= bit; + else + query[query_size] &=~ bit; + + bit = bit << 1; + } + query_size++; + } + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) + status = preset_response(mb_param, query); + else + status = query_ret; + + return status; +} + +/* Copy the values in an array to an array on the slave */ +int preset_multiple_registers(modbus_param_t *mb_param, int slave, + int start_addr, int reg_count, int *data_src) +{ + int function = 0x10; + int i; + int query_size; + int byte_count; + int status; + int query_ret; + + unsigned char query[MAX_PACKET_SIZE]; + + if (reg_count > MAX_WRITE_REGS) { + g_print("WARNING Trying to write to too many registers\n"); + reg_count = MAX_WRITE_REGS; + } + + query_size = build_request_packet(mb_param, slave, function, + start_addr, reg_count, query); + byte_count = reg_count * 2; + query[query_size++] = byte_count; + + for (i = 0; i < reg_count; i++) { + query[query_size++] = data_src[i] >> 8; + query[query_size++] = data_src[i] & 0x00FF; + } + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) + status = preset_response(mb_param, query); + else + status = query_ret; + + return status; +} + +/* Returns the slave id ! */ +int report_slave_id(modbus_param_t *mb_param, int slave, + unsigned char *data_dest) +{ + int function = 0x11; + int query_size; + int query_ret; + int response_ret; + + unsigned char query[MIN_QUERY_SIZE]; + unsigned char response[MAX_PACKET_SIZE]; + + query_size = build_request_packet(mb_param, slave, function, + 0, 0, query); + + /* start_addr and count are not used */ + query_size -= 4; + + query_ret = modbus_query(mb_param, query, query_size); + if (query_ret > 0) { + int i; + int offset; + int offset_length; + + /* Byte count, slave id, run indicator status, + additional data */ + response_ret = modbus_response(mb_param, query, response); + + offset = mb_param->header_length; + offset_length = offset + response_ret; + + for (i = offset; i < offset_length; i++) + data_dest[i] = response[i]; + } else { + response_ret = query_ret; + } + + return response_ret; +} + +/* Initialises the modbus_param_t structure for RTU */ +void modbus_init_rtu(modbus_param_t *mb_param, char *device, + int baud_i, char *parity, int data_bit, + int stop_bit) +{ + memset(mb_param, 0, sizeof(modbus_param_t)); + strcpy(mb_param->device, device); + mb_param->baud_i = baud_i; + strcpy(mb_param->parity, parity); + mb_param->debug = FALSE; + mb_param->data_bit = data_bit; + mb_param->stop_bit = stop_bit; + mb_param->type_com = RTU; + mb_param->header_length = HEADER_LENGTH_RTU; + mb_param->checksum_size = CHECKSUM_SIZE_RTU; +} + +/* Initialises the modbus_param_t structure for TCP */ +void modbus_init_tcp(modbus_param_t *mb_param, char *ip) +{ + memset(mb_param, 0, sizeof(modbus_param_t)); + strncpy(mb_param->ip, ip, sizeof(char)*16); + mb_param->type_com = TCP; + mb_param->header_length = HEADER_LENGTH_TCP; + mb_param->checksum_size = CHECKSUM_SIZE_TCP; +} + + +/* This function sets up a serial port for RTU communications to + modbus */ +static int modbus_connect_rtu(modbus_param_t *mb_param) +{ + struct termios tios; + speed_t baud_rate; + + if (mb_param->debug) { + g_print("Opening %s at %d bauds (%s)\n", + mb_param->device, mb_param->baud_i, mb_param->parity); + } + + /* The O_NOCTTY flag tells UNIX that this program doesn't want + to be the "controlling terminal" for that port. If you + don't specify this then any input (such as keyboard abort + signals and so forth) will affect your process + + Timeouts are ignored in canonical input mode or when the + NDELAY option is set on the file via open or fcntl */ + mb_param->fd = open(mb_param->device, O_RDWR | O_NOCTTY | O_NDELAY); + if (mb_param->fd < 0) { + perror("open"); + g_print("ERROR Opening device %s (no : %d)\n", + mb_param->device, errno); + return -1; + } + + /* Save */ + tcgetattr(mb_param->fd, &(mb_param->old_tios)); + + memset(&tios, 0, sizeof(struct termios)); + + /* C_ISPEED Input baud (new interface) + C_OSPEED Output baud (new interface) + */ + switch (mb_param->baud_i) { + case 110: + baud_rate = B110; + break; + case 300: + baud_rate = B300; + break; + case 600: + baud_rate = B600; + break; + case 1200: + baud_rate = B1200; + break; + case 2400: + baud_rate = B2400; + break; + case 4800: + baud_rate = B4800; + break; + case 9600: + baud_rate = B9600; + break; + case 19200: + baud_rate = B19200; + break; + case 38400: + baud_rate = B38400; + break; + case 57600: + baud_rate = B57600; + break; + case 115200: + baud_rate = B115200; + break; + default: + baud_rate = B9600; + g_print("WARNING Unknown baud rate %d for %s (B9600 used)\n", + mb_param->baud_i, mb_param->device); + } + + /* Set the baud rate */ + if ((cfsetispeed(&tios, baud_rate) < 0) || + (cfsetospeed(&tios, baud_rate) < 0)) { + perror("cfsetispeed/cfsetospeed\n"); + return -1; + } + + /* C_CFLAG Control options + CLOCAL Local line - do not change "owner" of port + CREAD Enable receiver + */ + tios.c_cflag |= (CREAD | CLOCAL); + /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */ + + /* Set data bits (5, 6, 7, 8 bits) + CSIZE Bit mask for data bits + */ + tios.c_cflag &= ~CSIZE; + switch (mb_param->data_bit) { + case 5: + tios.c_cflag |= CS5; + break; + case 6: + tios.c_cflag |= CS6; + break; + case 7: + tios.c_cflag |= CS7; + break; + case 8: + default: + tios.c_cflag |= CS8; + break; + } + + /* Stop bit (1 or 2) */ + if (mb_param->stop_bit == 1) + tios.c_cflag &=~ CSTOPB; + else /* 2 */ + tios.c_cflag |= CSTOPB; + + /* PARENB Enable parity bit + PARODD Use odd parity instead of even */ + if (strncmp(mb_param->parity, "none", 4) == 0) { + tios.c_cflag &=~ PARENB; + } else if (strncmp(mb_param->parity, "even", 4) == 0) { + tios.c_cflag |= PARENB; + tios.c_cflag &=~ PARODD; + } else { + /* odd */ + tios.c_cflag |= PARENB; + tios.c_cflag |= PARODD; + } + + /* Read your man page for the meaning of all this (man + termios). Its a bit to involved to comment here :) */ + tios.c_line = 0; + + /* C_LFLAG Line options + + ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals + ICANON Enable canonical input (else raw) + XCASE Map uppercase \lowercase (obsolete) + ECHO Enable echoing of input characters + ECHOE Echo erase character as BS-SP-BS + ECHOK Echo NL after kill character + ECHONL Echo NL + NOFLSH Disable flushing of input buffers after + interrupt or quit characters + IEXTEN Enable extended functions + ECHOCTL Echo control characters as ^char and delete as ~? + ECHOPRT Echo erased character as character erased + ECHOKE BS-SP-BS entire line on line kill + FLUSHO Output being flushed + PENDIN Retype pending input at next read or input char + TOSTOP Send SIGTTOU for background output + + Canonical input is line-oriented. Input characters are put + into a buffer which can be edited interactively by the user + until a CR (carriage return) or LF (line feed) character is + received. + + Raw input is unprocessed. Input characters are passed + through exactly as they are received, when they are + received. Generally you'll deselect the ICANON, ECHO, + ECHOE, and ISIG options when using raw input + */ + + /* Raw input */ + tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + + /* C_IFLAG Input options + + Constant Description + INPCK Enable parity check + IGNPAR Ignore parity errors + PARMRK Mark parity errors + ISTRIP Strip parity bits + IXON Enable software flow control (outgoing) + IXOFF Enable software flow control (incoming) + IXANY Allow any character to start flow again + IGNBRK Ignore break condition + BRKINT Send a SIGINT when a break condition is detected + INLCR Map NL to CR + IGNCR Ignore CR + ICRNL Map CR to NL + IUCLC Map uppercase to lowercase + IMAXBEL Echo BEL on input line too long + */ + if (strncmp(mb_param->parity, "none", 4) == 0) { + tios.c_iflag &= ~INPCK; + } else { + tios.c_iflag |= INPCK; + } + + /* Software flow control is disabled */ + tios.c_iflag &= ~(IXON | IXOFF | IXANY); + + /* C_OFLAG Output options + OPOST Postprocess output (not set = raw output) + ONLCR Map NL to CR-NL + + ONCLR ant others needs OPOST to be enabled + */ + + /* Raw ouput */ + tios.c_oflag &=~ OPOST; + + /* C_CC Control characters + VMIN Minimum number of characters to read + VTIME Time to wait for data (tenths of seconds) + + UNIX serial interface drivers provide the ability to + specify character and packet timeouts. Two elements of the + c_cc array are used for timeouts: VMIN and VTIME. Timeouts + are ignored in canonical input mode or when the NDELAY + option is set on the file via open or fcntl. + + VMIN specifies the minimum number of characters to read. If + it is set to 0, then the VTIME value specifies the time to + wait for every character read. Note that this does not mean + that a read call for N bytes will wait for N characters to + come in. Rather, the timeout will apply to the first + character and the read call will return the number of + characters immediately available (up to the number you + request). + + If VMIN is non-zero, VTIME specifies the time to wait for + the first character read. If a character is read within the + time given, any read will block (wait) until all VMIN + characters are read. That is, once the first character is + read, the serial interface driver expects to receive an + entire packet of characters (VMIN bytes total). If no + character is read within the time allowed, then the call to + read returns 0. This method allows you to tell the serial + driver you need exactly N bytes and any read call will + return 0 or N bytes. However, the timeout only applies to + the first character read, so if for some reason the driver + misses one character inside the N byte packet then the read + call could block forever waiting for additional input + characters. + + VTIME specifies the amount of time to wait for incoming + characters in tenths of seconds. If VTIME is set to 0 (the + default), reads will block (wait) indefinitely unless the + NDELAY option is set on the port with open or fcntl. + */ + /* Unused because we use open with the NDELAY option */ + tios.c_cc[VMIN] = 0; + tios.c_cc[VTIME] = 0; + + if (tcsetattr(mb_param->fd, TCSANOW, &tios) < 0) { + perror("tcsetattr\n"); + return -1; + } + + return 0; +} + +static int modbus_connect_tcp(modbus_param_t *mb_param) +{ + int ret; + int option; + struct sockaddr_in addr; + + addr.sin_family = AF_INET; + addr.sin_port = htons(MODBUS_TCP_PORT); + addr.sin_addr.s_addr = inet_addr(mb_param->ip); + + mb_param->fd = socket(AF_INET, SOCK_STREAM, 0); + if (mb_param->fd < 0) { + return mb_param->fd; + } + + /* Set the TCP no delay flag */ + /* SOL_TCP = IPPROTO_TCP */ + option = 1; + ret = setsockopt(mb_param->fd, SOL_TCP, TCP_NODELAY, + (const void *)&option, sizeof(int)); + if (ret < 0) { + perror("setsockopt"); + close(mb_param->fd); + return ret; + } + + /* Set the IP low delay option */ + option = IPTOS_LOWDELAY; + ret = setsockopt(mb_param->fd, SOL_TCP, IP_TOS, + (const void *)&option, sizeof(int)); + if (ret < 0) { + perror("setsockopt"); + close(mb_param->fd); + return ret; + } + + if (mb_param->debug) { + g_print("Connecting to %s\n", mb_param->ip); + } + + ret = connect(mb_param->fd, (struct sockaddr *)&addr, + sizeof(struct sockaddr_in)); + if (ret < 0) { + perror("connect"); + close(mb_param->fd); + return ret; + } + + return 0; +} + +int modbus_connect(modbus_param_t *mb_param) +{ + int ret; + + if (mb_param->type_com == RTU) + ret = modbus_connect_rtu(mb_param); + else + ret = modbus_connect_tcp(mb_param); + + return ret; +} + +void modbus_listen_tcp(modbus_param_t *mb_param) +{ + int ret; + int new_socket; + struct sockaddr_in addr; + int addrlen; + + addr.sin_family = AF_INET; + /* The modbus port is < 1024 + This program must be made setuid root. */ + addr.sin_port = htons(MODBUS_TCP_PORT); + addr.sin_addr.s_addr = INADDR_ANY; + memset(&(addr.sin_zero), '\0', 8); + + new_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (new_socket < 0) { + perror("socket"); + exit(1); + } else { + g_print("Socket OK\n"); + } + + ret = bind(new_socket, (struct sockaddr *)&addr, + sizeof(struct sockaddr_in)); + if (ret < 0) { + perror("bind"); + close(new_socket); + exit(1); + } else { + g_print("Bind OK\n"); + } + + ret = listen(new_socket, 1); + if (ret != 0) { + perror("listen"); + close(new_socket); + exit(1); + } else { + g_print("Listen OK\n"); + } + + addrlen = sizeof(struct sockaddr_in); + mb_param->fd = accept(new_socket, (struct sockaddr *)&addr, &addrlen); + if (ret < 0) { + perror("accept"); + close(new_socket); + exit(1); + } else { + unsigned char response[MAX_PACKET_SIZE]; + int response_size; + + g_print("The client %s is connected\n", + inet_ntoa(addr.sin_addr)); + + receive_response(mb_param, MAX_PACKET_SIZE, + response, &response_size); + } + + close(new_socket); +} + +/* Close the file descriptor */ +static void modbus_close_rtu(modbus_param_t *mb_param) +{ + if (tcsetattr(mb_param->fd, TCSANOW, &(mb_param->old_tios)) < 0) + perror("tcsetattr"); + + close(mb_param->fd); +} + +static void modbus_close_tcp(modbus_param_t *mb_param) +{ + shutdown(mb_param->fd, SHUT_RDWR); + close(mb_param->fd); +} + +void modbus_close(modbus_param_t *mb_param) +{ + if (mb_param->type_com == RTU) + modbus_close_rtu(mb_param); + else + modbus_close_tcp(mb_param); +} + +void modbus_set_debug(modbus_param_t *mb_param, int boolean) +{ + mb_param->debug = boolean; +} diff --git b/src/modbus.h a/src/modbus.h new file mode 100644 index 0000000..41a7f11 --- /dev/null +++ a/src/modbus.h @@ -0,0 +1,199 @@ +/* + Copyright (C) 2001-2005 Stéphane Raimbault + + This library 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 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + + These library of functions are designed to enable a program send and + receive data from a device that communicates using the Modbus protocol. +*/ + +#ifndef _MODBUS_H_ +#define _MODBUS_H_ + +#include +#include + +#define MODBUS_TCP_PORT 502 + +#define HEADER_LENGTH_RTU 0 +#define PRESET_QUERY_SIZE_RTU 6 + +#define HEADER_LENGTH_TCP 6 +#define PRESET_QUERY_SIZE_TCP 12 + +#define CHECKSUM_SIZE_RTU 2 +#define CHECKSUM_SIZE_TCP 0 + +/* 8 + HEADER_LENGTH_TCP */ +#define MIN_QUERY_SIZE 14 + +/* MIN_RESPONSE_LENGTH + MAX(MAX*) */ +#define MAX_PACKET_SIZE 261 + +#define MAX_READ_STATUS 800 +#define MAX_READ_HOLD_REGS 100 +#define MAX_READ_INPUT_REGS 100 +#define MAX_WRITE_COILS 800 +#define MAX_WRITE_REGS 100 + +#define REPORT_SLAVE_ID_SIZE 75 + +/* Time out between trames in microsecond */ +#define TIME_OUT_BEGIN_OF_TRAME 500000 +#define TIME_OUT_END_OF_TRAME 500000 + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +/* Protocol exceptions */ +#define ILLEGAL_FUNCTION -0x01 +#define ILLEGAL_DATA_ADDRESS -0x02 +#define ILLEGAL_DATA_VALUE -0x03 +#define SLAVE_DEVICE_FAILURE -0x04 +#define SERVER_FAILURE -0x04 +#define ACKNOWLEDGE -0x05 +#define SLAVE_DEVICE_BUSY -0x06 +#define SERVER_BUSY -0x06 +#define NEGATIVE_ACKNOWLEDGE -0x07 +#define MEMORY_PARITY_ERROR -0x08 +#define GATEWAY_PROBLEM_PATH -0x0A +#define GATEWAY_PROBLEM_TARGET -0x0B + +/* Local */ +#define COMM_TIME_OUT -0x0C +#define PORT_SOCKET_FAILURE -0x0D +#define SELECT_FAILURE -0x0E +#define TOO_MANY_DATAS -0x0F +#define INVALID_CRC -0x10 +#define INVALID_EXCEPTION_CODE -0x11 + +typedef enum { RTU, TCP } type_com_t; + +typedef struct _modbus_param_t { + /* Communication : RTU or TCP */ + type_com_t type_com; + /* Device: "/dev/ttyS0" */ + char device[11]; + /* Bauds: 19200 */ + int baud_i; + /* Parity: "even", "odd", "none" */ + char parity[5]; + /* Data bit */ + int data_bit; + /* Stop bit */ + int stop_bit; + /* Save old termios settings */ + struct termios old_tios; + /* Descriptor (tty or socket) */ + int fd; + /* Flag debug */ + int debug; + /* IP address */ + char ip[16]; + /* Header length used for offset */ + int header_length; + /* Checksum size RTU = 2 and TCP = 0 */ + int checksum_size; +} modbus_param_t; + +/* All functions used for sending or receiving data return : + - the numbers of values (bits or word) if success (0 or more) + - less than 0 for exceptions errors +*/ + +/* Reads the boolean status of coils and sets the array elements in + the destination to TRUE or FALSE */ +int read_coil_status(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *dest); + +/* Same as read_coil_status but reads the slaves input table */ +int read_input_status(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *dest); + +/* Read the holding registers in a slave and put the data into an + array */ +int read_holding_registers(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *dest); + + +/* Read the input registers in a slave and put the data into an + array */ +int read_input_registers(modbus_param_t *mb_param, int slave, + int start_addr, int count, int *dest); + +/* Turn on or off a single coil on the slave device */ +int force_single_coil(modbus_param_t *mb_param, int slave, + int coil_addr, int state); + +/* Sets a value in one holding register in the slave device */ +int preset_single_register(modbus_param_t *mb_param, int slave, + int reg_addr, int value); + +/* Takes an array of ints and sets or resets the coils on a slave + appropriatly */ +int force_multiple_coils(modbus_param_t *mb_param, int slave, + int start_addr, int coil_count, int *data); + +/* Copy the values in an array to an array on the slave */ +int preset_multiple_registers(modbus_param_t *mb_param, int slave, + int start_addr, int reg_count, int *data); + +/* Returns some useful information about the modbus controller */ +int report_slave_id(modbus_param_t *mb_param, int slave, + unsigned char *dest); + +/* Initialises a parameters structure + - device : "/dev/ttyS0" + - baud : 19200 + - parity : "even", "odd" or "none" + - data_bits : 5, 6, 7, 8 + - stop_bits : 1, 2 +*/ +void modbus_init_rtu(modbus_param_t *mb_param, char *device, + int baud, char *parity, int data_bit, + int stop_bit); +/* Initialises a parameters structure for TCP + - ip : "192.168.0.5" */ +void modbus_init_tcp(modbus_param_t *mb_param, char *ip_address); + + +/* This function sets up a serial port for RTU communications to + modbus or a TCP connexion */ +int modbus_connect(modbus_param_t *mb_param); + +/* This function closes the serial port and restores the previous port + configuration or close the TCP connexion */ +void modbus_close(modbus_param_t *mb_param); + +/* Set in debug mode */ +void modbus_set_debug(modbus_param_t *mb_param, int boolean); + +/* Useful for a 'daemon' */ +void modbus_listen_tcp(modbus_param_t *mb_param); + +/* Non implemented : + - read_exception_status() +*/ + +/* Find out what a master is trying to ask this slave device */ +int get_slave_query_tcp(modbus_param_t *mb_param, int *slave_addr, int *query, + int *start_addr, int *point_count, int *data); + +#endif /* _MODBUS_H_ */ diff --git b/src/test-modbus.c a/src/test-modbus.c new file mode 100644 index 0000000..46cb616 --- /dev/null +++ a/src/test-modbus.c @@ -0,0 +1,188 @@ +/* + Copyright (C) 2001-2005 Stéphane Raimbault + + This library 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 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + + These library of functions are designed to enable a program send and + receive data from a device that communicates using the Modbus protocol. +*/ + +#include +#include +#include +#include + +#include + +#define LOOP 1 +#define SLAVE 1 +#define ADDR_MIN 100 +#define ADDR_MAX 150 +#define FIELDS 50 + +int main(void) +{ + int ok, fail; + int loop_nb; + int addr; + int field_nb; + int *tab_rq; + int *tab_rq_bits; + int *tab_rp; + modbus_param_t mb_param; + + /* RTU parity : none, even, odd */ +/* modbus_init_rtu(&mb_param, "/dev/ttyS0", 19200, "none", 8, 1); */ + + /* TCP */ + modbus_init_tcp(&mb_param, "192.168.0.100"); + modbus_set_debug(&mb_param, TRUE); + + modbus_connect(&mb_param); + + tab_rq = (int *) malloc(FIELDS * sizeof(int)); + tab_rq_bits = (int *) malloc(FIELDS * sizeof(int)); + tab_rp = (int *) malloc(FIELDS * sizeof(int)); + + loop_nb = ok = fail = 0; + while (loop_nb++ < LOOP) { + for (addr=ADDR_MIN; addr <= ADDR_MAX; addr++) { + for (field_nb=1; field_nb<=FIELDS; field_nb++) { + int i; + + /* Random numbers (short) */ + for (i=0; i