/// <summary> /// 读取数据实体到指定结构体 /// </summary> /// <typeparam name="T">目标结构体</typeparam> /// <param name="buf">byte数组</param> /// <returns></returns> public static T ParseDataBodyToStructure <T>(byte[] buf) where T : struct { Pigeon_Comm_Data data = ByteArrayToStructure <Pigeon_Comm_Data>(buf); byte[] buf2 = new byte[data.Len]; // 复制buf+offset 到 buf2 Buffer.BlockCopy(buf, Marshal.SizeOf(data), buf2, 0, buf2.Length); return(ByteArrayToStructure <T>(buf2)); }
private static void OnRxEndPointData(object sender, EndpointDataEventArgs e) { Pigeon_Comm_Data data = Data.DataParse(e.Buffer); if (data.Head == 0x66) { Pigeon_Settings settingss = new Pigeon_Settings(); settingss.Brightness = 10; settingss.ProfileIdx = 0; settingss.KeyDef = 3; settingss.RLELen = 615; byte[] a = Data.ToBytes(settingss); Pigeon_Settings settings = Data.ParseDataBodyToStructure <Pigeon_Settings>(e.Buffer); if (settings.Brightness == 1) { } } }
/// <summary> /// 打开USB设备 /// </summary> /// <param name="usb"></param> private void OpenDevice() { if (inUsingDevice != null) { return; } // Open Device inUsingDevice = UsbDevice.OpenUsbDevice(MyUsbFinder); if (inUsingDevice != null) { IUsbDevice wholeUsbDevice = inUsingDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Select config #1 wholeUsbDevice.SetConfiguration(1); // Claim interface #0. wholeUsbDevice.ClaimInterface(0); } EndpointWriter = inUsingDevice.OpenEndpointWriter(WriteEndpointID.Ep02); EndpointReader = inUsingDevice.OpenEndpointReader(ReadEndpointID.Ep02); EndpointReader.DataReceived += (OnRxEndPointData); EndpointReader.DataReceivedEnabled = true; // Update controls lb_status.Text = "已连接"; lb_status.ForeColor = Color.Green; Pigeon_Comm_Data data = new Pigeon_Comm_Data(); data.Head = 0x66; data.Cmd = Pigeon_Comm_Cmd.READ_SETTINGS; data.Len = 0; // byte[] vs = Data.ToBytes(data); // Send to device int bytesWritten; EndpointWriter.Write(vs, 1000, out bytesWritten); } }