protected override bool TryCreateDevice(object key, out HidDevice device, out object creationState)
 {
     creationState = null;
     string syspath = (string)key; var hidDevice = new LinuxHidDevice(syspath);
     if (!hidDevice.GetInfo()) { device = null; return false; }
     device = hidDevice; return true;
 }
        protected override void CompleteDevice(object key, HidDevice device, object creationState)
        {
            var hidDevice = (WinHidDevice)device; var handle = (IntPtr)creationState;
			if (hidDevice.VendorID != 0x15C2 && hidDevice.ProductID != 0x0038) {
				hidDevice.GetInfoComplete (handle);
			}
        }
Example #3
0
        private HidGamepad(DeviceInformation deviceInformation, HidDevice device)
        {
            _deviceInformation = deviceInformation;

            _device = device;
            _device.InputReportReceived += HandleInputReportRecieved;
        }
 /// <summary>
 /// Disconnect from the EV3 brick.
 /// </summary>
 public void Disconnect()
 {
     if (_hidDevice != null)
     {
         _hidDevice.InputReportReceived -= HidDeviceInputReportReceived;
         _hidDevice.Dispose();
         _hidDevice = null;
     }
 }
        /// <summary>
        /// Handler for processing/filtering input from the controller
        /// </summary>
        /// <param name="sender">HidDevice handle to the controller</param>
        /// <param name="args">InputReport received from the controller</param>
        private void inputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args)
        {
            int dPad = (int)args.Report.GetNumericControl(0x01, 0x39).Value;

            ControllerDpadDirection dpadDirection = (ControllerDpadDirection)dPad;

            // see http://sviluppomobile.blogspot.com/2013/11/hid-communication-for-windows-81-store.html

            // Adjust X/Y so (0,0) is neutral position

            // sticks - left and right:
            int _leftStickX = (int)(args.Report.GetNumericControl(0x01, 0x30).Value);
            int _leftStickY = (int)(args.Report.GetNumericControl(0x01, 0x31).Value);

            int _rightStickX = (int)(args.Report.GetNumericControl(0x01, 0x33).Value);
            int _rightStickY = (int)(args.Report.GetNumericControl(0x01, 0x34).Value);

            // triggers - left and right:
            int _LT = (int)Math.Max(0, args.Report.GetNumericControl(0x01, 0x32).Value - 32768);
            int _RT = (int)Math.Max(0, (-1) * (args.Report.GetNumericControl(0x01, 0x32).Value - 32768));

            JoystickRawState jss = new JoystickRawState()
            {
                X = _leftStickX, Y = _leftStickY, Z = 0,
                XR = _rightStickX, YR = _rightStickY,
                LT = _LT, RT = _RT,
                DpadDirection = dpadDirection
            };

            /*
            * Buttons Boolean ID's mapped to 0-9 array
            * A (button1) - 5 
            * B (button2) - 6
            * X (button3) - 7
            * Y (button4) - 8
            * LB (Left Bumper, button5) - 9
            * RB (Right Bumper, button6) - 10
            * Back (button7) - 11
            * Start (button8) - 12
            * LStick - 13
            * RStick - 14
            */
            foreach (var btn in args.Report.ActivatedBooleanControls)
            {
                // both press and release button event processed here:
                jss.Buttons[btn.Id - 5] = btn.IsActive;
            }

            // only invoke event if there was a change:
            if (!jss.Equals(jssLast))
            {
                jssLast = jss;
                //Debug.WriteLine("--------- HID: Joystick event");
                JoystickDataChanged?.Invoke(this, new JoystickEventArgs(jss));
            }
        }
 protected override bool TryCreateDevice(object key, out HidDevice device, out object creationState)
 {
     creationState = null;
     var path = (NativeMethods.io_string_t)key; var hidDevice = new MacHidDevice(path);
     using (var handle = NativeMethods.IORegistryEntryFromPath(0, ref path).ToIOObject())
     {
         if (!handle.IsSet || !hidDevice.GetInfo(handle)) { device = null; return false; }
         device = hidDevice; return true;
     }
 }
Example #7
0
        public UwpHidDevice(HidDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            this.device = device;
            device.InputReportReceived += DeviceOnInputReportReceived;
        }
 private async Task ConnectAsyncInternal()
 {
     string selector = HidDevice.GetDeviceSelector(UsagePage, UsageId, VID, PID);
     DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
     DeviceInformation brick = (from d in devices where d.Id == _deviceId select d).FirstOrDefault();
     if (brick == null)
         throw new Exception("No LEGO EV3 bricks found.");
     _hidDevice = await HidDevice.FromIdAsync(brick.Id, FileAccessMode.ReadWrite);
     if (_hidDevice == null)
         throw new Exception("Unable to connect to LEGO EV3 brick...is the manifest set properly?");
     _hidDevice.InputReportReceived += HidDeviceInputReportReceived;
 }
        protected override bool TryCreateDevice(object key, out HidDevice device, out object completionState)
        {
            string path = (string)key; var hidDevice = new WinHidDevice(path);
            IntPtr handle = NativeMethods.CreateFileFromDevice(path, NativeMethods.EFileAccess.None, NativeMethods.EFileShare.All);
            device = null; completionState = null; if (handle == (IntPtr)(-1)) { return false; }

            bool ok = false;
            try { ok = hidDevice.GetInfo(handle); } catch { }
            if (!ok) { NativeMethods.CloseHandle(handle); return false; }

            device = hidDevice; completionState = handle;
            return true;
        }
		protected override bool TryCreateDevice (object key, out HidDevice device, out object creationState)
		{
			creationState = null;
            
			var hidDevice = new LibusbHidDevice((UsbRegistry)key);
            
			if (!hidDevice.GetInfo()) { 
				device = null; 
				return false; 
			}
            
			device = hidDevice; 
			return true;
		}
Example #11
0
 void DeviceOnInputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args)
 {
     lock (inputReportLock)
     {
         if (inputReportSource != null)
         {
             inputReportSource.SetResult(args.Report);
         }
         else
         {
             inputReportQueue.Enqueue(args.Report);
         }
     }
 }
        /// <summary>
        /// Device type of the device provided device.
        /// </summary>
        /// <param name="device"></param>
        /// <returns>The DeviceType of the device or DeviceType.None if there are no devices connected or is not recognized</returns>
        public static DeviceType GetDeviceType(HidDevice device)
        {
            if (device != null)
            {
                if (device != null
                    && device.VendorId == SuperMutt.Device.Vid
                    && device.ProductId == SuperMutt.Device.Pid)
                {
                    return DeviceType.SuperMutt;
                }

                return DeviceType.None;
            }

            return DeviceType.None;
        }
        private static async Task ConnectToController(DeviceInformationCollection deviceInformationCollection)
        {
            foreach (var d in deviceInformationCollection)
            {
                _deviceHandle = await HidDevice.FromIdAsync(d.Id, FileAccessMode.Read);

                if (_deviceHandle == null)
                {
                    await _display.WriteAsync("No Xbox controller");
                    continue;
                }

                _deviceHandle.InputReportReceived += InputReportReceived;

                _isConnected = true;
                break;
            }
        }
Example #14
0
		public DriverCommunicator()
		{
			comparer = new HidContactInfoEqualityComparer();
			lockCurrentContacts = new object();

			device = HidDevices.Enumerate(0xdddd, 0x0001).FirstOrDefault();
			if (device == null)
				throw new InvalidOperationException("Universal Software HID driver was not found. Please ensure that it is installed.");

			device.Open(HidDevice.DeviceMode.Overlapped, HidDevice.DeviceMode.NonOverlapped);

			currentContacts = new Queue<HidContactInfo>();
			lastContactInfo = new Dictionary<int, HidContactInfo>();

			timer = new Timer();
			timer.AutoReset = false;
			timer.Interval = 1000 / 133d;
			timer.Elapsed += timer_Elapsed;
			timer.Start();
		}
Example #15
0
        private void MyDetectMessageBoard()
        {
            HidDevice[] HidDeviceList;

            try
            {

                HidDeviceList = HidDevices.Enumerate(_VentodId, _ProductId);

                if (HidDeviceList.Length > 0)
                {
                    _MessageBoard = HidDeviceList[0];

                    _MessageBoard.Open();
                }
            }
            catch (Exception ex)
            {
                _LogProvider.Error(ex);
            }
        }
            public void Initialize()
            {
                HIDLibrary.HidDevice[] hidDeviceList = HidDevices.Enumerate(0x1D34, 0x0004);
                if (hidDeviceList.Length == 0)
                {
                    hidDeviceList = HidDevices.Enumerate(0x1294, 0x1320);
                    if (hidDeviceList.Length > 0)
                    {
                        this.dreamCheeky = false;
                    }
                }

                if (hidDeviceList.Length > 0)
                {
                    this.hidDevice = hidDeviceList[0];
                    this.hidDevice.Open();
                    while (!this.hidDevice.IsConnected || !this.hidDevice.IsOpen) { }
                    if (this.dreamCheeky)
                    {
                        this.hidDevice.Write(new byte[9] { 0x00, 0x1F, 0x01, 0x29, 0x00, 0xB8, 0x54, 0x2C, 0x03 });
                        this.hidDevice.Write(new byte[9] { 0x00, 0x00, 0x01, 0x29, 0x00, 0xB8, 0x54, 0x2C, 0x04 });
                    }
                }
            }
