commw32.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
  2. // This software may be modified and distributed under the terms
  3. // of the BSD license. See the LICENSE file for details.
  4. //go:build windows && cgo
  5. // +build windows,cgo
  6. // Port of commw32.c
  7. // To generate go types: go tool cgo commw32.go
  8. package main
  9. // #include <windows.h>
  10. import "C"
  11. import (
  12. "bufio"
  13. "fmt"
  14. "os"
  15. "syscall"
  16. )
  17. const port = "COM4"
  18. func main() {
  19. handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(port),
  20. syscall.GENERIC_READ|syscall.GENERIC_WRITE,
  21. 0, // mode
  22. nil, // security
  23. syscall.OPEN_EXISTING, // no creating new
  24. 0,
  25. 0)
  26. if err != nil {
  27. fmt.Print(err)
  28. return
  29. }
  30. fmt.Printf("handle created %d\n", handle)
  31. defer syscall.CloseHandle(handle)
  32. var dcb C.DCB
  33. dcb.BaudRate = 9600
  34. dcb.ByteSize = 8
  35. dcb.StopBits = C.ONESTOPBIT
  36. dcb.Parity = C.NOPARITY
  37. if C.SetCommState(C.HANDLE(handle), &dcb) == 0 {
  38. fmt.Printf("set comm state error %v\n", syscall.GetLastError())
  39. return
  40. }
  41. fmt.Printf("set comm state succeed\n")
  42. var timeouts C.COMMTIMEOUTS
  43. // time-out between charactor for receiving (ms)
  44. timeouts.ReadIntervalTimeout = 1000
  45. timeouts.ReadTotalTimeoutMultiplier = 0
  46. timeouts.ReadTotalTimeoutConstant = 1000
  47. timeouts.WriteTotalTimeoutMultiplier = 0
  48. timeouts.WriteTotalTimeoutConstant = 1000
  49. if C.SetCommTimeouts(C.HANDLE(handle), &timeouts) == 0 {
  50. fmt.Printf("set comm timeouts error %v\n", syscall.GetLastError())
  51. return
  52. }
  53. fmt.Printf("set comm timeouts succeed\n")
  54. var n uint32
  55. data := []byte("abc")
  56. err = syscall.WriteFile(handle, data, &n, nil)
  57. if err != nil {
  58. fmt.Println(err)
  59. return
  60. }
  61. fmt.Printf("write file succeed\n")
  62. fmt.Printf("Press Enter when ready for reading...")
  63. reader := bufio.NewReader(os.Stdin)
  64. _, _ = reader.ReadString('\n')
  65. data = make([]byte, 512)
  66. err = syscall.ReadFile(handle, data, &n, nil)
  67. if err != nil {
  68. fmt.Println(err)
  69. return
  70. }
  71. fmt.Printf("received data %v:\n", n)
  72. fmt.Printf("%x\n", data[:n])
  73. fmt.Printf("closed\n")
  74. }