Пример #1
0
        private void RefreshControllerList()
        {
            list_allControllers.Items.Clear();
            IntPtr ptr     = HIDapi.hid_enumerate(0x0, 0x0);
            IntPtr top_ptr = ptr;

            hid_device_info enumerate; // Add device to list

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (enumerate.serial_number == null)
                {
                    ptr = enumerate.next;
                    continue;
                }

                // TODO: try checking against interface number instead
                String name = enumerate.product_string + '(' + enumerate.vendor_id + '-' + enumerate.product_id + ')';
                if (!ContainsText(list_customControllers, name) && !ContainsText(list_allControllers, name))
                {
                    list_allControllers.Items.Add(new SController(name, enumerate.vendor_id, enumerate.product_id, 0));
                    // 0 type is undefined
                }

                ptr = enumerate.next;
            }
            HIDapi.hid_free_enumeration(top_ptr);
        }
Пример #2
0
        private int ReceiveRaw()
        {
            if (handle == IntPtr.Zero)
            {
                return(-2);
            }
            HIDapi.hid_set_nonblocking(handle, 0);
            byte[] raw_buf = new byte[report_len];
            int    ret     = HIDapi.hid_read(handle, raw_buf, new UIntPtr(report_len));

            if (ret > 0)
            {
                // Process packets as soon as they come
                for (int n = 0; n < 3; n++)
                {
                    ExtractIMUValues(raw_buf, n);

                    byte lag = (byte)Math.Max(0, raw_buf[1] - ts_en - 3);
                    if (n == 0)
                    {
                        Timestamp += (ulong)lag * 5000;                         // add lag once
                        ProcessButtonsAndStick(raw_buf);

                        int newbat = battery;
                        battery = (raw_buf[2] >> 4) / 2;
                        if (newbat != battery)
                        {
                            BatteryChanged();
                        }
                    }
                    Timestamp += 5000;                     // 5ms difference

                    packetCounter++;
                    if (Program.server != null)
                    {
                        Program.server.NewReportIncoming(this);
                    }

                    if (xin != null)
                    {
                        xin.SendReport(report);
                    }
                }

                if (ts_en == raw_buf[1])
                {
                    form.AppendTextBox("Duplicate timestamp enqueued.\r\n");
                    DebugPrint(string.Format("Duplicate timestamp enqueued. TS: {0:X2}", ts_en), DebugType.THREADING);
                }
                ts_en = raw_buf[1];
                DebugPrint(string.Format("Enqueue. Bytes read: {0:D}. Timestamp: {1:X2}", ret, raw_buf[1]), DebugType.THREADING);
            }
            return(ret);
        }
Пример #3
0
        private int ReceiveRaw()
        {
            if (handle == IntPtr.Zero)
            {
                return(-2);
            }
            HIDapi.hid_set_nonblocking(handle, 0);
            var raw_buf = new byte[report_len];
            var ret     = HIDapi.hid_read(handle, raw_buf, new UIntPtr(report_len));

            if (ret <= 0)
            {
                return(ret);
            }

            // Process packets as soon as they come
            for (var n = 0; n < 3; n++)
            {
                ExtractIMUValues(raw_buf, n);

                if (n == 0)
                {
                    var lag = (byte)Math.Max(0, raw_buf[1] - ts_en - 3);
                    Timestamp += (ulong)lag * 5000;  // add lag once
                    ProcessButtonsAndStick(raw_buf);
                }

                Timestamp += 5000; // 5ms difference

                packetCounter++;
                if (Program.server != null)
                {
                    Program.server.NewReportIncoming(this);
                }

                xin?.SendReport(report);
            }

            if (ts_en == raw_buf[1])
            {
                form.AppendTextBox("Duplicate timestamp enqueued.\r\n");
                DebugPrint($"Duplicate timestamp enqueued. TS: {ts_en:X2}", DebugType.THREADING);
            }

            ts_en = raw_buf[1];
            DebugPrint($"Enqueue. Bytes read: {ret:D}. Timestamp: {raw_buf[1]:X2}",
                       DebugType.THREADING);

            return(ret);
        }
Пример #4
0
        public void OnApplicationQuit()
        {
            foreach (Joycon v in j)
            {
                if (Boolean.Parse(ConfigurationManager.AppSettings["AutoPowerOff"]))
                {
                    v.PowerOff();
                }

                v.Detach();
            }

            controllerCheck.Stop();
            HIDapi.hid_exit();
        }
Пример #5
0
        public void OnApplicationQuit()
        {
            foreach (Joycon v in j)
            {
                v.Detach();

                if (v.xin != null)
                {
                    v.xin.Disconnect();
                    v.xin.Dispose();
                }
            }

            controllerCheck.Stop();
            HIDapi.hid_exit();
        }