Example #17
0
 protected abstract bool TryCreateDevice(object key, out HidDevice device, out object creationState);
        /// <summary>
        /// Register for the event that is triggered when the device sends a report to us.
        /// 
        /// All input reports share the same event in HidDevice, so once we register the event, all HidInputReports (regardless of the report id) will
        /// raise the event. Read the comment above OnInputReportEvent for more information on how to distinguish input reports.
        ///
        /// The function also saves the event token so that we can unregister from the event later on.
        /// </summary>
        private void RegisterForInputReportEvents()
        {
            if (!isRegisteredForInputReportEvents)
            {
                inputReportEventHandler = new TypedEventHandler<HidDevice, HidInputReportReceivedEventArgs>(this.OnInputReportEvent);

                // Remember which device we are registering the device with, in case there is a device disconnect and reconnect. We want to avoid unregistering
                // an event handler that is not registered with the device object.
                // Ideally, one should remove the event token (e.g. assign to null) upon the device removal to avoid using it again.
                registeredDevice = EventHandlerForDevice.Current.Device;

                registeredDevice.InputReportReceived += inputReportEventHandler;

                numInputReportEventsReceived = 0;
                totalNumberBytesReceived = 0;

                isRegisteredForInputReportEvents = true;
            }
        }
Example #19
0
        private void tmrCheckUSB_Tick(object sender, EventArgs e)
        {
            string GUID = _parent.GetUSBGUID(_CardSerialNumber, _usbDeviceID);
            if (GUID != "-1")
            {
                if (!_CardOpened)
                {
                    try
                    {
                        Card = _parent.GetHIDHandle(GUID);
                        Card.Open();
                        do
                        {
                            Application.DoEvents();     // Prevent App Freezing.
                        } while (Card.IsConnected == false);

                        _cardGUID = GUID;

                        Card.ReadReport(OnReport);
                        Card.Removed += DeviceRemovedHandler;

                        LogEvent("Card Attached", "C001", clsEventLogType.EventLogType.Info);
                        _parent.usbAddGUID(_cardGUID);
                        chkUSBConnected.Checked = true;

                        // Ask card for its inputs
                        tmrRequestButtonStatus.Enabled = true;
                        _CardOpened = true;
                    }
                    catch (Exception ex)
                    {
                        LogEvent(ex.Message, "E002", clsEventLogType.EventLogType.Error);
                    }
                }
            }
        }
        private static async void DisconnectCheckTimer(object sender)
        {
            var deviceInformationCollection = await DeviceInformation.FindAllAsync(HidDevice.GetDeviceSelector(0x01, 0x05));

            if (_isConnected && deviceInformationCollection.Count == 0)
            {
                _deviceHandle.Dispose();
                _deviceHandle = null;

                _isConnected = false;
                DisconnectedEvent?.Invoke(null, new DisconnectedEventArgs { IsConnected = false });
            }

            if (!_isConnected && deviceInformationCollection.Count > 0)
            {
                await ConnectToController(deviceInformationCollection);

                DisconnectedEvent?.Invoke(null, new DisconnectedEventArgs { IsConnected = true });
            }
        }
Example #21
0
        public static void RazerAttrWriteSetBrightness(HidDevice device, byte brightness)
        {
            RazerReport report = RazerChromaMiscSetBladeBrightness(brightness);

            RazerSendPayload(device, report);
        }
Example #22
0
        public static void RazerAttrWriteModeCustom(HidDevice device)
        {
            RazerReport report = RazerChromaStandardMatrixEffectCustomFrame(LED_STORAGE.VARSTORE);

            RazerSendPayload(device, report);
        }
Example #23
0
            //Reset controller status to defaults
            public void ResetControllerStatus()
            {
                try
                {
                    Debug.WriteLine("Reset the controller status for controller: " + NumberId);

                    //Controller Status
                    Activated = false;

                    //Battery Status
                    BatteryCurrent  = new ControllerBattery();
                    BatteryPrevious = new ControllerBattery();

                    //Time Variables
                    PrevInputTicks  = 0;
                    LastInputTicks  = 0;
                    LastActiveTicks = 0;

                    //Controller Details
                    Details       = null;
                    Disconnecting = false;

                    //Controller Tasks
                    InputVirtualOverlapped = new NativeOverlapped()
                    {
                        EventHandle = CreateEvent(IntPtr.Zero, true, false, null)
                    };
                    OutputVirtualOverlapped = new NativeOverlapped()
                    {
                        EventHandle = CreateEvent(IntPtr.Zero, true, false, null)
                    };
                    InputControllerTask  = new AVTaskDetails();
                    OutputControllerTask = new AVTaskDetails();
                    OutputVirtualTask    = new AVTaskDetails();
                    OutputGyroTask       = new AVTaskDetails();

                    //WinUsb Device Variables
                    WinUsbDevice = null;

                    //Hid Device Variables
                    HidDevice = null;

                    //Gyro Dsu Client Variables
                    GyroDsuClientPacketNumber = 0;
                    GyroDsuClientEndPoint     = null;

                    //Device In and Output
                    InputReport  = null;
                    OutputReport = null;
                    XInputData   = new XUSB_INPUT_REPORT();
                    XOutputData  = new XUSB_OUTPUT_REPORT();
                    XOutputCurrentRumbleHeavy  = 0;
                    XOutputCurrentRumbleLight  = 0;
                    XOutputPreviousRumbleHeavy = 0;
                    XOutputPreviousRumbleLight = 0;

                    //Controller Input
                    InputCurrent     = new ControllerInput();
                    SupportedCurrent = new ControllerSupported();
                }
                catch { }
            }
Example #24
0
 public static string GetSelector()
 {
     return(HidDevice.GetDeviceSelector(usagePage, usage, vendorId, productId));
 }
Example #25
0
        public void ConnectDevice(ICo2DeviceHandler co2DeviceHandler, IDataProcessor dataProcessor,
                                  int vendorId, int productId,
                                  ref JsonOutput output)
        {
            int    co2         = int.MinValue;
            double temperature = double.NaN;

            _hidDevice = co2DeviceHandler.ConnectDevice(vendorId, productId);
            _stream    = co2DeviceHandler.OpenStream(_hidDevice);

            //the device won't send anything before receiving this packet
            byte[] reportId = { 0x00 };
            byte[] request  = reportId.Concat(_key).ToArray();
            co2DeviceHandler.SendSetFeatureSetupRequest(_stream, request);

            var attempts         = 0;
            var exceptionMessage = "no attempts";

            while (true)
            {
                attempts++;
                if (attempts == 10)
                {
                    throw new Exception(exceptionMessage);
                }

                byte[] receivedData = co2DeviceHandler.ReadData(_stream);

                if (receivedData.Length == 0)
                {
                    exceptionMessage = "unable to read data";
                    continue;
                }

                if (receivedData.Length != 8 && receivedData.Length != 9)
                {
                    exceptionMessage = "transferred amount of bytes (" + receivedData.Length + ") != expected bytes amount (8 or 9)";
                    continue;
                }

                if (receivedData.Length == 9)
                {
                    var temp = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
                    for (var i = 0; i < 8; i++)
                    {
                        temp[i] = receivedData[i + 1];
                    }
                    receivedData = temp;
                }

                int[] data = dataProcessor.DecryptData(ref _key, ref receivedData);
                if (!dataProcessor.CheckEndOfMessage(ref data))
                {
                    exceptionMessage = "unexpected data from device";
                    continue;
                }

                if (!dataProcessor.CheckCheckSum(ref data))
                {
                    exceptionMessage = "checksum error";
                    continue;
                }

                dataProcessor.DataProcessing(ref data, ref co2);
                dataProcessor.DataProcessing(ref data, ref temperature);

                if (co2 != int.MinValue && !temperature.Equals(double.NaN))
                {
                    output = new JsonOutput(co2, temperature, DateTime.Now.ToString("g"));
                    break;
                }
            }
            co2DeviceHandler.CloseStream(_stream);
        }
 protected HIDU2FTransport(HidDevice device) : base(device, _UsageSpecification)
 {
     ReadTimeout = TimeSpan.FromSeconds(0.5);
 }
Example #27
0
 internal DeviceCommanderB(CorsairRootDevice root, HidDevice hidDevice) : base(root, hidDevice)
 {
 }
Example #28
0
        private void readButtonData(HidDeviceData InData)
        {
            timerHibernation.Enabled = false;

            if ((InData.Status == HidDeviceData.ReadStatus.Success) && (InData.Data[0] == 1))
            {
                SleepState = RemoteBtStates.Awake;
                timerFindRemote.Interval = 1500;

                DebugLog.write("Read button data: " + String.Join(",", InData.Data));

                if ((InData.Data[10] == 0) || (InData.Data[4] == 255)) // button released
                {
                    timerSleepButton.Stop();
                    if (ButtonReleased != null && isButtonDown)
                    {
                        ButtonReleased(this, new ButtonEventArgs(lastButton));
                    }
                }
                else // button pressed
                {
                    byte[] bCode = { InData.Data[1], InData.Data[2], InData.Data[3], InData.Data[4] };

                    int i, j;

                    for (j = 0; j < 56; j++)
                    {
                        for (i = 0; i < 4; i++)
                        {
                            if (bCode[i] != buttonCodes[j][i])
                            {
                                break;
                            }
                        }

                        if (i == 4)
                        {
                            break;
                        }
                    }

                    if (j != 56)
                    {
                        lastButton   = (Button)j;
                        isButtonDown = true;

                        if (ButtonDown != null)
                        {
                            ButtonDown(this, new ButtonEventArgs(lastButton));
                        }
                        if (lastButton == Button.Playstation)
                        {
                            timerSleepButton.Start();
                        }
                        else
                        {
                            timerSleepButton.Stop();
                        }
                    }
                }

                byte batteryReading = (byte)(InData.Data[11] * 20);

                if (batteryReading != _batteryLife) //Check battery life reading.
                {
                    _batteryLife = batteryReading;

                    if (BatteryLifeChanged != null)
                    {
                        BatteryLifeChanged(this, new EventArgs());
                    }
                }

                if (_hibernationEnabled)
                {
                    timerHibernation.Start();
                }

                hidRemote.Read(readButtonData); //Read next button pressed.

                return;
            }

            DebugLog.write("Read remote data: " + String.Join(",", InData.Data));

            if (Disconnected != null)
            {
                Disconnected(this, new EventArgs());
            }

            hidRemote.Dispose(); //Dispose of current remote.

            hidRemote = null;

            timerFindRemote.Enabled = true; //Try to reconnect.
            if (_hibernationEnabled)
            {
                timerHibernation.Enabled = false;
            }
        }
