示例#1
1
func (t *Interface) Write(ch chan []byte) (err error) {
	tx := syscall.Overlapped{}
	var hevent windows.Handle
	hevent, err = windows.CreateEvent(nil, 0, 0, nil)
	if err != nil {
		return
	}
	tx.HEvent = syscall.Handle(hevent)
	for {
		select {
		case data := <-ch:
			var l uint32
			syscall.WriteFile(t.file, data, &l, &tx)
			syscall.WaitForSingleObject(tx.HEvent, syscall.INFINITE)
			tx.Offset += uint32(len(data))
		}
	}
}
示例#2
0
文件: ct.go 项目: tajtiattila/test
func Write(fd int, p []byte) (n int, errno int) {
	var mode uint32
	var done uint32
	if isConsole, _ := GetConsoleMode(int32(fd), &mode); UnicodeConsoleOutput && isConsole {
		// TODO: The number of TCHARs to write. If the total size of the
		// specified number of characters exceeds 64 KB, the function fails with ERROR_NOT_ENOUGH_MEMORY.
		buf16 := utf16.Encode([]int(string(p)))
		//for _, c := range buf16 { print(c," ") } ; println()
		if ok, e := WriteConsole(int32(fd), buf16, &done); !ok {
			return 0, e
		}
		// convert length of utf16 characters to number of bytes written
		if done == uint32(len(buf16)) {
			done = uint32(len(p))
		} else {
			done = 0
			for _, rune := range utf16.Decode(buf16[:done]) {
				done += uint32(utf8.RuneLen(rune))
			}
		}
	} else {
		// TODO: This might as well fail with large writes, only Microsoft doesn't say that, see
		// http://code.google.com/p/msysgit/issues/detail?id=409 for example
		if ok, e := syscall.WriteFile(int32(fd), p, &done, nil); !ok {
			return 0, e
		}
	}
	return int(done), 0
}
示例#3
0
文件: hid_windows.go 项目: tam7t/hid
func (d *winDevice) Write(data []byte) error {
	// first make sure we send the correct amount of data to the device
	outSize := int(d.info.OutputReportLength)
	buffer := make([]byte, outSize, outSize)
	copy(buffer, data)

	ol := new(syscall.Overlapped)
	if err := syscall.WriteFile(d.handle, buffer, nil, ol); err != nil {
		// IO Pending is ok we simply wait for it to finish a few lines below
		// all other errors should be reported.
		if err != syscall.ERROR_IO_PENDING {
			return err
		}
	}

	// now wait for the overlapped device access to finish.
	var written C.DWORD
	if C.GetOverlappedResult(d.h(), (*C.OVERLAPPED)((unsafe.Pointer)(ol)), &written, C.TRUE) == 0 {
		return syscall.GetLastError()
	}

	if int(written) != outSize {
		return errors.New("written bytes missmatch!")
	}
	return nil
}
示例#4
0
func (p *Port) Write(buf []byte) (int, error) {
	p.wl.Lock()
	defer p.wl.Unlock()

	fmt.Println("Reset Event")

	if err := resetEvent(p.wo.HEvent); err != nil {
		return 0, err
	}

	fmt.Println("Reset Event Done")

	var n uint32

	fmt.Println("WriteFile")
	//Public Declare Auto Function WriteFile Lib "kernel32.dll" (ByVal hFile As IntPtr, _
	//   ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToWrite As Int32, _
	//      ByRef lpNumberOfBytesWritten As Int32, ByVal lpOverlapped As IntPtr) As Boolean
	// Success = WriteFile(hParallelPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
	err := syscall.WriteFile(p.fd, buf, &n, p.wo)

	fmt.Println("WriteFile Done")
	if err != nil && err != syscall.ERROR_IO_PENDING {
		return int(n), err
	}

	return getOverlappedResult(p.fd, p.wo)
}
示例#5
0
// Write writes data to the serial port.
func (p *port) Write(b []byte) (n int, err error) {
	var done uint32
	if err = syscall.WriteFile(p.handle, b, &done, nil); err != nil {
		return
	}
	n = int(done)
	return
}
示例#6
0
// Write writes to a file handle.
func (f *win32File) Write(b []byte) (int, error) {
	c, err := f.prepareIo()
	if err != nil {
		return 0, err
	}
	var bytes uint32
	err = syscall.WriteFile(f.handle, b, &bytes, &c.o)
	return f.asyncIo(c, f.writeDeadline, bytes, err)
}
示例#7
0
// Write implements the net.Conn Write method.
func (c *PipeConn) Write(b []byte) (int, error) {
	overlapped, err := newOverlapped()
	if err != nil {
		return 0, err
	}
	var n uint32
	err = syscall.WriteFile(c.handle, b, &n, overlapped)
	return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped)
}
示例#8
0
func (p *Port) write(b []byte) (n int, err error) {
	n = 0
	for {
		var done uint32
		err = syscall.WriteFile(p.handle, b[n:], &done, nil)
		n += int(done)
		if n == len(b) {
			break
		}
	}
	return
}
示例#9
0
func (p *virtioPort) Write(buf []byte) (int, error) {
	p.wl.Lock()
	defer p.wl.Unlock()
	if err := resetEvent(p.wo.HEvent); err != nil {
		return 0, err
	}
	var n uint32
	err := syscall.WriteFile(p.fd, buf, &n, p.wo)
	if err != nil && err != syscall.ERROR_IO_PENDING {
		return int(n), err
	}
	return getOverlappedResult(p.fd, p.wo)
}
示例#10
0
func (p *serialPort) Write(buf []byte) (int, os.Error) {
	p.wl.Lock()
	defer p.wl.Unlock()

	if err := resetEvent(p.wo.HEvent); err != nil {
		return 0, err
	}
	var n uint32
	e := syscall.WriteFile(p.fd, buf, &n, p.wo)
	if e != 0 && e != syscall.ERROR_IO_PENDING {
		return int(n), errno(uintptr(e))
	}
	return getOverlappedResult(p.fd, p.wo)
}
示例#11
0
func (p *Port) write(b []byte) (n int, err error) {
	for {
		var done uint32
		err = syscall.WriteFile(p.handle, b[n:], &done, nil)
		n += int(done)

		if err != nil || n == len(b) {
			break
		}
	}

	if err != nil {
		err = p.flush()
	}

	return
}
示例#12
0
func (dev *SerialDevice) Write(buf []byte) (int, error) {
	dev.wl.Lock()
	defer dev.wl.Unlock()

	if err := syscallEvent(dev.wo.HEvent, "reset"); err != nil {
		return 0, err
	}

	var n uint32
	err := syscall.WriteFile(dev.fd, buf, &n, dev.wo)
	if err != nil && err != syscall.ERROR_IO_PENDING {
		fmt.Printf("%v\n", err)
		return int(n), fmt.Errorf("%#v", err)
	}

	return getOverlapResult(dev.fd, dev.wo)
}
示例#13
0
func (p *serialPort) Write(buf []byte) (int, error) {
	p.wl.Lock()
	defer p.wl.Unlock()

	if err := resetEvent(p.wo.HEvent); err != nil {
		return 0, err
	}
	var n uint32
	err := syscall.WriteFile(p.fd, buf, &n, p.wo)
	//fmt.Printf("n %d  err %v\n", n, err)
	_ = fmt.Printf
	if err != nil && err != syscall.ERROR_IO_PENDING {
		//fmt.Printf("returning...\n")
		return int(n), err
	}
	return getOverlappedResult(p.fd, p.wo)
}
示例#14
0
// pwrite writes len(b) bytes to the File starting at byte offset off.
// It returns the number of bytes written and an error, if any.
func (f *File) pwrite(b []byte, off int64) (n int, err error) {
	f.l.Lock()
	defer f.l.Unlock()
	curoffset, e := syscall.Seek(f.fd, 0, 1)
	if e != nil {
		return 0, e
	}
	defer syscall.Seek(f.fd, curoffset, 0)
	o := syscall.Overlapped{
		OffsetHigh: uint32(off >> 32),
		Offset:     uint32(off),
	}
	var done uint32
	e = syscall.WriteFile(syscall.Handle(f.fd), b, &done, &o)
	if e != nil {
		return 0, e
	}
	return int(done), nil
}
示例#15
0
文件: windows.go 项目: jeffallen/g
func (p *dev) Write(buf []byte) (int, error) {
	var done uint32

	for {
		var ov syscall.Overlapped

		ov.HEvent = p.ev.w
		if e := syscall.WriteFile(p.fd, buf, &done, &ov); e != nil {
			if e != syscall.ERROR_IO_PENDING {
				return 0, &os.PathError{"writing to", p.name, e}
			}
			if e = win.GetOverlappedResult(p.fd, &ov, &done, 1); e != nil {
				return 0, &os.PathError{"writing to", p.name, e}
			}
		}
		if done > 0 {
			break
		}
	}
	return int(done), nil
}
示例#16
0
func (port *windowsPort) Write(p []byte) (int, error) {
	var writed uint32
	err := syscall.WriteFile(port.handle, p, &writed, nil)
	return int(writed), err
}
示例#17
0
func SerialChannels(name string, baud int, debug bool) (chan byte, chan byte, chan bool, chan bool, error) {
	var serFile *os.File
	var handle syscall.Handle
	var rl sync.Mutex
	var wl sync.Mutex
	var ro *syscall.Overlapped
	var wo *syscall.Overlapped

	chFromSerial := make(chan byte, 8192)
	chToSerial := make(chan byte, 8192)
	chQuitSerial := make(chan bool)
	chDTRSerial := make(chan bool)

	if len(name) > 0 && name[0] != '\\' {
		name = "\\\\.\\" + name
	}
	handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(name),
		syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING,
		syscall.FILE_ATTRIBUTE_NORMAL|syscall.FILE_FLAG_OVERLAPPED, 0)

	if err == nil {
		serFile = os.NewFile(uintptr(handle), name)
	}
	if err == nil {
		err = setCommState(handle, baud)
	}
	if err == nil {
		err = setupComm(handle, 64, 64)
	}
	if err == nil {
		err = setCommTimeouts(handle)
	}
	if err == nil {
		err = setCommMask(handle)
	}
	if err == nil {
		ro, err = newOverlapped()
	}
	if err == nil {
		wo, err = newOverlapped()
	}

	if err != nil {
		err = errors.New("OpenPort ERROR: " + err.Error())
	} else {
		chFromSerial = make(chan byte, 8192)
		chQuitFrom := make(chan bool)
		go func() {
			var count int
			var done uint32
			then := time.Now()
			datain := make([]byte, 8192)
			for q := false; q == false; {
				rl.Lock()
				readerr := resetEvent(ro.HEvent)
				if readerr == nil {
					readerr = syscall.ReadFile(handle, datain, &done, ro)
					if readerr == syscall.ERROR_IO_PENDING {
						count, readerr = getOverlappedResult(handle, ro)
					} else {
						count = int(done)
					}
				}
				rl.Unlock()

				din := datain[:count]

				if debug && len(din) > 0 {
					now := time.Now()
					fmt.Printf("\n(%v(%d)", now.Sub(then), len(din))
					then = now
					for _, c := range din {
						if c < byte(0x20) || c > byte(0x7E) {
							fmt.Printf("{%02X}", c)
						} else {
							fmt.Printf("%c", c)
						}
					}
					fmt.Print(")")
				}
				for _, c := range din {
					chFromSerial <- c
				}
				select {
				case q = <-chQuitFrom:
				default:
				}
				time.Sleep(10)
			}
		}()

		chToSerial = make(chan byte, 8192)
		chQuitTo := make(chan bool)
		go func() {
			dataout := make([]byte, 256)
			var count, wcount int
			var readflag bool
			then := time.Now()
			for q := false; q == false; {
				select {
				case q = <-chQuitTo:
				case dataout[0] = <-chToSerial:
					for readflag, wcount = true, 1; readflag && wcount < 256; wcount++ {
						select {
						case dataout[wcount] = <-chToSerial:
						default:
							readflag = false
							wcount--
						}
					}

					dout := dataout[:wcount]

					if debug {
						now := time.Now()
						fmt.Printf("\n\t[%v[%d]", now.Sub(then), len(dout))
						then = now
						for _, c := range dout {
							if c < byte(0x20) || c > byte(0x7E) {
								fmt.Printf("{%02X}", c)
							} else {
								fmt.Printf("%c", c)
							}
						}
						fmt.Print("]")
					}

					wl.Lock()

					writeerr := resetEvent(wo.HEvent)
					if writeerr == nil {
						var n uint32 = uint32(wcount)
						writeerr = syscall.WriteFile(handle, dout, &n, wo)
						count = int(n)
						if writeerr == syscall.ERROR_IO_PENDING {
							for i := 0; i < 10; i++ {
								count, writeerr = getOverlappedResult(handle, wo)
								if count != wcount {
									fmt.Printf("Serial port write erro3 %d %s %v %v %v\n", i, writeerr, writeerr, count, wcount)
								} else {
									break
								}
								time.Sleep(10)
							}
						}
					}
					wl.Unlock()
					if count != wcount {
						fmt.Printf("Serial port write error1 %s %v %v %v\n", writeerr, writeerr, count, wcount)
					}

				}
			}
		}()

		chQuitDTR := make(chan bool)
		go func() {
			for q := false; q == false; {
				select {
				case q = <-chQuitDTR:
				case dtr := <-chDTRSerial:
					if dtr {
						escapeCommFunction(handle, 5)
					} else {
						escapeCommFunction(handle, 6)
					}
				}
			}
		}()

		go func() {
			<-chQuitSerial
			serFile.Close()
			chQuitFrom <- true
			chQuitTo <- true
			chQuitDTR <- true
		}()
	}

	return chFromSerial, chToSerial, chDTRSerial, chQuitSerial, err
}
示例#18
0
文件: commw32.go 项目: akofoed/modbus
func main() {
	handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(port),
		syscall.GENERIC_READ|syscall.GENERIC_WRITE,
		0,   // mode
		nil, // security
		syscall.OPEN_EXISTING, // no creating new
		0,
		0)
	if err != nil {
		fmt.Print(err)
		return
	}
	fmt.Printf("handle created %d\n", handle)
	defer syscall.CloseHandle(handle)

	var dcb C.DCB
	dcb.BaudRate = 9600
	dcb.ByteSize = 8
	dcb.StopBits = C.ONESTOPBIT
	dcb.Parity = C.NOPARITY
	if C.SetCommState(C.HANDLE(handle), &dcb) == 0 {
		fmt.Printf("set comm state error %v\n", syscall.GetLastError())
		return
	}
	fmt.Printf("set comm state succeed\n")

	var timeouts C.COMMTIMEOUTS
	// time-out between charactor for receiving (ms)
	timeouts.ReadIntervalTimeout = 1000
	timeouts.ReadTotalTimeoutMultiplier = 0
	timeouts.ReadTotalTimeoutConstant = 1000
	timeouts.WriteTotalTimeoutMultiplier = 0
	timeouts.WriteTotalTimeoutConstant = 1000
	if C.SetCommTimeouts(C.HANDLE(handle), &timeouts) == 0 {
		fmt.Printf("set comm timeouts error %v\n", syscall.GetLastError())
		return
	}
	fmt.Printf("set comm timeouts succeed\n")

	var n uint32
	data := []byte("abc")
	err = syscall.WriteFile(handle, data, &n, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("write file succeed\n")
	fmt.Printf("Press Enter when ready for reading...")
	reader := bufio.NewReader(os.Stdin)
	_, _ = reader.ReadString('\n')

	data = make([]byte, 512)
	err = syscall.ReadFile(handle, data, &n, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("received data %v:\n", n)
	fmt.Printf("%x\n", data[:n])
	fmt.Printf("closed\n")
}