Пример #6
0
 private void SendRumble(byte[] buf)
 {
     byte[] buf_ = new byte[report_len];
     buf_[0] = 0x10;
     buf_[1] = global_count;
     if (global_count == 0xf)
     {
         global_count = 0;
     }
     else
     {
         ++global_count;
     }
     Array.Copy(buf, 0, buf_, 2, 8);
     PrintArray(buf_, DebugType.RUMBLE, format: "Rumble data sent: {0:S}");
     HIDapi.hid_write(handle, buf_, new UIntPtr(report_len));
 }
        private void RefreshControllerList()
        {
            list_allControllers.Items.Clear();
            IntPtr ptr     = HIDapi.hid_enumerate(0x0, 0x0);
            IntPtr top_ptr = ptr;

            hid_device_info enumerate; // Add device to list

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (!ContainsText(list_customControllers, enumerate.product_string) && !ContainsText(list_allControllers, enumerate.product_string))
                {
                    list_allControllers.Items.Add(new { Text = enumerate.product_string, Value = enumerate });
                }

                ptr = enumerate.next;
            }
        }
Пример #8
0
        public void Detach()
        {
            stop_polling = true;

            if (state > state_.NO_JOYCONS)
            {
                Subcommand(0x40, new byte[] { 0x0 }, 1);
                Subcommand(0x48, new byte[] { 0x0 }, 1);

                if (isUSB)
                {
                    byte[] a = Enumerable.Repeat((byte)0, 64).ToArray();
                    a[0] = 0x80; a[1] = 0x05;                     // Allow device to talk to BT again
                    HIDapi.hid_write(handle, a, new UIntPtr(2));
                }
            }
            if (state > state_.DROPPED)
            {
                HIDapi.hid_close(handle);
            }
            state = state_.NOT_ATTACHED;
        }
Пример #9
0
        private byte[] Subcommand(byte sc, byte[] buf, uint len, bool print = true)
        {
            var buf_     = new byte[report_len];
            var response = new byte[report_len];

            Array.Copy(default_buf, 0, buf_, 2, 8);
            Array.Copy(buf, 0, buf_, 11, len);
            buf_[10] = sc;
            buf_[1]  = global_count;
            buf_[0]  = 0x1;
            if (global_count == 0xf)
            {
                global_count = 0;
            }
            else
            {
                ++global_count;
            }
            if (print)
            {
                PrintArray(buf_, DebugType.COMMS, len, 11,
                           "Subcommand 0x" + $"{sc:X2}" + " sent. Data: 0x{0:S}");
            }
            ;
            HIDapi.hid_write(handle, buf_, new UIntPtr(len + 11));
            var res = HIDapi.hid_read_timeout(handle, response, new UIntPtr(report_len), 50);

            if (res < 1)
            {
                DebugPrint("No response.", DebugType.COMMS);
            }
            else if (print)
            {
                PrintArray(response, DebugType.COMMS, report_len - 1, 1,
                           "Response ID 0x" + $"{response[0]:X2}" + ". Data: 0x{0:S}");
            }
            return(response);
        }
Пример #10
0
 public void Awake()
 {
     instance = this;
     j        = new ConcurrentList <Joycon>();
     HIDapi.hid_init();
 }