Example #29
0
 public KeepKeyCommunicator(HidDevice device)
 {
     _device = device;
 }
Example #30
0
 internal BaseUSBDevice(CorsairRootDevice root, HidDevice hidDevice)
     : base(root)
 {
     this.hidDevice = hidDevice;
 }
Example #31
0
        private bool Initialise()
        {
            bool result = false;

            var devices = HidDevices.Enumerate(vid, pid);

            if (devices.Count() == 0)
            {
                configurationDevice = null;
                inputDevice         = null;
                result     = false;
                isDetected = false;
            }
            else
            {
                isDetected          = true;
                configurationDevice = devices.FirstOrDefault(x => x.DevicePath.Contains("&col01"));
                inputDevice         = devices.FirstOrDefault(x => x.DevicePath.Contains("&col02"));

                if (configurationDevice != null && inputDevice != null)
                {
                    var attached = Observable.FromEvent <InsertedEventHandler, Unit>(h => () => h(Unit.Default), h => configurationDevice.Inserted += h, h => configurationDevice.Inserted -= h);
                    var detached = Observable.FromEvent <RemovedEventHandler, Unit>(h => () => h(Unit.Default), h => configurationDevice.Removed += h, h => configurationDevice.Removed -= h);

                    CableAttached = attached.Select(s => true).Merge(detached.Select(s => false));

                    CableAttached.Subscribe(async connected =>
                    {
                        if (connected)
                        {
                            await Connect();
                        }
                        else
                        {
                            cancellationSource.Cancel();
                            inputDevice.CloseDevice();
                            configurationDevice.CloseDevice();
                            isConnected.OnNext(false);
                        }
                    });

                    configurationIdpInterface = new IdpInterface();

                    inputIdpInterface = new IdpInterface();

                    commandManager = new CommandManager();

                    commandManager.RegisterInterface(configurationIdpInterface);
                    commandManager.RegisterInterface(inputIdpInterface);

                    InitialiseCommands();

                    packetStream = inputIdpInterface.PacketParsed.Merge(configurationIdpInterface.PacketParsed);

                    Task.Run(() => Connect()).Wait();

                    result = true;
                }
            }

            return(result);
        }
Example #32
0
 private void ReadingFinished(HidDevice sender, HidInputReportReceivedEventArgs args)
 {
     NativeDevice.InputReportReceived -= ReadingFinished;
     ReadReport    = args.Report;
     WaitingOnRead = false;
 }
Example #33
0
        /* TODO: uhh this doesn't seem right */
        public static void RazerAttrWriteSetFnToggle(HidDevice device, byte state)
        {
            RazerReport report = RazerChromaMiscFnKeyToggle(state);

            RazerSendPayload(device, report);
        }
Example #34
0
        private void input_thread(HidDevice Device, ScpBus scpBus, int index)
        {
            scpBus.PlugIn(index);
            X360Controller controller   = new X360Controller();
            int            timeout      = 30;
            long           last_changed = 0;

            //long last_mi_button = 0;
            while (true)
            {
                HidDeviceData data         = Device.Read(timeout);
                var           currentState = data.Data;
                bool          changed      = false;

                string str = Program.ByteArrayToHexString(currentState);
                if (!string.IsNullOrEmpty(str))
                {
                    Console.WriteLine(Program.ByteArrayToHexString(currentState));
                }

                if (data.Status == HidDeviceData.ReadStatus.Success && currentState.Length >= 10 && currentState[0] == 0x02)
                {
                    // Console.WriteLine(Program.ByteArrayToHexString(currentState));
                    X360Buttons Buttons = X360Buttons.None;
                    if ((currentState[1] & 0x01) != 0)
                    {
                        Buttons |= X360Buttons.A;
                    }
                    if ((currentState[1] & 0x02) != 0)
                    {
                        Buttons |= X360Buttons.B;
                    }
                    if ((currentState[1] & 0x08) != 0)
                    {
                        Buttons |= X360Buttons.X;
                    }
                    if ((currentState[1] & 0x10) != 0)
                    {
                        Buttons |= X360Buttons.Y;
                    }
                    if ((currentState[1] & 0x40) != 0)
                    {
                        Buttons |= X360Buttons.LeftBumper;
                    }
                    if ((currentState[1] & 0x80) != 0)
                    {
                        Buttons |= X360Buttons.RightBumper;
                    }

                    if ((currentState[2] & 0x20) != 0)
                    {
                        Buttons |= X360Buttons.LeftStick;
                    }
                    if ((currentState[2] & 0x40) != 0)
                    {
                        Buttons |= X360Buttons.RightStick;
                    }

                    if (currentState[3] != 0x0F)
                    {
                        if (currentState[3] == 0 || currentState[3] == 1 || currentState[3] == 7)
                        {
                            Buttons |= X360Buttons.Up;
                        }
                        if (currentState[3] == 4 || currentState[3] == 3 || currentState[3] == 5)
                        {
                            Buttons |= X360Buttons.Down;
                        }
                        if (currentState[3] == 6 || currentState[3] == 5 || currentState[3] == 7)
                        {
                            Buttons |= X360Buttons.Left;
                        }
                        if (currentState[3] == 2 || currentState[3] == 1 || currentState[3] == 3)
                        {
                            Buttons |= X360Buttons.Right;
                        }
                    }

                    if ((currentState[2] & 0x04) != 0)
                    {
                        Buttons |= X360Buttons.Start;
                    }
                    if ((currentState[2] & 0x08) != 0)
                    {
                        Buttons |= X360Buttons.Back;
                    }

                    if ((currentState[2] & 0x10) != 0)
                    {
                        Buttons |= X360Buttons.Logo;
                    }
                    //按下Fuze Logo键一下是不触发任何按键的,0x10是短按并松开fuze键时触发的按键
                    if ((currentState[2] & 0x01) != 0)
                    {
                        Buttons |= X360Buttons.Logo;
                    }
                    //长按会触发0x01按键,在GNU/Linux系统下,会触发关机键

                    /*
                     * //if ((currentState[20] & 1) != 0)
                     * //{
                     * //    last_mi_button = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                     * //    Buttons |= X360Buttons.Logo;
                     * //}
                     * //if (last_mi_button != 0) Buttons |= X360Buttons.Logo;
                     */

                    if (controller.Buttons != Buttons)
                    {
                        changed            = true;
                        controller.Buttons = Buttons;
                    }

                    short LeftStickX = (short)((Math.Max(-127.0, currentState[4] - 128) / 127) * 32767);
                    if (LeftStickX == -32767)
                    {
                        LeftStickX = -32768;
                    }

                    if (LeftStickX != controller.LeftStickX)
                    {
                        changed = true;
                        controller.LeftStickX = LeftStickX;
                    }

                    short LeftStickY = (short)((Math.Max(-127.0, currentState[5] - 128) / 127) * -32767);
                    if (LeftStickY == -32767)
                    {
                        LeftStickY = -32768;
                    }

                    if (LeftStickY != controller.LeftStickY)
                    {
                        changed = true;
                        controller.LeftStickY = LeftStickY;
                    }

                    short RightStickX = (short)((Math.Max(-127.0, currentState[6] - 128) / 127) * 32767);
                    if (RightStickX == -32767)
                    {
                        RightStickX = -32768;
                    }

                    if (RightStickX != controller.RightStickX)
                    {
                        changed = true;
                        controller.RightStickX = RightStickX;
                    }

                    short RightStickY = (short)((Math.Max(-127.0, currentState[7] - 128) / 127) * -32767);
                    if (RightStickY == -32767)
                    {
                        RightStickY = -32768;
                    }

                    if (RightStickY != controller.RightStickY)
                    {
                        changed = true;
                        controller.RightStickY = RightStickY;
                    }

                    if (controller.LeftTrigger != currentState[8])
                    {
                        changed = true;
                        controller.LeftTrigger = currentState[8];
                    }

                    if (controller.RightTrigger != currentState[9])
                    {
                        changed = true;
                        controller.RightTrigger = currentState[9];
                    }
                }

                if (data.Status == HidDeviceData.ReadStatus.WaitTimedOut || (!changed && ((last_changed + timeout) < (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond))))
                {
                    changed = true;
                }

                if (changed)
                {
                    //Console.WriteLine("changed");
                    //Console.WriteLine((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond));
                    byte[] outputReport = new byte[8];
                    scpBus.Report(index, controller.GetReport(), outputReport);

                    //TODO: 震动
                    //if (outputReport[1] == 0x08)
                    //{
                    //    byte bigMotor = outputReport[3];
                    //    byte smallMotor = outputReport[4];
                    //    rumble_mutex.WaitOne();
                    //    if (bigMotor != Vibration[2] || Vibration[1] != smallMotor)
                    //    {
                    //        Vibration[1] = smallMotor;
                    //        Vibration[2] = bigMotor;
                    //    }
                    //    rumble_mutex.ReleaseMutex();
                    //}

                    /*
                     * //if (last_mi_button != 0)
                     * //{
                     * //    if ((last_mi_button + 100) < (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond))
                     * //    {
                     * //        last_mi_button = 0;
                     * //        controller.Buttons ^= X360Buttons.Logo;
                     * //    }
                     * //}
                     *
                     * //last_changed = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                     */
                }
            }
        }
Example #35
0
        //public EAll4Touchpad Touchpad { get { return touchpad; } }

        public static ConnectionType HidConnectionType(HidDevice hidDevice)
        {
            //return hidDevice.Capabilities.InputReportByteLength == InputReportByteLengthUSB ? ConnectionType.USB : ConnectionType.BT;
            return(ConnectionType.BT);
        }
