├── .gitignore ├── LICENSE ├── README.markdown ├── arduino └── increment_and_echo │ └── increment_and_echo.pde ├── go-serial-test └── go-serial-test.go └── serial ├── Makefile ├── integration_test.go ├── open_darwin.go ├── open_freebsd.go ├── open_linux.go ├── open_windows.go ├── serial.go └── serial_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | *.6 2 | */_obj/ 3 | _test/ 4 | _testmain.go 5 | 6.out 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | go-serial 2 | ========= 3 | 4 | This is a package that allows you to read from and write to serial ports in Go. 5 | 6 | 7 | OS support 8 | ---------- 9 | 10 | Currently this package works only on OS X, Linux and Windows. It could probably be ported 11 | to other Unix-like platforms simply by updating a few constants; get in touch if 12 | you are interested in helping and have hardware to test with. 13 | 14 | 15 | Installation 16 | ------------ 17 | 18 | Simply use `go get`: 19 | 20 | go get github.com/jacobsa/go-serial/serial 21 | 22 | To update later: 23 | 24 | go get -u github.com/jacobsa/go-serial/serial 25 | 26 | 27 | Use 28 | --- 29 | 30 | Set up a `serial.OpenOptions` struct, then call `serial.Open`. For example: 31 | 32 | ````go 33 | import "fmt" 34 | import "log" 35 | import "github.com/jacobsa/go-serial/serial" 36 | 37 | ... 38 | 39 | // Set up options. 40 | options := serial.OpenOptions{ 41 | PortName: "/dev/tty.usbserial-A8008HlV", 42 | BaudRate: 19200, 43 | DataBits: 8, 44 | StopBits: 1, 45 | MinimumReadSize: 4, 46 | } 47 | 48 | // Open the port. 49 | port, err := serial.Open(options) 50 | if err != nil { 51 | log.Fatalf("serial.Open: %v", err) 52 | } 53 | 54 | // Make sure to close it later. 55 | defer port.Close() 56 | 57 | // Write 4 bytes to the port. 58 | b := []byte{0x00, 0x01, 0x02, 0x03} 59 | n, err := port.Write(b) 60 | if err != nil { 61 | log.Fatalf("port.Write: %v", err) 62 | } 63 | 64 | fmt.Println("Wrote", n, "bytes.") 65 | ```` 66 | 67 | See the documentation for the `OpenOptions` struct in `serial.go` for more 68 | information on the supported options. 69 | -------------------------------------------------------------------------------- /arduino/increment_and_echo/increment_and_echo.pde: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // A program that echos each byte read from the serial connection back 16 | // across the connection, after incrementing it by one. 17 | 18 | void setup() { 19 | Serial.begin(19200); 20 | } 21 | 22 | void loop() { 23 | if (Serial.available() > 0) { 24 | const uint8_t incoming_byte = Serial.read(); 25 | Serial.write(incoming_byte + 1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /go-serial-test/go-serial-test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * This application can be used to experiment and test various serial port options 3 | */ 4 | 5 | package main 6 | 7 | import ( 8 | "encoding/hex" 9 | "flag" 10 | "fmt" 11 | "io" 12 | "os" 13 | 14 | "github.com/jacobsa/go-serial/serial" 15 | ) 16 | 17 | func usage() { 18 | fmt.Println("go-serial-test usage:") 19 | flag.PrintDefaults() 20 | os.Exit(-1) 21 | } 22 | 23 | func main() { 24 | fmt.Println("Go serial test") 25 | port := flag.String("port", "", "serial port to test (/dev/ttyUSB0, etc)") 26 | baud := flag.Uint("baud", 115200, "Baud rate") 27 | txData := flag.String("txdata", "", "data to send in hex format (01ab238b)") 28 | even := flag.Bool("even", false, "enable even parity") 29 | odd := flag.Bool("odd", false, "enable odd parity") 30 | rs485 := flag.Bool("rs485", false, "enable RS485 RTS for direction control") 31 | rs485HighDuringSend := flag.Bool("rs485_high_during_send", false, "RTS signal should be high during send") 32 | rs485HighAfterSend := flag.Bool("rs485_high_after_send", false, "RTS signal should be high after send") 33 | stopbits := flag.Uint("stopbits", 1, "Stop bits") 34 | databits := flag.Uint("databits", 8, "Data bits") 35 | chartimeout := flag.Uint("chartimeout", 100, "Inter Character timeout (ms)") 36 | minread := flag.Uint("minread", 0, "Minimum read count") 37 | rx := flag.Bool("rx", false, "Read data received") 38 | 39 | flag.Parse() 40 | 41 | if *port == "" { 42 | fmt.Println("Must specify port") 43 | usage() 44 | } 45 | 46 | if *even && *odd { 47 | fmt.Println("can't specify both even and odd parity") 48 | usage() 49 | } 50 | 51 | parity := serial.PARITY_NONE 52 | 53 | if *even { 54 | parity = serial.PARITY_EVEN 55 | } else if *odd { 56 | parity = serial.PARITY_ODD 57 | } 58 | 59 | options := serial.OpenOptions{ 60 | PortName: *port, 61 | BaudRate: *baud, 62 | DataBits: *databits, 63 | StopBits: *stopbits, 64 | MinimumReadSize: *minread, 65 | InterCharacterTimeout: *chartimeout, 66 | ParityMode: parity, 67 | Rs485Enable: *rs485, 68 | Rs485RtsHighDuringSend: *rs485HighDuringSend, 69 | Rs485RtsHighAfterSend: *rs485HighAfterSend, 70 | } 71 | 72 | f, err := serial.Open(options) 73 | 74 | if err != nil { 75 | fmt.Println("Error opening serial port: ", err) 76 | os.Exit(-1) 77 | } else { 78 | defer f.Close() 79 | } 80 | 81 | if *txData != "" { 82 | txData_, err := hex.DecodeString(*txData) 83 | 84 | if err != nil { 85 | fmt.Println("Error decoding hex data: ", err) 86 | os.Exit(-1) 87 | } 88 | 89 | fmt.Println("Sending: ", hex.EncodeToString(txData_)) 90 | 91 | count, err := f.Write(txData_) 92 | 93 | if err != nil { 94 | fmt.Println("Error writing to serial port: ", err) 95 | } else { 96 | fmt.Printf("Wrote %v bytes\n", count) 97 | } 98 | 99 | } 100 | 101 | if *rx { 102 | for { 103 | buf := make([]byte, 32) 104 | n, err := f.Read(buf) 105 | if err != nil { 106 | if err != io.EOF { 107 | fmt.Println("Error reading from serial port: ", err) 108 | } 109 | } else { 110 | buf = buf[:n] 111 | fmt.Println("Rx: ", hex.EncodeToString(buf)) 112 | } 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /serial/Makefile: -------------------------------------------------------------------------------- 1 | include $(GOROOT)/src/Make.inc 2 | 3 | TARG=github.com/jacobsa/go-serial/serial 4 | GOFILES=\ 5 | serial.go\ 6 | open_$(GOOS).go\ 7 | 8 | include $(GOROOT)/src/Make.pkg 9 | -------------------------------------------------------------------------------- /serial/integration_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Integration tests for the serial package. 16 | 17 | package serial 18 | 19 | import ( 20 | "errors" 21 | "io" 22 | ) 23 | 24 | import "testing" 25 | import "time" 26 | 27 | const ( 28 | DEVICE = "/dev/tty.usbserial-A8008HlV" 29 | ) 30 | 31 | ////////////////////////////////////////////////////// 32 | // Helpers 33 | ////////////////////////////////////////////////////// 34 | 35 | // Read at least n bytes from an io.Reader, making sure not to block if it 36 | // takes too long. 37 | func readWithTimeout(r io.Reader, n int) ([]byte, error) { 38 | buf := make([]byte, n) 39 | done := make(chan error) 40 | readAndCallBack := func() { 41 | _, err := io.ReadAtLeast(r, buf, n) 42 | done <- err 43 | } 44 | 45 | go readAndCallBack() 46 | 47 | timeout := make(chan bool) 48 | sleepAndCallBack := func() { time.Sleep(2e9); timeout <- true } 49 | go sleepAndCallBack() 50 | 51 | select { 52 | case err := <-done: 53 | return buf, err 54 | case <-timeout: 55 | return nil, errors.New("Timed out.") 56 | } 57 | 58 | return nil, errors.New("Can't get here.") 59 | } 60 | 61 | ////////////////////////////////////////////////////// 62 | // Tests 63 | ////////////////////////////////////////////////////// 64 | 65 | // The device is assumed to be running the increment_and_echo program from the 66 | // hardware directory. 67 | func TestIncrementAndEcho(t *testing.T) { 68 | // Open the port. 69 | var options OpenOptions 70 | options.PortName = DEVICE 71 | options.BaudRate = 19200 72 | options.DataBits = 8 73 | options.StopBits = 1 74 | options.MinimumReadSize = 4 75 | 76 | circuit, err := Open(options) 77 | if err != nil { 78 | t.Fatal(err) 79 | } 80 | 81 | defer circuit.Close() 82 | 83 | // Pause for a few seconds to deal with the Arduino's annoying startup delay. 84 | time.Sleep(3e9) 85 | 86 | // Write some bytes. 87 | b := []byte{0x00, 0x17, 0xFE, 0xFF} 88 | 89 | n, err := circuit.Write(b) 90 | if err != nil { 91 | t.Fatal(err) 92 | } 93 | 94 | if n != 4 { 95 | t.Fatal("Expected 4 bytes written, got ", n) 96 | } 97 | 98 | // Check the response. 99 | b, err = readWithTimeout(circuit, 4) 100 | if err != nil { 101 | t.Fatal(err) 102 | } 103 | 104 | if b[0] != 0x01 { 105 | t.Error("Expected 0x01, got ", b[0]) 106 | } 107 | if b[1] != 0x18 { 108 | t.Error("Expected 0x18, got ", b[1]) 109 | } 110 | if b[2] != 0xFF { 111 | t.Error("Expected 0xFF, got ", b[2]) 112 | } 113 | if b[3] != 0x00 { 114 | t.Error("Expected 0x00, got ", b[3]) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /serial/open_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This file contains OS-specific constants and types that work on OS X (tested 16 | // on version 10.6.8). 17 | // 18 | // Helpful documentation for some of these options: 19 | // 20 | // http://www.unixwiz.net/techtips/termios-vmin-vtime.html 21 | // http://www.taltech.com/support/entry/serial_intro 22 | // http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_16.html 23 | // http://permalink.gmane.org/gmane.linux.kernel/103713 24 | // 25 | 26 | package serial 27 | 28 | import ( 29 | "errors" 30 | "io" 31 | ) 32 | import "os" 33 | import "syscall" 34 | import "unsafe" 35 | 36 | // termios types 37 | type cc_t byte 38 | type speed_t uint64 39 | type tcflag_t uint64 40 | 41 | // sys/termios.h 42 | const ( 43 | kCS5 = 0x00000000 44 | kCS6 = 0x00000100 45 | kCS7 = 0x00000200 46 | kCS8 = 0x00000300 47 | kCLOCAL = 0x00008000 48 | kCREAD = 0x00000800 49 | kCSTOPB = 0x00000400 50 | kIGNPAR = 0x00000004 51 | kPARENB = 0x00001000 52 | kPARODD = 0x00002000 53 | kCCTS_OFLOW = 0x00010000 54 | kCRTS_IFLOW = 0x00020000 55 | kCRTSCTS = kCCTS_OFLOW | kCRTS_IFLOW 56 | 57 | kNCCS = 20 58 | 59 | kVMIN = tcflag_t(16) 60 | kVTIME = tcflag_t(17) 61 | ) 62 | 63 | const ( 64 | 65 | // sys/ttycom.h 66 | kTIOCGETA = 1078490131 67 | kTIOCSETA = 2152231956 68 | 69 | // IOKit: serial/ioss.h 70 | kIOSSIOSPEED = 0x80045402 71 | ) 72 | 73 | // sys/termios.h 74 | type termios struct { 75 | c_iflag tcflag_t 76 | c_oflag tcflag_t 77 | c_cflag tcflag_t 78 | c_lflag tcflag_t 79 | c_cc [kNCCS]cc_t 80 | c_ispeed speed_t 81 | c_ospeed speed_t 82 | } 83 | 84 | // setTermios updates the termios struct associated with a serial port file 85 | // descriptor. This sets appropriate options for how the OS interacts with the 86 | // port. 87 | func setTermios(fd uintptr, src *termios) error { 88 | // Make the ioctl syscall that sets the termios struct. 89 | r1, _, errno := 90 | syscall.Syscall( 91 | syscall.SYS_IOCTL, 92 | fd, 93 | uintptr(kTIOCSETA), 94 | uintptr(unsafe.Pointer(src))) 95 | 96 | // Did the syscall return an error? 97 | if errno != 0 { 98 | return os.NewSyscallError("SYS_IOCTL", errno) 99 | } 100 | 101 | // Just in case, check the return value as well. 102 | if r1 != 0 { 103 | return errors.New("Unknown error from SYS_IOCTL.") 104 | } 105 | 106 | return nil 107 | } 108 | 109 | func convertOptions(options OpenOptions) (*termios, error) { 110 | var result termios 111 | 112 | // Ignore modem status lines. We don't want to receive SIGHUP when the serial 113 | // port is disconnected, for example. 114 | result.c_cflag |= kCLOCAL 115 | 116 | // Enable receiving data. 117 | // 118 | // NOTE(jacobsa): I don't know exactly what this flag is for. The man page 119 | // seems to imply that it shouldn't really exist. 120 | result.c_cflag |= kCREAD 121 | 122 | // Sanity check inter-character timeout and minimum read size options. 123 | vtime := uint(round(float64(options.InterCharacterTimeout)/100.0) * 100) 124 | vmin := options.MinimumReadSize 125 | 126 | if vmin == 0 && vtime < 100 { 127 | return nil, errors.New("Invalid values for InterCharacterTimeout and MinimumReadSize.") 128 | } 129 | 130 | if vtime > 25500 { 131 | return nil, errors.New("Invalid value for InterCharacterTimeout.") 132 | } 133 | 134 | // Set VMIN and VTIME. Make sure to convert to tenths of seconds for VTIME. 135 | result.c_cc[kVTIME] = cc_t(vtime / 100) 136 | result.c_cc[kVMIN] = cc_t(vmin) 137 | 138 | if !IsStandardBaudRate(options.BaudRate) { 139 | // Non-standard baud-rates cannot be set via the standard IOCTL. 140 | // 141 | // Set an arbitrary baudrate. We'll set the real one later. 142 | result.c_ispeed = 14400 143 | result.c_ospeed = 14400 144 | } else { 145 | result.c_ispeed = speed_t(options.BaudRate) 146 | result.c_ospeed = speed_t(options.BaudRate) 147 | } 148 | 149 | // Data bits 150 | switch options.DataBits { 151 | case 5: 152 | result.c_cflag |= kCS5 153 | case 6: 154 | result.c_cflag |= kCS6 155 | case 7: 156 | result.c_cflag |= kCS7 157 | case 8: 158 | result.c_cflag |= kCS8 159 | default: 160 | return nil, errors.New("Invalid setting for DataBits.") 161 | } 162 | 163 | // Stop bits 164 | switch options.StopBits { 165 | case 1: 166 | // Nothing to do; CSTOPB is already cleared. 167 | case 2: 168 | result.c_cflag |= kCSTOPB 169 | default: 170 | return nil, errors.New("Invalid setting for StopBits.") 171 | } 172 | 173 | // Parity mode 174 | switch options.ParityMode { 175 | case PARITY_NONE: 176 | // Nothing to do; PARENB is already not set. 177 | case PARITY_ODD: 178 | // Enable parity generation and receiving at the hardware level using 179 | // PARENB, but continue to deliver all bytes to the user no matter what (by 180 | // not setting INPCK). Also turn on odd parity mode. 181 | result.c_cflag |= kPARENB 182 | result.c_cflag |= kPARODD 183 | case PARITY_EVEN: 184 | // Enable parity generation and receiving at the hardware level using 185 | // PARENB, but continue to deliver all bytes to the user no matter what (by 186 | // not setting INPCK). Leave out PARODD to use even mode. 187 | result.c_cflag |= kPARENB 188 | default: 189 | return nil, errors.New("Invalid setting for ParityMode.") 190 | } 191 | 192 | if options.RTSCTSFlowControl { 193 | result.c_cflag |= kCRTSCTS 194 | } 195 | 196 | return &result, nil 197 | } 198 | 199 | func openInternal(options OpenOptions) (io.ReadWriteCloser, error) { 200 | // Open the serial port in non-blocking mode, since otherwise the OS will 201 | // wait for the CARRIER line to be asserted. 202 | file, err := 203 | os.OpenFile( 204 | options.PortName, 205 | syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 206 | 0600) 207 | 208 | if err != nil { 209 | return nil, err 210 | } 211 | 212 | // We want to do blocking I/O, so clear the non-blocking flag set above. 213 | r1, _, errno := 214 | syscall.Syscall( 215 | syscall.SYS_FCNTL, 216 | uintptr(file.Fd()), 217 | uintptr(syscall.F_SETFL), 218 | uintptr(0)) 219 | 220 | if errno != 0 { 221 | return nil, os.NewSyscallError("SYS_FCNTL", errno) 222 | } 223 | 224 | if r1 != 0 { 225 | return nil, errors.New("Unknown error from SYS_FCNTL.") 226 | } 227 | 228 | // Set standard termios options. 229 | terminalOptions, err := convertOptions(options) 230 | if err != nil { 231 | return nil, err 232 | } 233 | 234 | err = setTermios(file.Fd(), terminalOptions) 235 | if err != nil { 236 | return nil, err 237 | } 238 | 239 | if !IsStandardBaudRate(options.BaudRate) { 240 | // Set baud rate with the IOSSIOSPEED ioctl, to support non-standard speeds. 241 | r2, _, errno2 := syscall.Syscall( 242 | syscall.SYS_IOCTL, 243 | uintptr(file.Fd()), 244 | uintptr(kIOSSIOSPEED), 245 | uintptr(unsafe.Pointer(&options.BaudRate))) 246 | 247 | if errno2 != 0 { 248 | return nil, os.NewSyscallError("SYS_IOCTL", errno2) 249 | } 250 | 251 | if r2 != 0 { 252 | return nil, errors.New("Unknown error from SYS_IOCTL.") 253 | } 254 | } 255 | 256 | // We're done. 257 | return file, nil 258 | } 259 | -------------------------------------------------------------------------------- /serial/open_freebsd.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package serial 16 | 17 | import "io" 18 | 19 | func openInternal(options OpenOptions) (io.ReadWriteCloser, error) { 20 | return nil, "Not implemented on this OS." 21 | } 22 | -------------------------------------------------------------------------------- /serial/open_linux.go: -------------------------------------------------------------------------------- 1 | package serial 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "os" 7 | "syscall" 8 | "unsafe" 9 | 10 | "golang.org/x/sys/unix" 11 | ) 12 | 13 | // 14 | // Grab the constants with the following little program, to avoid using cgo: 15 | // 16 | // #include 17 | // #include 18 | // #include 19 | // 20 | // int main(int argc, const char **argv) { 21 | // printf("TCSETS2 = 0x%08X\n", TCSETS2); 22 | // printf("BOTHER = 0x%08X\n", BOTHER); 23 | // printf("NCCS = %d\n", NCCS); 24 | // return 0; 25 | // } 26 | // 27 | const ( 28 | kTCSETS2 = 0x402C542B 29 | kBOTHER = 0x1000 30 | kNCCS = 19 31 | ) 32 | 33 | // 34 | // Types from asm-generic/termbits.h 35 | // 36 | 37 | type cc_t byte 38 | type speed_t uint32 39 | type tcflag_t uint32 40 | type termios2 struct { 41 | c_iflag tcflag_t // input mode flags 42 | c_oflag tcflag_t // output mode flags 43 | c_cflag tcflag_t // control mode flags 44 | c_lflag tcflag_t // local mode flags 45 | c_line cc_t // line discipline 46 | c_cc [kNCCS]cc_t // control characters 47 | c_ispeed speed_t // input speed 48 | c_ospeed speed_t // output speed 49 | } 50 | 51 | // Constants for RS485 operation 52 | 53 | const ( 54 | sER_RS485_ENABLED = (1 << 0) 55 | sER_RS485_RTS_ON_SEND = (1 << 1) 56 | sER_RS485_RTS_AFTER_SEND = (1 << 2) 57 | sER_RS485_RX_DURING_TX = (1 << 4) 58 | tIOCSRS485 = 0x542F 59 | ) 60 | 61 | type serial_rs485 struct { 62 | flags uint32 63 | delay_rts_before_send uint32 64 | delay_rts_after_send uint32 65 | padding [5]uint32 66 | } 67 | 68 | // 69 | // Returns a pointer to an instantiates termios2 struct, based on the given 70 | // OpenOptions. Termios2 is a Linux extension which allows arbitrary baud rates 71 | // to be specified. 72 | // 73 | func makeTermios2(options OpenOptions) (*termios2, error) { 74 | 75 | // Sanity check inter-character timeout and minimum read size options. 76 | 77 | vtime := uint(round(float64(options.InterCharacterTimeout)/100.0) * 100) 78 | vmin := options.MinimumReadSize 79 | 80 | if vmin == 0 && vtime < 100 { 81 | return nil, errors.New("invalid values for InterCharacterTimeout and MinimumReadSize") 82 | } 83 | 84 | if vtime > 25500 { 85 | return nil, errors.New("invalid value for InterCharacterTimeout") 86 | } 87 | 88 | ccOpts := [kNCCS]cc_t{} 89 | ccOpts[syscall.VTIME] = cc_t(vtime / 100) 90 | ccOpts[syscall.VMIN] = cc_t(vmin) 91 | 92 | t2 := &termios2{ 93 | c_cflag: syscall.CLOCAL | syscall.CREAD | kBOTHER, 94 | c_ispeed: speed_t(options.BaudRate), 95 | c_ospeed: speed_t(options.BaudRate), 96 | c_cc: ccOpts, 97 | } 98 | 99 | switch options.StopBits { 100 | case 1: 101 | case 2: 102 | t2.c_cflag |= syscall.CSTOPB 103 | 104 | default: 105 | return nil, errors.New("invalid setting for StopBits") 106 | } 107 | 108 | switch options.ParityMode { 109 | case PARITY_NONE: 110 | case PARITY_ODD: 111 | t2.c_cflag |= syscall.PARENB 112 | t2.c_cflag |= syscall.PARODD 113 | 114 | case PARITY_EVEN: 115 | t2.c_cflag |= syscall.PARENB 116 | 117 | default: 118 | return nil, errors.New("invalid setting for ParityMode") 119 | } 120 | 121 | switch options.DataBits { 122 | case 5: 123 | t2.c_cflag |= syscall.CS5 124 | case 6: 125 | t2.c_cflag |= syscall.CS6 126 | case 7: 127 | t2.c_cflag |= syscall.CS7 128 | case 8: 129 | t2.c_cflag |= syscall.CS8 130 | default: 131 | return nil, errors.New("invalid setting for DataBits") 132 | } 133 | 134 | if options.RTSCTSFlowControl { 135 | t2.c_cflag |= unix.CRTSCTS 136 | } 137 | 138 | return t2, nil 139 | } 140 | 141 | func openInternal(options OpenOptions) (io.ReadWriteCloser, error) { 142 | 143 | file, openErr := 144 | os.OpenFile( 145 | options.PortName, 146 | syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 147 | 0600) 148 | if openErr != nil { 149 | return nil, openErr 150 | } 151 | 152 | // Clear the non-blocking flag set above. 153 | nonblockErr := syscall.SetNonblock(int(file.Fd()), false) 154 | if nonblockErr != nil { 155 | return nil, nonblockErr 156 | } 157 | 158 | t2, optErr := makeTermios2(options) 159 | if optErr != nil { 160 | return nil, optErr 161 | } 162 | 163 | r, _, errno := syscall.Syscall( 164 | syscall.SYS_IOCTL, 165 | uintptr(file.Fd()), 166 | uintptr(kTCSETS2), 167 | uintptr(unsafe.Pointer(t2))) 168 | 169 | if errno != 0 { 170 | return nil, os.NewSyscallError("SYS_IOCTL", errno) 171 | } 172 | 173 | if r != 0 { 174 | return nil, errors.New("unknown error from SYS_IOCTL") 175 | } 176 | 177 | if options.Rs485Enable { 178 | rs485 := serial_rs485{ 179 | sER_RS485_ENABLED, 180 | uint32(options.Rs485DelayRtsBeforeSend), 181 | uint32(options.Rs485DelayRtsAfterSend), 182 | [5]uint32{0, 0, 0, 0, 0}, 183 | } 184 | 185 | if options.Rs485RtsHighDuringSend { 186 | rs485.flags |= sER_RS485_RTS_ON_SEND 187 | } 188 | 189 | if options.Rs485RtsHighAfterSend { 190 | rs485.flags |= sER_RS485_RTS_AFTER_SEND 191 | } 192 | 193 | r, _, errno := syscall.Syscall( 194 | syscall.SYS_IOCTL, 195 | uintptr(file.Fd()), 196 | uintptr(tIOCSRS485), 197 | uintptr(unsafe.Pointer(&rs485))) 198 | 199 | if errno != 0 { 200 | return nil, os.NewSyscallError("SYS_IOCTL (RS485)", errno) 201 | } 202 | 203 | if r != 0 { 204 | return nil, errors.New("Unknown error from SYS_IOCTL (RS485)") 205 | } 206 | } 207 | 208 | return file, nil 209 | } 210 | -------------------------------------------------------------------------------- /serial/open_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package serial 16 | 17 | import ( 18 | "fmt" 19 | "io" 20 | "os" 21 | "sync" 22 | "syscall" 23 | "unsafe" 24 | ) 25 | 26 | type serialPort struct { 27 | f *os.File 28 | fd syscall.Handle 29 | rl sync.Mutex 30 | wl sync.Mutex 31 | ro *syscall.Overlapped 32 | wo *syscall.Overlapped 33 | } 34 | 35 | type structDCB struct { 36 | DCBlength, BaudRate uint32 37 | flags [4]byte 38 | wReserved, XonLim, XoffLim uint16 39 | ByteSize, Parity, StopBits byte 40 | XonChar, XoffChar, ErrorChar, EofChar, EvtChar byte 41 | wReserved1 uint16 42 | } 43 | 44 | type structTimeouts struct { 45 | ReadIntervalTimeout uint32 46 | ReadTotalTimeoutMultiplier uint32 47 | ReadTotalTimeoutConstant uint32 48 | WriteTotalTimeoutMultiplier uint32 49 | WriteTotalTimeoutConstant uint32 50 | } 51 | 52 | func openInternal(options OpenOptions) (io.ReadWriteCloser, error) { 53 | if len(options.PortName) > 0 && options.PortName[0] != '\\' { 54 | options.PortName = "\\\\.\\" + options.PortName 55 | } 56 | 57 | h, err := syscall.CreateFile(syscall.StringToUTF16Ptr(options.PortName), 58 | syscall.GENERIC_READ|syscall.GENERIC_WRITE, 59 | 0, 60 | nil, 61 | syscall.OPEN_EXISTING, 62 | syscall.FILE_ATTRIBUTE_NORMAL|syscall.FILE_FLAG_OVERLAPPED, 63 | 0) 64 | if err != nil { 65 | return nil, err 66 | } 67 | f := os.NewFile(uintptr(h), options.PortName) 68 | defer func() { 69 | if err != nil { 70 | f.Close() 71 | } 72 | }() 73 | 74 | if err = setCommState(h, options); err != nil { 75 | return nil, err 76 | } 77 | if err = setupComm(h, 64, 64); err != nil { 78 | return nil, err 79 | } 80 | if err = setCommTimeouts(h, options); err != nil { 81 | return nil, err 82 | } 83 | if err = setCommMask(h); err != nil { 84 | return nil, err 85 | } 86 | 87 | ro, err := newOverlapped() 88 | if err != nil { 89 | return nil, err 90 | } 91 | wo, err := newOverlapped() 92 | if err != nil { 93 | return nil, err 94 | } 95 | port := new(serialPort) 96 | port.f = f 97 | port.fd = h 98 | port.ro = ro 99 | port.wo = wo 100 | 101 | return port, nil 102 | } 103 | 104 | func (p *serialPort) Close() error { 105 | return p.f.Close() 106 | } 107 | 108 | func (p *serialPort) Write(buf []byte) (int, error) { 109 | p.wl.Lock() 110 | defer p.wl.Unlock() 111 | 112 | if err := resetEvent(p.wo.HEvent); err != nil { 113 | return 0, err 114 | } 115 | var n uint32 116 | err := syscall.WriteFile(p.fd, buf, &n, p.wo) 117 | if err != nil && err != syscall.ERROR_IO_PENDING { 118 | return int(n), err 119 | } 120 | return getOverlappedResult(p.fd, p.wo) 121 | } 122 | 123 | func (p *serialPort) Read(buf []byte) (int, error) { 124 | if p == nil || p.f == nil { 125 | return 0, fmt.Errorf("Invalid port on read %v %v", p, p.f) 126 | } 127 | 128 | p.rl.Lock() 129 | defer p.rl.Unlock() 130 | 131 | if err := resetEvent(p.ro.HEvent); err != nil { 132 | return 0, err 133 | } 134 | var done uint32 135 | err := syscall.ReadFile(p.fd, buf, &done, p.ro) 136 | if err != nil && err != syscall.ERROR_IO_PENDING { 137 | return int(done), err 138 | } 139 | return getOverlappedResult(p.fd, p.ro) 140 | } 141 | 142 | var ( 143 | nSetCommState, 144 | nSetCommTimeouts, 145 | nSetCommMask, 146 | nSetupComm, 147 | nGetOverlappedResult, 148 | nCreateEvent, 149 | nResetEvent uintptr 150 | ) 151 | 152 | func init() { 153 | k32, err := syscall.LoadLibrary("kernel32.dll") 154 | if err != nil { 155 | panic("LoadLibrary " + err.Error()) 156 | } 157 | defer syscall.FreeLibrary(k32) 158 | 159 | nSetCommState = getProcAddr(k32, "SetCommState") 160 | nSetCommTimeouts = getProcAddr(k32, "SetCommTimeouts") 161 | nSetCommMask = getProcAddr(k32, "SetCommMask") 162 | nSetupComm = getProcAddr(k32, "SetupComm") 163 | nGetOverlappedResult = getProcAddr(k32, "GetOverlappedResult") 164 | nCreateEvent = getProcAddr(k32, "CreateEventW") 165 | nResetEvent = getProcAddr(k32, "ResetEvent") 166 | } 167 | 168 | func getProcAddr(lib syscall.Handle, name string) uintptr { 169 | addr, err := syscall.GetProcAddress(lib, name) 170 | if err != nil { 171 | panic(name + " " + err.Error()) 172 | } 173 | return addr 174 | } 175 | 176 | func setCommState(h syscall.Handle, options OpenOptions) error { 177 | var params structDCB 178 | params.DCBlength = uint32(unsafe.Sizeof(params)) 179 | 180 | params.flags[0] = 0x01 // fBinary 181 | params.flags[0] |= 0x10 // Assert DSR 182 | 183 | if options.ParityMode != PARITY_NONE { 184 | params.flags[0] |= 0x03 // fParity 185 | params.Parity = byte(options.ParityMode) 186 | } 187 | 188 | if options.StopBits == 1 { 189 | params.StopBits = 0 190 | } else if options.StopBits == 2 { 191 | params.StopBits = 2 192 | } 193 | 194 | params.BaudRate = uint32(options.BaudRate) 195 | params.ByteSize = byte(options.DataBits) 196 | 197 | if options.RTSCTSFlowControl { 198 | params.flags[0] |= 0x04 // fOutxCtsFlow = 0x1 199 | params.flags[1] |= 0x20 // fRtsControl = RTS_CONTROL_HANDSHAKE (0x2) 200 | } 201 | 202 | r, _, err := syscall.Syscall(nSetCommState, 2, uintptr(h), uintptr(unsafe.Pointer(¶ms)), 0) 203 | if r == 0 { 204 | return err 205 | } 206 | return nil 207 | } 208 | 209 | func setCommTimeouts(h syscall.Handle, options OpenOptions) error { 210 | var timeouts structTimeouts 211 | const MAXDWORD = 1<<32 - 1 212 | timeoutConstant := uint32(round(float64(options.InterCharacterTimeout) / 100.0)) 213 | readIntervalTimeout := uint32(options.MinimumReadSize) 214 | 215 | if timeoutConstant > 0 && readIntervalTimeout == 0 { 216 | //Assume we're setting for non blocking IO. 217 | timeouts.ReadIntervalTimeout = MAXDWORD 218 | timeouts.ReadTotalTimeoutMultiplier = MAXDWORD 219 | timeouts.ReadTotalTimeoutConstant = timeoutConstant 220 | } else if readIntervalTimeout > 0 { 221 | // Assume we want to block and wait for input. 222 | timeouts.ReadIntervalTimeout = readIntervalTimeout 223 | timeouts.ReadTotalTimeoutMultiplier = 1 224 | timeouts.ReadTotalTimeoutConstant = 1 225 | } else { 226 | // No idea what we intended, use defaults 227 | // default config does what it did before. 228 | timeouts.ReadIntervalTimeout = MAXDWORD 229 | timeouts.ReadTotalTimeoutMultiplier = MAXDWORD 230 | timeouts.ReadTotalTimeoutConstant = MAXDWORD - 1 231 | } 232 | 233 | /* 234 | Empirical testing has shown that to have non-blocking IO we need to set: 235 | ReadTotalTimeoutConstant > 0 and 236 | ReadTotalTimeoutMultiplier = MAXDWORD and 237 | ReadIntervalTimeout = MAXDWORD 238 | 239 | The documentation states that ReadIntervalTimeout is set in MS but 240 | empirical investigation determines that it seems to interpret in units 241 | of 100ms. 242 | 243 | If InterCharacterTimeout is set at all it seems that the port will block 244 | indefinitly until a character is received. Not all circumstances have been 245 | tested. The input of an expert would be appreciated. 246 | 247 | From http://msdn.microsoft.com/en-us/library/aa363190(v=VS.85).aspx 248 | 249 | For blocking I/O see below: 250 | 251 | Remarks: 252 | 253 | If an application sets ReadIntervalTimeout and 254 | ReadTotalTimeoutMultiplier to MAXDWORD and sets 255 | ReadTotalTimeoutConstant to a value greater than zero and 256 | less than MAXDWORD, one of the following occurs when the 257 | ReadFile function is called: 258 | 259 | If there are any bytes in the input buffer, ReadFile returns 260 | immediately with the bytes in the buffer. 261 | 262 | If there are no bytes in the input buffer, ReadFile waits 263 | until a byte arrives and then returns immediately. 264 | 265 | If no bytes arrive within the time specified by 266 | ReadTotalTimeoutConstant, ReadFile times out. 267 | */ 268 | 269 | r, _, err := syscall.Syscall(nSetCommTimeouts, 2, uintptr(h), uintptr(unsafe.Pointer(&timeouts)), 0) 270 | if r == 0 { 271 | return err 272 | } 273 | return nil 274 | } 275 | 276 | func setupComm(h syscall.Handle, in, out int) error { 277 | r, _, err := syscall.Syscall(nSetupComm, 3, uintptr(h), uintptr(in), uintptr(out)) 278 | if r == 0 { 279 | return err 280 | } 281 | return nil 282 | } 283 | 284 | func setCommMask(h syscall.Handle) error { 285 | const EV_RXCHAR = 0x0001 286 | r, _, err := syscall.Syscall(nSetCommMask, 2, uintptr(h), EV_RXCHAR, 0) 287 | if r == 0 { 288 | return err 289 | } 290 | return nil 291 | } 292 | 293 | func resetEvent(h syscall.Handle) error { 294 | r, _, err := syscall.Syscall(nResetEvent, 1, uintptr(h), 0, 0) 295 | if r == 0 { 296 | return err 297 | } 298 | return nil 299 | } 300 | 301 | func newOverlapped() (*syscall.Overlapped, error) { 302 | var overlapped syscall.Overlapped 303 | r, _, err := syscall.Syscall6(nCreateEvent, 4, 0, 1, 0, 0, 0, 0) 304 | if r == 0 { 305 | return nil, err 306 | } 307 | overlapped.HEvent = syscall.Handle(r) 308 | return &overlapped, nil 309 | } 310 | 311 | func getOverlappedResult(h syscall.Handle, overlapped *syscall.Overlapped) (int, error) { 312 | var n int 313 | r, _, err := syscall.Syscall6(nGetOverlappedResult, 4, 314 | uintptr(h), 315 | uintptr(unsafe.Pointer(overlapped)), 316 | uintptr(unsafe.Pointer(&n)), 1, 0, 0) 317 | if r == 0 { 318 | return n, err 319 | } 320 | 321 | return n, nil 322 | } 323 | -------------------------------------------------------------------------------- /serial/serial.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Aaron Jacobs. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package serial provides routines for interacting with serial ports. 16 | // Currently it supports only OS X; see the readme file for details. 17 | 18 | package serial 19 | 20 | import ( 21 | "io" 22 | "math" 23 | ) 24 | 25 | // Valid parity values. 26 | type ParityMode int 27 | 28 | const ( 29 | PARITY_NONE ParityMode = 0 30 | PARITY_ODD ParityMode = 1 31 | PARITY_EVEN ParityMode = 2 32 | ) 33 | 34 | var ( 35 | // The list of standard baud-rates. 36 | StandardBaudRates = map[uint]bool{ 37 | 50: true, 38 | 75: true, 39 | 110: true, 40 | 134: true, 41 | 150: true, 42 | 200: true, 43 | 300: true, 44 | 600: true, 45 | 1200: true, 46 | 1800: true, 47 | 2400: true, 48 | 4800: true, 49 | 7200: true, 50 | 9600: true, 51 | 14400: true, 52 | 19200: true, 53 | 28800: true, 54 | 38400: true, 55 | 57600: true, 56 | 76800: true, 57 | 115200: true, 58 | 230400: true, 59 | } 60 | ) 61 | 62 | // IsStandardBaudRate checks whether the specified baud-rate is standard. 63 | // 64 | // Some operating systems may support non-standard baud-rates (OSX) via 65 | // additional IOCTL. 66 | func IsStandardBaudRate(baudRate uint) bool { return StandardBaudRates[baudRate] } 67 | 68 | // OpenOptions is the struct containing all of the options necessary for 69 | // opening a serial port. 70 | type OpenOptions struct { 71 | // The name of the port, e.g. "/dev/tty.usbserial-A8008HlV". 72 | PortName string 73 | 74 | // The baud rate for the port. 75 | BaudRate uint 76 | 77 | // The number of data bits per frame. Legal values are 5, 6, 7, and 8. 78 | DataBits uint 79 | 80 | // The number of stop bits per frame. Legal values are 1 and 2. 81 | StopBits uint 82 | 83 | // The type of parity bits to use for the connection. Currently parity errors 84 | // are simply ignored; that is, bytes are delivered to the user no matter 85 | // whether they were received with a parity error or not. 86 | ParityMode ParityMode 87 | 88 | // Enable RTS/CTS (hardware) flow control. 89 | RTSCTSFlowControl bool 90 | 91 | // An inter-character timeout value, in milliseconds, and a minimum number of 92 | // bytes to block for on each read. A call to Read() that otherwise may block 93 | // waiting for more data will return immediately if the specified amount of 94 | // time elapses between successive bytes received from the device or if the 95 | // minimum number of bytes has been exceeded. 96 | // 97 | // Note that the inter-character timeout value may be rounded to the nearest 98 | // 100 ms on some systems, and that behavior is undefined if calls to Read 99 | // supply a buffer whose length is less than the minimum read size. 100 | // 101 | // Behaviors for various settings for these values are described below. For 102 | // more information, see the discussion of VMIN and VTIME here: 103 | // 104 | // http://www.unixwiz.net/techtips/termios-vmin-vtime.html 105 | // 106 | // InterCharacterTimeout = 0 and MinimumReadSize = 0 (the default): 107 | // This arrangement is not legal; you must explicitly set at least one of 108 | // these fields to a positive number. (If MinimumReadSize is zero then 109 | // InterCharacterTimeout must be at least 100.) 110 | // 111 | // InterCharacterTimeout > 0 and MinimumReadSize = 0 112 | // If data is already available on the read queue, it is transferred to 113 | // the caller's buffer and the Read() call returns immediately. 114 | // Otherwise, the call blocks until some data arrives or the 115 | // InterCharacterTimeout milliseconds elapse from the start of the call. 116 | // Note that in this configuration, InterCharacterTimeout must be at 117 | // least 100 ms. 118 | // 119 | // InterCharacterTimeout > 0 and MinimumReadSize > 0 120 | // Calls to Read() return when at least MinimumReadSize bytes are 121 | // available or when InterCharacterTimeout milliseconds elapse between 122 | // received bytes. The inter-character timer is not started until the 123 | // first byte arrives. 124 | // 125 | // InterCharacterTimeout = 0 and MinimumReadSize > 0 126 | // Calls to Read() return only when at least MinimumReadSize bytes are 127 | // available. The inter-character timer is not used. 128 | // 129 | // For windows usage, these options (termios) do not conform well to the 130 | // windows serial port / comms abstractions. Please see the code in 131 | // open_windows setCommTimeouts function for full documentation. 132 | // Summary: 133 | // Setting MinimumReadSize > 0 will cause the serialPort to block until 134 | // until data is available on the port. 135 | // Setting IntercharacterTimeout > 0 and MinimumReadSize == 0 will cause 136 | // the port to either wait until IntercharacterTimeout wait time is 137 | // exceeded OR there is character data to return from the port. 138 | // 139 | 140 | InterCharacterTimeout uint 141 | MinimumReadSize uint 142 | 143 | // Use to enable RS485 mode -- probably only valid on some Linux platforms 144 | Rs485Enable bool 145 | 146 | // Set to true for logic level high during send 147 | Rs485RtsHighDuringSend bool 148 | 149 | // Set to true for logic level high after send 150 | Rs485RtsHighAfterSend bool 151 | 152 | // set to receive data during sending 153 | Rs485RxDuringTx bool 154 | 155 | // RTS delay before send 156 | Rs485DelayRtsBeforeSend int 157 | 158 | // RTS delay after send 159 | Rs485DelayRtsAfterSend int 160 | } 161 | 162 | // Open creates an io.ReadWriteCloser based on the supplied options struct. 163 | func Open(options OpenOptions) (io.ReadWriteCloser, error) { 164 | // Redirect to the OS-specific function. 165 | return openInternal(options) 166 | } 167 | 168 | // Rounds a float to the nearest integer. 169 | func round(f float64) float64 { 170 | return math.Floor(f + 0.5) 171 | } 172 | -------------------------------------------------------------------------------- /serial/serial_test.go: -------------------------------------------------------------------------------- 1 | package serial 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestIsStandardBaudRate(t *testing.T) { 9 | testCases := []struct { 10 | BaudRate uint 11 | IsStandard bool 12 | }{ 13 | {50, true}, 14 | {75, true}, 15 | {110, true}, 16 | {134, true}, 17 | {150, true}, 18 | {200, true}, 19 | {300, true}, 20 | {600, true}, 21 | {1200, true}, 22 | {1800, true}, 23 | {2400, true}, 24 | {4800, true}, 25 | {7200, true}, 26 | {9600, true}, 27 | {14400, true}, 28 | {19200, true}, 29 | {28800, true}, 30 | {38400, true}, 31 | {57600, true}, 32 | {76800, true}, 33 | {115200, true}, 34 | {230400, true}, 35 | {0, false}, 36 | {123, false}, 37 | {14401, false}, 38 | } 39 | 40 | for _, testCase := range testCases { 41 | testName := fmt.Sprintf("%d", testCase.BaudRate) 42 | t.Run(testName, func(t *testing.T) { 43 | result := IsStandardBaudRate(testCase.BaudRate) 44 | 45 | if result != testCase.IsStandard { 46 | t.Errorf("expected result to be %t, but got %t", testCase.IsStandard, result) 47 | } 48 | }) 49 | } 50 | } 51 | --------------------------------------------------------------------------------