Пример #11
0
        public void CheckForNewControllers()
        {
            // move all code for initializing devices here and well as the initial code from Start()
            bool   isLeft  = false;
            IntPtr ptr     = HIDapi.hid_enumerate(0x0, 0x0);
            IntPtr top_ptr = ptr;

            hid_device_info enumerate; // Add device to list
            bool            foundNew = false;

            while (ptr != IntPtr.Zero)
            {
                SController thirdParty = null;
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (enumerate.serial_number == null)
                {
                    ptr = enumerate.next; // can't believe it took me this long to figure out why USB connections used up so much CPU.
                                          // it was getting stuck in an inf loop here!
                    continue;
                }

                bool validController = (enumerate.product_id == product_l || enumerate.product_id == product_r ||
                                        enumerate.product_id == product_pro || enumerate.product_id == product_snes) && enumerate.vendor_id == vendor_id;
                // check list of custom controllers specified
                foreach (SController v in Program.thirdPartyCons)
                {
                    if (enumerate.vendor_id == v.vendor_id && enumerate.product_id == v.product_id && enumerate.serial_number == v.serial_number)
                    {
                        validController = true;
                        thirdParty      = v;
                        break;
                    }
                }

                ushort prod_id = thirdParty == null ? enumerate.product_id : TypeToProdId(thirdParty.type);
                if (prod_id == 0)
                {
                    ptr = enumerate.next; // controller was not assigned a type, but advance ptr anyway
                    continue;
                }

                if (validController && !ControllerAlreadyAdded(enumerate.path))
                {
                    switch (prod_id)
                    {
                    case product_l:
                        isLeft = true;
                        form.AppendTextBox("Left Joy-Con connected.\r\n"); break;

                    case product_r:
                        isLeft = false;
                        form.AppendTextBox("Right Joy-Con connected.\r\n"); break;

                    case product_pro:
                        isLeft = true;
                        form.AppendTextBox("Pro controller connected.\r\n"); break;

                    case product_snes:
                        isLeft = true;
                        form.AppendTextBox("SNES controller connected.\r\n"); break;

                    default:
                        form.AppendTextBox("Non Joy-Con Nintendo input device skipped.\r\n"); break;
                    }

                    // Add controller to block-list for HidGuardian
                    if (Program.useHIDG)
                    {
                        HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(@"http://*****:*****@"hwids=HID\" + enumerate.path.Split('#')[1].ToUpper();
                        var            data     = Encoding.UTF8.GetBytes(postData);

                        request.Method        = "POST";
                        request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                        request.ContentLength = data.Length;

                        using (var stream = request.GetRequestStream())
                            stream.Write(data, 0, data.Length);

                        try {
                            var response       = (HttpWebResponse)request.GetResponse();
                            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        } catch {
                            form.AppendTextBox("Unable to add controller to block-list.\r\n");
                        }
                    }
                    // -------------------- //

                    IntPtr handle = HIDapi.hid_open_path(enumerate.path);
                    try {
                        HIDapi.hid_set_nonblocking(handle, 1);
                    } catch {
                        form.AppendTextBox("Unable to open path to device - are you using the correct (64 vs 32-bit) version for your PC?\r\n");
                        break;
                    }

                    bool isPro  = prod_id == product_pro;
                    bool isSnes = prod_id == product_snes;
                    j.Add(new Joycon(handle, EnableIMU, EnableLocalize & EnableIMU, 0.05f, isLeft, enumerate.path, enumerate.serial_number, j.Count, isPro, isSnes, thirdParty != null));

                    foundNew = true;
                    j.Last().form = form;

                    if (j.Count < 5)
                    {
                        int ii = -1;
                        foreach (Button v in form.con)
                        {
                            ii++;
                            if (!v.Enabled)
                            {
                                System.Drawing.Bitmap temp;
                                switch (prod_id)
                                {
                                case (product_l):
                                    temp = Properties.Resources.jc_left_s; break;

                                case (product_r):
                                    temp = Properties.Resources.jc_right_s; break;

                                case (product_pro):
                                    temp = Properties.Resources.pro; break;

                                case (product_snes):
                                    temp = Properties.Resources.snes; break;

                                default:
                                    temp = Properties.Resources.cross; break;
                                }

                                v.Invoke(new MethodInvoker(delegate {
                                    v.Tag             = j.Last(); // assign controller to button
                                    v.Enabled         = true;
                                    v.Click          += new EventHandler(form.conBtnClick);
                                    v.BackgroundImage = temp;
                                }));

                                form.loc[ii].Invoke(new MethodInvoker(delegate {
                                    form.loc[ii].Tag    = v;
                                    form.loc[ii].Click += new EventHandler(form.locBtnClickAsync);
                                }));

                                break;
                            }
                        }
                    }

                    byte[] mac = new byte[6];
                    try {
                        for (int n = 0; n < 6; n++)
                        {
                            mac[n] = byte.Parse(enumerate.serial_number.Substring(n * 2, 2), System.Globalization.NumberStyles.HexNumber);
                        }
                    } catch (Exception e) {
                        // could not parse mac address
                    }
                    j[j.Count - 1].PadMacAddress = new PhysicalAddress(mac);
                }

                ptr = enumerate.next;
            }

            if (foundNew)   // attempt to auto join-up joycons on connection
            {
                Joycon temp = null;
                foreach (Joycon v in j)
                {
                    // Do not attach two controllers if they are either:
                    // - Not a Joycon
                    // - Already attached to another Joycon (that isn't itself)
                    if (v.isPro || (v.other != null && v.other != v))
                    {
                        continue;
                    }

                    // Otherwise, iterate through and find the Joycon with the lowest
                    // id that has not been attached already (Does not include self)
                    if (temp == null)
                    {
                        temp = v;
                    }
                    else if (temp.isLeft != v.isLeft && v.other == null)
                    {
                        temp.other = v;
                        v.other    = temp;

                        if (temp.out_xbox != null)
                        {
                            try {
                                temp.out_xbox.Disconnect();
                            } catch (Exception e) {
                                // it wasn't connected in the first place, go figure
                            }
                        }
                        if (temp.out_ds4 != null)
                        {
                            try {
                                temp.out_ds4.Disconnect();
                            } catch (Exception e) {
                                // it wasn't connected in the first place, go figure
                            }
                        }
                        temp.out_xbox = null;
                        temp.out_ds4  = null;

                        foreach (Button b in form.con)
                        {
                            if (b.Tag == v || b.Tag == temp)
                            {
                                Joycon tt = (b.Tag == v) ? v : (b.Tag == temp) ? temp : v;
                                b.BackgroundImage = tt.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right;
                            }
                        }

                        temp = null;    // repeat
                    }
                }
            }

            HIDapi.hid_free_enumeration(top_ptr);

            bool on = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["HomeLEDOn"].Value.ToLower() == "true";

            foreach (Joycon jc in j)   // Connect device straight away
            {
                if (jc.state == Joycon.state_.NOT_ATTACHED)
                {
                    if (jc.out_xbox != null)
                    {
                        jc.out_xbox.Connect();
                    }
                    if (jc.out_ds4 != null)
                    {
                        jc.out_ds4.Connect();
                    }

                    try {
                        jc.Attach();
                    } catch (Exception e) {
                        jc.state = Joycon.state_.DROPPED;
                        continue;
                    }

                    jc.SetHomeLight(on);

                    jc.Begin();
                    if (form.allowCalibration)
                    {
                        jc.getActiveData();
                    }
                }
            }
        }
Пример #12
0
        public void CheckForNewControllers()
        {
            CleanUp();

            // move all code for initializing devices here and well as the initial code from Start()
            bool   isLeft  = false;
            IntPtr ptr     = HIDapi.hid_enumerate(vendor_id, 0x0);
            IntPtr top_ptr = ptr;

            hid_device_info enumerate;             // Add device to list
            bool            foundNew = false;

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (enumerate.serial_number == null)
                {
                    ptr = enumerate.next;                     // can't believe it took me this long to figure out why USB connections used up so much CPU.
                    // it was getting stuck in an inf loop here!
                    continue;
                }

                if (form.nonOriginal)
                {
                    enumerate.product_id = product_pro;
                }

                bool validController = (enumerate.product_id == product_l || enumerate.product_id == product_r ||
                                        enumerate.product_id == product_pro || enumerate.product_id == product_snes);
                if (validController && !ControllerAlreadyAdded(enumerate.path))
                {
                    switch (enumerate.product_id)
                    {
                    case product_l:
                        isLeft = true;
                        form.AppendTextBox("Left Joy-Con connected.\r\n"); break;

                    case product_r:
                        isLeft = false;
                        form.AppendTextBox("Right Joy-Con connected.\r\n"); break;

                    case product_pro:
                        isLeft = true;
                        form.AppendTextBox("Pro controller connected.\r\n"); break;

                    case product_snes:
                        isLeft = true;
                        form.AppendTextBox("SNES controller connected.\r\n"); break;

                    default:
                        form.AppendTextBox("Non Joy-Con Nintendo input device skipped.\r\n"); break;
                    }

                    // Add controller to block-list for HidGuardian
                    if (Program.useHIDG)
                    {
                        HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(@"http://*****:*****@"hwids=HID\" + enumerate.path.Split('#')[1].ToUpper();
                        var            data     = Encoding.UTF8.GetBytes(postData);

                        request.Method        = "POST";
                        request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                        request.ContentLength = data.Length;

                        using (var stream = request.GetRequestStream())
                            stream.Write(data, 0, data.Length);

                        try {
                            var response       = (HttpWebResponse)request.GetResponse();
                            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        } catch {
                            form.AppendTextBox("Unable to add controller to block-list.\r\n");
                        }
                    }
                    // -------------------- //

                    IntPtr handle = HIDapi.hid_open_path(enumerate.path);
                    try {
                        HIDapi.hid_set_nonblocking(handle, 1);
                    } catch {
                        form.AppendTextBox("Unable to open path to device - are you using the correct (64 vs 32-bit) version for your PC?\r\n");
                        break;
                    }

                    bool isPro  = enumerate.product_id == product_pro;
                    bool isSnes = enumerate.product_id == product_snes;
                    j.Add(new Joycon(handle, EnableIMU, EnableLocalize & EnableIMU, 0.05f, isLeft, enumerate.path, enumerate.serial_number, j.Count, isPro, isSnes));

                    foundNew = true;
                    j.Last().form = form;

                    if (j.Count < 5)
                    {
                        int ii = -1;
                        foreach (Button v in form.con)
                        {
                            ii++;
                            if (!v.Enabled)
                            {
                                System.Drawing.Bitmap temp;
                                switch (enumerate.product_id)
                                {
                                case (product_l):
                                    temp = Properties.Resources.jc_left_s; break;

                                case (product_r):
                                    temp = Properties.Resources.jc_right_s; break;

                                case (product_pro):
                                    temp = Properties.Resources.pro; break;

                                case (product_snes):
                                    temp = Properties.Resources.snes; break;

                                default:
                                    temp = Properties.Resources.cross; break;
                                }

                                v.Invoke(new MethodInvoker(delegate {
                                    v.Tag             = j.Last();                         // assign controller to button
                                    v.Enabled         = true;
                                    v.Click          += new EventHandler(form.conBtnClick);
                                    v.BackgroundImage = temp;
                                }));

                                form.loc[ii].Invoke(new MethodInvoker(delegate {
                                    form.loc[ii].Tag    = v;
                                    form.loc[ii].Click += new EventHandler(form.locBtnClick);
                                }));

                                break;
                            }
                        }
                    }

                    byte[] mac = new byte[6];
                    for (int n = 0; n < 6; n++)
                    {
                        mac[n] = byte.Parse(enumerate.serial_number.Substring(n * 2, 2), System.Globalization.NumberStyles.HexNumber);
                    }
                    j[j.Count - 1].PadMacAddress = new PhysicalAddress(mac);
                }

                ptr = enumerate.next;
            }

            if (foundNew)               // attempt to auto join-up joycons on connection
            {
                Joycon temp = null;
                foreach (Joycon v in j)
                {
                    if (!v.isPro)
                    {
                        if (temp == null)
                        {
                            temp = v;
                        }
                        else if (temp.isLeft != v.isLeft && v.other == null)
                        {
                            temp.other = v;
                            v.other    = temp;

                            //Set both Joycon LEDs to the one with the lowest ID
                            byte led = temp.LED <= v.LED ? temp.LED : v.LED;
                            temp.LED = led;
                            v.LED    = led;
                            temp.SetPlayerLED(led);
                            v.SetPlayerLED(led);

                            temp.xin.Dispose();
                            temp.xin = null;

                            foreach (Button b in form.con)
                            {
                                if (b.Tag == v || b.Tag == temp)
                                {
                                    Joycon tt = (b.Tag == v) ? v : (b.Tag == temp) ? temp : v;
                                    b.BackgroundImage = tt.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right;
                                }
                            }

                            temp = null;                                // repeat
                        }
                    }
                }
            }

            HIDapi.hid_free_enumeration(top_ptr);

            foreach (Joycon jc in j)               // Connect device straight away
            {
                if (jc.state == Joycon.state_.NOT_ATTACHED)
                {
                    if (jc.xin != null)
                    {
                        jc.xin.Connect();
                    }

                    jc.Attach(leds_: jc.LED);

                    bool on = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["HomeLEDOn"].Value.ToLower() == "true";
                    foreach (Joycon j in Program.mgr.j)
                    {
                        j.SetHomeLight(on);
                    }

                    jc.Begin();
                    if (form.nonOriginal)
                    {
                        jc.getActiveData();
                    }
                }
            }
        }
Пример #13
0
        public void Awake()
        {
            instance = this;
            int i = 0;

            j = new List <Joycon>();
            bool isLeft = false;

            HIDapi.hid_init();

            IntPtr ptr     = HIDapi.hid_enumerate(vendor_id, 0x0);
            IntPtr top_ptr = ptr;

            if (ptr == IntPtr.Zero)
            {
                ptr = HIDapi.hid_enumerate(vendor_id_, 0x0);
                if (ptr == IntPtr.Zero)
                {
                    HIDapi.hid_free_enumeration(ptr);
                    Console.WriteLine("No Joy-Cons found!");
                }
            }

            hid_device_info enumerate;

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (enumerate.product_id == product_l || enumerate.product_id == product_r || enumerate.product_id == product_pro)
                {
                    if (enumerate.product_id == product_l)
                    {
                        isLeft = true;
                        Console.WriteLine("Left Joy-Con connected.");
                    }
                    else if (enumerate.product_id == product_r)
                    {
                        isLeft = false;
                        Console.WriteLine("Right Joy-Con connected.");
                    }
                    else if (enumerate.product_id == product_pro)
                    {
                        isLeft = true;
                        Console.WriteLine("Pro controller connected.");
                    }
                    else
                    {
                        Console.WriteLine("Non Joy-Con input device skipped.");
                    }

                    IntPtr handle = HIDapi.hid_open_path(enumerate.path);
                    try {
                        HIDapi.hid_set_nonblocking(handle, 1);
                    } catch (Exception e) {
                        Console.WriteLine("Unable to open path to device - are you using the correct (64 vs 32-bit) version for your PC?");
                        break;
                    }

                    j.Add(new Joycon(handle, EnableIMU, EnableLocalize & EnableIMU, 0.05f, isLeft, j.Count, enumerate.product_id == product_pro, enumerate.serial_number == "000000000001"));

                    byte[] mac = new byte[6];
                    for (int n = 0; n < 6; n++)
                    {
                        mac[n] = byte.Parse(enumerate.serial_number.Substring(n * 2, 2), System.Globalization.NumberStyles.HexNumber);
                    }
                    j[j.Count - 1].PadMacAddress = new PhysicalAddress(mac);

                    ++i;
                }
                ptr = enumerate.next;
            }

            int found = 0;

            foreach (Joycon v in j)
            {
                if (v.isLeft && !v.isPro)
                {
                    found++;
                }
                if (!v.isLeft && !v.isPro)
                {
                    found++;
                }
            }

            if (found == 2)
            {
                Console.WriteLine("Both joycons successfully found.");
                Joycon temp = null;
                foreach (Joycon v in j)
                {
                    if (v.isLeft && !v.isPro)
                    {
                        if (temp == null)
                        {
                            temp = v;
                        }
                        else
                        {
                            temp.other = v;
                            v.other    = temp;
                        }
                    }

                    if (!v.isLeft && !v.isPro)
                    {
                        if (temp == null)
                        {
                            temp = v;
                        }
                        else
                        {
                            temp.other = v;
                            v.other    = temp;
                        }
                    }
                }                 // Join up the two joycons
            }
            else if (found != 0)
            {
                Console.WriteLine("Only one joycon found. Please connect both and then restart the program.");
            }

            HIDapi.hid_free_enumeration(top_ptr);
        }