Example #36
0
 static RazerReport RazerGetReport(HidDevice device, RazerReport request_report)
 {
     return(RazerGetUsbResponse(device, 0x02, request_report));
 }
Example #37
0
 public static Boolean IsSuperMuttDevice(HidDevice device)
 {
     return(GetDeviceType(device) == DeviceType.SuperMutt);
 }
Example #38
0
        private void performEAll4Input()
        {
            firstActive = DateTime.UtcNow;
            System.Timers.Timer readTimeout = new System.Timers.Timer(); // Await 30 seconds for the initial packet, then 3 seconds thereafter.
            readTimeout.Elapsed += delegate { HidDevice.CancelIO(); };
            List <long> Latency = new List <long>();
            long        oldtime = 0;
            Stopwatch   sw      = new Stopwatch();

            sw.Start();
            while (true)
            {
                string currerror = string.Empty;
                Latency.Add(sw.ElapsedMilliseconds - oldtime);
                oldtime = sw.ElapsedMilliseconds;

                if (Latency.Count > 100)
                {
                    Latency.RemoveAt(0);
                }

                this.Latency = Latency.Average();

                if (this.Latency > 10 && !warn && sw.ElapsedMilliseconds > 4000)
                {
                    warn = true;
                    //System.Diagnostics.Trace.WriteLine(System.DateTime.UtcNow.ToString("o") + "> " + "Controller " + /*this.DeviceNum*/ + 1 + " (" + this.MacAddress + ") is experiencing latency issues. Currently at " + Math.Round(this.Latency, 2).ToString() + "ms of recomended maximum 10ms");
                }
                else if (this.Latency <= 10 && warn)
                {
                    warn = false;
                }

                if (readTimeout.Interval != 3000.0)
                {
                    if (readTimeout.Interval != 30000.0)
                    {
                        readTimeout.Interval = 30000.0;
                    }
                    else
                    {
                        readTimeout.Interval = 3000.0;
                    }
                }
                readTimeout.Enabled = true;
                if (conType != ConnectionType.USB)
                {
                    HidDevice.ReadStatus res = hDevice.ReadFile(btInputReport);
                    readTimeout.Enabled = false;
                    if (res == HidDevice.ReadStatus.Success)
                    {
                        _isAvaliable = true;
                        Array.Copy(btInputReport, 0, inputReport, 0, inputReport.Length);
                    }
                    else
                    {
                        _isAvaliable = false;
                        Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                        Log.LogToTray(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                      "> disconnect due to read failure(notUsb): " + Marshal.GetLastWin32Error());
                        Nlog.Debug(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                   "> disconnect due to read failure(notUsb): " + Marshal.GetLastWin32Error());
                        IsDisconnecting = true;
                        if (Removal != null)
                        {
                            Removal(this, EventArgs.Empty);
                        }

                        break;
                        return;
                    }



                    //else
                    //{
                    //    Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                    //    sendOutputReport(true); // Kick Windows into noticing the disconnection.
                    //    StopOutputUpdate();
                    //    IsDisconnecting = true;
                    //    if (Removal != null)
                    //        Removal(this, EventArgs.Empty);
                    //    return;

                    //}
                }
                else
                {
                    HidDevice.ReadStatus res = hDevice.ReadFile(inputReport);
                    readTimeout.Enabled = false;
                    if (res != HidDevice.ReadStatus.Success)
                    {
                        Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                        Log.LogToTray(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                      "> disconnect due to read failure(USB): " + Marshal.GetLastWin32Error());

                        Nlog.Debug(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                   "> disconnect due to read failure(USB): " + Marshal.GetLastWin32Error());
                        StopOutputUpdate();
                        IsDisconnecting = true;
                        if (Removal != null)
                        {
                            Removal(this, EventArgs.Empty);
                        }
                        return;
                    }
                }
                //if (ConnectionType == ConnectionType.BT && btInputReport[0] != 0x11)
                //{
                //    //Received incorrect report, skip it
                //    continue;
                //}
                DateTime utcNow = System.DateTime.UtcNow; // timestamp with UTC in case system time zone changes
                //resetHapticState();
                cState.ReportTimeStamp = utcNow;
                cState.LX = inputReport[4]; // left joystick x-axis//左摇杆x轴
                cState.LY = inputReport[5]; // left joystick y-axis//左摇杆Y轴
                cState.RX = inputReport[6]; // right joystick x-axis//右摇杆x轴
                cState.RY = inputReport[7]; //right joystick y-axis//右摇杆y轴


                cState.LT = inputReport[8];
                cState.RT = inputReport[9];
                cState.LB = ((byte)inputReport[1] & Convert.ToByte(64)) != 0;
                cState.RB = ((byte)inputReport[1] & Convert.ToByte(128)) != 0;

                cState.A = ((byte)inputReport[1] & Convert.ToByte(1)) != 0;  // ok
                cState.B = ((byte)inputReport[1] & Convert.ToByte(2)) != 0;  //ok
                cState.X = ((byte)inputReport[1] & Convert.ToByte(8)) != 0;  //ok
                cState.Y = ((byte)inputReport[1] & Convert.ToByte(16)) != 0; //ok
                switch (inputReport[3])
                {
                case 0: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break;   //up

                case 1: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break;    //up right//fixed on 2016-12-28

                case 2: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break;   //right

                case 3: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = true; break;    //down right

                case 4: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = false; break;   //down

                case 5: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = true; cState.DpadRight = false; break;    //down left

                case 6: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break;   // left

                case 7: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break;    //up left

                default: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break;
                }

                cState.RS = ((byte)inputReport[2] & Convert.ToByte(64)) != 0;
                var leftStick = ((byte)inputReport[2] & Convert.ToByte(32)) != 0;
                cState.LS = leftStick;
                var menu = ((byte)inputReport[2] & Convert.ToByte(8)) != 0;
                var back = ((byte)inputReport[2] & Convert.ToByte(4)) != 0;
                cState.Start = menu;
                cState.Back  = back;


                cState.Guide = menu && leftStick;
                // XXX fix initialization ordering so the null checks all go away

                //battery level, the be-top protocal look like not contain battery data.. can not display battery level for now.
                //var batteryLevel = Convert.ToInt32(inputReport[18]) / 255;
                //battery = batteryLevel;

                //cState.Battery = 60;

                if (Report != null)
                {
                    Report(this, EventArgs.Empty);
                }
                //sendOutputReport(false);

                // the be-top bluetooth report protocal unknow fo now , the rumble function can not supported.
                //sendOutputReport(false);


                if (!string.IsNullOrEmpty(error))
                {
                    error = string.Empty;
                }
                if (!string.IsNullOrEmpty(currerror))
                {
                    error = currerror;
                }
                cState.CopyTo(pState);
            }
        }
Example #39
0
 public override void Disconnect()
 {
     _stream.Close();
     _stream = null;
     _device = null;
 }
 internal RawDataReceivedEventArgs(HidDevice device, byte[] buffer, int count)
 {
     this.Device = device;
     this.Buffer = buffer;
     this.Count  = count;
 }
