serialport-1.3.2/0000755000004100000410000000000014136323005013726 5ustar www-datawww-dataserialport-1.3.2/serialport.gemspec0000644000004100000410000000172514136323005017464 0ustar www-datawww-data# -*- encoding: utf-8 -*- require File.expand_path('../lib/serialport/version', __FILE__) Gem::Specification.new do |s| s.name = "serialport" s.license = "GPL-2" s.version = SerialPort::VERSION s.authors = ["Guillaume Pierronnet", "Alan Stern", "Daniel E. Shipton", "Tobin Richard", "Hector Parra", "Ryan C. Payne"] s.summary = "Library for using RS-232 serial ports." s.description = "Ruby/SerialPort is a Ruby library that provides a class for using RS-232 serial ports." s.email = "hector@hectorparra.com" s.homepage = "http://github.com/hparra/ruby-serialport/" s.add_development_dependency "bundler" s.add_development_dependency "rake" s.add_development_dependency "rake-compiler", ">= 0.4.1" s.require_paths = ["lib"] s.files = `git ls-files`.split($\) s.extensions = "ext/native/extconf.rb" s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) } s.extra_rdoc_files = ["LICENSE", "README.md"] end serialport-1.3.2/.travis.yml0000644000004100000410000000023014136323005016032 0ustar www-datawww-datalanguage: ruby script: "bundle exec rake test" rvm: - 1.8.7 - 1.9.2 - 1.9.3 - 2.0.0 compiler: - clang - gcc before_script: - rake compile serialport-1.3.2/test/0000755000004100000410000000000014136323005014705 5ustar www-datawww-dataserialport-1.3.2/test/miniterm.rb0000755000004100000410000000065414136323005017066 0ustar www-datawww-datarequire "../serialport.so" if ARGV.size < 4 STDERR.print < or run `yard` ## Issues See ## Alternatives The [Hybrid Group](http://hybridgroup.com/)'s MRI, JRuby, & Rubinius compatible [rubyserial](https://github.com/hybridgroup/rubyserial) gem may provide improved compatibilty in modern environments. ## License GPL ## Authors * Guillaume Pierronnet * Alan Stern * Tobin Richard * Hector Parra * Ryan C. Payne serialport-1.3.2/.gitignore0000644000004100000410000000025714136323005015722 0ustar www-datawww-data.DS_Store /pkg /doc /tmp /ext/native/*.bundle /ext/native/*.log /ext/native/*.o /ext/native/*.so /ext/native/Makefile lib/*.so .*.swp tags *.gem *.bundle Gemfile.lock .yardoc serialport-1.3.2/LICENSE0000644000004100000410000004310314136323005014734 0ustar www-datawww-data GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 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 Lesser 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 Lesser General Public License instead of this License. serialport-1.3.2/Rakefile0000644000004100000410000000105614136323005015375 0ustar www-datawww-data # :build # :install # :release require "bundler/gem_tasks" # :clean # :clobber # :compile # :compile:serialport require "rake/extensiontask" CLOBBER << FileList["doc"] CLOBBER << FileList["pkg"] GEMSPEC = eval File.read File.expand_path("../serialport.gemspec", __FILE__) Rake::ExtensionTask.new "serialport", GEMSPEC do |ext| ext.lib_dir = File.join(*['lib', ENV['FAT_DIR']].compact) ext.ext_dir = "ext/native" end # add your default gem packing task Gem::PackageTask.new(GEMSPEC) do |pkg| end task :default => [:clean, :clobber, :compile, :test]serialport-1.3.2/lib/0000755000004100000410000000000014136323005014474 5ustar www-datawww-dataserialport-1.3.2/lib/serialport.rb0000644000004100000410000000344414136323005017212 0ustar www-datawww-datarequire 'serialport.so' require 'serialport/version' # This class is used for communication over a serial port. # In addition to the methods here, you can use Ruby IO methods, e.g. read, write, getc, readlines, etc. # # @see http://rubydoc.info/stdlib/core/IO Ruby IO class # @see http://www.cmrr.umn.edu/~strupp/serial.html "Serial Programming Guide for POSIX Operating Systems" class SerialPort private_class_method(:create) # Creates a serial port object. # Accepts the port identifier and a variable list for configuration as paramaters or hash. # Please see SerialPort#set_modem_params # # @overload new(port, *params) # @param port [Integer] the serial port number, # where 0 is mapped to "COM1" on Windows, "/dev/ttyS0" on Linux, "/dev/cuaa0" on Mac OS X, etc. # @overload new(port, *params) # @param port [String] the serial port file e.g. "/dev/ttyS0" # @return [SerialPort] # @see SerialPort#set_modem_params def SerialPort::new(port, *params) sp = create(port) begin sp.set_modem_params(*params) rescue sp.close raise end return sp end # This behaves like SerialPort#new, except that you can pass a block # to which the new serial port object will be passed. In this case # the connection is automaticaly closed when the block has finished. # # @yield [serial_port] the serial port number or filename # @see SerialPort#new # @see SerialPort#set_modem_params def SerialPort::open(port, *params) sp = create(port) begin sp.set_modem_params(*params) rescue sp.close raise end if (block_given?) begin yield sp ensure sp.close end return nil end return sp end end serialport-1.3.2/lib/serialport/0000755000004100000410000000000014136323005016660 5ustar www-datawww-dataserialport-1.3.2/lib/serialport/version.rb0000644000004100000410000000005114136323005020666 0ustar www-datawww-dataclass SerialPort VERSION = "1.3.2" end serialport-1.3.2/Gemfile0000644000004100000410000000010614136323005015216 0ustar www-datawww-datasource "https://rubygems.org" source "http://gems.github.com" gemspec serialport-1.3.2/CHECKLIST0000644000004100000410000000042614136323005015164 0ustar www-datawww-data# Ruby-Serialport Gem Release Checklist * Update documentation * Update lib/serialport/version.rb * Update CHANGELOG * Update README * `rake build` * `rake install` * Test build * `git tag -a v{VERSION} -m "v{VERSION}: {ONE-LINE DESCRIPTION}"` * Merge and Push * `rake release`serialport-1.3.2/ext/0000755000004100000410000000000014136323005014526 5ustar www-datawww-dataserialport-1.3.2/ext/native/0000755000004100000410000000000014136323005016014 5ustar www-datawww-dataserialport-1.3.2/ext/native/posix_serialport_impl.c0000644000004100000410000003723514136323005022621 0ustar www-datawww-data/* Ruby/SerialPort * Guillaume Pierronnet * Alan Stern * Daniel E. Shipton * Ryan C. Payne * Manuel "MaG" A. Güílamo * * This code is hereby licensed for public consumption under either the * GNU GPL v2 or greater. * * 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. * * For documentation on serial programming, see the excellent: * "Serial Programming Guide for POSIX Operating Systems" * written Michael R. Sweet. * http://www.easysw.com/~mike/serial/ */ #include "serialport.h" /* Check if we are on a posix compliant system. */ #if !defined(OS_MSWIN) && !defined(OS_BCCWIN) && !defined(OS_MINGW) #include /* Standard input/output definitions */ #include /* UNIX standard function definitions */ #include /* File control definitions */ #include /* Error number definitions */ #include /* POSIX terminal control definitions */ #include #ifdef CRTSCTS #define HAVE_FLOWCONTROL_HARD 1 #else #undef HAVE_FLOWCONTROL_HARD #endif /* on mac os x, not all baud rates are defined in termios.h but they are mapped to the numeric value anyway, so we define them here */ #ifdef __APPLE__ #ifndef B460800 #define B460800 460800 #endif #ifndef B500000 #define B500000 500000 #endif #ifndef B576000 #define B576000 576000 #endif #ifndef B921600 #define B921600 921600 #endif #ifndef B1000000 #define B1000000 1000000 #endif #endif static char sTcgetattr[] = "tcgetattr"; static char sTcsetattr[] = "tcsetattr"; static char sIoctl[] = "ioctl"; int get_fd_helper(obj) VALUE obj; { #ifdef HAVE_RUBY_IO_H rb_io_t *fptr; #else OpenFile *fptr; #endif GetOpenFile(obj, fptr); #ifdef HAVE_RUBY_IO_H return (fptr->fd); #else return (fileno(fptr->f)); #endif } VALUE sp_create_impl(class, _port) VALUE class, _port; { #ifdef HAVE_RUBY_IO_H rb_io_t *fp; #else OpenFile *fp; #endif int fd; int num_port; char *port; char *ports[] = { #if defined(OS_LINUX) || defined(OS_CYGWIN) "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3", "/dev/ttyS4", "/dev/ttyS5", "/dev/ttyS6", "/dev/ttyS7" #elif defined(OS_FREEBSD) || defined(OS_NETBSD) || defined(OS_OPENBSD) || defined(OS_DARWIN) "/dev/cuaa0", "/dev/cuaa1", "/dev/cuaa2", "/dev/cuaa3", "/dev/cuaa4", "/dev/cuaa5", "/dev/cuaa6", "/dev/cuaa7" #elif defined(OS_SOLARIS) "/dev/ttya", "/dev/ttyb", "/dev/ttyc", "/dev/ttyd", "/dev/ttye", "/dev/ttyf", "/dev/ttyg", "/dev/ttyh" #elif defined(OS_AIX) "/dev/tty0", "/dev/tty1", "/dev/tty2", "/dev/tty3", "/dev/tty4", "/dev/tty5", "/dev/tty6", "/dev/tty7" #elif defined(OS_IRIX) "/dev/ttyf1", "/dev/ttyf2", "/dev/ttyf3", "/dev/ttyf4", "/dev/ttyf5", "/dev/ttyf6", "/dev/ttyf7", "/dev/ttyf8" #endif }; struct termios params; NEWOBJ(sp, struct RFile); OBJSETUP(sp, class, T_FILE); MakeOpenFile((VALUE) sp, fp); switch(TYPE(_port)) { case T_FIXNUM: num_port = FIX2INT(_port); if (num_port < 0 || num_port > sizeof(ports) / sizeof(ports[0])) { rb_raise(rb_eArgError, "illegal port number"); } port = ports[num_port]; break; case T_STRING: port = StringValueCStr(_port); break; default: rb_raise(rb_eTypeError, "wrong argument type"); break; } fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { rb_sys_fail(port); } if (!isatty(fd)) { close(fd); rb_raise(rb_eArgError, "not a serial port"); } /* enable blocking read */ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK); if (tcgetattr(fd, ¶ms) == -1) { close(fd); rb_sys_fail(sTcgetattr); } params.c_oflag = 0; params.c_lflag = 0; params.c_iflag &= (IXON | IXOFF | IXANY); params.c_cflag |= CLOCAL | CREAD; params.c_cflag &= ~HUPCL; if (tcsetattr(fd, TCSANOW, ¶ms) == -1) { close(fd); rb_sys_fail(sTcsetattr); } #ifdef HAVE_RUBY_IO_H fp->fd = fd; #else fp->f = rb_fdopen(fd, "r+"); #endif fp->mode = FMODE_READWRITE | FMODE_SYNC; return (VALUE) sp; } VALUE sp_set_modem_params_impl(argc, argv, self) int argc; VALUE *argv, self; { int fd; struct termios params; VALUE _data_rate, _data_bits, _parity, _stop_bits; int use_hash = 0; int data_rate, data_bits; _data_rate = _data_bits = _parity = _stop_bits = Qnil; if (argc == 0) { return self; } if (argc == 1 && T_HASH == TYPE(argv[0])) { use_hash = 1; _data_rate = rb_hash_aref(argv[0], sBaud); _data_bits = rb_hash_aref(argv[0], sDataBits); _stop_bits = rb_hash_aref(argv[0], sStopBits); _parity = rb_hash_aref(argv[0], sParity); } fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } if (!use_hash) { _data_rate = argv[0]; } if (NIL_P(_data_rate)) { goto SkipDataRate; } Check_Type(_data_rate, T_FIXNUM); switch(FIX2INT(_data_rate)) { case 50: data_rate = B50; break; case 75: data_rate = B75; break; case 110: data_rate = B110; break; case 134: data_rate = B134; break; case 150: data_rate = B150; break; case 200: data_rate = B200; break; case 300: data_rate = B300; break; case 600: data_rate = B600; break; case 1200: data_rate = B1200; break; case 1800: data_rate = B1800; break; case 2400: data_rate = B2400; break; case 4800: data_rate = B4800; break; case 9600: data_rate = B9600; break; case 19200: data_rate = B19200; break; case 38400: data_rate = B38400; break; #ifdef B57600 case 57600: data_rate = B57600; break; #endif #ifdef B76800 case 76800: data_rate = B76800; break; #endif #ifdef B115200 case 115200: data_rate = B115200; break; #endif #ifdef B230400 case 230400: data_rate = B230400; break; #endif #ifdef B460800 case 460800: data_rate = B460800; break; #endif #ifdef B500000 case 500000: data_rate = B500000; break; #endif #ifdef B576000 case 576000: data_rate = B576000; break; #endif #ifdef B921600 case 921600: data_rate = B921600; break; #endif #ifdef B1000000 case 1000000: data_rate = B1000000; break; #endif default: rb_raise(rb_eArgError, "unknown baud rate"); break; } cfsetispeed(¶ms, data_rate); cfsetospeed(¶ms, data_rate); SkipDataRate: if (!use_hash) { _data_bits = (argc >= 2 ? argv[1] : INT2FIX(8)); } if (NIL_P(_data_bits)) { goto SkipDataBits; } Check_Type(_data_bits, T_FIXNUM); switch(FIX2INT(_data_bits)) { case 5: data_bits = CS5; break; case 6: data_bits = CS6; break; case 7: data_bits = CS7; break; case 8: data_bits = CS8; break; default: rb_raise(rb_eArgError, "unknown character size"); break; } params.c_cflag &= ~CSIZE; params.c_cflag |= data_bits; SkipDataBits: if (!use_hash) { _stop_bits = (argc >= 3 ? argv[2] : INT2FIX(1)); } if (NIL_P(_stop_bits)) { goto SkipStopBits; } Check_Type(_stop_bits, T_FIXNUM); switch(FIX2INT(_stop_bits)) { case 1: params.c_cflag &= ~CSTOPB; break; case 2: params.c_cflag |= CSTOPB; break; default: rb_raise(rb_eArgError, "unknown number of stop bits"); break; } SkipStopBits: if (!use_hash) { _parity = (argc >= 4 ? argv[3] : ((params.c_cflag & CSIZE) == CS8 ? INT2FIX(NONE) : INT2FIX(EVEN))); } if (NIL_P(_parity)) { goto SkipParity; } Check_Type(_parity, T_FIXNUM); switch(FIX2INT(_parity)) { case EVEN: params.c_cflag |= PARENB; params.c_cflag &= ~PARODD; #ifdef CMSPAR params.c_cflag &= ~CMSPAR; #endif break; case ODD: params.c_cflag |= PARENB; params.c_cflag |= PARODD; #ifdef CMSPAR params.c_cflag &= ~CMSPAR; #endif break; #ifdef CMSPAR case SPACE: params.c_cflag |= PARENB; params.c_cflag &= ~PARODD; params.c_cflag |= CMSPAR; break; case MARK: params.c_cflag |= PARENB; params.c_cflag |= PARODD; params.c_cflag |= CMSPAR; break; #endif case NONE: params.c_cflag &= ~PARENB; #ifdef CMSPAR params.c_cflag &= ~CMSPAR; #endif break; default: rb_raise(rb_eArgError, "unknown parity"); break; } SkipParity: if (tcsetattr(fd, TCSANOW, ¶ms) == -1) { rb_sys_fail(sTcsetattr); } return argv[0]; } void get_modem_params_impl(self, mp) VALUE self; struct modem_params *mp; { int fd; struct termios params; fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } switch (cfgetospeed(¶ms)) { case B50: mp->data_rate = 50; break; case B75: mp->data_rate = 75; break; case B110: mp->data_rate = 110; break; case B134: mp->data_rate = 134; break; case B150: mp->data_rate = 150; break; case B200: mp->data_rate = 200; break; case B300: mp->data_rate = 300; break; case B600: mp->data_rate = 600; break; case B1200: mp->data_rate = 1200; break; case B1800: mp->data_rate = 1800; break; case B2400: mp->data_rate = 2400; break; case B4800: mp->data_rate = 4800; break; case B9600: mp->data_rate = 9600; break; case B19200: mp->data_rate = 19200; break; case B38400: mp->data_rate = 38400; break; #ifdef B57600 case B57600: mp->data_rate = 57600; break; #endif #ifdef B76800 case B76800: mp->data_rate = 76800; break; #endif #ifdef B115200 case B115200: mp->data_rate = 115200; break; #endif #ifdef B230400 case B230400: mp->data_rate = 230400; break; #endif #ifdef B460800 case B460800: mp->data_rate = 460800; break; #endif #ifdef B500000 case B500000: mp->data_rate = 500000; break; #endif #ifdef B576000 case B576000: mp->data_rate = 576000; break; #endif #ifdef B921600 case B921600: mp->data_rate = 921600; break; #endif #ifdef B1000000 case B1000000: mp->data_rate = 1000000; break; #endif } switch(params.c_cflag & CSIZE) { case CS5: mp->data_bits = 5; break; case CS6: mp->data_bits = 6; break; case CS7: mp->data_bits = 7; break; case CS8: mp->data_bits = 8; break; default: mp->data_bits = 0; break; } mp->stop_bits = (params.c_cflag & CSTOPB ? 2 : 1); if (!(params.c_cflag & PARENB)) { mp->parity = NONE; } else if (params.c_cflag & PARODD) { mp->parity = ODD; } else { mp->parity = EVEN; } } VALUE sp_set_flow_control_impl(self, val) VALUE self, val; { int fd; int flowc; struct termios params; Check_Type(val, T_FIXNUM); fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } flowc = FIX2INT(val); if (flowc & HARD) { #ifdef HAVE_FLOWCONTROL_HARD params.c_cflag |= CRTSCTS; } else { params.c_cflag &= ~CRTSCTS; } #else rb_raise(rb_eIOError, "Hardware flow control not supported"); } #endif if (flowc & SOFT) { params.c_iflag |= (IXON | IXOFF | IXANY); } else { params.c_iflag &= ~(IXON | IXOFF | IXANY); } if (tcsetattr(fd, TCSANOW, ¶ms) == -1) { rb_sys_fail(sTcsetattr); } return val; } VALUE sp_get_flow_control_impl(self) VALUE self; { int ret; int fd; struct termios params; fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } ret = 0; #ifdef HAVE_FLOWCONTROL_HARD if (params.c_cflag & CRTSCTS) { ret += HARD; } #endif if (params.c_iflag & (IXON | IXOFF | IXANY)) { ret += SOFT; } return INT2FIX(ret); } VALUE sp_set_read_timeout_impl(self, val) VALUE self, val; { int timeout; int fd; struct termios params; Check_Type(val, T_FIXNUM); timeout = FIX2INT(val); fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } if (timeout < 0) { params.c_cc[VTIME] = 0; params.c_cc[VMIN] = 0; } else if (timeout == 0) { params.c_cc[VTIME] = 0; params.c_cc[VMIN] = 1; } else { params.c_cc[VTIME] = (timeout + 50) / 100; params.c_cc[VMIN] = 0; } if (tcsetattr(fd, TCSANOW, ¶ms) == -1) { rb_sys_fail(sTcsetattr); } return val; } VALUE sp_get_read_timeout_impl(self) VALUE self; { int fd; struct termios params; fd = get_fd_helper(self); if (tcgetattr(fd, ¶ms) == -1) { rb_sys_fail(sTcgetattr); } if (params.c_cc[VTIME] == 0 && params.c_cc[VMIN] == 0) { return INT2FIX(-1); } return INT2FIX(params.c_cc[VTIME] * 100); } VALUE sp_set_write_timeout_impl(self, val) VALUE self, val; { rb_notimplement(); return self; } VALUE sp_get_write_timeout_impl(self) VALUE self; { rb_notimplement(); return self; } VALUE sp_break_impl(self, time) VALUE self, time; { int fd; Check_Type(time, T_FIXNUM); fd = get_fd_helper(self); if (tcsendbreak(fd, FIX2INT(time) / 3) == -1) { rb_sys_fail("tcsendbreak"); } return Qnil; } void get_line_signals_helper_impl(obj, ls) VALUE obj; struct line_signals *ls; { int fd, status; fd = get_fd_helper(obj); if (ioctl(fd, TIOCMGET, &status) == -1) { rb_sys_fail(sIoctl); } ls->rts = (status & TIOCM_RTS ? 1 : 0); ls->dtr = (status & TIOCM_DTR ? 1 : 0); ls->cts = (status & TIOCM_CTS ? 1 : 0); ls->dsr = (status & TIOCM_DSR ? 1 : 0); ls->dcd = (status & TIOCM_CD ? 1 : 0); ls->ri = (status & TIOCM_RI ? 1 : 0); } VALUE set_signal_impl(obj, val, sig) VALUE obj,val; int sig; { int status; int fd; int set; Check_Type(val, T_FIXNUM); fd = get_fd_helper(obj); if (ioctl(fd, TIOCMGET, &status) == -1) { rb_sys_fail(sIoctl); } set = FIX2INT(val); if (set == 0) { status &= ~sig; } else if (set == 1) { status |= sig; } else { rb_raise(rb_eArgError, "invalid value"); } if (ioctl(fd, TIOCMSET, &status) == -1) { rb_sys_fail(sIoctl); } return val; } VALUE sp_set_rts_impl(self, val) VALUE self, val; { return set_signal_impl(self, val, TIOCM_RTS); } VALUE sp_set_dtr_impl(self, val) VALUE self, val; { return set_signal_impl(self, val, TIOCM_DTR); } VALUE sp_get_rts_impl(self) VALUE self; { struct line_signals ls; get_line_signals_helper_impl(self, &ls); return INT2FIX(ls.rts); } VALUE sp_get_dtr_impl(self) VALUE self; { struct line_signals ls; get_line_signals_helper_impl(self, &ls); return INT2FIX(ls.dtr); } VALUE sp_flush_input_data_impl(self) VALUE self; { int fd; int ret; fd = get_fd_helper(self); ret = tcflush(fd, TCIFLUSH); if(ret<0) { return Qfalse; } return Qtrue; } VALUE sp_flush_output_data_impl(self) VALUE self; { int fd; int ret; fd = get_fd_helper(self); ret = tcflush(fd, TCOFLUSH); if(ret<0) { return Qfalse; } return Qtrue; } #endif /* !defined(OS_MSWIN) && !defined(OS_BCCWIN) && !defined(OS_MINGW) */ serialport-1.3.2/ext/native/serialport.c0000644000004100000410000003522114136323005020347 0ustar www-datawww-data/* Ruby/SerialPort * Guillaume Pierronnet * Alan Stern * Daniel E. Shipton * Jonas Bähr * Ryan C. Payne * * This code is hereby licensed for public consumption under either the * GNU GPL v2 or greater. * * 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. */ #include "serialport.h" VALUE cSerialPort; /* serial port class */ VALUE sBaud, sDataBits, sStopBits, sParity; /* strings */ VALUE sRts, sDtr, sCts, sDsr, sDcd, sRi; /* * @api private * * @see SerialPort#new * @see SerialPort#open */ static VALUE sp_create(class, _port) VALUE class, _port; { return sp_create_impl(class, _port); } /* * Configure the serial port. You can pass a hash or multiple values * as separate arguments. Invalid or unsupported values will raise * an ArgumentError. * * When using a hash the following keys are recognized: * ["baud"] Integer from 50 to 256000, depending on platform * ["data_bits"] Integer from 5 to 8 (4 is allowed on Windows too) * ["stop_bits"] Integer, only allowed values are 1 or 2 (1.5 is not supported) * ["parity"] One of the constants NONE, EVEN or ODD (Windows allows also MARK and SPACE) * * When using separate arguments, they are interpreted as: * (baud, data_bits = 8, stop_bits = 1, parity = (previous_databits == 8 ? NONE : EVEN)) * A baudrate of nil will keep the old value. * The default parity depends on the number of databits configured before this function call. * * @overload set_modem_params(baud, data_bits, stop_bits, parity) * @param baud [Integer] the baud rate * @param data_bits [Integer] the number of data bits * @param stop_bits [Integer] the number of stop bits * @param parity [Integer] the type of parity checking * @overload set_modem_params(hash) * @param opts [Hash] the options to configure port * * @return [Hash] the original paramters * @raise [ArgumentError] if values are invalide or unsupported */ static VALUE sp_set_modem_params(argc, argv, self) int argc; VALUE *argv, self; { return sp_set_modem_params_impl(argc, argv, self); } /* * Send a break for the given time * * @param time [Integer] break time in tenths-of-a-second * @return [nil] * @note (POSIX) this value is very approximate */ static VALUE sp_break(self, time) VALUE self, time; { return sp_break_impl(self, time); } /* * Get the state of the DTR line * * @note (Windows) DTR is not available * @return [Integer] the state of DTR line, 0 or 1 */ static VALUE sp_get_dtr(self) VALUE self; { return sp_get_dtr_impl(self); } /* * Get the flow control flag * * @return [Integer] the flow control flag * @see SerialPort#set_flow_control */ static VALUE sp_get_flow_control(self) VALUE self; { return sp_get_flow_control_impl(self); } /* * Get the read timeout value * * @return [Integer] the read timeout, in milliseconds * @see SerialPort#set_read_timeout */ static VALUE sp_get_read_timeout(self) VALUE self; { return sp_get_read_timeout_impl(self); } /* * Get the state of the RTS line * * @return [Integer] the state of RTS line, 0 or 1 * @note (Windows) RTS is not available */ static VALUE sp_get_rts(self) VALUE self; { return sp_get_rts_impl(self); } /* * Get the write timeout * * @return [Integer] the write timeout, in milliseconds * @note (POSIX) write timeouts are not implemented */ static VALUE sp_get_write_timeout(self) VALUE self; { return sp_get_write_timeout_impl(self); } /* * Set the state of the DTR line * * @param val [Integer] the desired state of the DTR line, 0 or 1 * @return [Integer] the original +val+ parameter */ static VALUE sp_set_dtr(self, val) VALUE self, val; { return sp_set_dtr_impl(self, val); } /* * Set the flow control * * @param val [Integer] the flow control flag, * +NONE+, +HARD+, +SOFT+, or (+HARD+ | +SOFT+) * @return [Integer] the original +val+ parameter * @note SerialPort::HARD mode is not supported on all platforms. * @note SerialPort::HARD uses RTS/CTS handshaking. * DSR/DTR is not supported. */ static VALUE sp_set_flow_control(self, val) VALUE self, val; { return sp_set_flow_control_impl(self, val); } /* * Set the timeout value (in milliseconds) for reading. * A negative read timeout will return all the available data without * waiting, a zero read timeout will not return until at least one * byte is available, and a positive read timeout returns when the * requested number of bytes is available or the interval between the * arrival of two bytes exceeds the timeout value. * * @param timeout [Integer] the read timeout in milliseconds * @return [Integer] the original +timeout+ parameter * @note Read timeouts don't mix well with multi-threading */ static VALUE sp_set_read_timeout(self, val) VALUE self, val; { return sp_set_read_timeout_impl(self, val); } /* * Set the state of the RTS line * * @param val [Integer] the state of RTS line, 0 or 1 * @return [Integer] the original +val+ parameter */ static VALUE sp_set_rts(self, val) VALUE self, val; { return sp_set_rts_impl(self, val); } /* * Set a write timeout * * @param val [Integer] the write timeout in milliseconds * @return [Integer] the original +val+ parameter * @note (POSIX) write timeouts are not implemented */ static VALUE sp_set_write_timeout(self, val) VALUE self, val; { return sp_set_write_timeout_impl(self, val); } /* * @private helper */ static void get_modem_params(self, mp) VALUE self; struct modem_params *mp; { get_modem_params_impl(self, mp); } /* * Set the baud rate * * @param data_rate [Integer] the baud rate * @return [Integer] the original +data_rate+ parameter * @see SerialPort#set_modem_params */ static VALUE sp_set_data_rate(self, data_rate) VALUE self, data_rate; { VALUE argv[4]; argv[0] = data_rate; argv[1] = argv[2] = argv[3] = Qnil; sp_set_modem_params(4, argv, self); return data_rate; } /* * Set the data bits * * @param data_bits [Integer] the number of data bits * @return [Integer] the original +data_bits+ parameter * @see SerialPort#set_modem_params */ static VALUE sp_set_data_bits(self, data_bits) VALUE self, data_bits; { VALUE argv[4]; argv[1] = data_bits; argv[0] = argv[2] = argv[3] = Qnil; sp_set_modem_params(4, argv, self); return data_bits; } /* * Set the stop bits * * @param stop_bits [Integer] the number of stop bits * @return [Integer] the original +stop_bits+ parameter * @see SerialPort#set_modem_params */ static VALUE sp_set_stop_bits(self, stop_bits) VALUE self, stop_bits; { VALUE argv[4]; argv[2] = stop_bits; argv[0] = argv[1] = argv[3] = Qnil; sp_set_modem_params(4, argv, self); return stop_bits; } /* * Set the parity * * @param parity [Integer] the parity type * @return [Integer] the original +parity+ parameter * @see SerialPort#set_modem_params */ static VALUE sp_set_parity(self, parity) VALUE self, parity; { VALUE argv[4]; argv[3] = parity; argv[0] = argv[1] = argv[2] = Qnil; sp_set_modem_params(4, argv, self); return parity; } /* * Get the current baud rate * * @return [Integer] the current baud rate * @see SerialPort#set_modem_params */ static VALUE sp_get_data_rate(self) VALUE self; { struct modem_params mp; get_modem_params(self, &mp); return INT2FIX(mp.data_rate); } /* * Get the current data bits * * @return [Integer] the current number of data bits * @see SerialPort#set_modem_params */ static VALUE sp_get_data_bits(self) VALUE self; { struct modem_params mp; get_modem_params(self, &mp); return INT2FIX(mp.data_bits); } /* * Get the current stop bits * * @return [Integer] the current number of stop bits * @see SerialPort#set_modem_params for details */ static VALUE sp_get_stop_bits(self) VALUE self; { struct modem_params mp; get_modem_params(self, &mp); return INT2FIX(mp.stop_bits); } /* * Get the current parity * * @return [Integer] the current parity * @see SerialPort#set_modem_params */ static VALUE sp_get_parity(self) VALUE self; { struct modem_params mp; get_modem_params(self, &mp); return INT2FIX(mp.parity); } /* * Get the configure of the serial port * * @return [Hash] the serial port configuration * @see SerialPort#set_modem_params */ static VALUE sp_get_modem_params(self) VALUE self; { struct modem_params mp; VALUE hash; get_modem_params(self, &mp); hash = rb_hash_new(); rb_hash_aset(hash, sBaud, INT2FIX(mp.data_rate)); rb_hash_aset(hash, sDataBits, INT2FIX(mp.data_bits)); rb_hash_aset(hash, sStopBits, INT2FIX(mp.stop_bits)); rb_hash_aset(hash, sParity, INT2FIX(mp.parity)); return hash; } /* * @api private */ void get_line_signals_helper(obj, ls) VALUE obj; struct line_signals *ls; { get_line_signals_helper_impl(obj, ls); } /* * Get the state of the CTS line * * @return [Integer] the state of the CTS line, 0 or 1 * @see SerialPort#get_signals */ static VALUE sp_get_cts(self) VALUE self; { struct line_signals ls; get_line_signals_helper(self, &ls); return INT2FIX(ls.cts); } /* * Get the state of the DSR line * * @return [Integer] the state of the DSR line, 0 or 1 * @see SerialPort#get_signals */ static VALUE sp_get_dsr(self) VALUE self; { struct line_signals ls; get_line_signals_helper(self, &ls); return INT2FIX(ls.dsr); } /* * Get the state of the DCD line * * @return [Integer] the state of the DCD line, 0 or 1 * @see SerialPort#get_signals */ static VALUE sp_get_dcd(self) VALUE self; { struct line_signals ls; get_line_signals_helper(self, &ls); return INT2FIX(ls.dcd); } /* * Get the state of the RI line * * @return [Integer] the state of the RI line, 0 or 1 * @see SerialPort#get_signals */ static VALUE sp_get_ri(self) VALUE self; { struct line_signals ls; get_line_signals_helper(self, &ls); return INT2FIX(ls.ri); } /* * Return a hash with the state of each line status bit. * Keys: * "rts", "dtr", "cts", "dsr", "dcd", and "ri". * * @return [Hash] the state line info * @note (Windows) the rts and dtr values are not included * @note This method is implemented as both SerialPort#signals and SerialPort#get_signals */ static VALUE sp_signals(self) VALUE self; { struct line_signals ls; VALUE hash; get_line_signals_helper(self, &ls); hash = rb_hash_new(); #if !(defined(OS_MSWIN) || defined(OS_BCCWIN) || defined(OS_MINGW)) rb_hash_aset(hash, sRts, INT2FIX(ls.rts)); rb_hash_aset(hash, sDtr, INT2FIX(ls.dtr)); #endif rb_hash_aset(hash, sCts, INT2FIX(ls.cts)); rb_hash_aset(hash, sDsr, INT2FIX(ls.dsr)); rb_hash_aset(hash, sDcd, INT2FIX(ls.dcd)); rb_hash_aset(hash, sRi, INT2FIX(ls.ri)); return hash; } /** * Flush data received but not read. * * @return [Boolean] true on success or false if an error occurs. */ static VALUE sp_flush_input_data(self) VALUE self; { return sp_flush_input_data_impl(self); } /** * Flush data written but not transmitted. * * @return [Boolean] true on success or false if an error occurs. */ static VALUE sp_flush_output_data(self) VALUE self; { return sp_flush_output_data_impl(self); } void Init_serialport() { sBaud = rb_str_new2("baud"); sDataBits = rb_str_new2("data_bits"); sStopBits = rb_str_new2("stop_bits"); sParity = rb_str_new2("parity"); sRts = rb_str_new2("rts"); sDtr = rb_str_new2("dtr"); sCts = rb_str_new2("cts"); sDsr = rb_str_new2("dsr"); sDcd = rb_str_new2("dcd"); sRi = rb_str_new2("ri"); rb_gc_register_address(&sBaud); rb_gc_register_address(&sDataBits); rb_gc_register_address(&sStopBits); rb_gc_register_address(&sParity); rb_gc_register_address(&sRts); rb_gc_register_address(&sDtr); rb_gc_register_address(&sCts); rb_gc_register_address(&sDsr); rb_gc_register_address(&sDcd); rb_gc_register_address(&sRi); cSerialPort = rb_define_class("SerialPort", rb_cIO); rb_define_singleton_method(cSerialPort, "create", sp_create, 1); rb_define_method(cSerialPort, "get_modem_params", sp_get_modem_params, 0); rb_define_method(cSerialPort, "set_modem_params", sp_set_modem_params, -1); rb_define_method(cSerialPort, "modem_params", sp_get_modem_params, 0); rb_define_method(cSerialPort, "modem_params=", sp_set_modem_params, -1); rb_define_method(cSerialPort, "baud", sp_get_data_rate, 0); rb_define_method(cSerialPort, "baud=", sp_set_data_rate, 1); rb_define_method(cSerialPort, "data_bits", sp_get_data_bits, 0); rb_define_method(cSerialPort, "data_bits=", sp_set_data_bits, 1); rb_define_method(cSerialPort, "stop_bits", sp_get_stop_bits, 0); rb_define_method(cSerialPort, "stop_bits=", sp_set_stop_bits, 1); rb_define_method(cSerialPort, "parity", sp_get_parity, 0); rb_define_method(cSerialPort, "parity=", sp_set_parity, 1); rb_define_method(cSerialPort, "flow_control=", sp_set_flow_control, 1); rb_define_method(cSerialPort, "flow_control", sp_get_flow_control, 0); rb_define_method(cSerialPort, "read_timeout", sp_get_read_timeout, 0); rb_define_method(cSerialPort, "read_timeout=", sp_set_read_timeout, 1); rb_define_method(cSerialPort, "write_timeout", sp_get_write_timeout, 0); rb_define_method(cSerialPort, "write_timeout=", sp_set_write_timeout, 1); rb_define_method(cSerialPort, "break", sp_break, 1); rb_define_method(cSerialPort, "signals", sp_signals, 0); rb_define_method(cSerialPort, "get_signals", sp_signals, 0); rb_define_method(cSerialPort, "rts", sp_get_rts, 0); rb_define_method(cSerialPort, "rts=", sp_set_rts, 1); rb_define_method(cSerialPort, "dtr", sp_get_dtr, 0); rb_define_method(cSerialPort, "dtr=", sp_set_dtr, 1); rb_define_method(cSerialPort, "cts", sp_get_cts, 0); rb_define_method(cSerialPort, "dsr", sp_get_dsr, 0); rb_define_method(cSerialPort, "dcd", sp_get_dcd, 0); rb_define_method(cSerialPort, "ri", sp_get_ri, 0); rb_define_method(cSerialPort, "flush_input", sp_flush_input_data, 0); rb_define_method(cSerialPort, "flush_output", sp_flush_output_data, 0); /* * 0 */ rb_define_const(cSerialPort, "NONE", INT2FIX(NONE)); /* * 1 */ rb_define_const(cSerialPort, "HARD", INT2FIX(HARD)); /* * 2 */ rb_define_const(cSerialPort, "SOFT", INT2FIX(SOFT)); /* * 0 */ rb_define_const(cSerialPort, "SPACE", INT2FIX(SPACE)); /* * 1 */ rb_define_const(cSerialPort, "MARK", INT2FIX(MARK)); /* * 2 */ rb_define_const(cSerialPort, "EVEN", INT2FIX(EVEN)); /* * 3 */ rb_define_const(cSerialPort, "ODD", INT2FIX(ODD)); } serialport-1.3.2/ext/native/extconf.rb0000644000004100000410000000046114136323005020010 0ustar www-datawww-datarequire 'mkmf' printf("checking for OS... ") STDOUT.flush os = /-([a-z]+)/.match(RUBY_PLATFORM)[1] puts(os) $CFLAGS += " -DOS_#{os.upcase}" if !(os == 'mswin' or os == 'bccwin' or os == 'mingw') exit(1) if not have_header("termios.h") or not have_header("unistd.h") end create_makefile('serialport') serialport-1.3.2/ext/native/win_serialport_impl.c0000644000004100000410000003144114136323005022245 0ustar www-datawww-data/* Ruby/SerialPort * Guillaume Pierronnet * Alan Stern * Daniel E. Shipton * Hector G. Parra * * This code is hereby licensed for public consumption under either the * GNU GPL v2 or greater. * * 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. * * For documentation on serial programming, see the excellent: * "Serial Programming Guide for POSIX Operating Systems" * written Michael R. Sweet. * http://www.easysw.com/~mike/serial/ */ #include "serialport.h" #if defined(OS_MSWIN) || defined(OS_BCCWIN) || defined(OS_MINGW) #include /* Standard input/output definitions */ #include /* Low-level I/O definitions */ #include /* File control definitions */ #include /* Windows standard function definitions */ static char sGetCommState[] = "GetCommState"; static char sSetCommState[] = "SetCommState"; static char sGetCommTimeouts[] = "GetCommTimeouts"; static char sSetCommTimeouts[] = "SetCommTimeouts"; static HANDLE get_handle_helper(obj) VALUE obj; { #ifdef HAVE_RUBY_IO_H rb_io_t *fptr; #else OpenFile *fptr; #endif GetOpenFile(obj, fptr); #ifdef HAVE_RUBY_IO_H return (HANDLE) _get_osfhandle(fptr->fd); #else return (HANDLE) _get_osfhandle(fileno(fptr->f)); #endif } /* hack to work around the fact that Ruby doesn't use GetLastError? */ static void _rb_win32_fail(const char *function_call) { rb_raise( rb_eRuntimeError, "%s failed: GetLastError returns %d", function_call, GetLastError( ) ); } VALUE RB_SERIAL_EXPORT sp_create_impl(class, _port) VALUE class, _port; { #ifdef HAVE_RUBY_IO_H rb_io_t *fp; #else OpenFile *fp; #endif int fd; HANDLE fh; int num_port; char *str_port; char port[260]; /* Windows XP MAX_PATH. See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx */ DCB dcb; NEWOBJ(sp, struct RFile); OBJSETUP(sp, class, T_FILE); MakeOpenFile((VALUE) sp, fp); switch(TYPE(_port)) { case T_FIXNUM: num_port = FIX2INT(_port); if (num_port < 0) { rb_raise(rb_eArgError, "illegal port number"); } snprintf(port, sizeof(port) - 1, "\\\\.\\COM%d", num_port + 1); /* '0' is actually COM1, etc. */ port[sizeof(port) - 1] = 0; break; case T_STRING: str_port = StringValueCStr(_port); if (str_port[0] != '\\') /* Check for Win32 Device Namespace prefix "\\.\" */ { snprintf(port, sizeof(port) - 1, "\\\\.\\%s", str_port); port[sizeof(port) - 1] = 0; } else { snprintf(port, sizeof(port) - 1, "%s", str_port); port[sizeof(port) - 1] = 0; } break; default: rb_raise(rb_eTypeError, "wrong argument type"); break; } fd = open(port, O_BINARY | O_RDWR); if (fd == -1) { rb_sys_fail(port); } fh = (HANDLE) _get_osfhandle(fd); if (SetupComm(fh, 1024, 1024) == 0) { close(fd); rb_raise(rb_eArgError, "not a serial port"); } dcb.DCBlength = sizeof(dcb); if (GetCommState(fh, &dcb) == 0) { close(fd); _rb_win32_fail(sGetCommState); } dcb.fBinary = TRUE; dcb.fParity = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fDsrSensitivity = FALSE; dcb.fTXContinueOnXoff = FALSE; dcb.fErrorChar = FALSE; dcb.fNull = FALSE; dcb.fAbortOnError = FALSE; dcb.XonChar = 17; dcb.XoffChar = 19; if (SetCommState(fh, &dcb) == 0) { close(fd); _rb_win32_fail(sSetCommState); } errno = 0; fp->mode = FMODE_READWRITE | FMODE_BINMODE | FMODE_SYNC; #ifdef HAVE_RUBY_IO_H fp->fd = fd; #else fp->f = fdopen(fd, "rb+"); #endif return (VALUE) sp; } VALUE RB_SERIAL_EXPORT sp_set_modem_params_impl(argc, argv, self) int argc; VALUE *argv, self; { HANDLE fh; DCB dcb; VALUE _data_rate, _data_bits, _parity, _stop_bits; int use_hash = 0; int data_rate, data_bits, parity; if (argc == 0) { return self; } if (argc == 1 && T_HASH == TYPE(argv[0])) { use_hash = 1; _data_rate = rb_hash_aref(argv[0], sBaud); _data_bits = rb_hash_aref(argv[0], sDataBits); _stop_bits = rb_hash_aref(argv[0], sStopBits); _parity = rb_hash_aref(argv[0], sParity); } fh = get_handle_helper(self); dcb.DCBlength = sizeof(dcb); if (GetCommState(fh, &dcb) == 0) { _rb_win32_fail(sGetCommState); } if (!use_hash) { _data_rate = argv[0]; } if (NIL_P(_data_rate)) { goto SkipDataRate; } Check_Type(_data_rate, T_FIXNUM); data_rate = FIX2INT(_data_rate); dcb.BaudRate = data_rate; SkipDataRate: if (!use_hash) { _data_bits = (argc >= 2 ? argv[1] : INT2FIX(8)); } if (NIL_P(_data_bits)) { goto SkipDataBits; } Check_Type(_data_bits, T_FIXNUM); data_bits = FIX2INT(_data_bits); if (4 <= data_bits && data_bits <= 8) { dcb.ByteSize = data_bits; } else { rb_raise(rb_eArgError, "unknown character size"); } SkipDataBits: if (!use_hash) { _stop_bits = (argc >= 3 ? argv[2] : INT2FIX(1)); } if (NIL_P(_stop_bits)) { goto SkipStopBits; } Check_Type(_stop_bits, T_FIXNUM); switch (FIX2INT(_stop_bits)) { case 1: dcb.StopBits = ONESTOPBIT; break; case 2: dcb.StopBits = TWOSTOPBITS; break; default: rb_raise(rb_eArgError, "unknown number of stop bits"); break; } SkipStopBits: if (!use_hash) { _parity = (argc >= 4 ? argv[3] : (dcb.ByteSize == 8 ? INT2FIX(NOPARITY) : INT2FIX(EVENPARITY))); } if (NIL_P(_parity)) { goto SkipParity; } Check_Type(_parity, T_FIXNUM); parity = FIX2INT(_parity); switch (parity) { case EVENPARITY: case ODDPARITY: case MARKPARITY: case SPACEPARITY: case NOPARITY: dcb.Parity = parity; break; default: rb_raise(rb_eArgError, "unknown parity"); break; } SkipParity: if (SetCommState(fh, &dcb) == 0) { _rb_win32_fail(sSetCommState); } return argv[0]; } void RB_SERIAL_EXPORT get_modem_params_impl(self, mp) VALUE self; struct modem_params *mp; { HANDLE fh; DCB dcb; fh = get_handle_helper(self); dcb.DCBlength = sizeof(dcb); if (GetCommState(fh, &dcb) == 0) { _rb_win32_fail(sGetCommState); } mp->data_rate = dcb.BaudRate; mp->data_bits = dcb.ByteSize; mp->stop_bits = (dcb.StopBits == ONESTOPBIT ? 1 : 2); mp->parity = dcb.Parity; } VALUE RB_SERIAL_EXPORT sp_set_flow_control_impl(self, val) VALUE self, val; { HANDLE fh; int flowc; DCB dcb; Check_Type(val, T_FIXNUM); fh = get_handle_helper(self); dcb.DCBlength = sizeof(dcb); if (GetCommState(fh, &dcb) == 0) { _rb_win32_fail(sGetCommState); } flowc = FIX2INT(val); if (flowc & HARD) { dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; dcb.fOutxCtsFlow = TRUE; } else { dcb.fRtsControl = RTS_CONTROL_ENABLE; dcb.fOutxCtsFlow = FALSE; } if (flowc & SOFT) { dcb.fOutX = dcb.fInX = TRUE; } else { dcb.fOutX = dcb.fInX = FALSE; } if (SetCommState(fh, &dcb) == 0) { _rb_win32_fail(sSetCommState); } return val; } VALUE RB_SERIAL_EXPORT sp_get_flow_control_impl(self) VALUE self; { HANDLE fh; int ret; DCB dcb; fh = get_handle_helper(self); dcb.DCBlength = sizeof(dcb); if (GetCommState(fh, &dcb) == 0) { _rb_win32_fail(sGetCommState); } ret = 0; if (dcb.fOutxCtsFlow) { ret += HARD; } if (dcb.fOutX) { ret += SOFT; } return INT2FIX(ret); } VALUE RB_SERIAL_EXPORT sp_set_read_timeout_impl(self, val) VALUE self, val; { int timeout; HANDLE fh; COMMTIMEOUTS ctout; Check_Type(val, T_FIXNUM); timeout = FIX2INT(val); fh = get_handle_helper(self); if (GetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sGetCommTimeouts); } if (timeout < 0) { ctout.ReadIntervalTimeout = MAXDWORD; ctout.ReadTotalTimeoutMultiplier = 0; ctout.ReadTotalTimeoutConstant = 0; } else if (timeout == 0) { ctout.ReadIntervalTimeout = MAXDWORD; ctout.ReadTotalTimeoutMultiplier = MAXDWORD; ctout.ReadTotalTimeoutConstant = MAXDWORD - 1; } else { ctout.ReadIntervalTimeout = timeout; ctout.ReadTotalTimeoutMultiplier = 0; ctout.ReadTotalTimeoutConstant = timeout; } if (SetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sSetCommTimeouts); } return val; } VALUE RB_SERIAL_EXPORT sp_get_read_timeout_impl(self) VALUE self; { HANDLE fh; COMMTIMEOUTS ctout; fh = get_handle_helper(self); if (GetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sGetCommTimeouts); } switch (ctout.ReadTotalTimeoutConstant) { case 0: return INT2FIX(-1); case MAXDWORD: return INT2FIX(0); } return INT2FIX(ctout.ReadTotalTimeoutConstant); } VALUE RB_SERIAL_EXPORT sp_set_write_timeout_impl(self, val) VALUE self, val; { int timeout; HANDLE fh; COMMTIMEOUTS ctout; Check_Type(val, T_FIXNUM); timeout = FIX2INT(val); fh = get_handle_helper(self); if (GetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sGetCommTimeouts); } if (timeout <= 0) { ctout.WriteTotalTimeoutMultiplier = 0; ctout.WriteTotalTimeoutConstant = 0; } else { ctout.WriteTotalTimeoutMultiplier = timeout; ctout.WriteTotalTimeoutConstant = 0; } if (SetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sSetCommTimeouts); } return val; } VALUE RB_SERIAL_EXPORT sp_get_write_timeout_impl(self) VALUE self; { HANDLE fh; COMMTIMEOUTS ctout; fh = get_handle_helper(self); if (GetCommTimeouts(fh, &ctout) == 0) { _rb_win32_fail(sGetCommTimeouts); } return INT2FIX(ctout.WriteTotalTimeoutMultiplier); } static void delay_ms(time) int time; { HANDLE ev; ev = CreateEvent(NULL, FALSE, FALSE, NULL); if (!ev) { _rb_win32_fail("CreateEvent"); } if (WaitForSingleObject(ev, time) == WAIT_FAILED) { _rb_win32_fail("WaitForSingleObject"); } CloseHandle(ev); } VALUE RB_SERIAL_EXPORT sp_break_impl(self, time) VALUE self, time; { HANDLE fh; Check_Type(time, T_FIXNUM); fh = get_handle_helper(self); if (SetCommBreak(fh) == 0) { _rb_win32_fail("SetCommBreak"); } delay_ms(FIX2INT(time) * 100); ClearCommBreak(fh); return Qnil; } void RB_SERIAL_EXPORT get_line_signals_helper_impl(obj, ls) VALUE obj; struct line_signals *ls; { HANDLE fh; unsigned long status; /* DWORD */ fh = get_handle_helper(obj); if (GetCommModemStatus(fh, &status) == 0) { _rb_win32_fail("GetCommModemStatus"); } ls->cts = (status & MS_CTS_ON ? 1 : 0); ls->dsr = (status & MS_DSR_ON ? 1 : 0); ls->dcd = (status & MS_RLSD_ON ? 1 : 0); ls->ri = (status & MS_RING_ON ? 1 : 0); } static VALUE set_signal(obj, val, sigoff, sigon) VALUE obj,val; int sigoff, sigon; { HANDLE fh; int set, sig; Check_Type(val, T_FIXNUM); fh = get_handle_helper(obj); set = FIX2INT(val); if (set == 0) { sig = sigoff; } else if (set == 1) { sig = sigon; } else { rb_raise(rb_eArgError, "invalid value"); } if (EscapeCommFunction(fh, sig) == 0) { _rb_win32_fail("EscapeCommFunction"); } return val; } VALUE RB_SERIAL_EXPORT sp_set_rts_impl(self, val) VALUE self, val; { return set_signal(self, val, CLRRTS, SETRTS); } VALUE RB_SERIAL_EXPORT sp_set_dtr_impl(self, val) VALUE self, val; { return set_signal(self, val, CLRDTR, SETDTR); } VALUE RB_SERIAL_EXPORT sp_get_rts_impl(self) VALUE self; { rb_notimplement(); return self; } VALUE RB_SERIAL_EXPORT sp_get_dtr_impl(self) VALUE self; { rb_notimplement(); return self; } #define PURGE_RXABORT 0x02 #define PURGE_RXCLEAR 0x08 VALUE RB_SERIAL_EXPORT sp_flush_input_data_impl(self) VALUE self; { BOOL ret; HANDLE fh; fh = get_handle_helper(self); ret = PurgeComm(fh, (DWORD)(PURGE_RXCLEAR | PURGE_RXABORT)); if(!ret) { return Qfalse; } return Qtrue; } #define PURGE_TXABORT 0x01 #define PURGE_TXCLEAR 0x04 VALUE RB_SERIAL_EXPORT sp_flush_output_data_impl(self) VALUE self; { BOOL ret; HANDLE fh; fh = get_handle_helper(self); ret = PurgeComm(fh, (DWORD)(PURGE_TXCLEAR | PURGE_TXABORT)); if(!ret) { return Qfalse; } return Qtrue; } #endif /* defined(OS_MSWIN) || defined(OS_BCCWIN) || defined(OS_MINGW) */ serialport-1.3.2/ext/native/serialport.h0000644000004100000410000000576614136323005020367 0ustar www-datawww-data/* Ruby/SerialPort * Guillaume Pierronnet * Alan Stern * Daniel E. Shipton * Tobin Richard * Ryan C. Payne * * This code is hereby licensed for public consumption under either the * GNU GPL v2 or greater. * * 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. * * For documentation on serial programming, see the excellent: * "Serial Programming Guide for POSIX Operating Systems" * written Michael R. Sweet. * http://www.easysw.com/~mike/serial/ */ #ifndef _RUBY_SERIAL_PORT_H_ #define _RUBY_SERIAL_PORT_H_ #include /* ruby inclusion */ #ifdef HAVE_RUBY_IO_H /* ruby io inclusion */ #include #else #include #endif struct modem_params { int data_rate; int data_bits; int stop_bits; int parity; }; struct line_signals { int rts; int dtr; int cts; int dsr; int dcd; int ri; }; #define NONE 0 #define HARD 1 #define SOFT 2 #if defined(OS_MSWIN) || defined(OS_BCCWIN) || defined(OS_MINGW) #define SPACE SPACEPARITY #define MARK MARKPARITY #define EVEN EVENPARITY #define ODD ODDPARITY #ifndef RB_SERIAL_EXPORT #ifndef HAVE_RUBY_IO_H #define RB_SERIAL_EXPORT __declspec(dllexport) #else #define RB_SERIAL_EXPORT #endif #endif #else #define EVEN 1 #define ODD 2 #define SPACE 3 #define MARK 4 #define RB_SERIAL_EXPORT #endif extern VALUE sBaud, sDataBits, sStopBits, sParity; /* strings */ extern VALUE sRts, sDtr, sCts, sDsr, sDcd, sRi; /* Implementation specific functions. */ VALUE RB_SERIAL_EXPORT sp_create_impl(VALUE class, VALUE _port); VALUE RB_SERIAL_EXPORT sp_set_modem_params_impl(int argc, VALUE *argv, VALUE self); void RB_SERIAL_EXPORT get_modem_params_impl(VALUE self, struct modem_params *mp); VALUE RB_SERIAL_EXPORT sp_set_flow_control_impl(VALUE self, VALUE val); VALUE RB_SERIAL_EXPORT sp_get_flow_control_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_set_read_timeout_impl(VALUE self, VALUE val); VALUE RB_SERIAL_EXPORT sp_get_read_timeout_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_set_write_timeout_impl(VALUE self, VALUE val); VALUE RB_SERIAL_EXPORT sp_get_write_timeout_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_break_impl(VALUE self, VALUE time); void RB_SERIAL_EXPORT get_line_signals_helper_impl(VALUE obj, struct line_signals *ls); VALUE RB_SERIAL_EXPORT set_signal_impl(VALUE obj, VALUE val, int sig); VALUE RB_SERIAL_EXPORT sp_set_rts_impl(VALUE self, VALUE val); VALUE RB_SERIAL_EXPORT sp_set_dtr_impl(VALUE self, VALUE val); VALUE RB_SERIAL_EXPORT sp_get_rts_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_get_dtr_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_flush_input_data_impl(VALUE self); VALUE RB_SERIAL_EXPORT sp_flush_output_data_impl(VALUE self); #endif serialport-1.3.2/CHANGELOG0000644000004100000410000000465414136323005015151 0ustar www-datawww-data1.3.1 => 07/26/2014: [FIXED] Ruby 2.2 support [NEW] UNIX MARK/SPACE parity (CMSPAR) support 1.3.0 => 11/17/2013: [NEW] flush_input() and flush_output() methods [Manuel A. Güílamo (MaG)] 1.2.3 => 11/04/2013: [FIXED] Improved documentation (yard) 1.2.2 => 11/03/2013: [FIXED] warning: already initialized constant VERSION 1.2.1 => 10/25/2013: [FIXED] removed absurd circular dependency 1.2.0 => 10/25/2013: [NEW] rake-compiler, bundler, and travis ci integration 1.1.0 => 05/14/2012: [NEW] Ruby 2.0 Support [Aaron Patterson (tenderlove)] [FIXED] Support for baud rates up to 1000000 in Windows [Will Koehler (willkoehler)] 1.0.4 => 07/17/2010: [FIXED] [Windows] No longer restricted to specific bitrates [FIXED] [Windows] Removed potentially insecure sprintf() use [FIXED] [Windows] Workaround for rb_sys_fail not checking GetLastError() 1.0.3 => 04/08/2010: [FIXED] [Windows] Could not specify 10 or "COM10" or higher [FIXED] [Windows] Warning passing INT instead of LONG to GetCommModemStatus 1.0.2 => 04/06/2010: [FIXED] Passing a block into open did not properly handle a return from within the block 1.0.1 => 01/20/2010: [FIXED] Conditional RB_SERIAL_EXPORT needed for Visual Studio bonked GCC 1.0.0 => 01/12/2010: [FIXED] x86_64 segmentation faults [NEW] Windows Ruby 1.9 support 0.7.4 => 10/12/2009: [NEW] Conditional 1.8.6 & 1.9 support (POSIX only). [NEW] MinGW support. 0.7.3 => 10/09/2009: [NEW] POSIX Ruby 1.9 support 0.7.2 => 02/09/2008: Fix several Windows and POSIX compilation problems. Make GCC compile the code without any warnings. Make RDoc not be so talkative during gem installation. 0.7.1 => 31/08/2008: Change to gemspec creation and fix posix compilation. 0.7.0 => 03/07/2008: Major Code Cleanup 0.6.1 => 25/03/2003: Minor changes 0.6 => 12/02/2003: Windows support Get/set modem parameters Read and write timeouts Open method 0.5 => 25/10/2002: Cygwin support 0.4 => 19/09/2002: Added more serial ports (total of 8 ports) 0.3 => 15/03/2002: Damn, another bug found 0.2 => 14/03/2002: A bug fixed (read() was not blocking) 0.1 => 14/03/2002: First release