Пример #14
0
        public int Attach(byte leds_ = 0x0)
        {
            state = state_.ATTACHED;

            // Make sure command is received
            HIDapi.hid_set_nonblocking(handle, 0);

            byte[] a = { 0x0 };

            // Connect
            if (!isUSB)
            {
                // Input report mode
                Subcommand(0x03, new byte[] { 0x30 }, 1, false);
                a[0] = 0x1;
                dump_calibration_data();
            }
            else
            {
                Subcommand(0x03, new byte[] { 0x3f }, 1, false);

                a = Enumerable.Repeat((byte)0, 64).ToArray();
                Console.WriteLine("Using USB.");

                a[0] = 0x80;
                a[1] = 0x01;
                HIDapi.hid_write(handle, a, new UIntPtr(2));
                HIDapi.hid_read(handle, a, new UIntPtr(64));

                if (a[2] != 0x3)
                {
                    PadMacAddress = new PhysicalAddress(new byte[] { a[9], a[8], a[7], a[6], a[5], a[4] });
                }

                // USB Pairing
                a    = Enumerable.Repeat((byte)0, 64).ToArray();
                a[0] = 0x80; a[1] = 0x02;                 // Handshake
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x03;                 // 3Mbit baud rate
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x02;                 // Handshake at new baud rate
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x04;                 // Prevent HID timeout
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                dump_calibration_data();
            }

            a[0] = leds_;
            Subcommand(0x30, a, 1);
            Subcommand(0x40, new byte[] { (imu_enabled ? (byte)0x1 : (byte)0x0) }, 1, true);
            Subcommand(0x3, new byte[] { 0x30 }, 1, true);
            Subcommand(0x48, new byte[] { 0x1 }, 1, true);

            Subcommand(0x41, new byte[] { 0x03, 0x00, 0x00, 0x01 }, 4, false);             // higher gyro performance rate

            DebugPrint("Done with init.", DebugType.COMMS);

            HIDapi.hid_set_nonblocking(handle, 1);

            return(0);
        }