Example #41
0
        static void Main(string[] args)
        {
            var       list          = DeviceList.Local;
            HidDevice XD75          = null;
            HidStream XD75Strm      = null;
            bool      reportEnabled = false;

            keyCounter = Extensions.ReadCounter();

            XD75 = TryConnectXD75();

            DeviceList.Local.Changed += (object sender, DeviceListChangedEventArgs a) =>
            {
                if (XD75 == null)
                {
                    XD75 = TryConnectXD75();
                }
            };

            Thread heartBeatThread = new Thread(() =>
            {
                while (true)
                {
                    Thread.Sleep(5000);
                    if (XD75 != null && XD75Strm != null)
                    {
                        var heartBeatMessage = Enums.RAW_COMMAND_ID.RAW_COMMAND_HEARTBEAT_PING.ConstructRawCommand();
                        lock (StreamLock)
                        {
                            XD75Strm.Write(heartBeatMessage);
                        }
                    }
                }
            });
            Thread mainThread = new Thread(() =>
            {
                while (true)
                {
                    if (XD75 == null)
                    {
                        Console.WriteLine("No XD75 found, searching in background...");
                        while (XD75 == null)
                        {
                            Thread.Sleep(100);
                        }
                    }

                    if (XD75.TryOpen(out XD75Strm))
                    {
                        reportEnabled = EnableReport(XD75Strm);

                        if (reportEnabled)
                        {
                            XD75Strm.ReadTimeout = Timeout.Infinite;

                            Console.CancelKeyPress += delegate
                            {
                                var DisableKeyEventReportCmd = Enums.RAW_COMMAND_ID.RAW_COMMAND_DISABLE_KEY_EVENT_REPORT.ConstructRawCommand();
                                lock (StreamLock)
                                {
                                    XD75Strm?.Write(DisableKeyEventReportCmd);
                                    XD75Strm.ReadTimeout = 50;
                                    XD75Strm?.Close();
                                }
                                keyCounter.DumpCounter();
                                XD75     = null;
                                XD75Strm = null;
                                heartBeatThread.Abort();
                                System.Environment.Exit(0);
                            };

                            while (true)
                            {
                                if (!heartBeatThread.IsAlive)
                                {
                                    heartBeatThread.Start();
                                }
                                try
                                {
                                    var report = XD75Strm.Read();

                                    if (report[1] == Enums.RAW_COMMAND_ID.RAW_COMMAND_HEARTBEAT_PING.ToByte())
                                    {
                                        Console.WriteLine("Received heartbeat response.");
                                        var heartBeatMsg = Enums.RAW_COMMAND_ID.RAW_COMMAND_HEARTBEAT_PING.ConstructRawCommand();
                                        var response     = report.Take(heartBeatMsg.Count()).ToArray();
                                        if (!response.SequenceEqual(heartBeatMsg))
                                        {
                                            Console.WriteLine($"Heart beat message of no.{HeartBeatCount} mismatches...");
                                        }
                                        else
                                        {
                                            Console.WriteLine($"Heart beat message of no.{HeartBeatCount} matches.");
                                            HeartBeatCount++;
                                            continue;
                                        }
                                    }

                                    if (report[1] == Enums.RAW_COMMAND_ID.RAW_COMMAND_CHANGE_COLOR.ToByte())
                                    {
                                        Console.WriteLine("Received change underglow color response.");
                                        if (report[2] == 1)
                                        {
                                            if (report[3] == FAILED)
                                            {
                                                Console.WriteLine("Command failed.");
                                            }
                                            else
                                            {
                                                Console.WriteLine("Command succeded unexpectely.");
                                            }
                                        }
                                        else if (report[2] == 4)
                                        {
                                            if (report[6] == SUCCESS)
                                            {
                                                Hsv hsv = new Hsv();
                                                hsv.H   = report[3] * 360d / 255d;
                                                hsv.S   = report[4] / 255d;
                                                hsv.V   = report[5] / 255d;
                                                Rgb rgb = hsv.To <Rgb>();
                                                Console.WriteLine($"Command succeded with value:{rgb.R} {rgb.G} {rgb.B}");
                                            }
                                            else
                                            {
                                                Console.WriteLine($"Command failed unexpectely.");
                                            }
                                        }
                                        continue;
                                    }

                                    if (report[1] != Enums.RAW_COMMAND_ID.RAW_COMMAND_REPORT_KEY_EVENT.ToByte())
                                    {
                                        Console.WriteLine("Received unknown command:");
                                        Console.WriteLine(BitConverter.ToString(report));
                                        continue;
                                    }

                                    int len = report[2];
                                    if (len != 0x2)
                                    {
                                        Console.WriteLine("Received unknown report:");
                                        Console.WriteLine(BitConverter.ToString(report));
                                        continue;
                                    }
                                    int col = (int)report[3]; //0-14
                                    int row = (int)report[4]; //0-4
                                    keyCounter[row * 15 + col]++;
                                    Console.WriteLine($"Received key event: {col},{row}");
                                    Console.WriteLine($"Total KeyCount:     {keyCounter.Sum()}");
                                    if (keyCounter.Sum() % 100 == 0)
                                    {
                                        Console.WriteLine("Saving keyCounter...");
                                        keyCounter.DumpCounter();
                                    }
                                }
                                catch (Exception e)
                                {
                                    XD75Strm?.Close();
                                    reportEnabled = false;
                                    XD75          = null;
                                    XD75Strm      = null;
                                    break;
                                }
                            }
                            continue;
                        }
                        else
                        {
                            Console.WriteLine("Report enable failed.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error communicating with XD75.");
                        continue;
                    }

                    XD75Strm?.Close();
                }
            });

            mainThread.Start();
            while (true)
            {
                var inputs = Console.ReadLine()?.Split();
                if (inputs == null)
                {
                    break;
                }
                if (inputs[0].ToLower() == "c")
                {
                    if (inputs.Length == 4)
                    {
                        try
                        {
                            var payload = inputs.Skip(1).Select(s =>
                            {
                                if (s[0] == 'd')
                                {
                                    return(Convert.ToByte(s.Trim('d'), 10));
                                }
                                return(Convert.ToByte(s, 16));
                            }).ToArray();

                            Rgb rgb = new Rgb();
                            rgb.R = payload[0];
                            rgb.G = payload[1];
                            rgb.B = payload[2];

                            Console.WriteLine("RGB: " + payload[0].ToString("X2") + payload[1].ToString("X2") + payload[2].ToString("X2"));

                            var hsv = rgb.To <Hsv>();
                            payload[0] = (byte)(hsv.H / 360d * 255d);
                            payload[1] = (byte)(hsv.S * 255d);
                            payload[2] = (byte)(hsv.V * 255d);



                            Console.WriteLine(payload[0].ToString() + " " + payload[1].ToString() + " " + payload[2].ToString());

                            if (XD75 != null && XD75Strm != null)
                            {
                                var colorMessage = Enums.RAW_COMMAND_ID.RAW_COMMAND_CHANGE_COLOR.ConstructRawCommand(payload);
                                lock (StreamLock)
                                {
                                    XD75Strm.Write(colorMessage);
                                }
                            }
                        }
                        catch { };
                    }
                }
            }
        }
Example #42
0
 public MuniaNgc(HidDevice hidDevice) : base(hidDevice)
 {
     _buttons.EnsureSize(12);
     _axes.EnsureSize(6);
     _hats.EnsureSize(1);
 }
        private static void InputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args)
        {
            var dPad = (int)args.Report.GetNumericControl(0x01, 0x39).Value;

            var lstickX = args.Report.GetNumericControl(0x01, 0x30).Value - 32768;
            var lstickY = args.Report.GetNumericControl(0x01, 0x31).Value - 32768;

            var rstickX = args.Report.GetNumericControl(0x01, 0x33).Value - 32768;
            var rstickY = args.Report.GetNumericControl(0x01, 0x34).Value - 32768;

            var lt = (int)Math.Max(0, args.Report.GetNumericControl(0x01, 0x32).Value - 32768);
            var rt = (int)Math.Max(0, -1 * (args.Report.GetNumericControl(0x01, 0x32).Value - 32768));

            foreach (var btn in args.Report.ActivatedBooleanControls) //StartAsync = 7, Back = 6
            {
                var id = (int)(btn.Id - 5);

                if (id < 4)
                    FunctionButtonChanged?.Invoke(id);
                else if (id >= 4 && id < 6)
                    BumperButtonChanged?.Invoke(id);
                else
                    FunctionButtonChanged?.Invoke(id);
            }

            if (_leftTrigger != lt)
            {
                LeftTriggerChanged?.Invoke(lt);
                _leftTrigger = lt;
            }

            if (_rightTrigger != rt)
            {
                RightTriggerChanged?.Invoke(rt);
                _rightTrigger = rt;
            }

            var lStickMagnitude = GetMagnitude(lstickX, lstickY);
            var rStickMagnitude = GetMagnitude(rstickX, rstickY);

            var vector = new ControllerVector
            {
                Direction = CoordinatesToDirection(lstickX, lstickY),
                Magnitude = lStickMagnitude
            };

            if (!_leftStickDirectionVector.Equals(vector) && LeftDirectionChanged != null)
            {
                _leftStickDirectionVector = vector;
                LeftDirectionChanged(_leftStickDirectionVector);
            }

            vector = new ControllerVector
            {
                Direction = CoordinatesToDirection(rstickX, rstickY),
                Magnitude = rStickMagnitude
            };

            if (!_rightStickDirectionVector.Equals(vector) && RightDirectionChanged != null)
            {
                _rightStickDirectionVector = vector;
                RightDirectionChanged(_rightStickDirectionVector);
            }

            vector = new ControllerVector
            {
                Direction = (ControllerDirection)dPad,
                Magnitude = 10000
            };

            if (_dpadDirectionVector.Equals(vector) || DpadDirectionChanged == null)
                return;

            _dpadDirectionVector = vector;
            DpadDirectionChanged(vector);
        }
 public static Boolean IsSuperMuttDevice(HidDevice device)
 {
     return (GetDeviceType(device) == DeviceType.SuperMutt);
 }
        /// <summary>
        /// This callback only increments the total number of events received and prints it
        ///
        /// This method is called whenever the device's state changes and sends a report. Since all input reports share the same event in 
        /// HidDevice, the app needs to get the HidInputReport from eventArgs.Report and compare report ids and usages with the desired
        /// report.
        /// </summary>
        /// <param name="sender">HidDevice that the event is being raised from</param> 
        /// <param name="eventArgs">Contains the HidInputReport that caused the event to raise</param> 
        private async void OnInputReportEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs)
        {
            // If we navigated away from this page, we don't need to process this event
            // This also prevents output from spilling into another page
            if (!navigatedAway)
            {
                numInputReportEventsReceived++;

                // The data from the InputReport
                HidInputReport inputReport = eventArgs.Report;
                IBuffer buffer = inputReport.Data;

                totalNumberBytesReceived += buffer.Length;

                // Create a DispatchedHandler for the because we are interracting with the UI directly and the
                // thread that this function is running on may not be the UI thread; if a non-UI thread modifies
                // the UI, an exception is thrown
                await rootPage.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(() =>
                    {
                        // If we navigated away from this page, do not print anything. The dispatch may be handled after
                        // we move to a different page.
                        if (!navigatedAway)
                        {
                            rootPage.NotifyUser(
                                "Total number of input report events received: " + numInputReportEventsReceived.ToString()
                                + "\nTotal number of bytes received: " + totalNumberBytesReceived.ToString(),
                                NotifyType.StatusMessage);
                        }
                    }));
            }
        }
        /// <summary>
        /// This method opens the device using the WinRT Hid API. After the device is opened, save the device
        /// so that it can be used across scenarios.
        ///
        /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
        /// on the UI thread.
        /// 
        /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
        /// </summary>
        /// <param name="deviceInfo">Device information of the device to be opened</param>
        /// <param name="deviceSelector">The AQS used to find this device</param>
        /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
        /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
        public async Task<Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
        {
            // This sample uses FileAccessMode.ReadWrite to open the device because we do not want other apps opening our device and 
            // changing the state of our device. FileAccessMode.Read can be used instead.
            device = await HidDevice.FromIdAsync(deviceInfo.Id, FileAccessMode.ReadWrite);

            Boolean successfullyOpenedDevice = false;
            NotifyType notificationStatus;
            String notificationMessage = null;

            // Device could have been blocked by user or the device has already been opened by another app.
            if (device != null)
            {
                successfullyOpenedDevice = true;

                deviceInformation = deviceInfo;
                this.deviceSelector = deviceSelector;

                notificationStatus = NotifyType.StatusMessage;
                notificationMessage = "Device " + deviceInformation.Id + " opened";

                if (appSuspendEventHandler == null || appResumeEventHandler == null)
                {
                    RegisterForAppEvents();
                }

                // User can block the device after it has been opened in the Settings charm. We can detect this by registering for the 
                // DeviceAccessInformation.AccessChanged event
                if (deviceAccessEventHandler == null)
                {
                    RegisterForDeviceAccessStatusChange();
                }

                // Create and register device watcher events for the device to be opened unless we're reopening the device
                if (deviceWatcher == null)
                {
                    deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);

                    RegisterForDeviceWatcherEvents();
                }

                if (!watcherStarted)
                {
                    // Start the device watcher after we made sure that the device is opened.
                    StartDeviceWatcher();
                }
            }
            else
            {
                successfullyOpenedDevice = false;

                notificationStatus = NotifyType.ErrorMessage;

                var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;

                if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
                {
                    notificationMessage = "Access to the device was blocked by the user : "******"Access to the device was blocked by the system : " + deviceInfo.Id;
                }
                else
                {
                    // Most likely the device is opened by another app, but cannot be sure
                    notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
                }
            }

            MainPage.Current.NotifyUser(notificationMessage, notificationStatus);

            // Notify registered callback handle that the device has been opened
            if (deviceConnectedCallback != null)
            {
                var deviceConnectedEventArgs = new OnDeviceConnectedEventArgs(successfullyOpenedDevice, deviceInfo);

                deviceConnectedCallback(this, deviceConnectedEventArgs);
            }

            return successfullyOpenedDevice;
        }
        /// <summary>
        /// Unregisters from the HidDevice's InputReportReceived event that was registered for in the RegisterForInputReportEvents();
        /// </summary>
        private void UnregisterFromInputReportEvent()
        {
            if (isRegisteredForInputReportEvents)
            {
                // Don't unregister event if the device was removed and reconnected because the endpoint event no longer contains our event handler
                if (registeredDevice == EventHandlerForDevice.Current.Device)
                {
                    registeredDevice.InputReportReceived -= inputReportEventHandler;
                }

                registeredDevice = null;
                isRegisteredForInputReportEvents = false;
            }
        }
