// Initialize a new Context. ctx := gousb.NewContext() defer ctx.Close()
// Open any device with a given VID/PID using a convenience function. dev, err := ctx.OpenDeviceWithVIDPID(0xba57, 0x1001) if err != nil { fmt.Println("Could not open a device: ", err) return } defer dev.Close()
// Detach INTERFACE1 & INTERFACE2 fmt.Println("Set auto-detach") if err := dev.SetAutoDetach(true); err != nil { fmt.Printf("Failed to set auto-detach: %v", err) return }
// Switch the configuration to #1 cfg, err := dev.Config(1) if err != nil { fmt.Printf("%s.Config(1): %v \n", dev, err) return } defer cfg.Close()
// In the config #1, claim interface #0 with alt setting #0. intf, err := cfg.Interface(0, 0) if err != nil { fmt.Printf("%s.Interface(0, 0): %v \n", cfg, err) return } defer intf.Close()
fmt.Println(intf.Setting.Endpoints)
// And in the same interface open endpoint #5 for writing. epOut, err := intf.OutEndpoint(0x02) if err != nil { fmt.Printf("%s.OutEndpoint(0x02): %v", intf, err) return } fmt.Println(epOut.String())
// In this interface open endpoint #6 for reading. 0x81 epIn, err := intf.InEndpoint(0x82) if err != nil { fmt.Printf("%s.InEndpoint(0x81): %v", intf, err) return } fmt.Println(epIn.String())
// writeBytes might be smaller than the buffer size if an error occurred. writeBytes might be greater than zero even if err is not nil. writes, err := epOut.Write([]byte(`{"xxx":"xxx"}\r`)) //writes, err := epOut.Write([]byte("123")) if err != nil { fmt.Println("Write returned an error:", err) return } fmt.Println("write :", writes)
buf := make([]byte, 20) readBytes, err := epIn.Read(buf) if err != nil { fmt.Println("Read returned an error:", err) } if readBytes == 0 { fmt.Println("IN endpoint returned 0 bytes of data.") return } fmt.Println("read :", readBytes, string(buf))
// OpenDevices is used to find the devices to open. devs, err := ctx.OpenDevices(func(desc *gousb.DeviceDesc)bool { // After inspecting the descriptor, return true or false depending on whether // the device is "interesting" or not. Any descriptor for which true is returned // opens a Device which is retuned in a slice (and must be subsequently closed). if desc.Vendor == gousb.ID(xxxx) && desc.Product == gousb.ID(xxxx) { log.Debugf("Found device: %v", desc) returntrue } returnfalse })