Пример #15
0
        public void CheckForNewControllers()
        {
            CleanUp();

            // move all code for initializing devices here and well as the initial code from Start()
            bool   isLeft  = false;
            IntPtr ptr     = HIDapi.hid_enumerate(vendor_id, 0x0);
            IntPtr top_ptr = ptr;

            hid_device_info enumerate; // Add device to list
            bool            foundNew = false;

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if ((enumerate.product_id == product_l || enumerate.product_id == product_r || enumerate.product_id == product_pro) && !ControllerAlreadyAdded(enumerate.path))
                {
                    switch (enumerate.product_id)
                    {
                    case product_l:
                        isLeft = true;
                        form.AppendTextBox("Left Joy-Con connected.\r\n"); break;

                    case product_r:
                        isLeft = false;
                        form.AppendTextBox("Right Joy-Con connected.\r\n"); break;

                    case product_pro:
                        isLeft = true;
                        form.AppendTextBox("Pro controller connected.\r\n"); break;

                    default:
                        form.AppendTextBox("Non Joy-Con Nintendo input device skipped.\r\n"); break;
                    }

                    // Add controller to block-list for HidGuardian
                    if (useHIDG)
                    {
                        HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(@"http://*****:*****@"hwids=HID\" + enumerate.path.Split('#')[1].ToUpper();
                        var            data     = Encoding.UTF8.GetBytes(postData);

                        request.Method        = "POST";
                        request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                        request.ContentLength = data.Length;

                        using (var stream = request.GetRequestStream())
                            stream.Write(data, 0, data.Length);

                        try {
                            var response       = (HttpWebResponse)request.GetResponse();
                            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        } catch {
                            form.AppendTextBox("Unable to add controller to block-list.\r\n");
                        }
                    }
                    else     // Remove affected devices from list
                    {
                        try {
                            HttpWebResponse r1 = (HttpWebResponse)WebRequest.Create(@"http://localhost:26762/api/v1/hidguardian/affected/purge/").GetResponse();
                        } catch { }
                    }
                    // -------------------- //

                    IntPtr handle = HIDapi.hid_open_path(enumerate.path);
                    try {
                        HIDapi.hid_set_nonblocking(handle, 1);
                    } catch {
                        form.AppendTextBox("Unable to open path to device - are you using the correct (64 vs 32-bit) version for your PC?\r\n");
                        break;
                    }

                    j.Add(new Joycon(handle, EnableIMU, EnableLocalize & EnableIMU, 0.05f, isLeft, enumerate.path, j.Count, enumerate.product_id == product_pro, enumerate.serial_number == "000000000001"));

                    foundNew = true;
                    j.Last().form = form;

                    if (j.Count < 5)
                    {
                        int ii = -1;
                        foreach (Button v in form.con)
                        {
                            ii++;
                            if (!v.Enabled)
                            {
                                System.Drawing.Bitmap temp;
                                switch (enumerate.product_id)
                                {
                                case (product_l):
                                    temp = Properties.Resources.jc_left_s; break;

                                case (product_r):
                                    temp = Properties.Resources.jc_right_s; break;

                                case (product_pro):
                                    temp = Properties.Resources.pro; break;

                                default:
                                    temp = Properties.Resources.cross; break;
                                }

                                v.Invoke(new MethodInvoker(delegate {
                                    v.Tag             = j.Last(); // assign controller to button
                                    v.Enabled         = true;
                                    v.Click          += new EventHandler(form.conBtnClick);
                                    v.BackgroundImage = temp;
                                }));

                                form.loc[ii].Invoke(new MethodInvoker(delegate {
                                    form.loc[ii].Tag    = v;
                                    form.loc[ii].Click += new EventHandler(form.locBtnClick);
                                }));

                                break;
                            }
                        }
                    }

                    byte[] mac = new byte[6];
                    for (int n = 0; n < 6; n++)
                    {
                        mac[n] = byte.Parse(enumerate.serial_number.Substring(n * 2, 2), System.Globalization.NumberStyles.HexNumber);
                    }
                    j[j.Count - 1].PadMacAddress = new PhysicalAddress(mac);
                }

                ptr = enumerate.next;
            }

            int found    = 0;
            int minPadID = 10;

            foreach (Joycon v in j)   // current system is designed for a maximum of two joycons connected to the PC
            {
                if (!v.isPro)
                {
                    found++;
                    minPadID = Math.Min(v.PadId, minPadID);
                }
                v.LED = (byte)(0x1 << v.PadId);
            }

            if (found == 2 && foundNew)
            {
                form.AppendTextBox("Both joycons successfully found.\r\n");
                Joycon temp = null;
                foreach (Joycon v in j)
                {
                    if (!v.isPro)
                    {
                        v.LED = (byte)(0x1 << minPadID);

                        if (temp == null)
                        {
                            temp = v;
                        }
                        else
                        {
                            temp.other = v;
                            v.other    = temp;

                            temp.xin.Dispose();
                            temp.xin = null;
                        }

                        foreach (Button b in form.con)
                        {
                            if (b.Tag == v)
                            {
                                if (v.isLeft)
                                {
                                    b.BackgroundImage = Properties.Resources.jc_left;
                                }
                                else
                                {
                                    b.BackgroundImage = Properties.Resources.jc_right;
                                }
                            }
                        }
                    }
                } // Join up the two joycons
            }

            HIDapi.hid_free_enumeration(top_ptr);

            foreach (Joycon jc in j)   // Connect device straight away
            {
                if (jc.state == Joycon.state_.NOT_ATTACHED)
                {
                    if (jc.xin != null)
                    {
                        jc.xin.Connect();
                    }

                    jc.Attach(leds_: jc.LED);
                    jc.Begin();
                }
            }
        }