Example #48
0
 public K380(HidDevice keyboard)
 {
     this.keyboard = keyboard;
 }
 private ProgrammatorDevice(HidDevice hidDevice)
 {
     _hidDevice = hidDevice;
 }
Example #50
0
        private void UpdateUI()
        {
            // enter bootloader button is enabled if vid/pid of MUNIA
            // is observed, if so all other functions are disabled
            var muniaInterfaces = MuniaController.GetMuniaConfigInterfaces();

            if (muniaInterfaces.Any())
            {
                // munia detected, so it's not in BL, but we can send a packet to request this
                tsbLoadHex.Enabled         = tsbProgram.Enabled = tsbReset.Enabled = false;
                _blDevice                  = null;
                _blInterface               = null;
                imgBlStatus.Image          = Resources.warn;
                lblStatus.Text             = "Status: user";
                imgBlStatus.ToolTipText    = "MUNIA is currently in user mode.\r\nReboot it in bootloader mode to continue.";
                tsbEnterBootloader.Enabled = true;
                lblHEX.Visible             = imgHexStatus.Visible = pbFlash.Visible = lblProgress.Visible = false;
                tsbLoadHex.Enabled         = tsbProgram.Enabled = tsbReset.Enabled = false;
                return;
            }
            else
            {
                tsbEnterBootloader.Enabled = false;
            }

            // see if there is a selected device, and whether is still valid
            HidStream s          = null;
            bool      blDeviceOk = false;

            if (_blDevice != null && _blDevice.TryOpen(out s))
            {
                s.Dispose();
                blDeviceOk = true;
            }
            else
            {
                _blDevice = null;
            }

            // if no device selected, see if we can find one
            if (_blDevice == null)
            {
                _blDevice  = MuniaController.GetMuniaBootloaderInterfaces().FirstOrDefault();
                blDeviceOk = _blDevice != null && _blDevice.TryOpen(out s);
                if (blDeviceOk)
                {
                    s.Dispose();
                    _blInterface = new HidBootloader(_blDevice);
                }
            }

            if (blDeviceOk)
            {
                imgBlStatus.Image     = Resources.ok;
                lblStatus.Text        = "Status: in BL";
                lblStatus.ToolTipText = "MUNIA is currently in bootloader mode,\r\n and is ready to be flashed.";
            }
            else
            {
                imgBlStatus.Image     = Resources.notok;
                lblStatus.Text        = "Status: not found";
                lblStatus.ToolTipText = "MUNIA is currently not plugged in or malfunctioning.";
                lblHEX.Visible        = imgHexStatus.Visible = pbFlash.Visible = lblProgress.Visible = false;
                tsbLoadHex.Enabled    = tsbProgram.Enabled = tsbReset.Enabled = false;
                return;
            }

            lblHEX.Visible     = imgHexStatus.Visible = pbFlash.Visible = lblProgress.Visible = true;
            tsbLoadHex.Enabled = true;
            tsbReset.Enabled   = true;
            if (_hexFile?.Size > 0x100)
            {
                tsbProgram.Enabled       = true;
                imgHexStatus.Image       = Resources.ok;
                imgHexStatus.ToolTipText = "Firmware hex file is successfully loaded.";
            }
            else
            {
                tsbProgram.Enabled       = false;
                imgHexStatus.Image       = Resources.notok;
                imgHexStatus.ToolTipText = "Load a firmware hex file to flash first.";
            }
        }
Example #51
0
 protected abstract void CompleteDevice(object key, HidDevice device, object creationState);
