예제 #1
0
        private void statusTimer_Tick(object sender, EventArgs e)
        {
            txbCountdown.Text = _Countdown.ToString();

            if (_Countdown == 0)
            {
                resultTimer.Start();
                statusTimer.Stop();
                txbCountdown.Text = "";
                ResetVariables();
                _device = HIDDevice.GetHIDDevice(0x57E, 0x306);
                _start  = true;

                if (_device != null)
                {
                    Report(0x11, new byte[1] {
                        _ledRumble
                    });
                    EnableConfigureIR();
                    Report(0x12, new byte[2] {
                        0x04, 0x37
                    });
                    RndNumber();
                }
                else
                {
                    Console.WriteLine("Geen device gevonden");
                }
            }
            else
            {
                _Countdown--;
            }
        }
예제 #2
0
        private void Connect()
        {
            HIDInfoSet device;

            if (m_connList.Count == 0)
            {
                return;
            }

            device = m_connList[m_ToolStripComboBox.SelectedIndex];
            if (HIDDevice.GetInfoSets(device.VendorID, device.ProductID, device.SerialNumberString).Count > 0)
            {
                if (m_usb.Connect(device.DevicePath, true))
                {
                    LogDataGridView.Enabled           = true;
                    ConnectToolStripButton.Text       = "Disconnect";
                    ConnectToolStripButton.Image      = Properties.Resources.Disconnect;
                    m_ToolStripComboBox.Enabled       = false;
                    m_ToolStripStatusString.Text      = "USB Device connected";
                    m_ToolStripStatusString.ForeColor = Color.DarkSlateGray;
                    m_ToolStripStatusIcon.Image       = Properties.Resources.USB_OK;
                    m_ToolStripStatusIcon.ToolTipText = "Manufacturer: " + m_usb.ManufacturerString + "\n" +
                                                        "Product Name: " + m_usb.ProductString + "\n" +
                                                        "Serial Number: " + m_usb.SerialNumberString + "\n" +
                                                        "SW Version: " + m_usb.VersionInBCD;
                }
            }
            else
            {
                ScanConnection();
                MessageBox.Show(String.Format("DEVICE: {0} is used in other program !", device.ProductString), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
예제 #3
0
        private void ScanConnection()
        {
            int vid = int.Parse(MutePuckApp.Properties.Resources.VID, System.Globalization.NumberStyles.HexNumber);
            int pid = int.Parse(MutePuckApp.Properties.Resources.PID, System.Globalization.NumberStyles.HexNumber);

            m_connList = HIDDevice.GetInfoSets(vid, pid);

            /* cbConnectionChooser.Items.Clear();
             *
             * foreach (var hidInfoSet in m_connList)
             * {
             *  if (hidInfoSet.ProductString == "")
             *  {
             *      cbConnectionChooser.Items.Add("Unknown HID device");
             *  }
             *  else
             *  {
             *      cbConnectionChooser.Items.Add(hidInfoSet.GetInfo());
             *  }
             * }
             *
             * if (cbConnectionChooser.Items.Count > 0)
             * {
             *  cbConnectionChooser.SelectedIndex = 0;
             *
             * } */
        }
예제 #4
0
    protected void openDevice(string devicePath = "")
    {
        if (mHIDDevice != null)
        {
            return;
        }
        try
        {
            mDeviceConnect = DEVICE_CONNENT.DC_PROCEED;
            if (devicePath != "")
            {
                mHIDDevice = new HIDDevice(devicePath);
            }
            else
            {
                mHIDDevice = new HIDDevice(VID, PID);
            }

            if (!mHIDDevice.deviceConnected)
            {
                mDeviceConnect = DEVICE_CONNENT.DC_CLOSE;
                UnityUtility.logInfo("无法连接输入设备!");
            }
            else
            {
                mDeviceConnect = DEVICE_CONNENT.DC_SUCCESS;
                UnityUtility.logInfo("输入设备连接成功!");
            }
        }
        catch (Exception)
        {
            closeDevice();
        }
    }
예제 #5
0
파일: Program.cs 프로젝트: xbwpc/hid-sharp
        // Apologies for the repeated code, however i feel it provides a better demonstration
        // of the functionality of this code.
        public void useSynchronousOperation()
        {
            //Get the details of all connected USB HID devices
            HIDDevice.interfaceDetails[] devices = HIDDevice.getConnectedDevices();

            //Arbitrarily select one of the devices which we found in the previous step
            //record the details of this device to be used in the class constructor
            int    selectedDeviceIndex = 0;
            ushort VID        = devices[selectedDeviceIndex].VID;
            ushort PID        = devices[selectedDeviceIndex].PID;
            int    SN         = devices[selectedDeviceIndex].serialNumber;
            string devicePath = devices[selectedDeviceIndex].devicePath;

            //create a handle to the device by calling the constructor of the HID class
            //This can be done using either the VID/PID/Serialnumber, or the device path (string)
            //all of these details are available from the HIDDevice.interfaceDetails[] struct array created above
            //The "false" boolean in the constructor tells the class we only want synchronous operation
            HIDDevice device = new HIDDevice(devicePath, false);

            //OR, the normal usage when you know the VID and PID of the device
            //HIDDevice device = new HIDDevice(VID, PID, (ushort)SN, false);

            //Write some data to the device (the write method throws an exception if the data is longer than the report length
            //specified by the device, this length can be found in the HIDDevice.interfaceDetails struct)
            byte[] writeData = { 0x00, 0x01, 0x02, 0x03, 0x04 };
            device.write(writeData);    //Its that easy!!

            //Read some data synchronously from the device. This method blocks the calling thread until the data
            //is returned. This takes 1-20ms for most HID devices
            byte[] readData = device.read();    //again, that easy!

            //close the device to release all handles etc
            device.close();
        }
예제 #6
0
        // Connect the microcontroller
        public bool Connect(ushort PID)
        {
            // Check if the MCU is already connected
            if (bMCUConnected)
            {
                return(true);
            }

            // Get all the connected devices
            HIDDevice.interfaceDetails[] devices = HIDDevice.getConnectedDevices();


            // List all available device paths in the listbox
            if (devices.Length > 0)
            {
                for (int i = 0; i < devices.Length; i++)
                {
                    // Search for the needed device
                    if (devices[i].VID == 0x0483 && devices[i].PID == PID)
                    {
                        // MCU found => connect it
                        device = new HIDDevice(devices[i].VID, devices[i].PID, (ushort)devices[i].serialNumber, false);
                    }
                }
                if (device != null)
                {
                    bMCUConnected = true;
                }
            }
            return(bMCUConnected);
        }
예제 #7
0
        public void USBinit()
        {
            HIDDevice.interfaceDetails[] devices = HIDDevice.getConnectedDevices();

            var buzzersFound = devices.Where((hiddev) => (((hiddev.PID.ToString("X4") == "1000") ||
                                                           (hiddev.PID.ToString("X4") == "0002")) &&
                                                          (hiddev.VID.ToString("X4") == "054C"))).ToList();

            buzzersBuffersLastIn[0] = new byte[6];
            buzzersBuffersOut[0]    = new byte[8];
            buzzersBuffersLastIn[1] = new byte[6];
            buzzersBuffersOut[1]    = new byte[8];

            if (buzzersFound.Count > 0)
            {
                buzzers[0]           = new HIDDevice(buzzersFound[0].devicePath, false);
                buzzersBuffersOut[0] = new byte[buzzers[0].productInfo.OUT_reportByteLength];
                irqstat[0]           = IrqState.check;
                Thread readOne = new Thread(this.ReadThread0);
                readOne.Start();
                if (buzzersFound.Count > 1)
                {
                    buzzers[1]           = new HIDDevice(buzzersFound[1].devicePath, false);
                    buzzersBuffersOut[1] = new byte[buzzers[1].productInfo.OUT_reportByteLength];
                    irqstat[1]           = IrqState.check;
                    Thread readTwo = new Thread(this.ReadThread1);
                    readTwo.Start();
                }
            }
        }
예제 #8
0
        static void ReadDJHDevice(string DevicePath)
        {
            // Create handle to the device
            HIDDevice DJH = new HIDDevice(DevicePath, false);

            // Read bytes & map DJH
            DJHControllerMap Map = new DJHControllerMap();

            while (true)
            {
                byte[] DJHBytes = DJH.read();

                // Map
                Map.Buttons = DJHBytes[1];
                Map.DPAD    = DJHBytes[3];
                Map.PS      = DJHBytes[2];

                Map.TT_normal     = DJHBytes[7];
                Map.Filter_normal = DJHBytes[20];
                Map.Filter_step   = DJHBytes[21];
                Map.Slider_normal = DJHBytes[22];
                Map.Slider_step   = DJHBytes[23];

                // Print
                Console.Write("\rButton: {0}\t DPAD: {1}\t PS: {2}\t TT: {3}\t Filter: {4}|{5}\tSlider: {6}|{7}\t",
                              Map.Buttons, Map.DPAD, Map.PS, Map.TT_normal, Map.Filter_normal, Map.Filter_step, Map.Slider_normal, Map.Slider_step);

                // Report vJoy
                UpdateGamepad(Map);
            }
        }
예제 #9
0
        private void Connect()
        {
            HIDInfoSet device;

            if (m_connList.Count == 0)
            {
                return;
            }

            device = m_connList[0];
            if (HIDDevice.GetInfoSets(device.VendorID, device.ProductID, device.SerialNumberString).Count > 0)
            {
                if (m_usb.Connect(device.DevicePath, true))
                {
                    //lbConnectionText.Text = "Connected";

                    //pbLED.Image = Properties.Resources.ledgreen;

                    IsMuted = false;

                    /*m_ToolStripStatusIcon.ToolTipText = "Manufacturer: " + m_usb.ManufacturerString + "\n" +
                     *                                  "Product Name: " + m_usb.ProductString + "\n" +
                     *                                  "Serial Number: " + m_usb.SerialNumberString + "\n" +
                     *                                  "SW Version: " + m_usb.VersionInBCD; */
                }
            }
            else
            {
                ScanConnection();
                MessageBox.Show(String.Format("DEVICE: {0} is used in other program !", device.ProductString));
            }
        }
예제 #10
0
        public MainForm()
        {
            m_usb      = new HIDDevice();
            m_cmds     = new List <Command>();
            m_connList = new List <HIDInfoSet>();

            try
            {
                m_settings = LoadFromFile(typeof(AppSettings), m_confName) as AppSettings;
            }
            catch
            {
                m_settings = new AppSettings();
            }

            InitializeComponent();

            m_usb.OnDeviceRemoved += usb_OnDeviceRemoved;
            m_usb.OnDeviceArrived += usb_OnDeviceArrived;
            m_usb.OnDataRecieved  += usb_OnDataReceived;

            LogDataGridView.Enabled       = false;
            EditToolStripButton.Enabled   = false;
            RemoveToolStripButton.Enabled = false;
            SaveToolStripButton.Enabled   = false;

            m_tclk = new DataGridViewCellEventHandler(TxDataGridView_CellClick);
        }
예제 #11
0
        private async Task <byte[]> ReadResponseAsync()
        {
            var remaining   = 0;
            var packetIndex = 0;

            using (var response = new MemoryStream())
            {
                do
                {
                    var packetData = await HIDDevice.ReadAsync();

                    var responseDataPacket = GetResponseDataPacket(packetData, packetIndex, ref remaining);
                    packetIndex++;

                    if (responseDataPacket == null)
                    {
                        return(null);
                    }

                    response.Write(responseDataPacket, 0, responseDataPacket.Length);
                } while (remaining != 0);

                return(response.ToArray());
            }
        }
예제 #12
0
        public bool startAsyncOperation(ushort MyDevVID, ushort MyDevPID)
        {
            //Get the details of all connected USB HID devices
            HIDDevice.interfaceDetails[] devices = HIDDevice.getConnectedDevices();


            //Arbitrarily select one of the devices which we found in the previous step
            //record the details of this device to be used in the class constructor
            int selectedDeviceIndex = -1;

            for (int i = 0; i < devices.Length; i++)
            {
                if ((devices[i].VID == MyDevVID) && (devices[i].PID == MyDevPID))
                {
                    selectedDeviceIndex = i;
                }
            }

            if (selectedDeviceIndex == -1)
            {
                return(false);
            }

            ushort VID        = devices[selectedDeviceIndex].VID;
            ushort PID        = devices[selectedDeviceIndex].PID;
            int    SN         = devices[selectedDeviceIndex].serialNumber;
            string devicePath = devices[selectedDeviceIndex].devicePath;

            //create a handle to the device by calling the constructor of the HID class
            //This can be done using either the VID/PID/Serialnumber, or the device path (string)
            //all of these details are available from the HIDDevice.interfaceDetails[] struct array created above
            //The "true" boolean in the constructor tells the class we want asynchronous operation this time
            device = new HIDDevice(devicePath, true);

            //OR, the normal usage when you know the VID and PID of the device
            //HIDDevice device = new HIDDevice(VID, PID, (ushort)SN, true);

            //next create the event handler for the incoming reports
            device.dataReceived += new HIDDevice.dataReceivedEvent(device_dataReceived);

            //Write some data to the device (the write method throws an exception if the data is longer than the report length
            //specified by the device, this length can be found in the HIDDevice.interfaceDetails struct)
            //The write method is identical to the synchronous mode of operation
            byte[] writeData = new byte[64];
            for (int i = 0; i < writeData.Length; i++)
            {
                writeData[i] = Convert.ToByte(i + 100);
            }

            device.write(writeData);    //Its that easy!!

            //Send your program off to do other stuff here, wait for UI events etc
            //When a report occurs, the device_dataReceived(byte[] message) method will be called
            //System.Threading.Thread.Sleep(100);

            //close the device to release all handles etc
            //device.close();
            return(true);
        }
예제 #13
0
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (OpenedPad != null)
     {
         OpenedPad.close();
     }
     OpenedPad = new HIDDevice(UtilValues.PublicValue.nanoPads[comboBox1.SelectedIndex].devicePath, false);
 }
예제 #14
0
 //close the device to release all handles etc
 public void Disconnect()
 {
     if (device != null)
     {
         device.close();
         device = null;
     }
 }
예제 #15
0
        public void find()
        {
            devices = HIDDevice.getConnectedDevices();

            //int selectedDeviceIndex = 0;

            /*ushort VID = devices[selectedDeviceIndex].VID;
             * ushort PID = devices[selectedDeviceIndex].PID;
             * int SN = devices[selectedDeviceIndex].serialNumber;*/
            // devicePath = devices[selectedDeviceIndex].devicePath;
            //devicePath = null;
            for (int i = 0; i <= devices.Length; i++)
            {
                try
                {
                    if (devices[i].VID == 9025 && devices[i].PID == 32822)
                    {
                        devicePath = devices[i].devicePath;
                        break;
                    }
                }
                catch (Exception)
                {
                }
            }

            if (devicePath == null)
            {
                Console.WriteLine("Device not found");
                connected = false;
            }

            //create a handle to the device by calling the constructor of the HID class
            //This can be done using either the VID/PID/Serialnumber, or the device path (string)
            //all of these details are available from the HIDDevice.interfaceDetails[] struct array created above
            //The "true" boolean in the constructor tells the class we want asynchronous operation this time
            //device = new HIDDevice(devicePath, true);
            //OR, the normal usage when you know the VID and PID of the device
            //HIDDevice device = new HIDDevice(VID, PID, (ushort)SN, true);

            //next create the event handler for the incoming reports
            //device.dataReceived += new HIDDevice.dataReceivedEvent(device_dataReceived);

            //Write some data to the device (the write method throws an exception if the data is longer than the report length
            //specified by the device, this length can be found in the HIDDevice.interfaceDetails struct)
            //The write method is identical to the synchronous mode of operation
            //byte[] writeData = { 0x00, 0x01, 0x02, 0x03, 0x04 };
            //device.write(writeData);    //Its that easy!!

            //Send your program off to do other stuff here, wait for UI events etc
            //When a report occurs, the device_dataReceived(byte[] message) method will be called

            /*while(!receiveData)
             * System.Threading.Thread.Sleep(100);*/

            //close the device to release all handles etc
            //device.close();
        }
예제 #16
0
        /// <summary>
        /// USB ͨѶ·½Ê½
        /// </summary>
        /// <param name="m_usb"></param>
        /// <returns></returns>
        public static ModbusSerialMaster CreateUsb(HIDDevice m_usb)
        {
            if (m_usb == null)
            {
                throw new ArgumentNullException("m_usb");
            }

            return(CreateRtu(new CzUsbHidAdapter(m_usb)));
        }
예제 #17
0
 //-----------------------------------------------------------------------------------------------------------------------------------------------------------------
 protected void closeDevice()
 {
     if (mHIDDevice != null)
     {
         mHIDDevice.close();
         mHIDDevice = null;
     }
     mDeviceConnect = DEVICE_CONNENT.DC_CLOSE;
 }
예제 #18
0
        public static void FindNanoPad()
        {
            if (UtilValues.PublicValue.nanoPads.Length != 0)
            {
                Array.Clear(UtilValues.PublicValue.nanoPads, 0, UtilValues.PublicValue.nanoPads.Length);
                Array.Resize(ref UtilValues.PublicValue.nanoPads, 0);
            }
            HIDDevice.interfaceDetails[] Pads = HIDDevice.getConnectedPads();
            foreach (HIDDevice.interfaceDetails Pad in Pads)
            {
                SayobotNanoPad pad = new SayobotNanoPad
                {
                    devicePath = Pad.devicePath,
                    ProductID  = Pad.PID
                };
                pad.ReadingPadSettings();
                HIDDevice PadDevice = new HIDDevice(pad.devicePath, false);
                byte[]    writeData = CalcSHA(new byte[] { 0x02, 0x00, 0x00 });
                PadDevice.write(writeData);
                System.Threading.Thread.Sleep(100);
                byte[] readData = PadDevice.read();
                if (readData[1] == 0)
                {
                    pad.OSVersion = readData[4].ToString();
                }
                else
                {
                    pad.OSVersion = "Unknown";
                }

                writeData = CalcSHA(new byte[] { 0x02, 0x08, 0x01, 0x00 });
                PadDevice.write(writeData);
                System.Threading.Thread.Sleep(100);
                readData = PadDevice.read();
                if (readData[0] != 0xff)
                {
                    byte[] nameEncode = new byte[readData[2]];
                    Array.Copy(readData, 3, nameEncode, 0, readData[2]);
                    nameEncode = ChangeToSystemUnicodeEncoding(nameEncode);
                    pad.Name   = Encoding.Unicode.GetString(nameEncode);
                }
                else
                {
                    pad.Name = Pad.product;
                }

                PadDevice.close();

                Array.Resize(ref UtilValues.PublicValue.nanoPads, UtilValues.PublicValue.nanoPads.Length + 1);
                UtilValues.PublicValue.nanoPads[UtilValues.PublicValue.nanoPads.Length - 1] = pad;
            }
        }
예제 #19
0
 public void connect()
 {
     if (!connected && devicePath != null)
     {
         device = new HIDDevice(devicePath, true);
         device.dataReceived += new HIDDevice.dataReceivedEvent(this.device_dataReceived);
         connected            = true;
     }
     else
     {
         find();
     }
 }
        public void DeviceDisconnectedEventHandler(object sender, AndroidMessageArgs <int> args)
        {
            string pid = args.data.ToString();

            if (__Generics.ContainsKey(pid))
            {
                HIDDevice device = __Generics[pid];
                this.droidHIDBehaviour.Log(TAG, "Device " + device.Name + " index:" + device.index + " Removed");
                this.__Generics.Remove(pid);

                this.DeviceDisconnectEvent(this, new DeviceEventArgs <string>(pid));
            }
        }
        void RemoveDevice(IOHIDDeviceRef deviceRef)
        {
            if (deviceRef == IntPtr.Zero)
            {
                Debug.LogWarning("IOHIDeviceRef equal to IntPtr.Zero");
                return;
            }


            int product_id = (int)(new Native.CFNumber(Native.IOHIDDeviceGetProperty(deviceRef, Native.CFSTR(Native.kIOHIDProductIDKey)))).ToInteger();



            int vendor_id = (int)(new Native.CFNumber(Native.IOHIDDeviceGetProperty(deviceRef, Native.CFSTR(Native.kIOHIDVendorIDKey)))).ToInteger();


            int    location  = (int)(new Native.CFNumber(Native.IOHIDDeviceGetProperty(deviceRef, Native.CFSTR(Native.kIOHIDLocationIDKey)))).ToInteger();
            string transport = (new Native.CFString(Native.IOHIDDeviceGetProperty(deviceRef, Native.CFSTR(Native.kIOHIDTransportKey)))).ToString();

            string path = String.Format("{0:s}_{1,4:X}_{2,4:X}_{3:X}",
                                        transport, vendor_id, product_id, location);          //"%s_%04hx_%04hx_%x"


            lock (syncRoot) {
                if (!__Generics.ContainsKey(path))
                {
                    return;
                }

                HIDDevice hidDevice = __Generics [path];


                Generics.Remove(path);

                Debug.Log("Device " + hidDevice.index + " PID:" + hidDevice.PID + " VID:" + hidDevice.VID + " Disconnected");
            }


            Debug.Log("Try to unshedule,unregister and close device");
            Native.IOHIDDeviceUnscheduleFromRunLoop(deviceRef, RunLoop, InputLoopMode);
            Native.IOHIDDeviceRegisterInputValueCallback(deviceRef, IntPtr.Zero, IntPtr.Zero);
            Native.IOHIDDeviceRegisterRemovalCallback(deviceRef, null, IntPtr.Zero);

            Native.IOHIDDeviceClose(deviceRef, (int)Native.IOHIDOptionsType.kIOHIDOptionsTypeNone);



            this.DeviceDisconnectEvent(this, new DeviceEventArgs <string>(path));
        }
예제 #22
0
        private async Task WriteRequestAsync(byte[] message)
        {
            var packetIndex = 0;

            byte[] data = null;
            using (var memory = new MemoryStream(message))
            {
                do
                {
                    data = GetRequestDataPacket(memory, packetIndex);
                    packetIndex++;
                    await HIDDevice.WriteAsync(data);
                } while (memory.Position != memory.Length);
            }
        }
예제 #23
0
        public bool FindDev()
        {
            bool result      = false;
            bool foundtarget = false;

            HIDDevice.interfaceDetails[]      devices      = HIDDevice.getConnectedDevices();
            List <HIDDevice.interfaceDetails> KingstonDevs = new List <HIDDevice.interfaceDetails>();

            for (int i = 0; i < devices.Length; i++)
            {
                // Alpha S
                if (devices[i].VID == TARGET_VID && devices[i].PID == TARGET_PID) //if (devices[i].VID == KTC_VID && devices[i].PID == ALPHAS_PID)
                {
                    label_vid.Text = devices[i].VID.ToString("X4");               //KTC_VID.ToString("X4");
                    label_pid.Text = devices[i].PID.ToString("X4");               //DART_PID1.ToString("X4");
                    //textBox_device.AppendText("\r\nProduct : " + devices[i].product.ToString());
                    //textBox_device.AppendText("\r\nRevision : " + "0x" + devices[i].versionNumber.ToString("X"));
                    label_manufacturer.Text = devices[i].manufacturer.ToString();
                    label_product.Text      = devices[i].product.ToString();
                    label_revision.Text     = devices[i].versionNumber.ToString("X");

                    label_status.Text = "Detected";

                    CheckDev();

                    foundtarget = true;

                    break;
                }

                if (!foundtarget)
                {
                    empty_fields();

                    if (button_detect.Text == "STOP")
                    {
                        label_status.Text = "Detecting...";
                    }
                    if (button_detect.Text == "START")
                    {
                        label_status.Text = "";
                    }
                }
                foundtarget = false;
            }

            return(result);
        }
예제 #24
0
        public OutputEvent(EventType eventType, ushort messageId, HIDDevice mirrorDevice, byte[] data) : base(mirrorDevice)
        {
            EventType = eventType;
            MessageId = messageId;
            var eventBytes     = BitConverter.GetBytes((Int32)EventType);
            var messageIdBytes = BitConverter.GetBytes(MessageId);

            Buffer[1] = eventBytes[1];
            Buffer[2] = eventBytes[0];
            Buffer[3] = messageIdBytes[0];
            Buffer[4] = messageIdBytes[1];
            if (data != null)
            {
                Buffer[5] = (byte)data.Length;
                data.CopyTo(Buffer, 6);
            }
        }
예제 #25
0
파일: OutputEvent.cs 프로젝트: suan/mirlite
 public OutputEvent(EventType eventType, ushort messageId, HIDDevice mirrorDevice, byte[] data)
     : base(mirrorDevice)
 {
     EventType = eventType;
     MessageId = messageId;
     var eventBytes =  BitConverter.GetBytes((Int32)EventType);
     var messageIdBytes = BitConverter.GetBytes(MessageId);
     Buffer[1] = eventBytes[1];
     Buffer[2] = eventBytes[0];
     Buffer[3] = messageIdBytes[0];
     Buffer[4] = messageIdBytes[1];
     if (data != null)
     {
         Buffer[5] = (byte) data.Length;
         data.CopyTo(Buffer, 6);
     }
 }
예제 #26
0
        private void ScanConnection()
        {
            m_connList = HIDDevice.GetInfoSets(m_settings.USB_VID, m_settings.USB_PID);
            m_ToolStripComboBox.Items.Clear();

            foreach (var hidInfoSet in m_connList)
            {
                if (hidInfoSet.ProductString == "")
                {
                    m_ToolStripComboBox.Items.Add("Unknovn HID device");
                }
                else
                {
                    m_ToolStripComboBox.Items.Add(hidInfoSet.GetInfo());
                }
            }

            if (m_ToolStripComboBox.Items.Count > 0)
            {
                m_ToolStripComboBox.Enabled       = true;
                ConnectToolStripButton.Text       = "Connect";
                ConnectToolStripButton.Image      = Properties.Resources.Connect;
                ConnectToolStripButton.Enabled    = true;
                m_ToolStripComboBox.SelectedIndex = 0;
                m_ToolStripStatusIcon.Enabled     = true;
                m_ToolStripStatusIcon.Image       = Properties.Resources.USB_Disable;
                m_ToolStripStatusIcon.ToolTipText = "USB Device Disconnected";

                m_ToolStripStatusString.Text      = "USB Device is ready for connecting";
                m_ToolStripStatusString.ForeColor = Color.DarkSlateGray;
            }
            else
            {
                m_ToolStripComboBox.Enabled       = false;
                ConnectToolStripButton.Text       = "Connect";
                ConnectToolStripButton.Image      = Properties.Resources.Connect;
                ConnectToolStripButton.Enabled    = false;
                m_ToolStripStatusIcon.Enabled     = false;
                m_ToolStripStatusIcon.Image       = Properties.Resources.USB;
                m_ToolStripStatusIcon.ToolTipText = string.Empty;

                m_ToolStripStatusString.Text      = "USB Device not found, check the HW connection on PC side !";
                m_ToolStripStatusString.ForeColor = Color.FromArgb(255, 204, 0, 0);
            }
        }
        /// <summary>
        /// Try to attach compatible driver based on device info
        /// </summary>
        /// <param name="deviceInfo"></param>
        protected void ResolveDevice(HIDDevice deviceInfo)
        {
            IDevice joyDevice = null;

            //loop thru drivers and attach the driver to device if compatible
            if (__drivers != null)
            {
                foreach (var driver in __drivers)
                {
                    joyDevice = driver.ResolveDevice(deviceInfo);
                    if (joyDevice != null)
                    {
                        Debug.Log("Device index:" + deviceInfo.index + " PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID
                                  + " attached to " + driver.GetType().ToString());
                        //  this.droidHIDBehaviour.Log("AndroidHIDInterface", "Device index:"+joyDevice.ID+" PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " attached to " + driver.GetType().ToString());
                        this.__Generics[deviceInfo.ID] = deviceInfo;

                        this.DeviceConnectEvent(this, new DeviceEventArgs <IDevice>(joyDevice));

                        break;
                    }
                }
            }

            if (joyDevice == null)
            {//set default driver as resolver if no custom driver match device
                joyDevice = defaultDriver.ResolveDevice(deviceInfo);


                if (joyDevice != null)
                {
                    // Debug.Log(__joysticks[deviceInfo.index]);
                    Debug.Log("Device index:" + deviceInfo.index + " PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " attached to " + __defaultJoystickDriver.GetType().ToString());

                    // this.droidHIDBehaviour.Log("AndroidHIDInterface", "Device index:" + joyDevice.ID + " PID:" + joyDevice.PID + " VID:" + joyDevice.VID + " attached to " + __defaultJoystickDriver.GetType().ToString() + " Path:" + deviceInfo.DevicePath + " Name:" + joyDevice.Name);
                    this.__Generics[joyDevice.ID] = deviceInfo;

                    this.DeviceConnectEvent(this, new DeviceEventArgs <IDevice>(joyDevice));
                }
                else
                {
                    Debug.LogWarning("Device PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " not found compatible driver thru WinHIDInterface!");
                }
            }
        }
예제 #28
0
    public bool disconnectDeviceTryOpenThread()
    {
        string devicePath = "";
        bool   exist      = false;

        // 检查当前设备是否可用
        InterfaceDetails[] devices = HIDDevice.getConnectedDevices();
        int deviceCount            = devices.Length;

        if (mCurDeviceCount != deviceCount)
        {
            mCurDeviceCount = deviceCount;
            exist           = false;
            for (int i = 0; i < deviceCount; ++i)
            {
                if (devices[i].VID == VID && devices[i].PID == PID)
                {
                    devicePath = devices[i].devicePath;
                    exist      = true;
                    break;
                }
            }
            if (!exist)
            {
                closeDevice();
            }
        }
        // 有设备,并且设备数量未变化,则认为有设备连接
        else if (deviceCount > 0)
        {
            exist = true;
        }
        // 如果发现设备被关闭,并且设备存在,则一直尝试打开设备
        if (!isDeviceConnect() && exist)
        {
            openDevice(devicePath);
        }
        // 暂时不实现热插拔
        if (isDeviceConnect())
        {
            return(false);
        }
        return(true);
    }
예제 #29
0
        private void usb_OnDeviceRemoved(object sender, EventArgs e)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(new EventHandler(usb_OnDeviceRemoved), new object[] { sender, e });
            }
            else
            {
                if (m_usb.IsConnected)
                {
                    if (HIDDevice.GetInfoSets(m_usb.VendorID, m_usb.ProductID, m_usb.SerialNumberString).Count == 0)
                    {
                        Disconnect();
                    }
                }

                ScanConnection();
            }
        }
예제 #30
0
        private async Task WriteRequestAsync(object request)
        {
            var byteArray = Helpers.ProtoBufSerialize(request);
            var size      = byteArray.Length;

            //await HIDDevice.WriteAsync(new byte[1]);

            var id   = (int)GetEnumValue("MessageType" + request.GetType().Name);
            var data = new byte[size + 1024]; // 32768);

            data[0] = (byte)'#';
            data[1] = (byte)'#';
            data[2] = (byte)((id >> 8) & 0xFF);
            data[3] = (byte)(id & 0xFF);
            data[4] = (byte)((size >> 24) & 0xFF);
            data[5] = (byte)((size >> 16) & 0xFF);
            data[6] = (byte)((size >> 8) & 0xFF);
            data[7] = (byte)(size & 0xFF);
            byteArray.CopyTo(data, 8);

            var position = size + 8;

            while (position % 63 > 0)
            {
                data[position] = 0;
                position++;
            }

            for (var i = 0; i < (position / 63); i++)
            {
                var chunk = new byte[64];
                chunk[0] = (byte)'?';

                for (var x = 0; x < 63; x++)
                {
                    chunk[x + 1] = data[(i * 63) + x];
                }

                await HIDDevice.WriteAsync(chunk);
            }

            lastRequest = request;
        }
예제 #31
0
        private void InitializeApp()
        {
            m_usb = new HIDDevice();
            m_usb.OnDeviceRemoved += usb_OnDeviceRemoved;
            m_usb.OnDeviceArrived += usb_OnDeviceArrived;
            m_usb.OnDataRecieved  += usb_OnDataReceived;

            m_connList = new List <HIDInfoSet>();
            m_cmds     = new List <Command>();

            m_settings = new AppSettings();

            ScanConnection();

            LogDataGridView.Enabled       = false;
            EditToolStripButton.Enabled   = false;
            RemoveToolStripButton.Enabled = false;
            SaveToolStripButton.Enabled   = false;
            m_tclk = new DataGridViewCellEventHandler(TxDataGridView_CellClick);
        }
예제 #32
0
 /// <summary>
 /// Construction. Setup the buffer with the correct output report length dictated by the device
 /// </summary>
 /// <param name="oDev">Creating device</param>
 protected OutputReport(HIDDevice oDev)
 {
     SetBuffer(new byte[oDev.OutputReportLength]);
 }
		public void Write (object data, string id, HIDDevice.WriteCallback callback)
		{
			__Generics [id].Write (data, callback);
		}
		public void Write (object data, string id, HIDDevice.WriteCallback callback, int timeout)
		{
			throw new NotImplementedException ();
		}
예제 #35
0
        public SpecifiedInputReport(HIDDevice oDev) : base(oDev)
		{

		}
 public override void Write(object data, HIDDevice.WriteCallback callback)
 {
     if (!IsConnected) return;
     if (IsOpen == false) OpenDevice();
     this.Write((byte[])data,callback, 0);
 }
예제 #37
0
		/// <summary>
		/// Construction. Setup the buffer with the correct output report length dictated by the device
		/// </summary>
		/// <param name="oDev">Creating device</param>
		public OutputReport(HIDDevice oDev) : base(oDev)
		{
			SetBuffer(new byte[oDev.OutputReportLength]);
		}
 public override void Write(object data, HIDDevice.WriteCallback callback,int timeout)
 {
     _listener.WriteComplete = callback;
     _device.Call("write", (byte[])data, _listener, timeout);
 }
		public void Write (object data, int device, HIDDevice.WriteCallback callback)
		{
			throw new NotImplementedException ();
		}
예제 #40
0
        /// <summary>
        /// Try to attach compatible driver based on device PID and VID
        /// </summary>
        /// <param name="hidDevice"></param>
        protected void ResolveDevice(HIDDevice hidDevice)
        {
            IDevice joyDevice = null;

            //loop thru drivers and attach the driver to device if compatible
            if (__drivers != null)
                foreach (var driver in __drivers)
                {

                    joyDevice = driver.ResolveDevice(hidDevice);
                    if (joyDevice != null)
                    {
                        joyDevice.Name = hidDevice.Name;

                        lock (syncRoot)
                        {
                            Generics[hidDevice.ID] = hidDevice;
                        }

                        Debug.Log("Device" + hidDevice.index + " PID:" + hidDevice.PID + " VID:" + hidDevice.VID + "[" + hidDevice.Name + "] attached to " + driver.GetType().ToString()

                          // +hidDevice.DevicePath
                            );

                        break;
                    }
                }

            if (joyDevice == null)
            {//set default driver as resolver if no custom driver match device

               // System.Threading.Thread.CurrentThread.n

                joyDevice = defaultDriver.ResolveDevice(hidDevice);

                if (joyDevice != null)
                {
                    joyDevice.Name = hidDevice.Name;

                    lock (syncRoot)
                    {
                        Generics[hidDevice.ID] = hidDevice;
                    }

                    Debug.Log("Device" + hidDevice.index + "  PID:" + hidDevice.PID + " VID:" + hidDevice.VID + "[" + hidDevice.Name + "] attached to " + __defaultJoystickDriver.GetType().ToString() + " Path:" + hidDevice.DevicePath);

                }
                else
                {
                    Debug.LogWarning("Device PID:" + hidDevice.PID + " VID:" + hidDevice.VID + " not found compatible driver thru WinHIDInterface!");

                }

            }

            if (joyDevice != null && DeviceConnectEvent!=null) DeviceConnectEvent(null, new DeviceEventArgs<IDevice>(joyDevice));
        }
예제 #41
0
 public void Write(object data, string id, HIDDevice.WriteCallback callback, int timeout)
 {
     this.__Generics[id].Write(data, callback, timeout);
 }
예제 #42
0
 public void Read(string id, HIDDevice.ReadCallback callback)
 {
     this.__Generics[id].Read(callback, 0);
 }
예제 #43
0
 public void Read(string id, HIDDevice.ReadCallback callback, int timeout)
 {
     this.__Generics[id].Read(callback, timeout);
 }
예제 #44
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="oDev">Device constructing this report</param>
 public BuzzOutputReport(HIDDevice oDev)
     : base(oDev)
 {
 }
        //	public void read(byte[] into,IReadWriteListener listener, int timeout)
        public override void Read(HIDDevice.ReadCallback callback,int timeout)
        {

            if (IsReadInProgress)
            {
                callback.Invoke(__lastHIDReport);
                return;
            }

            //TODO: create fields (as read should be called after onRead) or better Object.pool
            _listener.ReadComplete =  (bytes) => {
              
               
               
                    this.__lastHIDReport.index=this.index;
                    this.__lastHIDReport.Data=(byte[])bytes;
                    this.__lastHIDReport.Status=HIDReport.ReadStatus.Success;
                

             
                
                callback.Invoke(this.__lastHIDReport);

                IsReadInProgress = false;
            };

            IsReadInProgress = true;


         //   UnityEngine.Debug.Log("GenericHIDDevice >>>>> try read");  
            _device.Call("read", new byte[_InputReportByteLength], _listener, 0);
          //  UnityEngine.Debug.Log("GenericHIDDevice >>>>> read out"); 
           
        }
예제 #46
0
파일: Report.cs 프로젝트: suan/mirlite
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="device">Constructing device</param>
 protected Report(HIDDevice device)
 {
     // Do nothing
     Device = device;
 }
예제 #47
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="oDev">Constructing device</param>
		public Report(HIDDevice oDev)
		{
			// Do nothing
		}
        /// <summary>
        /// Try to attach compatible driver based on device info
        /// </summary>
        /// <param name="deviceInfo"></param>
        protected void ResolveDevice(HIDDevice deviceInfo)
        {

            IDevice joyDevice = null;

            //loop thru drivers and attach the driver to device if compatible
            if (__drivers != null)
                foreach (var driver in __drivers)
                {
                    joyDevice = driver.ResolveDevice(deviceInfo);
                    if (joyDevice != null)
                    {
                       

                        Debug.Log("Device index:" + deviceInfo.index + " PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID 
							          + " attached to " + driver.GetType().ToString());
                      //  this.droidHIDBehaviour.Log("AndroidHIDInterface", "Device index:"+joyDevice.ID+" PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " attached to " + driver.GetType().ToString());
                        this.__Generics[deviceInfo.ID] = deviceInfo;

							this.DeviceConnectEvent(this,new DeviceEventArgs<IDevice>(joyDevice));

                        break;
                    }
                }

            if (joyDevice == null)
            {//set default driver as resolver if no custom driver match device
                joyDevice = defaultDriver.ResolveDevice(deviceInfo);


                if (joyDevice != null)
                {

                      // Debug.Log(__joysticks[deviceInfo.index]);
                    Debug.Log("Device index:" + deviceInfo.index + " PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " attached to " + __defaultJoystickDriver.GetType().ToString());
                     
                   // this.droidHIDBehaviour.Log("AndroidHIDInterface", "Device index:" + joyDevice.ID + " PID:" + joyDevice.PID + " VID:" + joyDevice.VID + " attached to " + __defaultJoystickDriver.GetType().ToString() + " Path:" + deviceInfo.DevicePath + " Name:" + joyDevice.Name);
                    this.__Generics[joyDevice.ID] = deviceInfo;

							this.DeviceConnectEvent(this,new DeviceEventArgs<IDevice>(joyDevice));
                }
                else
                {
                    Debug.LogWarning("Device PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " not found compatible driver thru WinHIDInterface!");

                }

            }


        }
예제 #49
0
		/// <summary>
		/// Construction. Do nothing
		/// </summary>
		/// <param name="oDev">Creating device</param>
		public InputReport(HIDDevice oDev) : base(oDev)
		{
		}
		public void Read (string id, HIDDevice.ReadCallback callback, int timeout)
		{
			throw new NotImplementedException ();
		}
        public override void Write(object data, HIDDevice.WriteCallback callback,int timeout)
        {
            if (!IsConnected) return;
            if (IsOpen == false) OpenDevice();

            var writeDelegate = new WriteDelegate(Write);
            var asyncState = new HidAsyncState(writeDelegate, callback);
            writeDelegate.BeginInvoke((byte[])data,timeout, EndWrite, asyncState);

        }
예제 #52
0
파일: InputReport.cs 프로젝트: suan/mirlite
 /// <summary>
 /// Construction. Do nothing
 /// </summary>
 /// <param name="oDev">Creating device</param>
 protected InputReport(HIDDevice oDev)
     : base(oDev)
 {
 }
예제 #53
0
파일: InputEvent.cs 프로젝트: suan/mirlite
 public InputEvent(HIDDevice mirrorDevice)
     : base(mirrorDevice)
 {
 }
        /// <summary>
        /// Try to attach compatible driver based on device info
        /// </summary>
        /// <param name="deviceInfo"></param>
        protected void ResolveDevice(HIDDevice deviceInfo)
        {

            IDevice joyDevice = null;

            //loop thru drivers and attach the driver to device if compatible
            if (__drivers != null)
                foreach (var driver in __drivers)
                {
                    joyDevice = driver.ResolveDevice(deviceInfo);
                    if (joyDevice != null)
                    {
                      
                        this.webHIDBehaviour.Log("Device PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " attached to " + driver.GetType().ToString());
                        this.__Generics[deviceInfo.ID]=deviceInfo;
                        break;
                    }
                }

            if (joyDevice == null)
            {//set default driver as resolver if no custom driver match device
                joyDevice = defaultDriver.ResolveDevice(deviceInfo);


                if (joyDevice != null)
                {

                   // Debug.Log(__joysticks[deviceInfo.index]);

                    this.webHIDBehaviour.Log("Device index:" + joyDevice.Index+ " PID:" + joyDevice.PID + " VID:" + joyDevice.VID + " attached to " + __defaultJoystickDriver.GetType().ToString() + " Path:" + deviceInfo.DevicePath + " Name:" + joyDevice.Name);
                    
					webHIDBehaviour.PositionUpdateEvent += new EventHandler<WebMessageArgs<WebHIDReport>>(((GenericHIDDevice)deviceInfo).onPositionUpdate);

					this.__Generics[deviceInfo.ID]=deviceInfo;
                }
                else
                {
                    Debug.LogWarning("Device PID:" + deviceInfo.PID + " VID:" + deviceInfo.VID + " not found compatible driver thru WinHIDInterface!");

                }

            }


        }