Пример #16
0
        public void Awake()
        {
            instance = this;
            int i = 0;

            j = new List <Joycon>();
            bool isLeft = false;

            HIDapi.hid_init();

            IntPtr ptr     = HIDapi.hid_enumerate(vendor_id, 0x0);
            IntPtr top_ptr = ptr;

            if (ptr == IntPtr.Zero)
            {
                ptr = HIDapi.hid_enumerate(vendor_id_, 0x0);
                if (ptr == IntPtr.Zero)
                {
                    HIDapi.hid_free_enumeration(ptr);
                    form.console.Text += "No Joy-Cons found!\r\n";
                }
            }

            hid_device_info enumerate;

            while (ptr != IntPtr.Zero)
            {
                enumerate = (hid_device_info)Marshal.PtrToStructure(ptr, typeof(hid_device_info));

                if (enumerate.product_id == product_l || enumerate.product_id == product_r || enumerate.product_id == product_pro)
                {
                    if (enumerate.product_id == product_l)
                    {
                        isLeft             = true;
                        form.console.Text += "Left Joy-Con connected.\r\n";
                    }
                    else if (enumerate.product_id == product_r)
                    {
                        isLeft             = false;
                        form.console.Text += "Right Joy-Con connected.\r\n";
                    }
                    else if (enumerate.product_id == product_pro)
                    {
                        isLeft             = true;
                        form.console.Text += "Pro controller connected.\r\n";
                    }
                    else
                    {
                        form.console.Text += "Non Joy-Con input device skipped.\r\n";
                    }

                    // Add controller to block-list for HidGuardian
                    HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(@"http://*****:*****@"hwids=HID\" + enumerate.path.Split('#')[1].ToUpper();
                    var            data     = Encoding.UTF8.GetBytes(postData);

                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                    request.ContentLength = data.Length;

                    using (var stream = request.GetRequestStream())
                        stream.Write(data, 0, data.Length);

                    try {
                        var response       = (HttpWebResponse)request.GetResponse();
                        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    } catch (Exception e) {
                        form.console.Text += "Unable to add controller to block-list.\r\n";
                    }
                    // -------------------- //

                    IntPtr handle = HIDapi.hid_open_path(enumerate.path);
                    try {
                        HIDapi.hid_set_nonblocking(handle, 1);
                    } catch (Exception e) {
                        form.console.Text += "Unable to open path to device - are you using the correct (64 vs 32-bit) version for your PC?\r\n";
                        break;
                    }

                    j.Add(new Joycon(handle, EnableIMU, EnableLocalize & EnableIMU, 0.05f, isLeft, j.Count, enumerate.product_id == product_pro, enumerate.serial_number == "000000000001"));

                    j.Last().form = form;

                    byte[] mac = new byte[6];
                    for (int n = 0; n < 6; n++)
                    {
                        mac[n] = byte.Parse(enumerate.serial_number.Substring(n * 2, 2), System.Globalization.NumberStyles.HexNumber);
                    }
                    j[j.Count - 1].PadMacAddress = new PhysicalAddress(mac);

                    ++i;
                }
                ptr = enumerate.next;
            }

            int found = 0;

            foreach (Joycon v in j)
            {
                if (v.isLeft && !v.isPro)
                {
                    found++;
                }
                if (!v.isLeft && !v.isPro)
                {
                    found++;
                }
            }

            if (found == 2)
            {
                form.console.Text += "Both joycons successfully found.\r\n";
                Joycon temp = null;
                foreach (Joycon v in j)
                {
                    if (v.isLeft && !v.isPro)
                    {
                        if (temp == null)
                        {
                            temp = v;
                        }
                        else
                        {
                            temp.other = v;
                            v.other    = temp;
                        }
                    }

                    if (!v.isLeft && !v.isPro)
                    {
                        if (temp == null)
                        {
                            temp = v;
                        }
                        else
                        {
                            temp.other = v;
                            v.other    = temp;
                        }
                    }
                }                 // Join up the two joycons
            }
            else if (found != 0)
            {
                form.console.Text += "Only one joycon found. Please connect both and then restart the program.\r\n";
            }

            HIDapi.hid_free_enumeration(top_ptr);
        }
Пример #17
0
 public void Awake()
 {
     _instance = this;
     j         = new List <Joycon>();
     HIDapi.hid_init();
 }