Example #52
0
        private void DeviceInputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs e)
        {
            bool isXButtonDown               = false;
            bool isAButtonDown               = false;
            bool isBButtonDown               = false;
            bool isYButtonDown               = false;
            bool isLeftBumperButtonDown      = false;
            bool isRightBumperButtonDown     = false;
            bool isLeftTriggerButtonDown     = false;
            bool isRightTriggerButtonDown    = false;
            bool isBackButtonDown            = false;
            bool isStartButtonDown           = false;
            bool isLeftThumbstickButtonDown  = false;
            bool isRightThumbstickButtonDown = false;

            foreach (HidBooleanControl control in e.Report.ActivatedBooleanControls)
            {
                if (!Enum.IsDefined(typeof(LogitechF710ButtonUsage), control.UsageId))
                {
                    continue;
                }

                var usage = (LogitechF710ButtonUsage)control.UsageId;

                switch (usage)
                {
                case LogitechF710ButtonUsage.X:
                    isXButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.A:
                    isAButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.B:
                    isBButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.Y:
                    isYButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.LeftBumper:
                    isLeftBumperButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.RightBumper:
                    isRightBumperButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.LeftTigger:
                    isLeftTriggerButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.RightTrigger:
                    isRightTriggerButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.Back:
                    isBackButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.Start:
                    isStartButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.LeftThumbstick:
                    isLeftThumbstickButtonDown = control.IsActive;
                    break;

                case LogitechF710ButtonUsage.RightThumbstick:
                    isRightThumbstickButtonDown = control.IsActive;
                    break;
                }
            }

            const ushort usagePageGeneric = 0x01 /*Generic*/;

            long leftThumbstickHorizontal  = e.Report.GetNumericControl(usagePageGeneric, (ushort)LogitechF710GenericUsage.X).Value;
            long leftThumbstickVertical    = e.Report.GetNumericControl(usagePageGeneric, (ushort)LogitechF710GenericUsage.Y).Value;
            long rightThumbstickHorizontal = e.Report.GetNumericControl(usagePageGeneric, (ushort)LogitechF710GenericUsage.RX).Value;
            long rightThumbstickVertical   = e.Report.GetNumericControl(usagePageGeneric, (ushort)LogitechF710GenericUsage.RY).Value;
            long hatSwitch = e.Report.GetNumericControl(usagePageGeneric, (ushort)LogitechF710GenericUsage.HatSwitch).Value;

            bool isUpButtonDown    = hatSwitch == 7 || hatSwitch == 0 || hatSwitch == 1;
            bool isRightButtonDown = hatSwitch == 1 || hatSwitch == 2 || hatSwitch == 3;
            bool isDownButtonDown  = hatSwitch == 3 || hatSwitch == 4 || hatSwitch == 5;
            bool isLeftButtonDown  = hatSwitch == 5 || hatSwitch == 6 || hatSwitch == 7;

            var data = new LogitechF710InputData(
                isXButtonDown,
                isAButtonDown,
                isBButtonDown,
                isYButtonDown,
                isLeftBumperButtonDown,
                isRightBumperButtonDown,
                isLeftTriggerButtonDown,
                isRightTriggerButtonDown,
                isBackButtonDown,
                isStartButtonDown,
                isLeftThumbstickButtonDown,
                isRightThumbstickButtonDown,
                leftThumbstickHorizontal,
                leftThumbstickVertical,
                rightThumbstickHorizontal,
                rightThumbstickVertical,
                isUpButtonDown,
                isRightButtonDown,
                isDownButtonDown,
                isLeftButtonDown);

            OnInputChanged(data);

            if (_previousData == null || isXButtonDown != _previousData.IsXButtonDown)
            {
                if (isXButtonDown)
                {
                    OnButtonDown(LogitechF710Button.X);
                    OnButtonPressed(LogitechF710Button.X);

                    _xButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.X, _repeatDelayMilliseconds, _repeatRateMilliseconds, _xButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _xButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.X);
                }
            }

            if (_previousData == null || isAButtonDown != _previousData.IsAButtonDown)
            {
                if (isAButtonDown)
                {
                    OnButtonDown(LogitechF710Button.A);
                    OnButtonPressed(LogitechF710Button.A);

                    _aButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.A, _repeatDelayMilliseconds, _repeatRateMilliseconds, _aButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _aButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.A);
                }
            }

            if (_previousData == null || isBButtonDown != _previousData.IsBButtonDown)
            {
                if (isBButtonDown)
                {
                    OnButtonDown(LogitechF710Button.B);
                    OnButtonPressed(LogitechF710Button.B);

                    _bButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.B, _repeatDelayMilliseconds, _repeatRateMilliseconds, _bButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _bButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.B);
                }
            }

            if (_previousData == null || isYButtonDown != _previousData.IsYButtonDown)
            {
                if (isYButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Y);
                    OnButtonPressed(LogitechF710Button.Y);

                    _yButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Y, _repeatDelayMilliseconds, _repeatRateMilliseconds, _yButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _yButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Y);
                }
            }

            if (_previousData == null || isLeftBumperButtonDown != _previousData.IsLeftBumperButtonDown)
            {
                if (isLeftBumperButtonDown)
                {
                    OnButtonDown(LogitechF710Button.LeftBumber);
                    OnButtonPressed(LogitechF710Button.LeftBumber);

                    _leftBumperButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.LeftBumber, _repeatDelayMilliseconds, _repeatRateMilliseconds, _leftBumperButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _leftBumperButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.LeftBumber);
                }
            }

            if (_previousData == null || isRightBumperButtonDown != _previousData.IsRightBumperButtonDown)
            {
                if (isRightBumperButtonDown)
                {
                    OnButtonDown(LogitechF710Button.RightBumber);
                    OnButtonPressed(LogitechF710Button.RightBumber);

                    _rightBumperButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.RightBumber, _repeatDelayMilliseconds, _repeatRateMilliseconds, _rightBumperButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _rightBumperButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.RightBumber);
                }
            }

            if (_previousData == null || isLeftTriggerButtonDown != _previousData.IsLeftTriggerButtonDown)
            {
                if (isLeftTriggerButtonDown)
                {
                    OnButtonDown(LogitechF710Button.LeftTrigger);
                    OnButtonPressed(LogitechF710Button.LeftTrigger);

                    _leftTriggerButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.LeftTrigger, _repeatDelayMilliseconds, _repeatRateMilliseconds, _leftTriggerButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _leftTriggerButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.LeftTrigger);
                }
            }

            if (_previousData == null || isRightTriggerButtonDown != _previousData.IsRightTriggerButtonDown)
            {
                if (isRightTriggerButtonDown)
                {
                    OnButtonDown(LogitechF710Button.RightTrigger);
                    OnButtonPressed(LogitechF710Button.RightTrigger);

                    _rightTriggerButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.RightTrigger, _repeatDelayMilliseconds, _repeatRateMilliseconds, _rightTriggerButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _rightTriggerButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.RightTrigger);
                }
            }

            if (_previousData == null || isBackButtonDown != _previousData.IsBackButtonDown)
            {
                if (isBackButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Back);
                    OnButtonPressed(LogitechF710Button.Back);

                    _backButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Back, _repeatDelayMilliseconds, _repeatRateMilliseconds, _backButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _backButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Back);
                }
            }

            if (_previousData == null || isStartButtonDown != _previousData.IsStartButtonDown)
            {
                if (isStartButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Start);
                    OnButtonPressed(LogitechF710Button.Start);

                    _startButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Start, _repeatDelayMilliseconds, _repeatRateMilliseconds, _startButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _startButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Start);
                }
            }

            if (_previousData == null || isLeftThumbstickButtonDown != _previousData.IsLeftThumbstickButtonDown)
            {
                if (isLeftThumbstickButtonDown)
                {
                    OnButtonDown(LogitechF710Button.LeftThumbstick);
                    OnButtonPressed(LogitechF710Button.LeftThumbstick);

                    _leftThumbstickButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.LeftThumbstick, _repeatDelayMilliseconds, _repeatRateMilliseconds, _leftThumbstickButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _leftThumbstickButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.LeftThumbstick);
                }
            }

            if (_previousData == null || isRightThumbstickButtonDown != _previousData.IsRightThumbstickButtonDown)
            {
                if (isRightThumbstickButtonDown)
                {
                    OnButtonDown(LogitechF710Button.RightThumbstick);
                    OnButtonPressed(LogitechF710Button.RightThumbstick);

                    _rightThumbstickButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.RightThumbstick, _repeatDelayMilliseconds, _repeatRateMilliseconds, _rightThumbstickButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _rightThumbstickButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.RightThumbstick);
                }
            }

            if (_previousData == null || isUpButtonDown != _previousData.IsUpButtonDown)
            {
                if (isUpButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Up);
                    OnButtonPressed(LogitechF710Button.Up);

                    _upButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Up, _repeatDelayMilliseconds, _repeatRateMilliseconds, _upButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _upButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Up);
                }
            }

            if (_previousData == null || isRightButtonDown != _previousData.IsRightButtonDown)
            {
                if (isRightButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Right);
                    OnButtonPressed(LogitechF710Button.Right);

                    _rightButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Right, _repeatDelayMilliseconds, _repeatRateMilliseconds, _rightButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _rightButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Right);
                }
            }

            if (_previousData == null || isDownButtonDown != _previousData.IsDownButtonDown)
            {
                if (isDownButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Down);
                    OnButtonPressed(LogitechF710Button.Down);

                    _downButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Down, _repeatDelayMilliseconds, _repeatRateMilliseconds, _downButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _downButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Down);
                }
            }

            if (_previousData == null || isLeftButtonDown != _previousData.IsLeftButtonDown)
            {
                if (isLeftButtonDown)
                {
                    OnButtonDown(LogitechF710Button.Left);
                    OnButtonPressed(LogitechF710Button.Left);

                    _leftButtonPressedSource = new CancellationTokenSource();
                    RepeatButtonPressed(LogitechF710Button.Left, _repeatDelayMilliseconds, _repeatRateMilliseconds, _leftButtonPressedSource.Token);
                }
                else if (_previousData != null)
                {
                    _leftButtonPressedSource.Cancel();
                    OnButtonUp(LogitechF710Button.Left);
                }
            }

            if (_previousData != null)
            {
                if (leftThumbstickHorizontal != _previousData.LeftThumbstickHorizontal ||
                    leftThumbstickVertical != _previousData.LeftThumbstickVertical)
                {
                    OnThumbstickChanged(LogitechF710Thumbstick.Left, leftThumbstickHorizontal, leftThumbstickVertical);
                }

                if (rightThumbstickHorizontal != _previousData.RightThumbstickHorizontal ||
                    rightThumbstickVertical != _previousData.RightThumbstickVertical)
                {
                    OnThumbstickChanged(LogitechF710Thumbstick.Right, rightThumbstickHorizontal, rightThumbstickVertical);
                }
            }

            _previousData = data;
        }
 protected override void CompleteDevice(object key, HidDevice device, object creationState)
 {
     
 }
Example #54
0
        public static IMacroBoard FromHid(HidDevice device)
        {
            var hidWrapper = new StreamDeckHidWrapper(device);

            return(new CachedHidClient(hidWrapper, device.GetHardwareInformation()));
        }
Example #55
0
        /// <summary>
        /// This method is called each time the motion sensor forwards data to the host.
        ///
        /// Note that reading is relatively straight forward and follows the general WinRT paradigm of using events args
        /// and reading from buffers.
        /// </summary>
        /// <param name="sender">The hidDevice that raised the event (the one that received the interrupt)</param>
        /// <param name="eventArgs">Contains the HidInputReport that caused the interrupt</param>
        private async void OnGeneralInterruptEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs)
        {
            // Retrieve the sensor data
            HidInputReport inputReport = eventArgs.Report;
            IBuffer        buffer      = inputReport.Data;
            DataReader     dr          = DataReader.FromBuffer(buffer);

            byte[] bytes = new byte[inputReport.Data.Length];
            dr.ReadBytes(bytes);

            // Set the video length and delay values.
            TimeSpan length     = TimeSpan.FromSeconds(5);        // Video length 5 seconds
            TimeSpan delay      = TimeSpan.FromSeconds(15);       // Pause or delay 15 seconds
            TimeSpan radioDelay = TimeSpan.FromMilliseconds(250); // Duration of radio-button highlight

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // Briefly check the radio button to show that an event was fired
                radio1.IsChecked = true;
            });

            // Create a threadpool timer which toggles the radio button on for the radioDelay interval
            ThreadPoolTimer RadioButtonTimer = ThreadPoolTimer.CreateTimer(
                async(source) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // Radio button is unchecked once duration expires
                    radio1.IsChecked = false;
                });
            }, radioDelay);

            // The first byte contains the motion data
            if ((bytes[1] == 1) && !Capture)
            {
                Capture = true;

                // Create a threadpool timer which stops the video capture after "length" seconds
                ThreadPoolTimer VideoStopTimer = ThreadPoolTimer.CreateTimer(
                    async(source) =>
                {
                    await CaptureMgr.StopRecordAsync();

                    await rootPage.Dispatcher.RunAsync(
                        CoreDispatcherPriority.Normal,
                        new DispatchedHandler(() =>
                    {
                        rootPage.NotifyUser("Video capture concluded.", NotifyType.StatusMessage);
                    }));
                }, length);

                // Create a threadpool timer which prevents false captures by pausing detection for "delay" seconds
                ThreadPoolTimer CapturePauseTimer = ThreadPoolTimer.CreateTimer(
                    async(source) =>
                {
                    Capture = false;
                    await rootPage.Dispatcher.RunAsync(
                        CoreDispatcherPriority.Normal,
                        new DispatchedHandler(() =>
                    {
                        rootPage.NotifyUser("Presence sensor enabled.", NotifyType.StatusMessage);
                    }));
                }, delay);

                await rootPage.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(() =>
                {
                    rootPage.NotifyUser("Video capture started.", NotifyType.StatusMessage);
                }));

                String fileName;
                fileName    = VIDEO_FILE_NAME;
                StorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto);
                await CaptureMgr.StartRecordToStorageFileAsync(recordProfile, StorageFile);
            }
        }
