Debian Codegraph @

test/commw32/commw32.go

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