Example #56
0
        public static void RazerAttrWriteModeStatic(HidDevice device, RazerRgb rgb)
        {
            RazerReport report = RazerChromaStandardMatrixEffectStatic(LED_STORAGE.VARSTORE, LEDS.BACKLIGHT_LED, rgb);

            RazerSendPayload(device, report);
        }
Example #57
0
 protected override void CompleteDevice(object key, HidDevice device, object creationState)
 {
     var hidDevice = (WinHidDevice)device; var handle = (IntPtr)creationState;
     hidDevice.GetInfoComplete(handle);
 }
Example #58
0
 void device_DataRead(HidDevice device, HidDeviceData data)
 {
     Debug.WriteLine(data.ToString());
 }
        /// <summary>
        /// This method demonstrates how to close the device properly using the WinRT Hid API.
        ///
        /// When the HidDevice is closing, it will cancel all IO operations that are still pending (not complete).
        /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
        /// the IO completion callbacks are called.
        /// The pending IO operations will still call their respective completion callbacks with either a task 
        /// cancelled error or the operation completed.
        /// </summary>
        private async void CloseCurrentlyConnectedDevice()
        {
            if (device != null)
            {
                // Notify callback that we're about to close the device
                if (deviceCloseCallback != null)
                {
                    deviceCloseCallback(this, deviceInformation);
                }

                // This closes the handle to the device
                device.Dispose();

                device = null;

                // Save the deviceInformation.Id in case deviceInformation is set to null when closing the
                // device
                String deviceId = deviceInformation.Id;

                await rootPage.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(() =>
                    {
                        MainPage.Current.NotifyUser(deviceId + " is closed", NotifyType.StatusMessage);
                    }));
            }
        }
Example #60
0
        public List <IT8297ControlDevice> GetDevices()
        {
            var mbmanu    = MotherboardInfo.Manufacturer;
            var mbmodel   = MotherboardInfo.Model;
            var mbpn      = MotherboardInfo.PartNumber;
            var mbproduct = MotherboardInfo.Product;
            var bm        = MotherboardInfo.SystemName;

            var terp = new OpenConfiguration();

            terp.SetOption(OpenOption.Transient, true);

            var       loader = new HidDeviceLoader();
            HidDevice device = null;

            HidSharp.HidDevice[] devices = null;
            foreach (var supportedId in supportedIds)
            {
                HidSharp.HidDevice[] tempdevices = loader.GetDevices(VENDOR_ID, supportedId).ToArray();
                if (tempdevices.Length > 0)
                {
                    devices = tempdevices;
                }
            }

            if (devices == null || devices.Length == 0)
            {
                return(new List <IT8297ControlDevice>());
            }


            int  attempts = 0;
            bool success  = false;

            foreach (HidDevice ddevice in devices)
            {
                device = ddevice;
                try
                {
                    var ps = attempts % devices.Count();
                    Console.WriteLine("Trying connection " + ps);
                    //    device = devices[attempts % devices.Count()];
                    Console.WriteLine(device.DevicePath);
                    byte[] t = device.GetRawReportDescriptor();
                    Debug.WriteLine("got raw");
                    Console.WriteLine(device.GetFriendlyName());
                    Debug.WriteLine("got friendly name");
                    stream = device.Open(terp);
                    Debug.WriteLine("got strean");
                    stream.SetCalibration();
                    Debug.WriteLine("set callibration");
                    stream.SendPacket(0x60, 0);
                    success = true;
                }
                catch
                {
                    attempts++;
                    Thread.Sleep(100);
                }
            }

            if (!success)
            {
                return(new List <IT8297ControlDevice>());
            }

            Bitmap pcieArea;
            Bitmap rgbPins;
            Bitmap vrm;

            Debug.WriteLine("Loading PCI Area png");

            pcieArea = (Bitmap)Image.FromStream(new MemoryStream(PCIArea_png.binary));


            Debug.WriteLine("Loading RGB Pins png");

            rgbPins = (Bitmap)Image.FromStream(new MemoryStream(rgbpins_png.binary));


            Debug.WriteLine("Loading VRM Area png");

            vrm = (Bitmap)Image.FromStream(new MemoryStream(VRM_png.binary));



            byte[] buffer = new byte[64];
            buffer[0] = 0xCC;
            stream.GetFeature(buffer);
            It8297ReportComplete report = GetReport(buffer);

            stream.SetLedCount();

            stream.Init();


            string name = report.ProductName;

            boardname = mbproduct;

            string layout = "";

            if (!GBMaps.ContainsKey(name))
            {
                name = "IT8297BX-GBX570";
            }

            layout = GBMaps[name];


            if (GBoverrides.ContainsKey(mbproduct))
            {
                layout = GBoverrides[mbproduct];
            }

            List <IT8297ControlDevice> result = new List <IT8297ControlDevice>();

            switch (layout)
            {
            case "FALLBACK":
            {
                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 1",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x58,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 2",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x59,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "VRM Block",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 32,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "PCI Area",
                        ProductImage      = pcieArea,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 35,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "C1C2 Header",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x24,
                            Setter       = RGBSetter.Single
                        }
                    });



                break;
            }

            case "390":
            {
                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 1",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x58,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[21],
                        Driver            = this,
                        DeviceType        = DeviceTypes.MotherBoard,
                        Name              = "VRM",
                        ProductImage      = vrm,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x59,
                            Setter       = RGBSetter.Strip,
                            RGBOrder     = RGBOrder.GRB
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 1",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x20,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 2",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x21,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 3",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x22,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Chipset",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x23,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 4",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x24,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 5",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x25,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 6",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x26,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Thing 7",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x27,
                            Setter       = RGBSetter.Single
                        }
                    });



                break;
            }

            case "MINI_ITX":
            {
                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 1",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x58,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Back I/O",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_BACK_IO,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[4],
                        Driver            = this,
                        Name              = "MOBO Backlight",
                        ProductImage      = pcieArea,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress   = HDR_CPU,
                            Setter         = RGBSetter.Composite,
                            CompositeOrder = new int[]
                            {
                                0x20, 0x21, 0x22, 0x23
                            }
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "C1C2 Header",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x24,
                            Setter       = RGBSetter.Single
                        }
                    });

                //result.Add(new IT8297ControlDevice
                //{
                //    LEDs = new ControlDevice.LedUnit[1],
                //    Driver = this,
                //    Name = "PCIExpress",
                //    ProductImage = pcieArea,
                //    DeviceType = DeviceTypes.MotherBoard,
                //    GigabyteRGBDevice = new GigabyteRGBDevice
                //    {
                //        FirstAddress = HDR_PCIE,
                //        Setter = RGBSetter.Single
                //    }
                //});


                //result.Add(new IT8297ControlDevice
                //{
                //    LEDs = new ControlDevice.LedUnit[1],
                //    Driver = this,
                //    DeviceType = DeviceTypes.Fan,
                //    Name = "C1C2 Header",
                //    ProductImage = rgbPins,
                //    GigabyteRGBDevice = new GigabyteRGBDevice
                //    {
                //        FirstAddress = 0x24,
                //        Setter = RGBSetter.Single
                //    }
                //});

                break;
            }

            case "ITX":
            {
                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 1",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x58,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Back I/O",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_BACK_IO,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "CPU Header",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_CPU,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "PCIExpress",
                        ProductImage      = pcieArea,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_PCIE,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "C1C2 Header",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x24,
                            Setter       = RGBSetter.Single
                        }
                    });

                break;
            }

            case "STD_ATX":
            {
                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 1",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x58,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        OverrideSupport = OverrideSupport.All,

                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "ARGB Header 2",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x59,
                            Setter       = RGBSetter.Strip
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "Back I/O",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_BACK_IO,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "CPU Header",
                        ProductImage      = vrm,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_CPU,
                            Setter       = RGBSetter.Single
                        }
                    });

                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        Name              = "PCIExpress",
                        ProductImage      = pcieArea,
                        DeviceType        = DeviceTypes.MotherBoard,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = HDR_PCIE,
                            Setter       = RGBSetter.Single
                        }
                    });


                result.Add(new IT8297ControlDevice
                    {
                        LEDs              = new ControlDevice.LedUnit[1],
                        Driver            = this,
                        DeviceType        = DeviceTypes.Fan,
                        Name              = "C1C2 Header",
                        ProductImage      = rgbPins,
                        GigabyteRGBDevice = new GigabyteRGBDevice
                        {
                            FirstAddress = 0x24,
                            Setter       = RGBSetter.Single
                        }
                    });

                break;
            }
            }


            foreach (IT8297ControlDevice it8297ControlDevice in result.Where(x => x.LEDs == null || x.LEDs.Length < 1))
            {
                SetDeviceOverride(it8297ControlDevice, new GenericFan());
            }


            foreach (IT8297ControlDevice it8297ControlDevice in result)
            {
                for (int i = 0; i < it8297ControlDevice.LEDs.Length; i++)
                {
                    it8297ControlDevice.LEDs[i] = new ControlDevice.LedUnit
                    {
                        Color = new LEDColor(0, 0, 0),
                        Data  = new ControlDevice.LEDData
                        {
                            LEDNumber = i
                        },
                        LEDName = it8297ControlDevice.Name + " " + (i + 1)
                    };
                }
            }



            return(result);
        }